Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
34.8 KB
Raw Blame

Google connector + open-loop engine (key files cluster)

Subsystem index.

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.ts retains these receipts and google-render.ts stores them in connector-owned gmail_attachment_receipts frontmatter alongside readable per-message summaries.

  • src/core/google/attachment-backfill.ts + src/commands/google-attachments.ts — google attachments backfill --source previews imported-thread scope without Google calls; explicit --yes runs 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.ts cover 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 under src/core/creds/providers/). Two backends behind one frozen interface: FileVaultBackend (~/.gbrain/credentials.json, 0600, atomic writes — the CLI/self-host default) and the DB-backed EngineVaultBackend shape hosted gbrain.io implements. Custody rules: secrets live ONLY in the vault (never the config plane; sources.config stores a credential-id pointer, mirroring how github sources store an env NAME); list() returns redacted metadata only. No CLI imports — prompts live in src/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 (--json envelopes). Single source of truth for the troubleshooting table in docs/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 with access_type=offline&prompt=consent so a refresh token is always minted; client_ref on the vault entry routes refresh (byo → direct against the Google token endpoint with the user's own client; hosted-relay → through the relay). invalid_grant is sub-classified into the catalog: clock skew (local clock vs Google's Date response header), the 7-day Testing-mode expiry (age heuristic on last_refresh_ok_at/connected_at), and plain revocation. GOOGLE_SERVICE_SCOPES is 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 fixed PASTE_REDIRECT_URI fails to load, the user pastes the full address-bar URL back) and is auto-selected by sniffHeadless (SSH/WSL/container/no-display). Google's device-code flow is NOT an option — Gmail/Calendar/Contacts scopes are excluded from it; don't re-litigate.

  • src/core/creds/relay-client.ts — the typed CLIENT half of the gbrain.io zero-retention consent relay (createSession → user clicks the consent URL → poll a one-time claim; the relay deletes tokens on first successful claim or at session TTL). Inert unless GBRAIN_OAUTH_RELAY_URL is set (unset = the BYO flow, which always works). test/creds-relay-client.test.ts is the server conformance spec — a server that round-trips those fixtures is compatible.

  • src/core/creds/export.ts — versioned passphrase-encrypted credential bundles (scrypt N=2^15, r=8, p=1 → AES-256-GCM) for machine moves and hosted-upgrade transfer. A bundle carries selected vault entries PLUS the provider client records they depend on (Google refresh tokens are bound to the client that minted them — moving one without the other produces dead tokens). Format frozen here; hosted's import endpoint conforms to it.

  • src/core/google/types.ts — pure data shapes for the google source kind: normalized Gmail/Calendar/People payloads, GoogleSourceConfig (account pointer, services, historyDays, managed dir), and the GoogleSourceState cursor file persisted at <managed dir>/.google-source.json (gmail history id, downward-moving backfill floor, per-service syncTokens). No I/O. Exports DEFAULT_CALENDAR_ID = 'primary' (the Calendar API's own alias; every 'primary' literal in google-clients/google-source/sources/sources-ops resolves through it) and GoogleSourceConfig.calendarId (one calendar per source). GoogleSourceState.calendar_id records which calendar calendar_sync_token was minted for — a token is only valid against its own calendar; absent on legacy state, which is therefore primary's. GoogleSourceState.calendar_horizon_ms is the ceiling of the last calendar list that reached it (calendar-window.ts); absent on state saved before it existed. GoogleSourceState.contacts_person_fields (#6324) is the field mask contacts_sync_token was minted under and contacts_relist (#8906) the full re-list's resume page. contact_groups caches the group directory (resource name → display name) and is never authoritative on its own. 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 disabled API → GoogleApiDisabledError and insufficient scope → scope_missing (API access), 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); a connections 400 with a pageToken is GoogleCursorExpiredError (#8906, listConnectionsPage reads 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; 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 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, and it and the held-thread retries settle a thread older than cutoffMs (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 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 (only the command/env NAME does). Honesty invariants: last_sync_at is gated on the GMAIL sweep's success (it feeds gbrain waiting's staleness gate; 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 (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 --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 (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. An unmanaged --dry-run returns connectorDryRunResult before any credential read or provider call, and runGitHubSync does 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, default CALENDAR_HORIZON_DAYS = 60; the parsed futureDays leaf exists only when the key is set, so an unset knob leaves every existing source's connector identity unchanged), checked by the sweep itself on every list because a syncToken delta cannot carry timeMin/timeMax. CalendarSyncWindow is built once per sweep: side(start, end) follows Google's rule (an event is before when it ends at or before the floor, after when it starts at or past the ceiling, unparseable dates stay inside); coverageStartMs(horizon, listedWholeWindow) says where the catch-up list for unchanged instances crossing the leading edge starts (none after a whole-window list, now for state without calendar_horizon_ms, the recorded horizon once the ceiling is a day past it); startsInside and startsAfter are the --full reconcile tests. planCalendarPage maps one listed event to a page change (a cancellation removes its page anywhere, aged-out history is left as it is, a page past the horizon is removed, otherwise write after removing a copy at an older path). unlistedCalendarPages returns sweep pages (with an event_id) starting inside the window that a complete --full list did not name; staleCalendarPages adds the sweep pages starting at or past the ceiling, which no windowed list can name (#5442), and is what the --full reconcile deletes through. people-calendar-sweep.ts (the contacts and calendar sweeps, peeled from google-source.ts) performs the changes with importRendered/deletePageByRelPath, discards the catch-up list's sync token, advances calendar_horizon_ms only after a list reached the ceiling, and sends reconcile deletes through the >200 mass-delete guard (a refusal marks the run partial). Its contacts cursor contract (#6324): contacts_sync_token and contacts_person_fields (the mask that minted it) commit together after the whole sweep, never on abort or import failure; a recorded mask other than CONTACT_PERSON_FIELDS (legacy state has none) drops the token for one full list; an expired or GoogleSyncTokenRejectedError token gets one full list, whose failure propagates with the token nulled; a full list with no replacement token nulls contacts_sync_token when the mask changed and keeps it otherwise. A full list (#8906) checkpoints contacts_relist per clean page, stops at CONTACT_RELIST_PAGES_PER_RUN (10) pages (not partial), resumes under the same mask, restarts once on a stale saved token, clears with the token. resolveContactGroups reads the directory once, when a listed contact first has a user group: a complete read replaces the contact_groups cache, an incomplete one merges and logs, a failed one falls back to it; unresolved groups render as raw ids. Pinned by test/contacts-phone-only-groups-6324.test.ts and test/contacts-relist-checkpoint{-8906.slow,-managed-8906}.test.ts; the migration-176 test in test/connector-wave3.test.ts asserts 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 page source_path under emails/, calendar/, people/ (malformed paths ignored), each page's .tmp, and the directories between the root and those pages. Each path is lstat-ed component by component (a symlink anywhere on the path, another owner, or the wrong file type is counted in skipped, never followed); an entry is loose when mode & 0o077. tightenGoogleEntry(root, entry) re-checks the path, opens the leaf O_NOFOLLOW (O_DIRECTORY for dirs), re-checks the owner on the fd and fchmods mode & ~0o077, so a swap after the scan is refused, not followed; the user-chosen root is never in the candidate set. googleFileModesPreviewCommand/googleFileModesApplyCommand build the gbrain repair google-file-modes --source <id> [--apply] strings every surface prints. win32: scan returns nothing. Tests: test/google-file-modes-repair.test.ts.

  • src/commands/google.ts — gbrain google connect|status|calendars|disconnect (+ setup and attachments dispatch). Agent-first contract: every subcommand supports --json emitting { ok, status, next_action: { command?, user_message? }, error? } (calendars adds account + calendars[] — id/summary/primary/accessRole — and carries the sources add --calendar-id template in next_action.command; it resolves a lone connected account, exits 2 when there are none or several without --account, and throws not_connected for an unknown --account); human copy the harness must relay verbatim is fenced in [SHOW USER] ... [/SHOW USER] blocks; secret intake is --client-json <path|-> (preferred) / env GOOGLE_CLIENT_ID+GOOGLE_CLIENT_SECRET / TTY prompt, with raw argv flags accepted but documented last-resort; connect is an idempotent state machine (detects what exists, performs only the missing step — re-running is the documented fix for most errors). Credential commands are engine-free; status has a best-effort linked-sources listing, while attachments backfill requires the explicitly selected local managed brain. Funnel events append to ~/.gbrain/integrations/google/heartbeat.jsonl; account addresses are hashed to a short non-reversible tag, never raw. The vault entry's meta.scopes records what Google ACTUALLY granted (the token response's scope — the consent screen lets users uncheck scopes; the requested set is only the fallback), which is what lets downstream preflights report scope_missing instead of opaque per-sweep 403s. status reports each linked source's calendar readability (google-calendar-status.ts, live probe unless --no-probe); an unreadable calendar makes the JSON ok: false and the exit 1.

  • src/commands/google-calendar-status.ts — calendar readability per linked Google source for gbrain google status (#5012 item 9). sourceCalendarReadability returns null for a source that does not sync Calendar; with a probe it makes one live read of the configured calendar, otherwise it reports the calendar_unreadable record the last sweep stored in connector state (only when it names the current calendar id). An unreadable result carries code: calendar_unreadable, the HTTP status and calendarUnreadableFix (gbrain google calendars --account <a>, gbrain sources set-calendar <src> <calendar-id>). The sweep side is people-calendar-sweep.ts recordCalendarUnreadable: a 403/404 from events.list stores 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-key updateSourceConfig write of g_calendar_id on 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 with confirmation_required (exit 3, ask_user fix with --yes) because the change re-reads their history.

  • src/commands/doctor/checks/google-calendar.ts — doctor google_calendar_readable (resolution operator, zero network): warns per Google source whose stored state records calendar_unreadable for its current calendar, with a read-only agent fix gbrain google calendars --account <a> --json and the set-calendar command 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 behind gbrain 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 what waiting needs; the remainder resumes on every later sync, and setup says so honestly) → the first gbrain waiting digest 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 — the google_oauth doctor check: zero-network vault health (live refresh probes belong to gbrain 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 — the google_file_modes doctor check (ops category; a WAVE_CHECKS entry in src/commands/doctor/wave-checks.ts, resolution: 'repair', host-only so remote doctor never sees host paths). Detection only: warns per Google source dir outside ~/.gbrain with loose_files/loose_dirs counts 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 is warn with count: 'unknown', never ok. Remediation runs the google-file-modes repair 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). googleFileModesNoticePhase prints one content-free line per Google source outside ~/.gbrain (source id, dir, count of readable entries found now, preview and apply commands, the docs/guides/google-connect.md pointer) and sets the brain config marker google.file_modes_notice so 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.ts checks 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: before createPgliteBackup takes the lock, pgliteBackupPreflight refuses a flat or symlinked data dir (unmanaged_database_path) and an estimated archive over BACKUP_ARCHIVE_MAX_BYTES (backup_too_large: estimatedTarBytes counts tar headers and padding, plus managed files), both with the ask-user physical-copy runbook fix. backup.ts renders those two codes as their own envelope (legacy reason kept) instead of storage_error. Doctor's pglite_data_dir (backupSizeCheck in checks/db-connection.ts) warns on a healthy PGLite brain from 75% of the cap. test/backup-preflight-6649.serial.test.ts uses 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.ts emits the user-facing adapter reference. A manual adapter such as hermes (stdio, docs/mcp/HERMES.md) installs as pending with 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. readCredentials throws PlainBearerKeyFile for a file that holds one bare bearer key (a member-keys/<member>.key) instead of a handoff, so harness-connect.ts can print the bearer-token gbrain connect command for it (test/connect-member-key-gbra585.test.ts).

Continue this subsystem · More entries.