Garry's Opinionated OpenClaw/Hermes Agent Brain
Google connector + open-loop engine (key files cluster)
User-facing contracts: docs/guides/google-connect.md (setup + the typed error
catalog) and docs/guides/open-loops.md (detection + close semantics).
Hosted-relay server design: docs/designs/HOSTED_OAUTH_RELAY.md (the CLI-side
seams are frozen in this repo; the server is gbrain.io's build). Agent-facing
operation: skills/google-loops/SKILL.md. The open-loop engine's own files
(loops-exclusion.ts, loop-detect.ts, loops-extract.ts, loops-store.ts,
ops/loops.ts, commands/loops.ts) are in
open-loops-engine.md.
Historical Gmail repair selects explicit nested MIME metadata fields, excluding body.data at every depth. Depth-33 child sentinels preserve incomplete inspection beyond the depth-32 traversal bound. Its decoded HTTP response is capped at 2 MiB before JSON parsing; overflow cancels the stream and preserves the affected page/cursor. Ordinary sync's body requests remain unchanged.
src/core/google/attachment-receipts.ts— bounded iterative Gmail MIME inspection and inert receipt rendering. Per-message depth/part limits and a per-thread aggregate byte budget distinguish not-inspected, incomplete, inspected-none and present-not-downloaded/not-indexed states. Receipt identity includes account, message and MIME part/path; body parts, inline assets and calendar documents are distinguished.google-clients.tsretains these receipts andgoogle-render.tsstores them in connector-ownedgmail_attachment_receiptsfrontmatter alongside readable per-message summaries.src/core/google/attachment-backfill.ts+src/commands/google-attachments.ts—google attachments backfill --sourcepreviews imported-thread scope without Google calls; explicit--yesruns at most 25 metadata-only repairs through an existing managed source. Account-bound keyset checkpoints use a fixed historical page-ID boundary and advance only after committed receipts. Confirmed thread 404s and missing historical message IDs retain prior metadata with explicit unavailable diagnostics, advance traversal, and count separately from inspected pages; traversal completion is not inspection completeness. Malformed or otherwise incomplete inspection stops before the affected page; conflicts preserve edits and withdrawals. This local-only path never enables persistence or services, downloads attachment content, or invokes loop/fact extraction. Incremental sync does not imply historical completeness. Tests:google-attachment-{receipts,sync,backfill,recovery}.test.tscover normalization, real managed publication on both engines, private visibility, races, and SIGKILL recovery.src/core/creds/vault.ts— the generic credential vault: one home for every outbound credential gbrain holds (Google OAuth today; provider-agnostic by design, providers register undersrc/core/creds/providers/). Two backends behind one frozen interface:FileVaultBackend(~/.gbrain/credentials.json, 0600, atomic writes — the CLI/self-host default) and the DB-backedEngineVaultBackendshape hosted gbrain.io implements. Custody rules: secrets live ONLY in the vault (never the config plane;sources.configstores a credential-id pointer, mirroring how github sources store an env NAME);list()returns redacted metadata only. No CLI imports — prompts live insrc/commands/.src/core/creds/errors.ts— the typed credential error catalog (CredentialError): every connect/refresh failure a user can hit maps to one code with four user-facing fields ({code, problem, cause, fix, doc_url}), rendered two ways — a conversational fix-first one-liner (stderr /[SHOW USER]blocks) and structured JSON (--jsonenvelopes). Single source of truth for the troubleshooting table indocs/guides/google-connect.md— update both together. No CLI imports; hosted reuses it.src/core/creds/providers/google.ts— Google OAuth2 client, BYO + relay-minted; hand-rolled fetch (no googleapis dependency,fetchImpl-injectable). PKCE S256 withaccess_type=offline&prompt=consentso a refresh token is always minted;client_refon the vault entry routes refresh (byo→ direct against the Google token endpoint with the user's own client;hosted-relay→ through the relay).invalid_grantis sub-classified into the catalog: clock skew (local clock vs Google'sDateresponse header), the 7-day Testing-mode expiry (age heuristic on last_refresh_ok_at/connected_at), and plain revocation.GOOGLE_SERVICE_SCOPESis read-only by construction — the connector never writes to Google.src/core/creds/redirect.ts— how the authorization code gets back to us:RedirectStrategy = 'loopback' | 'paste' | 'hosted-callback'. Loopback is an ephemeral 127.0.0.1 listener; paste mode needs NO listener (the fixedPASTE_REDIRECT_URIfails to load, the user pastes the full address-bar URL back) and is auto-selected bysniffHeadless(SSH/WSL/container/no-display). Google's device-code flow is NOT an option — Gmail/Calendar/Contacts scopes are excluded from it; don't re-litigate.src/core/creds/relay-client.ts— the typed CLIENT half of the gbrain.io zero-retention consent relay (createSession→ user clicks the consent URL → poll a one-timeclaim; the relay deletes tokens on first successful claim or at session TTL). Inert unlessGBRAIN_OAUTH_RELAY_URLis set (unset = the BYO flow, which always works).test/creds-relay-client.test.tsis the server conformance spec — a server that round-trips those fixtures is compatible.src/core/creds/export.ts— versioned passphrase-encrypted credential bundles (scrypt N=2^15, r=8, p=1 → AES-256-GCM) for machine moves and hosted-upgrade transfer. A bundle carries selected vault entries PLUS the provider client records they depend on (Google refresh tokens are bound to the client that minted them — moving one without the other produces dead tokens). Format frozen here; hosted's import endpoint conforms to it.src/core/google/types.ts— pure data shapes for the google source kind: normalized Gmail/Calendar/People payloads,GoogleSourceConfig(account pointer, services, historyDays, managed dir), and theGoogleSourceStatecursor file persisted at<managed dir>/.google-source.json(gmail history id, downward-moving backfill floor, per-service syncTokens). No I/O. ExportsDEFAULT_CALENDAR_ID = 'primary'(the Calendar API's own alias; every'primary'literal in google-clients/google-source/sources/sources-ops resolves through it) andGoogleSourceConfig.calendarId(one calendar per source).GoogleSourceState.calendar_idrecords which calendarcalendar_sync_tokenwas minted for — a token is only valid against its own calendar; absent on legacy state, which is therefore primary's.GoogleSourceState.calendar_horizon_msis 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 field maskcontacts_sync_tokenwas minted under andcontacts_relist(#8906) the full re-list's resume page.contact_groupscaches the group directory (resource name → display name) and is never authoritative on its own.GoogleSourceConfig.futureDays(#5442) andloopsExcludeLabels(#5445) are optional and absent when their keys are unset;source-config.tsparses them (g_future_days1..3650 floored,g_loops_exclude_labelsthroughparseExcludeLabelTokens) andgoogleTuningConfigis the one writer of those keys plusg_calendar_id, each only when set, foraddSource. Bothsources addparsers accept--future-daysand--loops-exclude-labels: the connected-source parser validates through the operation contract (sources-lifecycle-args.ts), the legacy parser throughcommands/sources-google-flags.ts(parseGoogleAddFlag, exit 2 on a bad value), so neitherrunAddnoraddSourcegrows for a new tuning key.src/core/google/access.ts— the pluggable Google-access seam:GoogleAccessProvider(getAccessToken/forceRefresh) withCommandAccessProvider(--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_failedcarrying the stderr tail) andEnvAccessProvider(--access env: a live token read from a NAMED env var each call, refreshed outside gbrain; missing =access_env_missing). The vault flow'sGoogleTokenProvidersatisfies 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 anyGoogleAccessProvider(vault-backedGoogleTokenProviderby default), 401 → forceRefresh + single retry, Retry-After honored (delta-seconds AND http-date), 403 disabled API →GoogleApiDisabledErrorand insufficient scope →scope_missing(API access), uniform pageToken pagination with a safety cap,fetchImplinjectable for tests.extractCalendarMethod(part)walks the MIME tree for atext/calendar/application/icspart and reads the iCalendarmethod=parameter from the PART's ownContent-Typeheader (headers[]on nested parts withformat=full— Gmail'sMessagePart.mimeTypeis 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.icsfilename with a non-calendar MIME type claims nothing.CalendarClient.listEvents({calendarId})sweeps one calendar (defaultDEFAULT_CALENDAR_ID). A People request with a nonemptysyncTokenmaps HTTP 400 toGoogleCursorExpiredErroronly for typedgoogle.rpc.ErrorInforeasonEXPIRED_SYNC_TOKENor a message beginningSync token [is] expired; any other 400 on such a request is aGoogleSyncTokenRejectedError(aCredentialError('upstream')subclass the contacts sweep alone treats as cursor-invalid, #6324); a connections 400 with apageTokenisGoogleCursorExpiredError(#8906,listConnectionsPagereads one page); other initial-list requests and 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;ContactDatacarries deduplicated E.164phonesand user-groupgroups({id, name: null}, system groups dropped), andlistContactGroups()walkscontactGroupsfor at most ten 1000-row pages and reportscomplete: falsepast that. The Gmail mapper also capturesprecedence(lower-cased),listId(present or not) andreplyTofor the automated-mail loop rule (#5012). A 403 that is not API-disabled, rate-limit or quota isGoogleForbiddenError(stillCredentialErrorupstream);calendarUnreadableStatus(e)maps it and a 404GoogleCursorExpiredErrorto 403/404, andCalendarClient.probeCalendar(id)is onemaxResults=1read. Pinned by injected-response tests intest/google-clients.test.ts,test/contacts-phone-only-groups-6324.test.tsandtest/google-source-reconcile.test.ts, not live-provider validation.src/core/google/gmail-categories.ts—BULK_CATEGORY_LABELS(CATEGORY_PROMOTIONS/SOCIAL/FORUMS) andhasBulkCategory, the one list both open-loop lanes read (#5103):loopExtractionEligibilityreturnsbulk_categoryanddetectThreadLoopwithholds an inbound open, in both cases unless the owner wrote a substantive message in the thread;CATEGORY_UPDATESis deliberately not in it.isNoiseSenderadditionally matchesGOOGLE_SYSTEM_SENDERS(the Meet notes digest address) by equality only.src/core/google/google-render.ts—isPositivelyAutomated(meta)(#5012):Precedence: bulk|list|junk, aList-Id, a noise From or a noise Reply-To. Pure render functions ({relPath, markdown}out; no I/O, no engine): thread pages underemails/YYYY/MM/(type email), events undercalendar/YYYY/MM/(type meeting), contacts underpeople/(type person). Gmail deep links are code-generated via the typedemailCitationscaffold, never LLM-composed. The noise/signature rulesrecipes/email-to-brain.mdspecifies 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 acalendarMethodin theCALENDAR_METHODSallowlist (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 likeNotification:is a human/vendor subject and never matches.renderThreadPagestampsparticipants:(every address on the thread) ANDsenders:(sorted unique message AUTHORS only — the listloops mute sendergates on, so muting one person cannot silence a whole group thread).renderPersonPage(#6324) renders a contact with emails OR phones:emails:always,phones:andgroups:(names, or the rawcontactGroups/<id>when unresolved) only when non-empty, phones never inaliases; a contact with neither name nor email lives atcontactIdSlug=<dir>/contact-<sha8(resourceName)>, whichpersonSlugFromContactreturns for a phone-only nameless contact and the sweep's tombstone path lists as a delete candidate. Pinned bytest/google-render.test.tsandtest/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, and it and the held-thread retries settle a thread older thancutoffMs(now - g_history_days) without a page unless one exists (test/google-gmail-delta-window-8482.test.ts); the INITIAL backfill drains newest→oldest with a batch-committed floor cursor so a killed backfill resumes at the floor, and the historyId anchor is captured BEFORE the backfill so the delta lane takes over with zero gap (overlap re-renders are idempotent). Emits thesync.google_materializeprogress 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 insources.config(only the command/env NAME does). Honesty invariants:last_sync_atis gated on the GMAIL sweep's success (it feedsgbrain waiting's staleness gate; a gmail sweep with real thread failures must not advance it); contacts/calendar failures mark the runpartialbut 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;--fullretries 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 onlyresourceName + 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:sweepCalendarcomparesstate.calendar_id(legacy state without it is treated as primary's) with the configuredcalendarId; on a mismatch it logs[google] calendar changed (<old> → <new>), discards the token and takes the windowed first-sync path (nosyncTokenon 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).enqueueLoopsExtractionenqueues EVERY eligible thread (newest first) under a waiting-depth budgetLOOPS_EXTRACT_ENQUEUE_CEILING − waitingthat counts only THIS source's waitingloops_extractjobs (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 indelayedduring a flapping provider cannot stack past the ceiling. With no chat provider (isAvailable('chat')false) the enqueue is skipped 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--fullsweep. Managed Google API sync uses journaled connector checkpoints; an unbound source is explicitlyconnector_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):writeGoogleStatewrites.google-source.jsonthroughatomicWriteFileSync(..., { mode: 0o600 })undermkdirPrivate(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 throughwritePrivateTemp: a stale<page>.tmpis removed withlstat(never followed; a stale.tmpdirectory fails that item withStale temporary path <path> is a directory; remove it and re-run the sync.), the temp file is createdwxat 0600 and fchmod-ed past the umask, imported, then renamed over the page; page directories come frommkdirPrivate(dirname(page), cfg.dir). 0600 is reasserted on every rewrite (unchanged pages are not rewritten). Managed pages get the same modes throughpublishMode(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-extractgates only the inline link/timeline extract), logs every skip reason and reportsloops_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 inloop-catchup.ts); a partial managed run publishes that state with its item holds (publishHoldsextra), never the Gmail cursor. An unmanaged--dry-runreturnsconnectorDryRunResultbefore any credential read or provider call, andrunGitHubSyncdoes the same; a managed brain refuses--dry-run.src/core/google/calendar-window.ts— which calendar events a google source keeps pages for:[now - historyDays, now + futureDays](g_future_days, 1..3650, defaultCALENDAR_HORIZON_DAYS= 60; the parsedfutureDaysleaf exists only when the key is set, so an unset knob leaves every existing source's connector identity unchanged), checked by the sweep itself on every list because a syncToken delta cannot carry timeMin/timeMax.CalendarSyncWindowis built once per sweep:side(start, end)follows Google's rule (an event isbeforewhen it ends at or before the floor,afterwhen it starts at or past the ceiling, unparseable dates stayinside);coverageStartMs(horizon, listedWholeWindow)says where the catch-up list for unchanged instances crossing the leading edge starts (none after a whole-window list, now for state withoutcalendar_horizon_ms, the recorded horizon once the ceiling is a day past it);startsInsideandstartsAfterare the--fullreconcile tests.planCalendarPagemaps one listed event to a page change (a cancellation removes its page anywhere, aged-out history is left as it is, a page past the horizon is removed, otherwise write after removing a copy at an older path).unlistedCalendarPagesreturns sweep pages (with anevent_id) starting inside the window that a complete--fulllist did not name;staleCalendarPagesadds the sweep pages starting at or past the ceiling, which no windowed list can name (#5442), and is what the--fullreconcile deletes through.people-calendar-sweep.ts(the contacts and calendar sweeps, peeled fromgoogle-source.ts) performs the changes withimportRendered/deletePageByRelPath, discards the catch-up list's sync token, advancescalendar_horizon_msonly after a list reached the ceiling, and sends reconcile deletes through the >200 mass-delete guard (a refusal marks the run partial). Its contacts cursor contract (#6324):contacts_sync_tokenandcontacts_person_fields(the mask that minted it) commit together after the whole sweep, never on abort or import failure; a recorded mask other thanCONTACT_PERSON_FIELDS(legacy state has none) drops the token for one full list; an expired orGoogleSyncTokenRejectedErrortoken gets one full list, whose failure propagates with the token nulled; a full list with no replacement token nullscontacts_sync_tokenwhen the mask changed and keeps it otherwise. A full list (#8906) checkpointscontacts_relistper clean page, stops atCONTACT_RELIST_PAGES_PER_RUN(10) pages (not partial), resumes under the same mask, restarts once on a stale saved token, clears with the token.resolveContactGroupsreads the directory once, when a listed contact first has a user group: a complete read replaces thecontact_groupscache, an incomplete one merges and logs, a failed one falls back to it; unresolved groups render as raw ids. Pinned bytest/contacts-phone-only-groups-6324.test.tsandtest/contacts-relist-checkpoint{-8906.slow,-managed-8906}.test.ts; the migration-176 test intest/connector-wave3.test.tsasserts the resumed legacy token is not reused. Tests:test/google-calendar-window.test.ts(pure rules),test/google-source-reconcile.test.ts(calendar window suite).src/core/google/file-modes.ts— detection and tightening for group/world-readable files gbrain wrote under a Google source directory outside~/.gbrain(inside it the 0700 home already protects them).scanGoogleFileModes(engine, { sourceIds? })reads non-archived Google sources, skips dirs inside the home (outsideGbrainHome, realpath-aware), and inspects only gbrain's own layout:.google-source.json*in the root, every recorded pagesource_pathunderemails/,calendar/,people/(malformed paths ignored), each page's.tmp, and the directories between the root and those pages. Each path islstat-ed component by component (a symlink anywhere on the path, another owner, or the wrong file type is counted inskipped, never followed); an entry is loose whenmode & 0o077.tightenGoogleEntry(root, entry)re-checks the path, opens the leafO_NOFOLLOW(O_DIRECTORYfor dirs), re-checks the owner on the fd andfchmodsmode & ~0o077, so a swap after the scan is refused, not followed; the user-chosen root is never in the candidate set.googleFileModesPreviewCommand/googleFileModesApplyCommandbuild thegbrain repair google-file-modes --source <id> [--apply]strings every surface prints. win32: scan returns nothing. Tests:test/google-file-modes-repair.test.ts.src/commands/google.ts—gbrain google connect|status|calendars|disconnect(+setupandattachmentsdispatch). Agent-first contract: every subcommand supports--jsonemitting{ ok, status, next_action: { command?, user_message? }, error? }(calendarsaddsaccount+calendars[]— id/summary/primary/accessRole — and carries thesources add --calendar-idtemplate innext_action.command; it resolves a lone connected account, exits 2 when there are none or several without--account, and throwsnot_connectedfor an unknown--account); human copy the harness must relay verbatim is fenced in[SHOW USER] ... [/SHOW USER]blocks; secret intake is--client-json <path|->(preferred) / envGOOGLE_CLIENT_ID+GOOGLE_CLIENT_SECRET/ TTY prompt, with raw argv flags accepted but documented last-resort; connect is an idempotent state machine (detects what exists, performs only the missing step — re-running is the documented fix for most errors). Credential commands are engine-free;statushas a best-effort linked-sources listing, whileattachments backfillrequires the explicitly selected local managed brain. Funnel events append to~/.gbrain/integrations/google/heartbeat.jsonl; account addresses are hashed to a short non-reversible tag, never raw. The vault entry'smeta.scopesrecords what Google ACTUALLY granted (the token response'sscope— the consent screen lets users uncheck scopes; the requested set is only the fallback), which is what lets downstream preflights reportscope_missinginstead of opaque per-sweep 403s.statusreports each linked source's calendar readability (google-calendar-status.ts, live probe unless--no-probe); an unreadable calendar makes the JSONok: falseand the exit 1.src/commands/google-calendar-status.ts— calendar readability per linked Google source forgbrain google status(#5012 item 9).sourceCalendarReadabilityreturns null for a source that does not sync Calendar; with a probe it makes one live read of the configured calendar, otherwise it reports thecalendar_unreadablerecord the last sweep stored in connector state (only when it names the current calendar id). An unreadable result carriescode: calendar_unreadable, the HTTP status andcalendarUnreadableFix(gbrain google calendars --account <a>,gbrain sources set-calendar <src> <calendar-id>). The sweep side ispeople-calendar-sweep.tsrecordCalendarUnreadable: a 403/404 fromevents.liststores the record, logs both commands and returns without failing the run; a successful list clears it. Tests:test/google-calendar-unreadable-5012.test.ts.src/commands/sources-set-calendar.ts—gbrain sources set-calendar <source> <calendar-id> [--yes]: a single-keyupdateSourceConfigwrite ofg_calendar_idon a Google source (usage error for another kind, a no-op when unchanged), then prints the sync to run. On a managed brain the connector cursor is keyed by the source's configuration, so when the source also syncs Gmail or Contacts it refuses withconfirmation_required(exit 3,ask_userfix with--yes) because the change re-reads their history.src/commands/doctor/checks/google-calendar.ts— doctorgoogle_calendar_readable(resolution operator, zero network): warns per Google source whose stored state recordscalendar_unreadablefor its current calendar, with a read-only agent fixgbrain google calendars --account <a> --jsonand theset-calendarcommand in the message; ok otherwise.src/commands/creds.ts—gbrain creds list|remove|export|import: the provider-agnostic vault surface; never prints a secret (list is always redacted). Provider-SPECIFIC connect flows live in their own commands. Export custody: a loud per-credential warning when a byo Google entry's consent screen is not known published-to-Production (its 7-day Testing expiry travels with the tokens).src/commands/google-setup.ts+google-setup-tail.ts— the one-command orchestrator behindgbrain google setup: connect (skipped when tokens exist) → source registration (skipped when registered) → first bounded sync under a wall-clock budget (the newest-first backfill floor means whatever lands is the NEWEST mail — exactly whatwaitingneeds; the remainder resumes on every later sync, and setup says so honestly) → the firstgbrain waitingdigest in the same session as consent. Split in two so the connect half stays engine-free. Every step idempotent; re-running resumes wherever the last run stopped.src/commands/doctor/checks/google-oauth.ts— thegoogle_oauthdoctor check: zero-network vault health (live refresh probes belong togbrain google status; doctor stays fast and offline-safe). fail: a connected account with an expired access token AND no successful refresh in >2 days (refresh is broken — revoked, rotated client, or the Testing-mode expiry already hit); warn: a consent screen not known Production whose last proof of life is ≥5 days old (the proactive day-6 re-auth demand, cheaper than a dead pipeline on day 8); ok: accounts healthy or nothing connected (the connector is optional, not an error).src/commands/doctor/checks/google-file-modes.ts— thegoogle_file_modesdoctor check (ops category; aWAVE_CHECKSentry insrc/commands/doctor/wave-checks.ts,resolution: 'repair', host-only so remote doctor never sees host paths). Detection only: warns per Google source dir outside~/.gbrainwithloose_files/loose_dirscounts and the exact preview and apply commands (details.sources[],details.count,repair: 'google-file-modes'); never prints file names, because Gmail page names embed subject words. A scan error iswarnwithcount: 'unknown', never ok. Remediation runs thegoogle-file-modesrepair kind.src/commands/migrations/v0_60_31-google-file-modes.ts— the Google file-mode notice phase of the v0.60.31 orchestrated migration (v0_60_31.ts, which runs it after the credential re-chunk phase).googleFileModesNoticePhaseprints one content-free line per Google source outside~/.gbrain(source id, dir, count of readable entries found now, preview and apply commands, thedocs/guides/google-connect.mdpointer) and sets the brain config markergoogle.file_modes_noticeso it prints once per brain (a brain with no such source writes no marker, keeping the phase a no-op on a fresh install); dry runs and brains without a config skip it. Detection only: nothing is chmod-ed.src/core/agent-install/+scripts/setup-in-agent.sh— Package-versioned non-root installation into a verified persistent root. Absolute launchers isolate ambient routing and credentials; local launchers pin the host brain and installed source, while thin-client launchers leave unqualified routing to the remote grant and preserve explicit CLI arguments. Receipts track ownership, pending enablement, non-secret failure codes, and an exact repair command, and repair retains database contents. Upgrades journal pending schema migrations before switching runtime metadata; retries use schema-only initialization without invoking host orchestration. Busy results remain structured and retryable without deleting live locks. Native instructions/routines remain pending until observed in the actual harness.src/core/backup/{archive,snapshot,quarantine,private-path}.ts— bounded full-PGLite snapshots with checksums, credential-reference exclusions and fresh-root restoration. Portable entry validation rejects traversal, Windows aliases and case/normalization/file-directory collisions independently of native confinement. Recorded path flavor controls nested managed-path rebasing; unrecognized absolute page origins stay unchanged with reconnect guidance. Hold the database lock, detect changing inventories, detach external roots and quarantine unfinished jobs without deleting spending evidence. Windows uses direct .NET file/directory security APIs through bounded built-in PowerShell, without cmdlets, to protect new empty work/root/archive-temp paths before payload writes. Readback requires the current owner, protected DACL and exact deduplicated owner-plus-SYSTEM full-control rules, inheritance and propagation; unavailable enforcement refuses without changing existing parents or source data. Never replace the source installation.backup-portability-native.serial.test.tschecks real restore, fresh-process reopen, failure preservation and platform-native access controls with an independent read-only ACL inspector.src/core/backup/preflight.ts— #6649: beforecreatePgliteBackuptakes the lock,pgliteBackupPreflightrefuses a flat or symlinked data dir (unmanaged_database_path) and an estimated archive overBACKUP_ARCHIVE_MAX_BYTES(backup_too_large:estimatedTarBytescounts tar headers and padding, plus managed files), both with the ask-user physical-copy runbook fix.backup.tsrenders those two codes as their own envelope (legacyreasonkept) instead ofstorage_error. Doctor'spglite_data_dir(backupSizeCheckinchecks/db-connection.ts) warns on a healthy PGLite brain from 75% of the cap.test/backup-preflight-6649.serial.test.tsuses sparse files and runs the restore drill.src/core/harness/registry.ts— Canonical adapter identities, supported transports, credential-delivery mechanisms, guide links and dated evidence; legacy connection/register vocabularies derive their facts here.scripts/build-harness-docs.tsemits the user-facing adapter reference. Amanualadapter such ashermes(stdio,docs/mcp/HERMES.md) installs aspendingwith its guide; no adapter claims a runtime-tested session without dated evidence.src/core/harness/credentials.ts+delivery.ts+install.ts— Private credential handoff and host delivery journal, ownership-preserving native configuration and isolated thin launchers. A committed active client and matching current secret are prerequisites for recovery. Machine handoffs preserve optional POST/Basic authentication methods. Native setup is a distinct nested-client artifact; metadata reads never access journals or SDK client objects containing hashes. Configuration removal and server revocation are separate actions.readCredentialsthrowsPlainBearerKeyFilefor a file that holds one bare bearer key (amember-keys/<member>.key) instead of a handoff, soharness-connect.tscan print the bearer-tokengbrain connectcommand for it (test/connect-member-key-gbra585.test.ts).