Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(google): resolve the account through userinfo and name every disabled API at setup, status and doctor (#7004, #7073)
garrytanfb1cee45c183
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex 1e43bf38d0..ad68142cf0 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -17,7 +17,7 @@ The #6188 fence check and fence repair live in [fence repair](core-fence-repair.- `src/core/connectors/item-holds.ts` — fix wave 4 connector item holds, shared by Gmail and GitHub on managed and unmanaged brains: `classifyConnectorError` (the one table: source-scoped, rate-limit and item-scoped codes, content vs transient class) and `ItemHoldsRun` (hold after 3 consecutive attempted runs at one upstream version; circuit breaker at 5 attempted items with half transient or 5 and half one code; backoff 1 h/6 h/24 h/daily for 7 days; cap 100, `connector_holds_exhausted`). A run's changes merge only in `finish()`, so mid-run checkpoints carry the holds the run began with and a cursor never passes an item that is not already held. `carryLegacyFailCounts` reads the retired Gmail ledger once.- `src/core/connectors/item-holds-store.ts` + `connector-hold-session.ts` — reads holds from the cursor state (managed checkpoint row or the unmanaged state file) for `sources status`, doctor `connector_held_items` and `open_loops` completeness; the `connector-hold-retry` request rows and the pending `managed-connector-retry` pointers `sources retry-held` writes; the per-run session that skips held items, publishes holds on a managed abort (`publishHolds`), releases held items' terminal receipts from the automatic retry set and consumes retry-held keys. Git-source holds are not read here: only `sources status` (`persistence/connector-status.ts` `readGitHoldStatuses`, `sources status <id>` filters to one source) and `sources retry-held` (a Git source records a `sync-hold-retry` re-screen request for its held paths; `gbrain sync --retry-held` refuses with that pointer) show them beside connector holds. Writer deactivation and activation never read or block on them.- `src/core/connectors/connector-text.ts` — #5752 render boundary: prose sanitized with `sanitizeForJsonb` before the no-op screen; identity fields refuse with `invalid_connector_text`.-- `src/core/persistence/connector-account.ts` — resolves the credential's account before any service runs: Google through Gmail profile, Calendar primary calendar or People `me` (first enabled service that answers; none refuses), GitHub App installation id from the minted token, or the `/user` login for token auth under `scope: auto`.+- `src/core/persistence/connector-account.ts` — resolves the credential's account before any service runs: Google through `probeGoogleAccount` in `google/api-access.ts` (Gmail profile, Calendar primary calendar or People `me`, first enabled service that answers, else OAuth userinfo, #7073), returning the probe with every per-service error; when nothing names the account it rethrows `api_not_enabled` first, then another credential error, then the first other failure, so `connector_account_changed` means a resolved account that differs from the pin (test/google-api-access-managed-7073.test.ts), GitHub App installation id from the minted token, or the `/user` login for token auth under `scope: auto`.- `src/core/persistence/connector-errors.ts` — `connector_account_changed` with its two-exit hint, the retired-intent messages, and `receiptDeliveredHint`, which rebuilds `suggestion`/`detail`/`docs` for codes delivered through a stored receipt (the coordinator persists only code and message); `writeResponse` applies it.- `src/core/persistence/noop-kernel.ts` — the #5470 no-op kernel. `inspectUnchanged` takes a preparer's `PreparedMutation` for an unadmitted `screeningRequest` and returns `contentUnchanged`, `projectionWorkRequired` (safe-chunk fence, text projection behind the knowledge revision, embedded page without a contextual mode), `metadataWorkRequired` (source path) and `observedRevision`; bound pages also need local file bytes equal to the serialized page. The page's current `knowledge_revision`, read with the projection flags, must still equal the snapshot's revision (a write after the screen's snapshot admits as `revision_moved`). Callers run the preparer's own `validate` before counting a skip. An optional `waive` list (#5751) lets a caller skip two admit reasons its no-op publication can never resolve, a pending contextual-mode stamp and file bytes that differ from the prepared content (never a missing file); the result lists each waiver applied in `waived`; only managed working-tree sync entries and `put-page-screen.ts` pass it. Used by connector sync, `import-mutations.ts`, `sync-run.ts` (working-tree and company-profile entries; renames and overlays always admit) and `put-page-screen.ts` (the managed transcript import's `put_page`, waiving `canonical_file_differs` for a file the preparer accepted). Tests: `test/noop-kernel-paths.test.ts`, `test/connector-wave3.test.ts`.diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex 6976894ab3..231da5febb 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -1,6 +1,6 @@# Google connector + open-loop engine (key files cluster) (continued)-[Subsystem index](../KEY_FILES.md) · [Previous entries](google-and-loops.md).+[Subsystem index](../KEY_FILES.md) · [Previous entries](google-and-loops.md) · [Account identity and API access](google-api-access.md).- `src/core/tailscale.ts` — Tailscale helpers with an injected exec seam (`CommandRunner = (argv, { inherit?, timeoutMs?, stdoutToStderr? }) => Promise<CommandResult>` where `CommandResult = { status, stdout, stderr }` and `status: null` means killed at the timeout or never spawned; `defaultCommandRunner` on `Bun.spawn` — at `timeoutMs` it sends SIGTERM and, when the child has still not exited `SIGKILL_GRACE_MS` (3s) later, SIGKILL, so a child that ignores SIGTERM never hangs the caller; both timers are cleared in a `finally` — also the runner `serve-service.ts` types against; `stdoutToStderr` sends an inherited child's stdout to fd 2 so `--json` stdout stays pure): `parseTailscaleStatus` (`BackendState` — `Running`, `NeedsLogin`, `NeedsMachineAuth`, `NoState`, `Stopped`; `Self.DNSName`, `CertDomains`, and `funnelCapable`: true/false from `Self.CapMap` keys or `Self.Capabilities` entries carrying any Funnel form — `funnel` (`NodeAttrFunnel`), `https://tailscale.com/cap/funnel-ports` with or without its `?ports=` query, or the legacy `https://tailscale.com/cap/funnel` — null when both are absent), `publicUrlFromDnsName` (strip trailing dot, lowercase, `https://`), `TAILSCALE_BINARY_CANDIDATES` + `findTailscaleBinary` (`Bun.which`, then the macOS app bundle, Homebrew and `/usr/bin` paths; the candidate list doubles as `mcp-expose.ts`'s allowlist for a binary path recorded in a receipt) + `isSystemTailscaleBinary(binary, realpath = realpathSync)` (true when the path is a candidate literally or resolves to one through symlinks; an unresolvable path is false — `mcp-expose.ts` puts `sudo` in front of the binary only when this holds), `tailscaleInstallPlan(platform, hasBrew)`, `tailscaleLoginArgv(platform, user, binary)` → `{ setOperator?, up }` (Linux: `sudo <bin> set --operator=<user>` then a flagless `sudo <bin> up` — a flagged `up` trips the CLI's settings-revert check on a node with non-default prefs; macOS: `<bin> up`), `tailscaleManualLoginCommand(binary = 'tailscale')` (the Linux login the operator runs themselves when gbrain refuses to `sudo` a non-system binary — `sudo <bin> set --operator=$USER && sudo <bin> up` with the DISCOVERED path shell-quoted through `shellQuote`, because a binary outside sudo's `secure_path` is exactly that case) and `TAILSCALE_ACCEPT_DNS_COMMAND` (`tailscale set --accept-dns=true`, the MagicDNS-off remedy) — both keep their tailscale flag literals in this module so the flag-registry scan of `mcp-expose.ts` never sees them, `tailscaleServeArgv(port, { funnel })` (`serve --bg` / `funnel --bg`) + `tailscaleServeOffArgv({ funnel })` (`serve|funnel --https=443 --set-path=/ off` — `--set-path=/` scopes `off` to OUR `/` mount; without it the CLI removes every mount under `:443` and, when more than one exists, prompts interactively — with stdin ignored the prompt reads EOF and the command exits 0 having removed nothing; never `serve reset`), `parseServeStatusStrict` (the only serve-status parser, fail-closed: background `Web` handlers, `Foreground[<session>].Web` handlers marked `foreground: true`, and `TCP['443'].TCPForward` as a non-proxy root handler; an empty document / `{}` / `null` is the legitimately empty view, but non-JSON, an array or a scalar returns `null` so `mcp-expose.ts`'s `readServeView` can tell "could not read" from "nothing configured") + `findProxiedHandler(view, port)`, `classifyTailscaleError(stderr)` (Funnel rule before the HTTPS rule; the HTTPS rule matches certificate vocabulary, never a bare `https://` URL: `funnel_not_enabled` | `https_not_enabled` | `needs_operator` | `needs_login` | `daemon_not_running` | `unknown`), and the admin/KB URL constants (`TAILSCALE_ADMIN_DNS_URL`, `TAILSCALE_ADMIN_ACL_URL`, `TAILSCALE_FUNNEL_KB_URL` = `https://tailscale.com/kb/1223/funnel`, `TAILSCALE_DOWNLOAD_URL`). The parsers and argv builders are pure; the injectable `which` / `fileExists` / runner defaults touch `existsSync`, `process.env.PATH` and `process.platform`, and tests replace them. Note `tailscale status --json` exits 0 in every `BackendState` (only the human-readable form exits 1 when logged out), and `serve`/`funnel` wait interactively rather than failing when HTTPS certificates or the Funnel attribute are off — which is why `mcp-expose.ts` pre-checks before starting them.- `src/core/serve-service.ts` — the persistent-service half of `mcp expose`, everything under `gbrainPath('serve')` (`serveDir`, `adminTokenPath`, `wrapperPath`, `receiptPath`, `serveLogPath`, `serveErrPath`) so `GBRAIN_HOME` is honored. `SERVE_LAUNCHD_LABEL = 'com.gbrain.serve'`, `SERVE_SYSTEMD_UNIT = 'gbrain-serve.service'`, `detectServiceTarget(signals)` → `'macos' | 'linux-systemd' | 'none'` (a working user bus is required for systemd; cloud sandboxes and ephemeral containers fall to `none`). `renderServeWrapper` produces the 0755 launcher that sources the shell profiles and `~/.gbrain/env`, prepends the Bun dir to `PATH`, reads the admin token from its file at run time into `GBRAIN_ADMIN_BOOTSTRAP_TOKEN` (the token is never written into the wrapper, plist or unit), resolves `gbrain` the way autopilot's wrapper does (baked installer path, `type -P gbrain` fallback) and `exec`s `serve --http --port N --public-url URL [--surface] [--enable-dcr]`. `resolveServeGbrainCommand({ which, execPath, argv1, metaUrl, fileExists })` picks the baked program: a `gbrain` on PATH wins; a COMPILED binary — `import.meta.url` (or the injected `metaUrl`) under `/$bunfs/`, or an `execPath` that is not the bun runtime while `argv[1]` is absent/virtual — is `[execPath]` whatever its basename (release assets are renamed); otherwise the `[bun, <cli.ts>]` dev form only when that `cli.ts` exists on disk, else `[execPath]` rather than a path that cannot run; `renderServeLaunchdPlist` (RunAtLoad, KeepAlive, ThrottleInterval 30, logs to `serve.log` / `serve.err`, local `escapeXml`) and `renderServeSystemdUnit` (After=network-online.target, Restart=always, RestartSec=10, start-limit window; systemd specifiers escaped — `%` → `%%` in `ExecStart` and both `append:` log paths, `$` → `$$` in `ExecStart`). `ensureAdminToken` (0700 dir, 0600 file created with `wx` semantics, 64 hex chars; reuse a file matching the exported `ADMIN_TOKEN_SHAPE` = `^[A-Za-z0-9_-]{32,}$` — the same regex `serve-http.ts`'s `resolveBootstrapToken` accepts, so the file and the env var can never disagree on what a valid token is — unlink and regenerate otherwise), `installServeService` (launchd: domain-explicit `launchctl bootout gui/<uid> <plist>` — failure ignored — then `launchctl bootstrap gui/<uid> <plist>`, both through the one `launchctl(run, uid, plist, { modern, legacy })` helper whose legacy `launchctl unload` / `load` fallback is used ONLY when the modern verb exits non-zero with stderr matching `/Unknown command|unrecognized|not found/i`, never on a genuine failure or a killed call, and which reports the `verb` whose result it returns; a bootstrap that fails with stderr matching `LAUNCHCTL_SETTLE_RE` (`Input/output error`, `already in progress`, `\b5\b`, `\b37\b` — launchd still unloading the previous job) is retried up to `LAUNCHCTL_SETTLE_RETRIES` (5) times, `LAUNCHCTL_SETTLE_MS` (1s) apart through the injectable `sleep` param (default `setTimeout`; `mcp-expose.ts` passes `d.sleep`), a success after retries is a note and an exhausted retry appends "(after N settle retries)" to `error`; systemd: `daemon-reload` → `enable` → `restart` so a regenerated wrapper takes effect; `loginctl enable-linger` best effort) / `uninstallServeService` (launchd: the same `bootout gui/<uid>` with the same fallback; a bootout that exits non-zero — or is killed — with stderr NOT matching `LAUNCHCTL_NOT_LOADED_RE` (`No such process|not loaded|Could not find|not find service`) pushes `launchctl <verb> failed: <describeFailure>` into `notes`, and the exported `launchdBootoutFailed(result)` recognizes that note so `mcp-expose.ts` can say the job may still be loaded) / `serveServiceState` (`launchctl print gui/<uid>/<label>` / `systemctl --user is-active`); all three take `uid?: number` defaulting to `process.getuid?.() ?? 501`, threaded from `mcp-expose.ts`. Every supervisor subprocess carries a timeout — 60s for `launchctl bootstrap/bootout` (and the legacy `load/unload`) and `systemctl --user enable/restart/disable`, 15s for `launchctl print`, `daemon-reload`, `is-active` and `loginctl enable-linger` — and a `status: null` (killed) result counts as a failure (`error` / note) or `unknown` state; a failed call is described by `describeFailure` (its stderr, else stdout, else `exit <status>`). `readExposeReceipt` / `writeExposeReceipt` (`expose.json`, 0600, version 1, no secrets): the reader is a structural shape guard, not just `version`/`port`/`public_url` — it also requires `mode` in `tailnet|funnel`, a `service` object with a string `wrapper_path`, a `target` in `macos|linux-systemd|none`, a string `state` and string-or-null `plist_path` / `unit_path`, a `tailscale` object whose `binary` / `dns_name` are string-or-null, and string `mcp_url` / `admin_url` / `admin_token_file`; anything less is null (absent), so `--status` / `--remove` never dereference a half-written receipt. The token, receipt, wrapper, plist and unit writers refuse (clear error) when the target path is a symlink (`lstatSync`) before any supervisor call runs. Uses `shellQuote` from `src/core/mcp-registration.ts`; every filesystem/exec effect is behind injectable deps.diff --git a/docs/architecture/key-files/google-and-loops.md b/docs/architecture/key-files/google-and-loops.mdindex f33c301abb..0812b0271f 100644--- a/docs/architecture/key-files/google-and-loops.md+++ b/docs/architecture/key-files/google-and-loops.md@@ -24,7 +24,7 @@ Historical Gmail repair selects explicit nested MIME metadata fields, excluding- `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. `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`; 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/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 disabled API → `GoogleApiDisabledError` and insufficient scope → `scope_missing` ([API access](google-api-access.md)), 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 sweep left no failing item that is not yet held (410 GONE drops the token and re-runs windowed); GBRA-130 A-3: contacts and events go through connector item holds (`contact:`/`event:` keys), so one failing item no longer pins the token or stops Gmail (`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.diff --git a/docs/architecture/key-files/google-api-access.md b/docs/architecture/key-files/google-api-access.mdnew file mode 100644index 0000000000..5e7b20a5c8--- /dev/null+++ b/docs/architecture/key-files/google-api-access.md@@ -0,0 +1,11 @@+# Google connector account identity and API access (key files cluster)++[Subsystem index](../KEY_FILES.md) · [Google connector + open-loop engine](google-and-loops.md).++- `src/core/google/api-access.ts` — #7004/#7073 account identity and API reachability. `probeGoogleAccount(clients, services, { every })` asks Gmail profile, Calendar primary and People `me` in order (stopping at the first address unless `every`), then OAuth userinfo when none named the account, and records each failure per attempt. `resolveGoogleAccount` (`persistence/connector-account.ts`) is the managed sync's stop-at-first use: when nothing names the account it rethrows `api_not_enabled` first, then another credential error, then the first other failure (a network error stays transient), so `connector_account_changed` means a resolved account that differs from the pin. `probeGoogleApiAccess` probes every service of a setup or status run (an ungranted scope is `scope_missing` with no request) and returns `{ resolved_account, resolved_via, services, problems, fix }`; `googleApiProblem` maps `GoogleApiDisabledError` and `scope_missing` to a `GoogleApiProblem`; `googleApiAccessFix` is one Action naming every problem (`ask_user` with each enable link when an API is disabled, else the user's `gbrain google connect --reauth` command), verified by `gbrain google status --json`.+ - The clients (`google-clients.ts`) throw `GoogleApiDisabledError` (`api_not_enabled`) for a 403 with reason `accessNotConfigured`, ErrorInfo `SERVICE_DISABLED` or the disabled-API message, carrying the API, its title, the project and the enable link from the error body (ErrorInfo `activationUrl`, then the Help link, then the message; only console.cloud.google.com and console.developers.google.com links are relayed, otherwise the client id's project number builds it). A 403 for insufficient authentication scopes (`insufficientPermissions`, ErrorInfo `ACCESS_TOKEN_SCOPE_INSUFFICIENT`) is `scope_missing`, never `GoogleForbiddenError`, so a calendar read never names it `calendar_unreadable`.+ - The sweep (`google-source.ts`) records each `api_not_enabled` / `scope_missing` failure, plus an unmanaged source's ungranted services, as `api_access: { problems, at }` in source state; a service leaves it when its sweep reaches the API again, `at` changes only when the problems do, and a partial managed run publishes it with the loop recovery state.+ - `gbrain google status` (with a probe) runs `probeGoogleApiAccess` per refreshed account over its linked sources' services (every granted service when none is linked) and reports `accounts[].api_access`; a problem makes `ok: false` and exit 1. `gbrain google setup` probes every requested service (`--services`, default all) before registering anything; a problem stops it with one report (`status: api_access_blocked`, exit 3, the rendered fix and the narrower `--services` command for the reachable services).+ - When the Gmail label list itself fails, the loop exclusion log (`loops-enqueue.ts`) says the names could not be checked, never that they are not labels of the account.+ - Tests: `test/google-api-access-7073.test.ts`, `test/google-api-access-cmd-7073.serial.test.ts`, `test/google-api-access-managed-7073.test.ts` (real PGLite, and Postgres under `DATABASE_URL`).+- `src/commands/doctor/checks/google-api-access.ts` — doctor `google_api_access` (wave check, resolution operator, zero network): warns per Google source whose stored `api_access` names a service it still syncs, listing each disabled API with project and enable link, with `googleApiAccessFix` for the first source.diff --git a/docs/guides/google-connect.md b/docs/guides/google-connect.mdindex d4ff4681bf..f7ef9dfdce 100644--- a/docs/guides/google-connect.md+++ b/docs/guides/google-connect.md@@ -215,6 +215,47 @@ gbrain sync --source <source>gbrain doctor --only google_calendar_readable --json # verify```+### API access++Each service reads through its own Google Cloud API: Gmail through+`gmail.googleapis.com`, Calendar through `calendar-json.googleapis.com` and+Contacts through `people.googleapis.com`. Every one must be enabled once in+the project that owns your OAuth client, and its scope must be granted at+consent. When one is not:++- `gbrain google setup` probes every service it is about to register before+ it registers anything. A disabled API or an ungranted scope stops setup+ with one report (exit 3, `status: api_access_blocked` under `--json`)+ that names each API, the Google Cloud project, and the enable link from+ Google's own error, plus the narrower `--services` command for the+ services that already work;+- `gbrain google status` probes the services each linked source syncs+ (every granted service when no source is linked yet) and reports them under+ `accounts[].api_access` (`problems` and a `fix`), with `ok: false` and+ exit 1 while any remains;+- the sync records the services it could not reach in the source's state.+ The other services keep syncing and the run is `partial`; a service leaves+ the record once its sweep reaches the API again. `gbrain doctor` warns+ `google_api_access` from that record, with no network call.++The fix's `next` is `ask_user` when an API is disabled (only the project+owner can enable it in the console) and `tell_user_to_run` with+`gbrain google connect --reauth <email>` when only a scope is missing.++```bash+gbrain google status --json # names every disabled API with its enable link+# enable each one at its link, or reauth for a missing scope, then:+gbrain google status --json # verify: api_access.problems is empty+gbrain sync --source <source>+```++A managed source resolves its account before any service runs. When no+enabled service can name the account (Gmail profile, Calendar primary+calendar, People `me`), it asks the OAuth userinfo endpoint, which the+`email` scope gbrain always requests can read. So a disabled API is reported+as itself, and `connector_account_changed` means a credential that resolved+to a different account than the source is pinned to.+## Calendar windowCalendar pages cover events from `--history-days` ago up to 60 days from@@ -421,8 +462,8 @@ gbrain sources add gmail-work --kind google --account [email protected] \What changes vs the vault flow: `gbrain google status`'s refresh probe and`gbrain doctor`'s `google_oauth` check cover vault accounts only (yourexternal tool owns token health); the scope preflight trusts `--services`-(a token missing a scope surfaces as `api_not_enabled`/`upstream` per sweep-instead of `scope_missing`); send-as aliases are fetched live when the token+(a token missing a scope surfaces per sweep as Google's 403, reported as+`scope_missing`, rather than up front); send-as aliases are fetched live when the tokenallows it, otherwise identity degrades to the account address alone. Thetoken command runs locally at sync time with your shell — it lives in localsource config, is never reachable over MCP, and is the same trust class as a@@ -453,9 +494,9 @@ attached. The catalog (also emitted as structured JSON with `--json`):| `code_reused` | Authorization code used twice | Re-run connect (codes are single-use) || `invalid_client` | Client secret rotated/deleted in the console | Download the current JSON, reconnect || `no_refresh_token` | Google returned no refresh token | Re-run connect; if persistent, revoke at <https://myaccount.google.com/permissions> and reconnect |-| `api_not_enabled` | An API isn't enabled in your project | The error carries the exact enable link (project pre-selected) |+| `api_not_enabled` | An API isn't enabled in your project | The error carries the project and the enable link from Google's error; `gbrain google status` names every disabled API at once (see [API access](#api-access)) || `rate_limited` | Google quota hit | Automatic backoff; nothing to do |-| `scope_missing` | Connected with narrower `--scopes` than needed | `gbrain google connect --reauth <email>` |+| `scope_missing` | Connected with narrower `--scopes` than needed, or Google answered a request with "insufficient authentication scopes" | `gbrain google connect --reauth <email>` || `relay_unreachable` / `relay_session_expired` / `claim_already_used` / `relay_disabled` | Hosted fast-path (gbrain.io relay) issues | BYO connect always works: `gbrain google connect` || `not_connected` | No vault entry for the account | `gbrain google connect` || `calendar_unreadable` | Google answered the source's calendar read with HTTP 403 or 404: the account cannot read that calendar | `gbrain google calendars --account <email>`, then `gbrain sources set-calendar <source> <calendar-id>`; see [Unreadable calendar](#unreadable-calendar) |diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 6bf83b4e23..37c95fa79d 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -61,6 +61,7 @@| [`gbrain repair fences` skipped a file `sync_in_progress` while a sync runs](repair.md#fence-repair-during-a-sync) | nothing: a write in flight or the running sync's frozen manifest still names that file; every other candidate repairs now and the next run picks this one up (`gbrain sync --source <id> --no-pull` finishes the sync) | agent | none | `gbrain doctor --only fence_integrity --json` || [A Google or GitHub item is held (`connector_held_items`)](#held-connector-items) | `gbrain sources status <id>`, fix the cause, then `gbrain sources retry-held <id>` and `gbrain sync --source <id>` | agent, after the user agrees | `egress` (fetches from the provider again) | `gbrain doctor --only connector_held_items --json` || `gbrain google status` exits 1 naming `calendar_unreadable`, doctor warns `google_calendar_readable`, or the sync log prints `[google] calendar_unreadable` (calendar pages stop arriving) | `gbrain google calendars --account <email>` lists the calendars the account can read; then `gbrain sources set-calendar <source> <calendar-id>` and `gbrain sync --source <source>` ([unreadable calendar](google-connect.md#unreadable-calendar)) | agent, after the user agrees which calendar | none (on a managed brain whose source also syncs Gmail or Contacts, the change re-reads their history: `confirmation_required`, re-run with `--yes` after the user agrees) | `gbrain doctor --only google_calendar_readable --json` is ok |+| `gbrain google setup` stops with `api_access_blocked`, `gbrain google status` exits 1 listing `api_access.problems`, or doctor warns `google_api_access` (a Google API disabled for the OAuth project, or a scope not granted) | enable each API at the link the report names (the Google Cloud project is in the report), or `gbrain google connect --reauth <email>` for a missing scope; then `gbrain sync --source <source>` ([API access](google-connect.md#api-access)) | user (only the project owner can enable an API) | none | `gbrain google status --json` shows no `api_access.problems` || `gbrain waiting` lists bank, payment or shipping alerts as people waiting on you | upgrade (#5012: mail with `Precedence: bulk/list/junk`, a `List-Id` or a no-reply `Reply-To` opens no reply-owed loop); for loops opened before the upgrade, `gbrain waiting` prints `gbrain loops drop sender <email> --source <id> --dry-run` per sender; preview, then run it without `--dry-run` (cannot be undone), or `gbrain loops mute sender <email>` for a reversible stop ([open loops](open-loops.md#the-surfaces)) | agent, after the user agrees | none to preview | `gbrain waiting --json` no longer lists the sender || [`gbrain migrate --to` refused with `writer_coordinator_required`](../ENGINES.md#engine-migration-refused) | follow the refusal's `fix`: relay its `user_message` (stay on PGLite and share with `gbrain mcp expose`, or leave the brain as it is) | agent, after the user agrees | `persistent_install`, `egress` (for `gbrain mcp expose`) | `gbrain doctor --no-migrate --json` || [A write was refused with a named reason](#write-refused) | the reason's recovery in [write refusal reasons](write-refusals.md) | as the refusal's `fix` | as the refusal's `fix` | the refusal's `verify` |diff --git a/llms-full.txt b/llms-full.txtindex 8844e977f3..0207033af5 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -10435,6 +10435,7 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro| [`gbrain repair fences` skipped a file `sync_in_progress` while a sync runs](repair.md#fence-repair-during-a-sync) | nothing: a write in flight or the running sync's frozen manifest still names that file; every other candidate repairs now and the next run picks this one up (`gbrain sync --source <id> --no-pull` finishes the sync) | agent | none | `gbrain doctor --only fence_integrity --json` || [A Google or GitHub item is held (`connector_held_items`)](#held-connector-items) | `gbrain sources status <id>`, fix the cause, then `gbrain sources retry-held <id>` and `gbrain sync --source <id>` | agent, after the user agrees | `egress` (fetches from the provider again) | `gbrain doctor --only connector_held_items --json` || `gbrain google status` exits 1 naming `calendar_unreadable`, doctor warns `google_calendar_readable`, or the sync log prints `[google] calendar_unreadable` (calendar pages stop arriving) | `gbrain google calendars --account <email>` lists the calendars the account can read; then `gbrain sources set-calendar <source> <calendar-id>` and `gbrain sync --source <source>` ([unreadable calendar](google-connect.md#unreadable-calendar)) | agent, after the user agrees which calendar | none (on a managed brain whose source also syncs Gmail or Contacts, the change re-reads their history: `confirmation_required`, re-run with `--yes` after the user agrees) | `gbrain doctor --only google_calendar_readable --json` is ok |+| `gbrain google setup` stops with `api_access_blocked`, `gbrain google status` exits 1 listing `api_access.problems`, or doctor warns `google_api_access` (a Google API disabled for the OAuth project, or a scope not granted) | enable each API at the link the report names (the Google Cloud project is in the report), or `gbrain google connect --reauth <email>` for a missing scope; then `gbrain sync --source <source>` ([API access](google-connect.md#api-access)) | user (only the project owner can enable an API) | none | `gbrain google status --json` shows no `api_access.problems` || `gbrain waiting` lists bank, payment or shipping alerts as people waiting on you | upgrade (#5012: mail with `Precedence: bulk/list/junk`, a `List-Id` or a no-reply `Reply-To` opens no reply-owed loop); for loops opened before the upgrade, `gbrain waiting` prints `gbrain loops drop sender <email> --source <id> --dry-run` per sender; preview, then run it without `--dry-run` (cannot be undone), or `gbrain loops mute sender <email>` for a reversible stop ([open loops](open-loops.md#the-surfaces)) | agent, after the user agrees | none to preview | `gbrain waiting --json` no longer lists the sender || [`gbrain migrate --to` refused with `writer_coordinator_required`](../ENGINES.md#engine-migration-refused) | follow the refusal's `fix`: relay its `user_message` (stay on PGLite and share with `gbrain mcp expose`, or leave the brain as it is) | agent, after the user agrees | `persistent_install`, `egress` (for `gbrain mcp expose`) | `gbrain doctor --no-migrate --json` || [A write was refused with a named reason](#write-refused) | the reason's recovery in [write refusal reasons](write-refusals.md) | as the refusal's `fix` | as the refusal's `fix` | the refusal's `verify` |diff --git a/src/commands/doctor/checks/google-api-access.ts b/src/commands/doctor/checks/google-api-access.tsnew file mode 100644index 0000000000..7245fc3bf3--- /dev/null+++ b/src/commands/doctor/checks/google-api-access.ts@@ -0,0 +1,43 @@+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { readConnectorCursorState, type ConnectorSourceRow } from '../../../core/connectors/item-holds-store.ts';+import { parseGoogleSourceConfig } from '../../../core/google/source-config.ts';+import type { GoogleApiProblem } from '../../../core/google/types.ts';+import { googleApiAccessFix } from '../../../core/google/api-access.ts';++/**+ * #7073: Google sources whose last sweep could not reach a service because+ * its API is disabled for the OAuth project or its scope was not granted+ * (`api_access` in connector state). Zero-network: it reads the stored+ * result; `gbrain google status` and `gbrain google setup` probe live. One+ * finding names every blocked service with its project and enable link.+ */+export async function googleApiAccessCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {+ try {+ const rows = await engine.executeRaw<ConnectorSourceRow>(+ "SELECT id, incarnation::text AS incarnation, local_path, config FROM sources WHERE archived IS NOT TRUE AND config->>'kind' = 'google' ORDER BY id");+ const blocked: Array<{ source_id: string; account: string; at: string; problems: GoogleApiProblem[] }> = [];+ for (const row of rows) {+ if (sourceIds && !sourceIds.includes(row.id)) continue;+ const cfg = parseGoogleSourceConfig(row.config, '');+ const stored = (await readConnectorCursorState(engine, row))?.api_access as { problems?: GoogleApiProblem[]; at?: string } | null | undefined;+ const problems = (stored?.problems ?? []).filter((p) => cfg.services.includes(p.service));+ if (problems.length) blocked.push({ source_id: row.id, account: cfg.account, at: stored?.at ?? '', problems });+ }+ const details = { count: blocked.length, sources: blocked, docs: 'docs/guides/google-connect.md#api-access' };+ if (!blocked.length) return { name: 'google_api_access', status: 'ok', message: 'No Google source recorded a disabled API or missing scope at its last sync.', details };+ const describe = (p: GoogleApiProblem): string => p.code === 'api_not_enabled'+ ? `${p.service}: ${p.api_title} (${p.api}) is disabled for Google Cloud project ${p.project ?? 'unknown'}, enable it at ${p.enable_url}`+ : `${p.service}: the credential was not granted this scope`;+ const first = blocked[0]!;+ return {+ name: 'google_api_access', status: 'warn', details,+ message: blocked.map((b) => `Google source ${b.source_id} (${b.account}) could not reach ${b.problems.length} service(s) at its last sync: ${b.problems.map(describe).join('; ')}.`).join(' ')+ + ' Those services import nothing until this is fixed; gbrain google status re-checks live.',+ fix: googleApiAccessFix(first.account, first.problems),+ };+ } catch (error) {+ return { name: 'google_api_access', status: 'warn', fix_unavailable_reason: 'check_errored', details: { count: 'unknown' },+ message: `Google API access could not be read from source state: ${error instanceof Error ? error.message : String(error)}. Health is unknown.` };+ }+}diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.tsindex 4258ba2dbb..9415d0f260 100644--- a/src/commands/doctor/checks/graph-health.ts+++ b/src/commands/doctor/checks/graph-health.ts@@ -345,6 +345,7 @@ export const timelineHistoryEntry: DoctorEntry = {'stale_embedding_effects','google_file_modes','google_calendar_readable',+ 'google_api_access','atom_retirements_restorable','extractor_facts_expired','conversation_label_facts',diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.tsindex f0c0ed32c9..ff3446e00e 100644--- a/src/commands/doctor/wave-checks.ts+++ b/src/commands/doctor/wave-checks.ts@@ -300,6 +300,14 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [instruction: 'List the readable calendars with `gbrain google calendars --account <email>`, then `gbrain sources set-calendar <source> <calendar-id>` and `gbrain sync --source <source>` (docs/guides/google-connect.md#unreadable-calendar).',run: async (engine, scope) => (await import('./checks/google-calendar.ts')).googleCalendarReadableCheck(engine, scope.sourceIds),},+ {+ id: 'google_api_access', resolution: 'operator', registration: 'wave',+ hostOnly: 'Connector state, the account address and the Google Cloud project live on the brain host.',+ count: d => Number(d.count ?? 0),+ impact: 'A Google source could not reach a service because its API is disabled for the OAuth project or its scope was not granted, so that service imports nothing',+ instruction: 'Enable each named API at the console link in the finding (or run `gbrain google connect --reauth <email>` for a missing scope), then confirm with `gbrain google status --json` and run `gbrain sync --source <source>` (docs/guides/google-connect.md#api-access).',+ run: async (engine, scope) => (await import('./checks/google-api-access.ts')).googleApiAccessCheck(engine, scope.sourceIds),+ },{id: 'atom_provenance_drift', resolution: 'repair', registration: 'doctor.ts',hostOnly: 'Retiring stale atoms is a host-side, explicit-only repair.',diff --git a/src/commands/google-setup.ts b/src/commands/google-setup.tsindex 0184800f56..7ff17c95b4 100644--- a/src/commands/google-setup.ts+++ b/src/commands/google-setup.ts@@ -10,8 +10,10 @@*/import { credentialId, openVault } from '../core/creds/vault.ts';-import { GOOGLE_PROVIDER } from '../core/creds/providers/google.ts';-import { runGoogleConnect } from './google.ts';+import { GOOGLE_PROVIDER, GoogleTokenProvider } from '../core/creds/providers/google.ts';+import { ALL_GOOGLE_SERVICES } from '../core/google/types.ts';+import { setCliExitVerdict } from '../core/cli-force-exit.ts';+import { parseServicesCsv, runGoogleConnect } from './google.ts';export async function runGoogleSetup(args: string[]): Promise<void> {const json = args.includes('--json');@@ -44,7 +46,38 @@ export async function runGoogleSetup(args: string[]): Promise<void> {}if (!account) return;- // Step 2 — register the source + first sync + waiting digest.+ // Step 2 (#7073) — probe every requested service before registering anything,+ // so each disabled API or missing scope is named at once instead of one per sync.+ const entry = await vault.get(credentialId(GOOGLE_PROVIDER, account));+ if (entry) {+ const servicesIdx = args.indexOf('--services');+ const services = servicesIdx !== -1 ? parseServicesCsv(args[servicesIdx + 1] ?? '') : [...ALL_GOOGLE_SERVICES];+ const { googleIdentityClients, probeGoogleApiAccess } = await import('../core/google/api-access.ts');+ const access = await probeGoogleApiAccess(googleIdentityClients(new GoogleTokenProvider(vault, entry.id), entry.meta.client_id),+ account, services, entry.meta.scopes ?? []);+ if (access.fix) {+ const { cliRenderContext, renderAction } = await import('../core/agent-output.ts');+ const fix = renderAction(access.fix, cliRenderContext());+ const reachable = services.filter((service) => access.services[service]?.status === 'ok');+ const narrower = reachable.length > 0 ? `gbrain google setup --account ${account} --services ${reachable.join(',')}` : null;+ if (json) {+ process.stdout.write(JSON.stringify({ ok: false, status: 'api_access_blocked', account, api_access: { ...access, fix },+ ...(narrower ? { reachable_services_command: narrower } : {}) }, null, 2) + '\n');+ } else {+ const { agentBlock } = await import('../core/agent-markers.ts');+ process.stderr.write([`Google account ${account} cannot reach every service yet; nothing was registered or synced.`,+ ...access.problems.map((p) => p.code === 'api_not_enabled'+ ? ` - ${p.api_title} (${p.api}) is disabled for Google Cloud project ${p.project ?? 'unknown'}. Enable it: ${p.enable_url}`+ : ` - ${p.service}: access was not granted. Run: gbrain google connect --reauth ${account}`),+ 'Then re-run: gbrain google setup', ...(narrower ? [`Or set up only the services it can reach now: ${narrower}`] : [])].join('\n') + '\n'+ + agentBlock({ why: fix.why, actor: fix.actor, next: fix.next, verify: 'gbrain google status --json' }, { showUser: fix.user_message ?? '' }));+ }+ setCliExitVerdict(3);+ return;+ }+ }++ // Step 3 — register the source + first sync + waiting digest.const { runGoogleSetupTail } = await import('./google-setup-tail.ts');await runGoogleSetupTail({ account, json, args });}diff --git a/src/commands/google.ts b/src/commands/google.tsindex 4cc1e0f36b..d2afc7ea62 100644--- a/src/commands/google.ts+++ b/src/commands/google.ts@@ -32,6 +32,7 @@ import {} from '../core/creds/vault.ts';import {GOOGLE_PROVIDER,+ GOOGLE_SERVICE_SCOPES,GoogleTokenProvider,apiEnableLink,buildAuthUrl,@@ -58,7 +59,7 @@ import { setCliExitVerdict } from '../core/cli-force-exit.ts';// ── Shared bits ──────────────────────────────────────────────────────────────-import { ALL_GOOGLE_SERVICES, type GoogleService } from '../core/google/types.ts';+import { ALL_GOOGLE_SERVICES, type GoogleApiProblem, type GoogleService } from '../core/google/types.ts';import { sourceCalendarReadability, type CalendarProbe, type CalendarReadability } from './google-calendar-status.ts';export const GOOGLE_SERVICES = ALL_GOOGLE_SERVICES;@@ -677,6 +678,7 @@ export async function runGoogleStatus(args: string[]): Promise<void> {// Linked sources: best-effort, engine optional. #5012 item 9: each one that// syncs Calendar reports whether its configured calendar is readable.let linkedSources: Array<{ id: string; account: string | null; calendar?: CalendarReadability }> = [];+ const linkedServices = new Map<string, Set<GoogleService>>();try {const { loadConfig, toEngineConfig } = await import('../core/config.ts');const cfg = loadConfig();@@ -702,6 +704,9 @@ export async function runGoogleStatus(args: string[]): Promise<void> {? (JSON.parse(r.config) as Record<string, unknown>): ((r.config ?? {}) as Record<string, unknown>);if (c.kind !== 'google') continue;+ const { parseGoogleSourceConfig } = await import('../core/google/source-config.ts');+ const sourceCfg = parseGoogleSourceConfig(c, '');+ for (const service of sourceCfg.services) linkedServices.set(sourceCfg.account, (linkedServices.get(sourceCfg.account) ?? new Set()).add(service));const calendar = await sourceCalendarReadability(engine, { ...r, config: c }, calendarProbe).catch(() => null);linkedSources.push({ id: r.id, account: typeof c.g_account === 'string' ? c.g_account : null, ...(calendar ? { calendar } : {}) });}@@ -713,13 +718,30 @@ export async function runGoogleStatus(args: string[]): Promise<void> {/* no engine — vault-only status */}+ // #7073: every service a linked source syncs (else every granted one) is+ // probed at once, so each disabled API or missing scope is named together.+ if (probe) {+ const { googleIdentityClients, probeGoogleApiAccess } = await import('../core/google/api-access.ts');+ const { cliRenderContext, renderAction } = await import('../core/agent-output.ts');+ for (const [i, m] of metas.entries()) {+ const row = accounts[i]!;+ if (row.refresh_probe !== 'ok') continue;+ const account = m.account ?? m.id;+ const granted = GOOGLE_SERVICES.filter((service) => !m.scopes?.length || m.scopes.includes(GOOGLE_SERVICE_SCOPES[service]));+ const services = [...(linkedServices.get(account) ?? granted)];+ const entry = await vault.get(m.id);+ const access = await probeGoogleApiAccess(googleIdentityClients(new GoogleTokenProvider(vault, m.id), entry?.meta.client_id), account, services, m.scopes ?? []);+ row.api_access = { ...access, ...(access.fix ? { fix: renderAction(access.fix, cliRenderContext()) } : {}) };+ }+ }+ const apiBlocked = accounts.filter((a) => ((a.api_access as { problems?: unknown[] } | undefined)?.problems?.length ?? 0) > 0);const unreadableCalendars = linkedSources.filter((s) => s.calendar?.code === 'calendar_unreadable');- if (unreadableCalendars.length > 0) setCliExitVerdict(1);+ if (unreadableCalendars.length > 0 || apiBlocked.length > 0) setCliExitVerdict(1);if (json) {process.stdout.write(JSON.stringify({- ok: unreadableCalendars.length === 0,+ ok: unreadableCalendars.length === 0 && apiBlocked.length === 0,status: accounts.length > 0 ? 'connected' : 'not_connected',client_on_file: client !== null,accounts,@@ -750,6 +772,13 @@ export async function runGoogleStatus(args: string[]): Promise<void> {const err = a.refresh_error as { fix?: string };if (err.fix) process.stdout.write(` fix: ${err.fix}\n`);}+ const access = a.api_access as { problems: GoogleApiProblem[]; fix?: { user_message?: string } } | undefined;+ for (const p of access?.problems ?? []) {+ process.stdout.write(p.code === 'api_not_enabled'+ ? ` ${p.service}: api_not_enabled — ${p.api_title} (${p.api}) is disabled for project ${p.project ?? 'unknown'}; enable: ${p.enable_url}\n`+ : ` ${p.service}: scope_missing — the credential was not granted ${p.service} access\n`);+ }+ if (access?.fix?.user_message) process.stdout.write(` fix: ${access.fix.user_message}\n`);}if (linkedSources.length > 0) {process.stdout.write(diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 0e71e7f8e2..622354a04c 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -952,6 +952,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.312.0', text: 'A name written only in Katakana (an alias such as デン) no longer links a page that has it inside a longer Katakana word (インシデント, デンタル): the name must stand as a whole Katakana run, so 「デン」, デンに, 喫茶デン and デン・カフェ still link. A short name inside a real Katakana compound is refused too; add the compound as its own alias when it names the entity. Mention links already written that way are counted by `gbrain doctor` (`stale_mentions`) and removed by `gbrain extract links --by-mention --rebuild --source db`.', id: 'katakana_mention_boundaries' },{ since: '0.60.312.0', text: 'On Windows, cancelling or timing out a job now ends its whole process tree with taskkill: a per-job child and a shell job first get a polite close (`taskkill /T`), then a forced one (`/T /F`) after the grace window, instead of only the direct child being killed. A windowless console program refuses the polite close, so a cancelled Windows shell job now takes up to its 5-second grace window to end. A descendant whose parent already exited is no longer in the tree and is not ended.', id: 'windows_tree_kill' },{ since: '0.60.312.0', text: '`get_links` and `get_backlinks` (`gbrain links`, `gbrain backlinks`) now return at most 500 link rows per call instead of every edge of the page. When more match, the last row carries `truncated: true` and `next_cursor`: pass it back as `cursor` (`--cursor`) with the same filters for the next rows, raise `limit` (`--limit`, up to 5000), or use `--all` for every row. `--all` is local only: over a thin client (and from any remote caller) it is refused with `invalid_params`, so page with `--cursor` there. Remote callers also get a `listing_truncated` notice naming the next call. Rows come in link order, `link_type`, `get_backlinks` `type` and the live/history filter apply before the cap so hidden former relationships never use a row, and each row\'s `context` is cut to 2000 characters (ending in an ellipsis). A cursor from another listing is refused `link_cursor_invalid`. `get_backlinks` with `limit` no longer points at `group: "page"`; it pages the rows with `cursor`.', id: 'link_read_cap' },+ { since: 'TBD', id: 'google_api_access_probe', text: 'A managed Google source whose enabled services cannot name the account (an API disabled for the OAuth project, a scope not granted) now resolves it through the OAuth userinfo endpoint: the account pins, the services that work keep syncing, the run is `partial`, and the disabled API is reported as `api_not_enabled` instead of failing the whole sync. `connector_account_changed` is raised only when an account resolved and differs from the pin; when nothing can name the account (userinfo also failing), the sync fails with the underlying error, a network failure included, instead of refusing as an account change. `gbrain google setup` now probes every requested service before registering a source and stops (exit 3, `status: api_access_blocked`) naming each disabled API with its Google Cloud project and enable link, or each scope not granted, in one report. `gbrain google status` adds `accounts[].api_access` and exits 1 while a problem remains, and doctor adds `google_api_access`, read from what the last sync recorded. A Google 403 for insufficient authentication scopes is now `scope_missing` (before: `upstream`, and a calendar read named it `calendar_unreadable`).' },{ since: '0.60.312.0', id: 'google_account_credential_refusal', text: 'A managed Google source whose account cannot be read because the Google API is disabled for the OAuth project (or the grant is missing, or Google answers 403) now fails the sync with that credential error (`api_not_enabled` with the console link to enable the API, `scope_missing`, or `upstream` naming the 403) instead of `connector_account_changed`. A credential that no service can name for another reason still refuses as before.' },{ since: '0.60.312.0', id: 'auth_rescope_client_print_only', text: '`gbrain auth rescope --client <id>` (and `gbrain auth rescope-client <id>`) with no grant flag and no `--profile` now prints the client\'s stored grants and writes nothing (`--json`: `changed: false`, `written: false`), as the help always said, instead of refusing with `invalid_grant`. An unknown client id refuses with `client_not_found`, whose fix is `gbrain auth clients --json`. `--repair` alone still refuses.' },{ since: '0.60.312.0', id: 'file_drift_unknown_listed', text: '`gbrain repair file-drift --all-drifted` previews and the bare `gbrain repair file-drift` survey now list a conflicted page the live check cannot classify (canonical file missing, page gone, not the owner host, a refused or failed check) as `unknown`, counted under `unknown_<reason>` with the next step for that reason. They used to drop it silently, so a preview could read as empty. Unknown pages are never repaired and get no `--class` preview command.' },diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex a634a2ef0f..d3a09fecea 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -71,7 +71,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'friction': ['--agent', '--base', '--brain', '--compare', '--help', '--hint', '--json', '--kind', '--message', '--no-redact', '--phase', '--run-id', '--severity', '--source', '--transcript-path', '--transcripts'],'frontmatter': ['--allow-catch-all', '--batch', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fix', '--force', '--full-name', '--get', '--git-common-dir', '--help', '--importable', '--include-ambiguous', '--include-catch-all', '--json', '--literal-pathspecs', '--name-only', '--no-verify', '--others', '--path', '--show-prefix', '--show-toplevel', '--source', '--stage', '--staged', '--stdin', '--type', '--uninstall'],'git': ['--abbrev-ref', '--add', '--aggressive', '--all', '--autostash', '--brain', '--branch', '--cached', '--cacheinfo', '--count', '--dry-run', '--enable', '--exit-code', '--expect-remote', '--ff-only', '--file', '--force', '--force-remove', '--get', '--get-url', '--git-dir', '--git-path', '--hard', '--help', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-checkout', '--literal-pathspecs', '--local', '--local-env-vars', '--message', '--name-only', '--name-status', '--no-autostash', '--no-cron', '--no-recurse-submodules', '--no-tags', '--no-verify', '--no-write-fetch-head', '--only', '--pat-file', '--path', '--porcelain', '--pull', '--push', '--push-only', '--quiet', '--rebase', '--repo', '--require-clean', '--resolve', '--short', '--show-toplevel', '--source', '--unset-all', '--verify', '--write-tree'],- 'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--limit', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--plan', '--port', '--prefer-postgres', '--provenance', '--purge-client', '--query', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--search-mode', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via', '--yes'],+ 'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--limit', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--plan', '--port', '--prefer-postgres', '--probe', '--provenance', '--purge-client', '--query', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--search-mode', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via', '--yes'],'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 765cfee9b0..cc81e8ee79 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -282,6 +282,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['google_file_modes',// #5012 item 9: a Google source's configured calendar was unreadable at its last sync (doctor/checks/google-calendar.ts).'google_calendar_readable',+ // #7073: a Google source's last sync could not reach a service (API disabled, scope not granted) (doctor/checks/google-api-access.ts).+ 'google_api_access','google_oauth','home_dir_in_worktree','index_audit',diff --git a/src/core/google/api-access.ts b/src/core/google/api-access.tsnew file mode 100644index 0000000000..705351680b--- /dev/null+++ b/src/core/google/api-access.ts@@ -0,0 +1,146 @@+/**+ * #7004/#7073: which account a Google credential belongs to, and which of the+ * Gmail, Calendar and People APIs it can reach.+ *+ * `probeGoogleAccount` asks each enabled service to name the account (Gmail+ * profile, Calendar primary calendar, People `me`) and, when none can, the+ * OAuth userinfo endpoint (the `email` scope is always requested). Every+ * per-service failure stays in the result: the managed sync uses the first+ * address it finds, while `gbrain google setup` and `gbrain google status`+ * probe every service and name each disabled API or missing scope at once.+ */+import { CredentialError } from '../creds/errors.ts';+import { GOOGLE_SERVICE_SCOPES, fetchUserinfoEmail } from '../creds/providers/google.ts';+import type { Action } from '../agent-output.ts';+import type { GoogleAccessProvider } from './access.ts';+import { CalendarClient, GmailClient, GoogleApiDisabledError, PeopleClient, type FetchImpl } from './google-clients.ts';+import { ALL_GOOGLE_SERVICES, GOOGLE_SERVICE_API, type GoogleApiProblem, type GoogleService } from './types.ts';++export interface GoogleIdentityClients {+ gmail: Pick<GmailClient, 'getProfile'>;+ calendar: Pick<CalendarClient, 'fetchJSON'>;+ people: Pick<PeopleClient, 'fetchJSON'>;+ userinfo: () => Promise<string | undefined>;+}++export interface GoogleAccountProbe {+ /** Lower-cased address, or null when nothing named the account. */+ email: string | null;+ via: GoogleService | 'userinfo' | null;+ /** Each attempt that threw, in attempt order. */+ errors: Partial<Record<GoogleService | 'userinfo', unknown>>;+}++/** The clients a probe needs for one token source. */+export function googleIdentityClients(tokens: GoogleAccessProvider, clientId: string | undefined, fetchImpl: FetchImpl = fetch): GoogleIdentityClients {+ const args = [tokens, fetchImpl, () => {}, clientId] as const;+ return { gmail: new GmailClient(...args), calendar: new CalendarClient(...args), people: new PeopleClient(...args), userinfo: googleUserinfo(tokens, fetchImpl) };+}++export function googleUserinfo(tokens: GoogleAccessProvider, fetchImpl: FetchImpl = fetch): () => Promise<string> {+ return async () => fetchUserinfoEmail(await tokens.getAccessToken(), fetchImpl);+}++/**+ * Each listed service in order, stopping at the first address unless `every`+ * is set; userinfo only when no service named the account. Aborts propagate;+ * every other failure is recorded under its attempt.+ */+export async function probeGoogleAccount(clients: GoogleIdentityClients, services: readonly GoogleService[],+ opts: { signal?: AbortSignal; every?: boolean } = {}): Promise<GoogleAccountProbe> {+ const { signal } = opts;+ const request = signal ? { signal } : {};+ const attempts: Array<[GoogleService | 'userinfo', () => Promise<string | undefined>]> = [+ ['gmail', async () => (await clients.gmail.getProfile(request)).emailAddress],+ ['calendar', async () => (await clients.calendar.fetchJSON<{ id?: string }>('https://www.googleapis.com/calendar/v3/calendars/primary', 'calendar-json', request)).id],+ ['contacts', async () => {+ const me = await clients.people.fetchJSON<{ emailAddresses?: Array<{ value?: string; metadata?: { primary?: boolean } }> }>(+ 'https://people.googleapis.com/v1/people/me?personFields=emailAddresses', 'people', request);+ return (me.emailAddresses?.find(address => address.metadata?.primary) ?? me.emailAddresses?.[0])?.value;+ }],+ ['userinfo', clients.userinfo],+ ];+ const probe: GoogleAccountProbe = { email: null, via: null, errors: {} };+ for (const [attempt, run] of attempts) {+ if (attempt === 'userinfo' ? probe.email !== null : !services.includes(attempt)) continue;+ signal?.throwIfAborted();+ try {+ const email = (await run())?.trim().toLowerCase();+ if (email?.includes('@') && probe.email === null) {+ probe.email = email;+ probe.via = attempt;+ if (!opts.every) return probe;+ }+ } catch (error) {+ if (signal?.aborted) throw error;+ probe.errors[attempt] = error;+ }+ }+ return probe;+}++/** The problem behind one service failure, or null when the failure is something else. */+export function googleApiProblem(service: GoogleService, error: unknown): GoogleApiProblem | null {+ if (error instanceof GoogleApiDisabledError) {+ return { service, code: 'api_not_enabled', api: error.api, api_title: error.apiTitle, project: error.project, enable_url: error.enableUrl };+ }+ if (error instanceof CredentialError && error.code === 'scope_missing') {+ return { service, code: 'scope_missing', api: GOOGLE_SERVICE_API[service].api, api_title: GOOGLE_SERVICE_API[service].title, project: null, enable_url: null };+ }+ return null;+}++export interface GoogleApiAccessReport {+ account: string;+ /** The address the probe resolved, and how; null when nothing named the account. */+ resolved_account: string | null;+ resolved_via: GoogleAccountProbe['via'];+ services: Partial<Record<GoogleService, { status: 'ok' | GoogleApiProblem['code'] | 'error'; error?: string }>>;+ problems: GoogleApiProblem[];+ fix?: Action;+}++/**+ * Probe every service in `services`: one not in a known grant is+ * `scope_missing` without a request; the rest are read live.+ */+export async function probeGoogleApiAccess(clients: GoogleIdentityClients, account: string, services: readonly GoogleService[],+ grantedScopes: readonly string[], signal?: AbortSignal): Promise<GoogleApiAccessReport> {+ const ordered = ALL_GOOGLE_SERVICES.filter(service => services.includes(service));+ const ungranted = grantedScopes.length > 0 ? ordered.filter(service => !grantedScopes.includes(GOOGLE_SERVICE_SCOPES[service])) : [];+ const probe = await probeGoogleAccount(clients, ordered.filter(service => !ungranted.includes(service)), { every: true, ...(signal ? { signal } : {}) });+ const report: GoogleApiAccessReport = { account, resolved_account: probe.email, resolved_via: probe.via, services: {}, problems: [] };+ for (const service of ordered) {+ const problem = ungranted.includes(service) ? googleApiProblem(service, new CredentialError('scope_missing')) : googleApiProblem(service, probe.errors[service]);+ const error = probe.errors[service];+ if (problem) report.problems.push(problem);+ report.services[service] = problem ? { status: problem.code }+ : error === undefined ? { status: 'ok' } : { status: 'error', error: error instanceof Error ? error.message : String(error) };+ }+ if (report.problems.length > 0) report.fix = googleApiAccessFix(account, report.problems);+ return report;+}++/**+ * One fix naming every problem: enabling an API is the user's step in the+ * Cloud console (`ask_user` with each link); a missing grant alone is the+ * user's reauth command (`tell_user_to_run`).+ */+export function googleApiAccessFix(account: string, problems: readonly GoogleApiProblem[]): Action {+ const verify = ['gbrain', 'google', 'status', '--json'];+ const disabled = problems.filter(problem => problem.code === 'api_not_enabled');+ const ungranted = problems.filter(problem => problem.code === 'scope_missing');+ const reauth = ['gbrain', 'google', 'connect', '--reauth', account];+ const steps = [+ ...disabled.map(problem => `enable the ${problem.api_title} (${problem.api}) for Google Cloud project ${problem.project ?? 'that owns the OAuth client'}: ${problem.enable_url}`),+ ...(ungranted.length ? [`grant ${ungranted.map(problem => problem.service).join(', ')} access: ${reauth.join(' ')}`] : []),+ ];+ const userMessage = `Google account ${account} cannot reach ${problems.map(problem => problem.service).join(', ')}. To fix it, ${steps.join('; ')}. `+ + `Then re-check with: ${verify.join(' ')}`;+ const shared = { consent: [], actor: 'user' as const, user_message: userMessage, verify: { argv: verify }, docs: 'docs/guides/google-connect.md#api-access', requires_exclusive: false };+ if (disabled.length > 0) {+ return { ask_user: true, ...shared,+ why: `${disabled.map(problem => problem.api_title).join(', ')} ${disabled.length === 1 ? 'is' : 'are'} disabled for the OAuth client's Google Cloud project; only the project owner can enable ${disabled.length === 1 ? 'it' : 'them'} in the console.` };+ }+ return { argv: reauth, ...shared, why: `The credential was granted without the ${ungranted.map(problem => problem.service).join(', ')} scope; a reauth asks the user to grant it.` };+}diff --git a/src/core/google/google-clients.ts b/src/core/google/google-clients.tsindex 97b1f3d5b0..efb91f1b6a 100644--- a/src/core/google/google-clients.ts+++ b/src/core/google/google-clients.ts@@ -12,21 +12,25 @@* under backfill burst load is common and self-clearing; giving up after* two tries used to poison threads that would have succeeded a few* seconds later.- * - 403 accessNotConfigured → CredentialError 'api_not_enabled' with the- * exact enable deep link (project number extracted from the client id)+ * - 403 accessNotConfigured / SERVICE_DISABLED → GoogleApiDisabledError+ * ('api_not_enabled') naming the API, the project and the enable link+ * Google put in the error body (the client id's project number otherwise)+ * - 403 insufficient authentication scopes → CredentialError 'scope_missing'* - uniform pageToken pagination with a safety cap* - fetchImpl injectable for tests*/import { CredentialError } from '../creds/errors.ts';import type { GoogleAccessProvider } from './access.ts';-import { apiEnableLink } from '../creds/providers/google.ts';+import { apiEnableLink, projectNumberFromClientId } from '../creds/providers/google.ts';import { parseRetryAfterMs } from '../github-source.ts';import { readBoundedHttpBody } from '../guarded-http.ts';import {bareAddress,DEFAULT_CALENDAR_ID,+ GOOGLE_SERVICE_API,splitAddressList,+ type GoogleService,type CalendarEventData,type ContactData,type GmailMessageMeta,@@ -78,7 +82,7 @@ interface GoogleErrorBody {status?: string;message?: string;errors?: Array<{ reason?: string }>;- details?: Array<{ '@type'?: string; reason?: string }>;+ details?: Array<{ '@type'?: string; reason?: string; metadata?: Record<string, unknown>; links?: Array<{ url?: unknown }> }>;};}@@ -127,8 +131,12 @@ export class GoogleApiClient {if (res.status === 403) {const reason = body.error?.errors?.[0]?.reason ?? '';const msg = body.error?.message ?? '';- if (reason === 'accessNotConfigured' || /has not been used|is disabled/i.test(msg)) {- throw new CredentialError('api_not_enabled', apiEnableLink(apiHint, this.clientId));+ const errorInfo = body.error?.details?.find(detail => detail?.['@type'] === 'type.googleapis.com/google.rpc.ErrorInfo');+ if (reason === 'accessNotConfigured' || errorInfo?.reason === 'SERVICE_DISABLED' || /has not been used|is disabled/i.test(msg)) {+ throw googleApiDisabledError(body, apiHint, this.clientId);+ }+ if (reason === 'insufficientPermissions' || errorInfo?.reason === 'ACCESS_TOKEN_SCOPE_INSUFFICIENT' || /insufficient authentication scopes/i.test(msg)) {+ throw new CredentialError('scope_missing', undefined, `HTTP 403 on ${apiHint}: ${msg || reason}`);}if (reason === 'rateLimitExceeded' || reason === 'userRateLimitExceeded' || /rate/i.test(msg)) {// fall through to the retry-after sleep below@@ -197,6 +205,45 @@ export class GoogleApiClient {}}+const SERVICE_FOR_HINT: Record<ApiHint, GoogleService> = { gmail: 'gmail', 'calendar-json': 'calendar', people: 'contacts' };++/** Only a Google Cloud console link is relayed from an error body; anything else falls back to the derived link. */+function consoleUrl(value: unknown): string | null {+ if (typeof value !== 'string') return null;+ try {+ const url = new URL(value);+ return url.protocol === 'https:' && (url.hostname === 'console.developers.google.com' || url.hostname === 'console.cloud.google.com') ? url.toString() : null;+ } catch {+ return null;+ }+}++/**+ * #7073: an API disabled for the OAuth client's project. Carries the API, its+ * title, the project and the enable link from Google's ErrorInfo (the Help+ * link or the message when ErrorInfo is absent), so setup, status and doctor+ * can name every disabled API with its own link.+ */+export class GoogleApiDisabledError extends CredentialError {+ constructor(readonly api: string, readonly apiTitle: string, readonly project: string | null, readonly enableUrl: string) {+ super('api_not_enabled', enableUrl);+ this.name = 'GoogleApiDisabledError';+ }+}++function googleApiDisabledError(body: GoogleErrorBody, apiHint: ApiHint, clientId: string | undefined): GoogleApiDisabledError {+ const details = body.error?.details ?? [];+ const metadata = details.find(detail => detail?.['@type'] === 'type.googleapis.com/google.rpc.ErrorInfo')?.metadata ?? {};+ const text = (key: string): string | null => typeof metadata[key] === 'string' && (metadata[key] as string).trim() ? (metadata[key] as string).trim() : null;+ const helpUrl = details.flatMap(detail => detail?.links ?? []).map(link => consoleUrl(link?.url)).find(url => url !== null) ?? null;+ const messageUrl = consoleUrl(body.error?.message?.match(/https:\/\/\S+/)?.[0]?.replace(/[.,;)]+$/, ''));+ const consumer = text('consumer')?.replace(/^projects\//, '') ?? text('containerInfo');+ const project = consumer ?? body.error?.message?.match(/in project (\d+)/)?.[1] ?? (clientId ? projectNumberFromClientId(clientId) : null);+ const fallback = GOOGLE_SERVICE_API[SERVICE_FOR_HINT[apiHint]];+ return new GoogleApiDisabledError(text('service') ?? fallback.api, text('serviceTitle') ?? fallback.title, project,+ consoleUrl(metadata.activationUrl) ?? helpUrl ?? messageUrl ?? apiEnableLink(apiHint, clientId));+}+/** Gmail 404-on-historyId / Calendar-People 410-on-syncToken. */export class GoogleCursorExpiredError extends Error {constructor(diff --git a/src/core/google/google-source.ts b/src/core/google/google-source.tsindex 8d4c0c8c71..f8ac5059be 100644--- a/src/core/google/google-source.ts+++ b/src/core/google/google-source.ts@@ -1,5 +1,6 @@import { withConnectorSync, rethrowConnectorWriteError, pendingConnectorResult, type ManagedConnectorSync } from '../persistence/connector-sync.ts';import { resolveGoogleAccount } from '../persistence/connector-account.ts';+import { googleApiProblem, googleUserinfo } from './api-access.ts';import { ConnectorHoldSession, connectorHoldsResult } from '../connectors/connector-hold-session.ts';import { carryLegacyFailCounts } from '../connectors/item-holds.ts';/**@@ -58,6 +59,7 @@ import {ALL_GOOGLE_SERVICES,isGmailHoldKey,type GmailThreadData,+ type GoogleApiProblem,type GoogleService,type GoogleSourceConfig,type GoogleSourceState,@@ -154,7 +156,8 @@ async function saveGoogleState(deps: GoogleSyncDeps, state: GoogleSourceState):/** #5867/#5868 state a partial managed run still publishes (E20): never the Gmail cursor. */function loopRecoveryState(state: GoogleSourceState): Record<string, unknown> {const fields = { loop_grace_holds: state.loop_grace_holds, loop_grace_backfill_done: state.loop_grace_backfill_done, loops_catchup: state.loops_catchup,- loop_withheld_senders: state.loop_withheld_senders, loop_automated_backfill_done: state.loop_automated_backfill_done, calendar_unreadable: state.calendar_unreadable };+ loop_withheld_senders: state.loop_withheld_senders, loop_automated_backfill_done: state.loop_automated_backfill_done, calendar_unreadable: state.calendar_unreadable,+ api_access: state.api_access };return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));}@@ -789,7 +792,7 @@ async function runGoogleSyncInner(engine: BrainEngine, sourceId: string, cfg: Goconst activeServices = grantedScopes.length > 0 ? grantedServices : cfg.services;// #5686: every enabled service reads as the pinned account; checked before any service runs.if (managed) {- const email = await resolveGoogleAccount({ gmail, calendar, people }, activeServices, opts.signal);+ const { email } = await resolveGoogleAccount({ gmail, calendar, people, userinfo: googleUserinfo(tokens, fetchImpl ?? fetch) }, activeServices, opts.signal);await managed.assertAccount(email ? { kind: 'google', email } : null);}@@ -805,13 +808,22 @@ async function runGoogleSyncInner(engine: BrainEngine, sourceId: string, cfg: Gotry {const serviceErrors: string[] = [];+ // #7073: services this run could not reach, and those it reached, for the stored api_access record.+ const apiProblems: GoogleApiProblem[] = (grantedScopes.length > 0 ? missingServices : []).flatMap((svc) => googleApiProblem(svc, new CredentialError('scope_missing')) ?? []);+ const reached = new Set<GoogleService>();+ const serviceFailed = (svc: GoogleService, e: unknown): void => {+ const problem = googleApiProblem(svc, e);+ if (problem) apiProblems.push(problem);+ };if (activeServices.includes('contacts')) {const stop = startHeartbeat(progress, 'contacts sweep');try {await sweepContacts(deps, people, state, activePack, summary, countedSlugs, holds);+ reached.add('contacts');} catch (e) {if (managed) rethrowConnectorWriteError(e);+ serviceFailed('contacts', e);serviceErrors.push(`contacts: ${e instanceof Error ? e.message : String(e)}`);summary.status = 'partial';if (isCredentialError(e)) log(e.toHuman());@@ -825,8 +837,10 @@ async function runGoogleSyncInner(engine: BrainEngine, sourceId: string, cfg: Goconst stop = startHeartbeat(progress, 'calendar sweep');try {await sweepCalendar(deps, calendar, state, activePack, summary, countedSlugs, holds);+ reached.add('calendar');} catch (e) {if (managed) rethrowConnectorWriteError(e);+ serviceFailed('calendar', e);serviceErrors.push(`calendar: ${e instanceof Error ? e.message : String(e)}`);summary.status = 'partial';if (isCredentialError(e)) log(e.toHuman());@@ -850,9 +864,11 @@ async function runGoogleSyncInner(engine: BrainEngine, sourceId: string, cfg: Goawait managed.saveState(state, true, new Date(state.gmail_newest_ms ?? Date.now()).toISOString());}});+ reached.add('gmail');if (opts.full) await reconcileGmailDeletes(deps, gmail, summary);} catch (e) {if (managed) rethrowConnectorWriteError(e);+ serviceFailed('gmail', e);serviceErrors.push(`gmail: ${e instanceof Error ? e.message : String(e)}`);summary.status = 'partial';if (isCredentialError(e)) log(e.toHuman());@@ -863,6 +879,11 @@ async function runGoogleSyncInner(engine: BrainEngine, sourceId: string, cfg: Go}summary.pagesAffected = [...new Set(summary.pagesAffected)];+ const settled = new Set<GoogleService>([...reached, ...apiProblems.map((p) => p.service)]);+ const keptProblems = (state.api_access?.problems ?? []).filter((p) => !settled.has(p.service) && cfg.services.includes(p.service));+ const problems = [...apiProblems, ...keptProblems];+ if (problems.length > 0 && JSON.stringify(problems) !== JSON.stringify(state.api_access?.problems)) state.api_access = { problems, at: new Date().toISOString() };+ else if (problems.length === 0 && state.api_access) state.api_access = null;if (grantedScopes.length > 0 && missingServices.length > 0) summary.status = 'partial';if (opts.signal?.aborted) summary.status = 'partial';if (opts.full && summary.status === 'synced') state.last_full_at = new Date().toISOString();diff --git a/src/core/google/loops-enqueue.ts b/src/core/google/loops-enqueue.tsindex 70395081f9..753941828e 100644--- a/src/core/google/loops-enqueue.ts+++ b/src/core/google/loops-enqueue.ts@@ -29,7 +29,9 @@ export async function resolveSweepExclusion(deps: Pick<GoogleSyncDeps, 'engine'}const policy = resolveExcludedLabels(tokens, catalog);if (policy.unresolved.length > 0) {- deps.log(`[google] loop exclusion: ${policy.unresolved.map((t) => JSON.stringify(t)).join(', ')} ${policy.unresolved.length === 1 ? 'is not a label' : 'are not labels'} of ${deps.cfg.account}; ` ++ const names = policy.unresolved.map((t) => JSON.stringify(t)).join(', ');+ deps.log(`[google] loop exclusion: ${catalog === null ? `${names} could not be checked against the labels of ${deps.cfg.account} (the label list failed, see above)`+ : `${names} ${policy.unresolved.length === 1 ? 'is not a label' : 'are not labels'} of ${deps.cfg.account}`}; ` +'no new loop extraction runs for this source until the names resolve (excluded_label_unresolved)');}try {diff --git a/src/core/google/types.ts b/src/core/google/types.tsindex 114c0d8e8b..ba553e3e84 100644--- a/src/core/google/types.ts+++ b/src/core/google/types.ts@@ -10,6 +10,27 @@ export type GoogleService = 'gmail' | 'calendar' | 'contacts';export const ALL_GOOGLE_SERVICES: readonly GoogleService[] = ['gmail', 'calendar', 'contacts'];+/** The Google Cloud API behind each service: the name the console enables and its title. */+export const GOOGLE_SERVICE_API: Record<GoogleService, { api: string; title: string }> = {+ gmail: { api: 'gmail.googleapis.com', title: 'Gmail API' },+ calendar: { api: 'calendar-json.googleapis.com', title: 'Google Calendar API' },+ contacts: { api: 'people.googleapis.com', title: 'People API' },+};++/**+ * #7073: a service the credential cannot reach because its API is disabled+ * for the OAuth client's project (`api_not_enabled`, with the project and the+ * enable link Google returned) or its scope was not granted (`scope_missing`).+ */+export interface GoogleApiProblem {+ service: GoogleService;+ code: 'api_not_enabled' | 'scope_missing';+ api: string;+ api_title: string;+ project: string | null;+ enable_url: string | null;+}+/** The account's primary calendar — the Calendar API's own alias, and the default a google source sweeps. *//** Where a Google source renders its contact pages unless `g_contacts_dir` says otherwise. */export const DEFAULT_CONTACTS_DIR = 'people';@@ -130,6 +151,12 @@ export interface GoogleSourceState {* list. `gbrain doctor` and `gbrain google status --no-probe` read it.*/calendar_unreadable?: CalendarUnreadable | null;+ /**+ * #7073: services the last sweep could not reach (API disabled, scope not+ * granted). A service leaves it when its sweep reaches the API again.+ * `gbrain doctor` (google_api_access) reads it with no network call.+ */+ api_access?: { problems: GoogleApiProblem[]; at: string } | null;calendar_sync_token: string | null;/*** Calendar id `calendar_sync_token` was minted for. A token is only validdiff --git a/src/core/persistence/connector-account.ts b/src/core/persistence/connector-account.tsindex a13cd487f5..150b82a5a3 100644--- a/src/core/persistence/connector-account.ts+++ b/src/core/persistence/connector-account.ts@@ -5,46 +5,29 @@* `g_token_env` / `gh_token_env` name is caught here instead.*/import type { GoogleService } from '../google/types.ts';-import type { GmailClient, CalendarClient, PeopleClient } from '../google/google-clients.ts';+import { probeGoogleAccount, type GoogleAccountProbe, type GoogleIdentityClients } from '../google/api-access.ts';import type { GitHubClient, GitHubSourceConfig } from '../github-source.ts';import type { ConnectorAccount } from './connector-state.ts';import { CredentialError } from '../creds/errors.ts';/*** Google: the first enabled service whose granted scope can name the account- * (Gmail profile, Calendar primary calendar, People `me`). Null when none can.- * When no service names the account and one refused with a credential error- * (API disabled, scope missing, forbidden), that error is rethrown, preferring- * api_not_enabled, so the caller reports the real cause instead of an account- * change (#7004).+ * (Gmail profile, Calendar primary calendar, People `me`), else the OAuth+ * userinfo endpoint (#7073), with every per-service failure kept in the+ * result. When nothing names the account, the failure is rethrown instead of+ * reported as an account change (#7004): api_not_enabled first, then any+ * other credential error, then the first other failure (a network error stays+ * a transient failure, never an account refusal). `email` is null only when+ * every attempt answered without an address.*/-export async function resolveGoogleAccount(clients: { gmail: GmailClient; calendar: CalendarClient; people: PeopleClient },- services: readonly GoogleService[], signal?: AbortSignal): Promise<string | null> {- const opts = signal ? { signal } : {};- const attempts: Array<[GoogleService, () => Promise<string | undefined>]> = [- ['gmail', async () => (await clients.gmail.getProfile(opts)).emailAddress],- ['calendar', async () => (await clients.calendar.fetchJSON<{ id?: string }>('https://www.googleapis.com/calendar/v3/calendars/primary', 'calendar-json', opts)).id],- ['contacts', async () => {- const me = await clients.people.fetchJSON<{ emailAddresses?: Array<{ value?: string; metadata?: { primary?: boolean } }> }>(- 'https://people.googleapis.com/v1/people/me?personFields=emailAddresses', 'people', opts);- return (me.emailAddresses?.find(address => address.metadata?.primary) ?? me.emailAddresses?.[0])?.value;- }],- ];- const credentialErrors: CredentialError[] = [];- for (const [service, attempt] of attempts) {- if (!services.includes(service)) continue;- signal?.throwIfAborted();- try {- const email = (await attempt())?.trim().toLowerCase();- if (email && email.includes('@')) return email;- } catch (error) {- if (signal?.aborted) throw error;- if (error instanceof CredentialError) credentialErrors.push(error);- }- }- const refusal = credentialErrors.find(error => error.code === 'api_not_enabled') ?? credentialErrors[0];- if (refusal) throw refusal;- return null;+export async function resolveGoogleAccount(clients: GoogleIdentityClients, services: readonly GoogleService[], signal?: AbortSignal): Promise<GoogleAccountProbe> {+ const probe = await probeGoogleAccount(clients, services, signal ? { signal } : {});+ if (probe.email) return probe;+ const failures = Object.values(probe.errors);+ const refusal = failures.find(error => error instanceof CredentialError && error.code === 'api_not_enabled')+ ?? failures.find(error => error instanceof CredentialError) ?? failures[0];+ if (refusal !== undefined) throw refusal;+ return probe;}/**diff --git a/test/connector-account-api-disabled-7004.test.ts b/test/connector-account-api-disabled-7004.test.tsindex cfe802c97e..3582e52c7d 100644--- a/test/connector-account-api-disabled-7004.test.ts+++ b/test/connector-account-api-disabled-7004.test.ts@@ -5,17 +5,18 @@ import { resolveGoogleAccount } from '../src/core/persistence/connector-account.const disabled = () => { throw new CredentialError('api_not_enabled'); };const scopeMissing = () => { throw new CredentialError('scope_missing'); };const network = () => { throw new Error('ECONNRESET'); };+const noUserinfo = async () => { throw new CredentialError('upstream', ': userinfo HTTP 401'); };describe('#7004 resolveGoogleAccount', () => {test('a disabled Gmail API surfaces as api_not_enabled, never as an unresolvable account', async () => {- const clients = { gmail: { getProfile: disabled }, calendar: { fetchJSON: disabled }, people: { fetchJSON: disabled } } as never;+ const clients = { gmail: { getProfile: disabled }, calendar: { fetchJSON: disabled }, people: { fetchJSON: disabled }, userinfo: noUserinfo } as never;const error = await resolveGoogleAccount(clients, ['gmail', 'calendar', 'contacts']).catch(e => e);expect(error).toBeInstanceOf(CredentialError);expect((error as CredentialError).code).toBe('api_not_enabled');});test('api_not_enabled is preferred over an earlier credential error', async () => {- const clients = { gmail: { getProfile: scopeMissing }, calendar: { fetchJSON: disabled }, people: { fetchJSON: scopeMissing } } as never;+ const clients = { gmail: { getProfile: scopeMissing }, calendar: { fetchJSON: disabled }, people: { fetchJSON: scopeMissing }, userinfo: noUserinfo } as never;const error = await resolveGoogleAccount(clients, ['gmail', 'calendar', 'contacts']).catch(e => e);expect((error as CredentialError).code).toBe('api_not_enabled');});@@ -25,12 +26,18 @@ describe('#7004 resolveGoogleAccount', () => {gmail: { getProfile: disabled },calendar: { fetchJSON: async () => ({ id: '[email protected]' }) },people: { fetchJSON: disabled },+ userinfo: noUserinfo,} as never;- expect(await resolveGoogleAccount(clients, ['gmail', 'calendar', 'contacts'])).toBe('[email protected]');+ expect((await resolveGoogleAccount(clients, ['gmail', 'calendar', 'contacts'])).email).toBe('[email protected]');});- test('non-credential failures still mean no service could name the account', async () => {- const clients = { gmail: { getProfile: network }, calendar: { fetchJSON: network }, people: { fetchJSON: network } } as never;- expect(await resolveGoogleAccount(clients, ['gmail', 'calendar', 'contacts'])).toBeNull();+ test('#7073: a network failure everywhere is rethrown as itself, never reported as an unresolvable account', async () => {+ const clients = { gmail: { getProfile: network }, calendar: { fetchJSON: network }, people: { fetchJSON: network }, userinfo: async () => network() } as never;+ await expect(resolveGoogleAccount(clients, ['gmail', 'calendar', 'contacts'])).rejects.toThrow('ECONNRESET');+ });++ test('#7073: services and userinfo that answer without an address still leave the account unresolved', async () => {+ const clients = { gmail: { getProfile: async () => ({}) }, calendar: { fetchJSON: async () => ({}) }, people: { fetchJSON: async () => ({}) }, userinfo: async () => undefined } as never;+ expect(await resolveGoogleAccount(clients, ['gmail', 'calendar', 'contacts'])).toEqual({ email: null, via: null, errors: {} });});});diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.jsonindex fd8f676fe4..363028b87b 100644--- a/test/fixtures/goldens/doctor/content-pglite-human.json+++ b/test/fixtures/goldens/doctor/content-pglite-human.json@@ -122,6 +122,7 @@" [OK] stale_embedding_effects: No committed write has a stale queued or failed embedding effect."," [OK] google_file_modes: No group- or world-readable gbrain files under Google source directories outside ~/.gbrain."," [OK] google_calendar_readable: No Google source recorded an unreadable calendar at its last sync.",+ " [OK] google_api_access: No Google source recorded a disabled API or missing scope at its last sync."," [OK] atom_retirements_restorable: No atom retired by an empty re-extraction is waiting to be restored."," [OK] extractor_facts_expired: No conversation-extractor fact is left expired by the pre-v0.60.11.0 projection."," [OK] conversation_label_facts: No conversation fact carries the pre-fix meeting-label signature (a 1970-01-01 segment on a label page).",diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.jsonindex 0fd5e4b235..7073f50918 100644--- a/test/fixtures/goldens/doctor/content-pglite-json.json+++ b/test/fixtures/goldens/doctor/content-pglite-json.json@@ -1640,6 +1640,18 @@"name": "google_calendar_readable","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/google-connect.md#api-access",+ "sources": []+ },+ "elapsed_ms": "<volatile>",+ "message": "No Google source recorded a disabled API or missing scope at its last sync.",+ "name": "google_api_access",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.jsonindex beade6096c..f89669488e 100644--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json@@ -1808,6 +1808,18 @@"name": "google_calendar_readable","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/google-connect.md#api-access",+ "sources": []+ },+ "elapsed_ms": "<volatile>",+ "message": "No Google source recorded a disabled API or missing scope at its last sync.",+ "name": "google_api_access",+ "status": "ok"+ },{"category": "brain","details": {@@ -6159,6 +6171,18 @@"name": "google_calendar_readable","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/google-connect.md#api-access",+ "sources": []+ },+ "elapsed_ms": "<volatile>",+ "message": "No Google source recorded a disabled API or missing scope at its last sync.",+ "name": "google_api_access",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex e2a26987c4..f1e77f625f 100644--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json@@ -1813,6 +1813,18 @@"name": "google_calendar_readable","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/google-connect.md#api-access",+ "sources": []+ },+ "elapsed_ms": "<volatile>",+ "message": "No Google source recorded a disabled API or missing scope at its last sync.",+ "name": "google_api_access",+ "status": "ok"+ },{"category": "brain","details": {@@ -6165,6 +6177,18 @@"name": "google_calendar_readable","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/google-connect.md#api-access",+ "sources": []+ },+ "elapsed_ms": "<volatile>",+ "message": "No Google source recorded a disabled API or missing scope at its last sync.",+ "name": "google_api_access",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 2405d4d5c9..0aa9c09489 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -1528,6 +1528,18 @@"name": "google_calendar_readable","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/google-connect.md#api-access",+ "sources": []+ },+ "elapsed_ms": "<volatile>",+ "message": "No Google source recorded a disabled API or missing scope at its last sync.",+ "name": "google_api_access",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 1b2d41942f..17a02ad793 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -1584,6 +1584,18 @@"name": "google_calendar_readable","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/google-connect.md#api-access",+ "sources": []+ },+ "elapsed_ms": "<volatile>",+ "message": "No Google source recorded a disabled API or missing scope at its last sync.",+ "name": "google_api_access",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex 2603cc3770..978bf14f8f 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -1589,6 +1589,18 @@"name": "google_calendar_readable","status": "ok"},+ {+ "category": "ops",+ "details": {+ "count": 0,+ "docs": "docs/guides/google-connect.md#api-access",+ "sources": []+ },+ "elapsed_ms": "<volatile>",+ "message": "No Google source recorded a disabled API or missing scope at its last sync.",+ "name": "google_api_access",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex d8e4e0317f..3a5f8aadb9 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -533,6 +533,10 @@"category": "ops","name": "google_calendar_readable"},+ {+ "category": "ops",+ "name": "google_api_access"+ },{"category": "brain","name": "atom_retirements_restorable"diff --git a/test/google-api-access-7073.test.ts b/test/google-api-access-7073.test.tsnew file mode 100644index 0000000000..822a9180c0--- /dev/null+++ b/test/google-api-access-7073.test.ts@@ -0,0 +1,165 @@+/**+ * #7073: the Google account resolves through OAuth userinfo when no enabled+ * service can name it, a disabled API carries its project and the enable+ * link from Google's error body, an insufficient-scope 403 is scope_missing+ * (not an unreadable calendar), and one probe names every blocked service.+ *+ * Synthetic responses only: example.invalid addresses, made-up project+ * numbers, no network.+ */+import { describe, expect, test } from 'bun:test';+import { CredentialError } from '../src/core/creds/errors.ts';+import { cliRenderContext, renderAction } from '../src/core/agent-output.ts';+import { CalendarClient, GmailClient, GoogleApiDisabledError, PeopleClient, calendarUnreadableStatus, type FetchImpl } from '../src/core/google/google-clients.ts';+import { probeGoogleApiAccess, type GoogleIdentityClients } from '../src/core/google/api-access.ts';+import { resolveGoogleAccount } from '../src/core/persistence/connector-account.ts';++const OWNER = '[email protected]';+const PROJECT = '987654321';+const CLIENT_ID = '123-abc.apps.googleusercontent.com';+const tokens = { getAccessToken: async () => 'token', forceRefresh: async () => 'token' };++const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });++/** Google's 403 for an API disabled in the project (ErrorInfo SERVICE_DISABLED with the activation link). */+function serviceDisabled(api: string, title: string): Response {+ const url = `https://console.developers.google.com/apis/api/${api}/overview?project=${PROJECT}`;+ return json({ error: { code: 403, status: 'PERMISSION_DENIED',+ message: `${title} has not been used in project ${PROJECT} before or it is disabled. Enable it by visiting ${url} then retry.`,+ errors: [{ reason: 'accessNotConfigured', domain: 'usageLimits' }],+ details: [+ { '@type': 'type.googleapis.com/google.rpc.ErrorInfo', reason: 'SERVICE_DISABLED', domain: 'googleapis.com',+ metadata: { service: api, consumer: `projects/${PROJECT}`, activationUrl: url, serviceTitle: title, containerInfo: PROJECT } },+ { '@type': 'type.googleapis.com/google.rpc.Help', links: [{ description: 'Google developers console API activation', url }] },+ ] } }, 403);+}++const insufficientScopes = () => json({ error: { code: 403, status: 'PERMISSION_DENIED', message: 'Request had insufficient authentication scopes.',+ errors: [{ reason: 'insufficientPermissions', domain: 'global' }],+ details: [{ '@type': 'type.googleapis.com/google.rpc.ErrorInfo', reason: 'ACCESS_TOKEN_SCOPE_INSUFFICIENT', domain: 'googleapis.com' }] } }, 403);++interface Routes { gmail?: () => Response; calendar?: () => Response; people?: () => Response; userinfo?: () => Response }++function clientsFor(routes: Routes): { clients: GoogleIdentityClients; calls: string[] } {+ const calls: string[] = [];+ const fetchImpl: FetchImpl = async (url) => {+ calls.push(url);+ const path = new URL(url).pathname;+ if (path.endsWith('/users/me/profile')) return routes.gmail?.() ?? json({ emailAddress: OWNER, historyId: '1' });+ if (path.endsWith('/calendars/primary')) return routes.calendar?.() ?? json({ id: OWNER });+ if (path.endsWith('/people/me')) return routes.people?.() ?? json({ emailAddresses: [{ value: OWNER, metadata: { primary: true } }] });+ if (path.endsWith('/userinfo')) return routes.userinfo?.() ?? json({ email: OWNER });+ throw new Error(`unexpected route ${url}`);+ };+ const args = [tokens, fetchImpl, () => {}, CLIENT_ID] as const;+ return {+ calls,+ clients: { gmail: new GmailClient(...args), calendar: new CalendarClient(...args), people: new PeopleClient(...args),+ userinfo: async () => ((await (await fetchImpl('https://openidconnect.googleapis.com/v1/userinfo')).json()) as { email?: string }).email },+ };+}++describe('#7073 disabled API errors carry the project and the enable link from the body', () => {+ test('SERVICE_DISABLED names the API, its title, the project and the activation URL', async () => {+ const { clients } = clientsFor({ gmail: () => serviceDisabled('gmail.googleapis.com', 'Gmail API') });+ const error = await clients.gmail.getProfile().catch(e => e);+ expect(error).toBeInstanceOf(GoogleApiDisabledError);+ expect(error).toMatchObject({ code: 'api_not_enabled', api: 'gmail.googleapis.com', apiTitle: 'Gmail API', project: PROJECT,+ enableUrl: `https://console.developers.google.com/apis/api/gmail.googleapis.com/overview?project=${PROJECT}` });+ expect((error as CredentialError).fix).toContain(`overview?project=${PROJECT}`);+ });++ test('a link that is not a Google Cloud console URL is never relayed', async () => {+ const { clients } = clientsFor({ people: () => json({ error: { code: 403, message: 'People API is disabled.', errors: [{ reason: 'accessNotConfigured' }],+ details: [{ '@type': 'type.googleapis.com/google.rpc.ErrorInfo', reason: 'SERVICE_DISABLED', metadata: { activationUrl: 'https://attacker.example.invalid/enable' } }] } }, 403) });+ const error = await clients.people.fetchJSON('https://people.googleapis.com/v1/people/me', 'people').catch(e => e) as GoogleApiDisabledError;+ expect(error.enableUrl).toBe('https://console.cloud.google.com/apis/library/people.googleapis.com?project=123');+ expect(error.api).toBe('people.googleapis.com');+ });++ test('an insufficient-scope 403 is scope_missing, never an unreadable calendar', async () => {+ const { clients } = clientsFor({ calendar: insufficientScopes });+ const error = await clients.calendar.fetchJSON('https://www.googleapis.com/calendar/v3/calendars/primary', 'calendar-json').catch(e => e);+ expect(error).toBeInstanceOf(CredentialError);+ expect((error as CredentialError).code).toBe('scope_missing');+ expect(calendarUnreadableStatus(error)).toBeNull();+ });+});++describe('#7073 resolveGoogleAccount falls back to userinfo', () => {+ test('disabled Gmail with a valid userinfo resolves the account and keeps api_not_enabled in the result', async () => {+ const { clients, calls } = clientsFor({ gmail: () => serviceDisabled('gmail.googleapis.com', 'Gmail API') });+ const resolution = await resolveGoogleAccount(clients, ['gmail']);+ expect(resolution.email).toBe(OWNER);+ expect(resolution.via).toBe('userinfo');+ expect(resolution.errors.gmail).toBeInstanceOf(GoogleApiDisabledError);+ expect(resolution.errors.gmail).toMatchObject({ code: 'api_not_enabled', project: PROJECT });+ expect(calls.some(url => url.endsWith('/v1/userinfo'))).toBe(true);+ });++ test('every service disabled or ungranted with userinfo working resolves through userinfo', async () => {+ const { clients } = clientsFor({+ gmail: () => serviceDisabled('gmail.googleapis.com', 'Gmail API'),+ calendar: insufficientScopes,+ people: () => serviceDisabled('people.googleapis.com', 'People API'),+ });+ const resolution = await resolveGoogleAccount(clients, ['gmail', 'calendar', 'contacts']);+ expect(resolution).toMatchObject({ email: OWNER, via: 'userinfo' });+ expect(Object.keys(resolution.errors)).toEqual(['gmail', 'calendar', 'contacts']);+ expect((resolution.errors.calendar as CredentialError).code).toBe('scope_missing');+ });++ test('userinfo is not called when a service names the account', async () => {+ const { clients, calls } = clientsFor({ gmail: () => serviceDisabled('gmail.googleapis.com', 'Gmail API') });+ expect(await resolveGoogleAccount(clients, ['gmail', 'calendar'])).toMatchObject({ email: OWNER, via: 'calendar' });+ expect(calls.some(url => url.endsWith('/v1/userinfo'))).toBe(false);+ });++ test('with userinfo failing too, the disabled API is the refusal', async () => {+ const { clients } = clientsFor({ gmail: () => serviceDisabled('gmail.googleapis.com', 'Gmail API') });+ const resolution = resolveGoogleAccount({ ...clients, userinfo: async () => { throw new CredentialError('upstream', ': userinfo HTTP 401'); } }, ['gmail']);+ await expect(resolution).rejects.toMatchObject({ code: 'api_not_enabled', project: PROJECT });+ });+});++describe('#7073 one probe names every disabled API and missing scope', () => {+ test('Gmail and People disabled plus an ungranted Calendar scope: three problems, one ask_user fix with every link', async () => {+ const { clients, calls } = clientsFor({+ gmail: () => serviceDisabled('gmail.googleapis.com', 'Gmail API'),+ people: () => serviceDisabled('people.googleapis.com', 'People API'),+ });+ const granted = ['openid', 'email', 'https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/contacts.readonly'];+ const report = await probeGoogleApiAccess(clients, OWNER, ['gmail', 'calendar', 'contacts'], granted);+ expect(report.resolved_account).toBe(OWNER);+ expect(report.resolved_via).toBe('userinfo');+ expect(report.problems.map(p => [p.service, p.code, p.project])).toEqual([+ ['gmail', 'api_not_enabled', PROJECT], ['calendar', 'scope_missing', null], ['contacts', 'api_not_enabled', PROJECT],+ ]);+ expect(report.services).toEqual({ gmail: { status: 'api_not_enabled' }, calendar: { status: 'scope_missing' }, contacts: { status: 'api_not_enabled' } });+ // The ungranted service is not requested; both disabled ones are.+ expect(calls.some(url => url.includes('/calendars/primary'))).toBe(false);+ const fix = renderAction(report.fix!, cliRenderContext());+ expect(fix.next).toBe('ask_user');+ expect(fix.user_message).toContain(`https://console.developers.google.com/apis/api/gmail.googleapis.com/overview?project=${PROJECT}`);+ expect(fix.user_message).toContain(`https://console.developers.google.com/apis/api/people.googleapis.com/overview?project=${PROJECT}`);+ expect(fix.user_message).toContain(`gbrain google connect --reauth ${OWNER}`);+ expect(fix.verify).toEqual({ argv: ['gbrain', 'google', 'status', '--json'] });+ });++ test('a missing scope alone is the reauth command for the user to run', async () => {+ const { clients } = clientsFor({ calendar: insufficientScopes });+ const report = await probeGoogleApiAccess(clients, OWNER, ['gmail', 'calendar'], []);+ expect(report.problems.map(p => p.code)).toEqual(['scope_missing']);+ const fix = renderAction(report.fix!, cliRenderContext());+ expect(fix.next).toBe('tell_user_to_run');+ expect(fix.argv).toEqual(['gbrain', 'google', 'connect', '--reauth', OWNER]);+ });++ test('every service reachable: no problems and no fix', async () => {+ const { clients } = clientsFor({});+ const report = await probeGoogleApiAccess(clients, OWNER, ['gmail', 'calendar', 'contacts'], []);+ expect(report).toMatchObject({ resolved_account: OWNER, resolved_via: 'gmail', problems: [] });+ expect(report.fix).toBeUndefined();+ expect(report.services).toEqual({ gmail: { status: 'ok' }, calendar: { status: 'ok' }, contacts: { status: 'ok' } });+ });+});diff --git a/test/google-api-access-cmd-7073.serial.test.ts b/test/google-api-access-cmd-7073.serial.test.tsnew file mode 100644index 0000000000..3b3588fd58--- /dev/null+++ b/test/google-api-access-cmd-7073.serial.test.ts@@ -0,0 +1,141 @@+/**+ * #7073: `gbrain google status` and `gbrain google setup` probe Gmail,+ * Calendar and People together and name every disabled API (project, API,+ * the console link from Google's error body) and missing scope in one report+ * with an agent-protocol fix. Setup stops before registering a source.+ *+ * Serial file: swaps globalThis.fetch. Every run uses a fresh GBRAIN_HOME+ * with no brain configured, so only the fixture vault is read. Synthetic+ * data only: example.invalid addresses and a made-up project number.+ */+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++import { runGoogleStatus } from '../src/commands/google.ts';+import { runGoogleSetup } from '../src/commands/google-setup.ts';+import { currentExitCode, _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';+import { withEnv } from './helpers/with-env.ts';++const ACCOUNT = '[email protected]';+const PROJECT = '987654321';+const CLIENT_ID = `${PROJECT}-abcdef.apps.googleusercontent.com`;+const SCOPES = ['openid', 'email', 'https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/calendar.readonly', 'https://www.googleapis.com/auth/contacts.readonly'];+const enableUrl = (api: string) => `https://console.developers.google.com/apis/api/${api}/overview?project=${PROJECT}`;++const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });+const disabled = (api: string, title: string) => json({ error: { code: 403, status: 'PERMISSION_DENIED', message: `${title} has not been used in project ${PROJECT} before or it is disabled.`,+ errors: [{ reason: 'accessNotConfigured' }],+ details: [{ '@type': 'type.googleapis.com/google.rpc.ErrorInfo', reason: 'SERVICE_DISABLED',+ metadata: { service: api, serviceTitle: title, consumer: `projects/${PROJECT}`, activationUrl: enableUrl(api) } }] } }, 403);++let disabledApis = new Set<string>();+const realFetch = globalThis.fetch;+const mockFetch = (async (input: string | URL | Request) => {+ const url = new URL(typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url);+ if (url.hostname === 'oauth2.googleapis.com') return json({ access_token: 'ya29.fixture', expires_in: 3600 });+ if (url.hostname === 'openidconnect.googleapis.com') return json({ email: ACCOUNT });+ if (url.pathname.endsWith('/users/me/profile')) return disabledApis.has('gmail') ? disabled('gmail.googleapis.com', 'Gmail API') : json({ emailAddress: ACCOUNT, historyId: '1' });+ if (url.pathname.endsWith('/calendars/primary')) return disabledApis.has('calendar') ? disabled('calendar-json.googleapis.com', 'Google Calendar API') : json({ id: ACCOUNT });+ if (url.pathname.endsWith('/people/me')) return disabledApis.has('people') ? disabled('people.googleapis.com', 'People API') : json({ emailAddresses: [{ value: ACCOUNT, metadata: { primary: true } }] });+ throw new Error(`unexpected fetch in test: ${url}`);+}) as typeof fetch;++beforeEach(() => { disabledApis = new Set(); globalThis.fetch = mockFetch; _resetCliExitVerdictForTests(); });+afterEach(() => { globalThis.fetch = realFetch; _resetCliExitVerdictForTests(); });++function home(scopes = SCOPES): string {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-7073-'));+ mkdirSync(join(dir, '.gbrain'), { recursive: true });+ const now = new Date().toISOString();+ writeFileSync(join(dir, '.gbrain', 'credentials.json'), JSON.stringify({ version: 1,+ clients: [{ provider: 'google', client_id: CLIENT_ID, client_secret: 'GOCSPX-test-secret-0000', created_at: now }],+ credentials: { [`google:${ACCOUNT}`]: { id: `google:${ACCOUNT}`, provider: 'google', kind: 'oauth2', client_ref: 'byo',+ secret: { access_token: 'ya29.fixture', refresh_token: '1//fixture', expiry: new Date(Date.now() + 3_600_000).toISOString() },+ meta: { account: ACCOUNT, scopes, client_id: CLIENT_ID, connected_at: now, last_refresh_ok_at: now, consent_publish_state: 'production' } } } }), { mode: 0o600 });+ return dir;+}++async function run(fn: () => Promise<void>): Promise<{ out: string; err: string; verdict: number }> {+ const out: string[] = [];+ const err: string[] = [];+ const outOrig = process.stdout.write.bind(process.stdout);+ const errOrig = process.stderr.write.bind(process.stderr);+ const prevExitCode = process.exitCode;+ process.stdout.write = ((c: string | Uint8Array) => { out.push(String(c)); return true; }) as typeof process.stdout.write;+ process.stderr.write = ((c: string | Uint8Array) => { err.push(String(c)); return true; }) as typeof process.stderr.write;+ try { await fn(); } finally { process.stdout.write = outOrig; process.stderr.write = errOrig; }+ const verdict = currentExitCode();+ _resetCliExitVerdictForTests();+ process.exitCode = prevExitCode ?? 0;+ return { out: out.join(''), err: err.join(''), verdict };+}++const env = (dir: string) => ({ GBRAIN_HOME: dir, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined });++describe('#7073 gbrain google status probes every service at once', () => {+ test('Gmail and People disabled: one account report lists both with project and link, ok:false, exit 1', async () => {+ disabledApis = new Set(['gmail', 'people']);+ const dir = home();+ const r = await withEnv(env(dir), () => run(() => runGoogleStatus(['--json'])));+ const body = JSON.parse(r.out) as { ok: boolean; accounts: Array<{ refresh_probe: string; api_access: { resolved_account: string; problems: Array<Record<string, unknown>>; fix: { next: string; user_message: string } } }> };+ expect(body.ok).toBe(false);+ expect(r.verdict).toBe(1);+ const access = body.accounts[0]!.api_access;+ expect(access.resolved_account).toBe(ACCOUNT);+ expect(access.problems).toEqual([+ { service: 'gmail', code: 'api_not_enabled', api: 'gmail.googleapis.com', api_title: 'Gmail API', project: PROJECT, enable_url: enableUrl('gmail.googleapis.com') },+ { service: 'contacts', code: 'api_not_enabled', api: 'people.googleapis.com', api_title: 'People API', project: PROJECT, enable_url: enableUrl('people.googleapis.com') },+ ]);+ expect(access.fix.next).toBe('ask_user');+ expect(access.fix.user_message).toContain(enableUrl('gmail.googleapis.com'));+ expect(access.fix.user_message).toContain(enableUrl('people.googleapis.com'));+ });++ test('human output names each disabled API on its own line', async () => {+ disabledApis = new Set(['gmail', 'calendar']);+ const r = await withEnv(env(home()), () => run(() => runGoogleStatus([])));+ expect(r.out).toContain(`gmail: api_not_enabled — Gmail API (gmail.googleapis.com) is disabled for project ${PROJECT}; enable: ${enableUrl('gmail.googleapis.com')}`);+ expect(r.out).toContain(`calendar: api_not_enabled — Google Calendar API (calendar-json.googleapis.com) is disabled for project ${PROJECT}`);+ expect(r.verdict).toBe(1);+ });++ test('every API enabled: ok:true and no problems', async () => {+ const r = await withEnv(env(home()), () => run(() => runGoogleStatus(['--json'])));+ const body = JSON.parse(r.out) as { ok: boolean; accounts: Array<{ api_access: { problems: unknown[] } }> };+ expect(body.ok).toBe(true);+ expect(body.accounts[0]!.api_access.problems).toEqual([]);+ expect(r.verdict).toBe(0);+ });+});++describe('#7073 gbrain google setup probes before registering anything', () => {+ test('two disabled APIs and an ungranted scope stop setup with one report and exit 3', async () => {+ disabledApis = new Set(['gmail', 'people']);+ const dir = home(SCOPES.filter(s => !s.includes('calendar')));+ const r = await withEnv(env(dir), () => run(() => runGoogleSetup(['--json'])));+ const body = JSON.parse(r.out) as { ok: boolean; status: string; api_access: { problems: Array<{ service: string; code: string }>; fix: { next: string } } };+ expect(body).toMatchObject({ ok: false, status: 'api_access_blocked' });+ expect(body.api_access.problems.map(p => `${p.service}:${p.code}`)).toEqual(['gmail:api_not_enabled', 'calendar:scope_missing', 'contacts:api_not_enabled']);+ expect(body.api_access.fix.next).toBe('ask_user');+ expect(r.verdict).toBe(3);+ });++ test('human output names every API and the narrower setup, with the fix in one [SHOW USER] relay', async () => {+ disabledApis = new Set(['people']);+ const r = await withEnv(env(home()), () => run(() => runGoogleSetup([])));+ expect(r.err).toContain('[SHOW USER]');+ expect(r.err).toContain('next: ask_user');+ expect(r.err).toContain(`People API (people.googleapis.com) is disabled for Google Cloud project ${PROJECT}. Enable it: ${enableUrl('people.googleapis.com')}`);+ expect(r.err).toContain(`gbrain google setup --account ${ACCOUNT} --services gmail,calendar`);+ expect(r.err).not.toContain('Registered source');+ expect(r.verdict).toBe(3);+ });++ test('every API reachable: setup continues past the probe to the brain step', async () => {+ const r = await withEnv(env(home()), () => run(() => runGoogleSetup(['--json'])));+ expect(JSON.parse(r.out)).toMatchObject({ ok: false, status: 'no_brain' });+ expect(r.verdict).toBe(2);+ });+});diff --git a/test/google-api-access-managed-7073.test.ts b/test/google-api-access-managed-7073.test.tsnew file mode 100644index 0000000000..ec4d080b82--- /dev/null+++ b/test/google-api-access-managed-7073.test.ts@@ -0,0 +1,67 @@+/**+ * #7073 on a managed Google source (real PGLite, and Postgres when+ * DATABASE_URL is set): with the People API disabled and OAuth userinfo+ * answering, the account resolves and pins, the run reports the disabled API+ * instead of refusing, and doctor google_api_access reads the stored record+ * with no network call. A different account behind userinfo still refuses+ * connector_account_changed.+ *+ * Synthetic responses only: example.invalid addresses, a made-up project.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { parseGoogleSourceConfig, runGoogleSync } from '../src/core/google/google-source.ts';+import { readManagedConnectorState } from '../src/core/persistence/connector-state.ts';+import { googleApiAccessCheck } from '../src/commands/doctor/checks/google-api-access.ts';+import { withEnv } from './helpers/with-env.ts';+import { createConnectorFixture, options, json, googleConfig } from './helpers/connector-fixture.ts';++const { engines, env, source, setup, teardown } = createConnectorFixture();+beforeAll(setup, 120_000);+afterAll(teardown);++const PROJECT = '987654321';+const ENABLE_URL = `https://console.developers.google.com/apis/api/people.googleapis.com/overview?project=${PROJECT}`;+const incarnation = async (engine: BrainEngine, id: string) => (await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text FROM sources WHERE id=$1', [id]))[0].incarnation;++function peopleDisabled(userinfoAccount: string) {+ return async (url: string) => {+ const path = new URL(url).pathname;+ if (path.endsWith('/settings/sendAs')) return json({ sendAs: [] });+ if (path.endsWith('/v1/userinfo')) return json({ email: userinfoAccount });+ if (path.includes('/people/')) {+ return json({ error: { code: 403, status: 'PERMISSION_DENIED', message: `People API has not been used in project ${PROJECT} before or it is disabled.`,+ errors: [{ reason: 'accessNotConfigured' }],+ details: [{ '@type': 'type.googleapis.com/google.rpc.ErrorInfo', reason: 'SERVICE_DISABLED',+ metadata: { service: 'people.googleapis.com', serviceTitle: 'People API', consumer: `projects/${PROJECT}`, activationUrl: ENABLE_URL } }] } }, 403);+ }+ throw new Error(`unexpected route ${url}`);+ };+}++test('disabled People API with a valid userinfo: the account pins, the run is partial, doctor names the API', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await source(engine, googleConfig);+ const result = await runGoogleSync(engine, f.id, parseGoogleSourceConfig(googleConfig, f.dir), options, peopleDisabled(googleConfig.g_account));+ expect(result.status).toBe('partial');+ const state = await readManagedConnectorState(engine, f.id, await incarnation(engine, f.id));+ expect(state.account).toEqual({ kind: 'google', email: googleConfig.g_account });+ expect(state.account_mismatch ?? null).toBeNull();++ const check = await googleApiAccessCheck(engine, [f.id]);+ expect(check.status).toBe('warn');+ expect(check.details).toMatchObject({ count: 1, sources: [{ source_id: f.id, account: googleConfig.g_account,+ problems: [{ service: 'contacts', code: 'api_not_enabled', api: 'people.googleapis.com', project: PROJECT, enable_url: ENABLE_URL }] }] });+ expect(check.message).toContain(ENABLE_URL);+ expect(check.fix).toMatchObject({ ask_user: true, actor: 'user', verify: { argv: ['gbrain', 'google', 'status', '--json'] } });+ }+}), 180_000);++test('a different account behind userinfo still refuses connector_account_changed', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await source(engine, googleConfig);+ const refused = await runGoogleSync(engine, f.id, parseGoogleSourceConfig(googleConfig, f.dir), options, peopleDisabled('[email protected]')).catch(e => e);+ expect(refused).toMatchObject({ code: 'connector_account_changed', detail: 'account_changed' });+ expect((refused as { suggestion: string }).suggestion).toContain('the credential resolves to [email protected]');+ }+}), 180_000);diff --git a/test/google-source-reconcile.test.ts b/test/google-source-reconcile.test.tsindex 3839740391..4658633e59 100644--- a/test/google-source-reconcile.test.ts+++ b/test/google-source-reconcile.test.ts@@ -1491,6 +1491,9 @@ describe('loops_extract enqueue completeness', () => {const { result: byName, err } = await capturedStderr(() => sweep(dir, fx, vault, { full: true }));expect(byName.loops_enqueue).toMatchObject({ enqueued: 0, skipped_reason: 'excluded_label_unresolved' });expect(err).toContain("could not read the account's labels");+ // #7073: a failed list never claims the name is not a label of the account.+ expect(err).toContain('"Newsletters" could not be checked against the labels of [email protected] (the label list failed');+ expect(err).not.toContain('is not a label');});} finally {await engine.setConfig('loops.extraction_exclude_labels', '');