Files
Garry Tan b36ec092b0 v0.47.0.0 feat(google-loops): Gmail-first open-loop engine — connector, credential vault, gbrain waiting (#4590)
* feat(creds): generic credential vault + Google OAuth client + hosted-relay stub

src/core/creds/: provider-agnostic CredentialVault (0600 file backend, DB
backend interface for hosted), typed CredentialError catalog (problem/cause/
fix/doc_url per failure), Google OAuth2 client (PKCE loopback + headless
paste-back; invalid_grant sub-classified incl. the 7-day Testing-mode expiry
heuristic and clock-skew detection), gbrain.io relay client (feature-gated,
zero-retention claim protocol; its test suite is the server conformance
spec), and scrypt+AES-GCM export bundles for hosted-upgrade transfer.
No googleapis dependency; every client is fetchImpl-injectable.

* feat(google): Gmail/Calendar/People API clients + pure page renderers

GoogleApiClient with 401-refresh-retry, Retry-After honoring, and
api_not_enabled deep links (project number extracted from the client id);
GmailClient (history deltas, thread fetch with MIME walk + quoted-reply
trim), CalendarClient/PeopleClient (syncToken with 410 recovery).
Renderers are pure: thread pages keyed on the first message (stable slugs),
code-generated Gmail deep links via the emailCitation scaffold, noise/
signature rules from recipes/email-to-brain.md implemented as code.

* feat(loops): open_loops substrate + deterministic thread-state detector

Migration v142: open_loops (dedup per source, close-by-state-transition,
fact_id projection) + loop_suppressions (gbrain loops mute). Store rides
engine.executeRaw with identical SQL on both engines (parity by
construction); timestamps normalized to ISO strings; evidence binds through
$N::text::jsonb. Detector: zero-LLM thread-state machine — unanswered
inbound (they wait on you, 24h grace, To:-only) / unanswered outbound (you
wait on them, 72h grace, question heuristic); noise/list/self/CC-only
excluded; reply auto-closes; suppression never closes existing loops.
Pinned by a 45-case labeled precision corpus.

* feat(google): --kind google source + sync orchestration + LLM loop extraction

sources add <id> --kind google --account <email> (vault-pointer config, no
secrets; CLI-only registration like github). runGoogleSync dispatches from
performSyncInner: contacts -> calendar -> gmail (aliases exist before
counterparty resolution), per-service cursors commit only on full success,
and the initial Gmail backfill is explicitly resumable (newest-first floor
cursor, batch-committed, never advanced past a failed thread; 404 threads
skip instead of wedging the delta cursor).

loops_extract minion job (gateway-refresh registered): ONE model call per
recent thread projects commitments into open_loops + a facts row
(kind=commitment, fence-first) + typed owes_to/awaiting_reply_from edges
(added to KNOWN_LINK_TYPES + the base pack). All-or-nothing parse barrier
with calendar-real due-date validation; injection-hardened; trickle + 30-day
window only; kill switch loops.extraction_enabled; 50/sweep cap.

* feat(loops): open_loops ops + gbrain waiting/loops/google/creds CLI + doctor check

open_loops (scope read, fail-closed evidence redaction for remote callers;
quotes/deep-links/text digest trusted-local only), loops_close (expires the
projected fact), loops_mute. gbrain waiting refuses on stale google sources
and names the exact fix; gbrain google connect/setup/status/disconnect
implements the [SHOW USER] agent protocol (GCP checklist, client_secret.json
intake incl. stdin, two-interaction setup, funnel heartbeats); gbrain creds
is the provider-agnostic vault surface. Entity cards surface loop-backed
open_threads with additive optional fields (direction/due/counterparty/
status/loop_id — MEMORY_VERBS v1 additive-legal). google_oauth doctor check
warns at day ~6 of a Testing-mode consent screen, before Google kills the
tokens at day 7. All exit codes route through setCliExitVerdict.

* docs(google-loops): skill, rewritten recipes, guides, relay design doc, plugin regen

skills/google-loops (harness contract: relay [SHOW USER] verbatim, exactly
two user interactions, secrets never in argv); recipes/credential-gateway +
email-to-brain + calendar-to-brain rewritten to drive the real commands;
docs/guides/google-connect.md (setup + the full typed error catalog) and
open-loops.md; docs/designs/HOSTED_OAUTH_RELAY.md (the gbrain.io team spec:
confidential-client relay, zero-retention claims, CASA track); briefing +
daily-task-prep + executive-assistant now call gbrain waiting; KEY_FILES
cluster entries; plugin tree regen (66 skills, google-loops bundled with
recorded starter gaps); module-size ratchet bumps; TODOS follow-ups filed
(relay server + CASA clock, Pub/Sub push, fulfillment-by-reply, providers).

* test(loops): classify the three loop ops in the remote privacy sweep registry

open_loops → 'ok' (fail-closed redacted envelope for remote callers);
loops_close / loops_mute → 'error' on the sweep's generic empty invocation
(required params). Redaction + remote-scope semantics pinned in
test/ops-loops.test.ts.

* fix: pre-landing review fixes (specialist army pass)

Security: loops_mute scalar-scope bypass closed (remote writes stay strictly
inside the caller's grant, mirroring loops_close) and both write-op denials
now throw enumerated OperationErrors instead of success-shaped payloads;
--via relay base requires https and resolves 'gbrain.io' only through the
GBRAIN_OAUTH_RELAY_URL gate; full-URL pastes must carry the matching OAuth
state; delete/reconcile rmSync paths get the same containment guard as
writes.

Performance: the Gmail backfill lists page-BOUNDED (partialOk) so a >50k-
message window can't wedge on the pagination cap; open_loops gains a
(source_id, thread_id) partial index; deepLinksFor is source-scoped onto
the composite pages index; HTML bodies pre-truncate before conversion.

Contract: creds/waiting/loops --json envelopes carry consistent ok/status
(+ export --json, show honors --json, status exit-code parity across output
modes); open_loops reports a truncated marker at the 500-row fetch ceiling;
the EntityOpenThread additive fields land in the response-shape registry +
MEMORY_VERBS_v1.md (loop-backing subsection documents the kind derivation).

Durability: engine migration copies open_loops + loop_suppressions (manual
mutes/closes are not re-derivable); sources remove cleans g_managed dirs.

Maintainability: shared deriveSourceId (connect hint can't diverge from
setup), pending two-step flow honors step-1 scopes, setup no longer dies on
tail-only flags, single connect_error funnel emission, dead --yes flag and
GBRAIN_OAUTH_RELAY_ENABLE gate removed, service-list/sha8 dedup, stale
comments fixed, doc_url anchors land on #troubleshooting.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: red-team hardening wave + coverage-gap tests + 4 surfaced CLI/op bugs

Red-team fixes (batches A-E): tri-state thread-loop verdicts (turn-flip-only
closes; grace/noise/suppression are holds, not closes), gmailSweepOk gating of
last_sync_at, per-group source_id for entity-card context, migrate-engine
sequence setval, calendar event_id keying for reschedules, scope preflight +
scope_missing tracing, vault O_EXCL lock (EEXIST-only contention, parent-dir
mkdir, post-network re-read merge), atomic state writes + .corrupt quarantine,
bounded history-fallback with conditional re-anchor, markStaleLoops overdue
now also requires 14d inactivity, loops idempotency keys fold the source.

Coverage-gap test wave: 4 new suites (loops CLI, google connect state machine,
oauth doctor, source reconcile) + 7 extended (relay-client, clients, redirect,
materialize, extract-run, ops-loops, engine-parity open_loops section).

Bugs the wave surfaced, fixed here:
- gbrain waiting / loops read paths were silently scoped to source 'default',
  hiding every loop in a real google source; they now span the brain
  (__all__, trusted local) with --source to narrow, and loops mute resolves
  the single google source instead of writing a useless 'default' suppression.
- open_loops now fail-closes an unscoped remote caller (permission_denied)
  instead of spanning every source, per the trust invariant.
- loops show no longer renders a literal "undefined" status (view carries
  status); done/drop --json keeps the envelope status ('closed') and moves the
  row's terminal state to loop_status instead of clobbering.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* v0.47.0.0 feat(google-loops): Gmail-first open-loop engine — version bump, CHANGELOG, manifest lockstep

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: raise sources.ts module-size ceiling to 1876 (v0.47 google source-kind flags)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: adversarial-review wave — sweep honesty, close-guard, vault/OAuth hardening

Six High findings from the fresh-context adversarial pass, all fixed with
regression pins, plus seven mediums:

- A persistently-failing Gmail thread can no longer wedge the pipeline while
  the staleness gate reads fresh: sweepGmail reports thread-level failures via
  its return value (failed sweeps never stamp last_sync_at) and a per-thread
  fail ledger skips a thread after 3 consecutive failures — loudly, with
  --full retrying it.
- Manual `gbrain loops done/drop` survives sweeps: the upsert's reopen now
  requires genuinely newer activity, so label-only history touches and
  same-content re-extraction leave closed loops closed (upsertOpenLoop
  returns `applied`).
- Vault lock fail-open paths no longer delete another process's live lock.
- The vault persists the scopes Google ACTUALLY granted (consent lets users
  uncheck) so narrowed grants surface as scope_missing, not opaque 403s.
- Contact deletion tombstones (no names attached) and renames resolve by
  google_contact_id in the DB — deletes land, renames don't strand pages.
- The history-expired fallback anchors before listing (zero-gap ordering).
- Mediums: freshness gate fails toward stale on error; LLM evidence quotes
  verified verbatim against the thread (fabricated quotes dropped, edge label
  falls back to the commitment text); two-step connect keeps the --account
  binding, clears consumed pending state, and survives corrupt timestamps;
  replacing the OAuth client warns about client-bound sibling refresh tokens;
  malformed relay expiry can't crash connect; creds import arg parsing skips
  valued-flag values; suppression cache keyed per engine; doctor treats a
  missing expiry as unknown, not expired.

INVESTIGATE-class findings (auto-reply/spoof close precision, model-worded
commitment dedup, extreme-volume history caps, per-loop staleness markers)
filed as P3 follow-ups in TODOS.md.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: full-suite gate wave — skill conformance, resolver triggers, recipe pin, pack bump, flag registry

The fresh evidence run's in-branch failures, all six fixed:
- skills/google-loops/SKILL.md gains the required Output Format and
  Anti-Patterns sections and quotes its frontmatter triggers so the
  RESOLVER round-trip parser sees them.
- gbrain-base-v2 bumps to 1.2.0 for the two open-loop link verbs
  (owes_to/awaiting_reply_from); schema-cli + lens-pack pins updated
  (15 → 17 link verbs).
- The calendar-to-brain recipe test now pins the recipe's NEW shape
  (native connector: no repo-relative output_paths, command probe instead
  of a mismatched heartbeat id).
- Flag registry regenerated for the new --source flags on waiting/loops.
- Plugin tree + llms bundles regenerated for the skill edit.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: post-release audit for v0.47.0.0 — late-wave behavior into guides, KEY_FILES, README discoverability

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: cross-model doc-review fixes — precise staleness/close semantics, error-catalog completeness, two CHANGELOG over-sell corrections

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(cli): OPEN LOOPS section in gbrain --help + vault-readiness TODO

/document-release flagged that the top-level help listed none of the four new
commands (google, waiting, loops, creds); the recipes' vault-blind readiness
check is filed as a P2 TODO (code fix in integrations.ts, not a doc fix).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: post-ship audit round 2 — AGENTS.md waiting task, hosted-relay design-doc discoverability

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: cross-model doc-review round 3 — freshness-gate precision, doctor-warning honesty, cold-start native path

Six gaps from the independent doc review, all verified against src first:
- The "fully-successful sweep" freshness claim overstated the gate: the
  last_sync_at stamp is gated on the GMAIL sweep (KEY_FILES + guide reworded
  to the exact predicate; contacts/calendar failures mark partial only).
- The doctor google_oauth warning was over-promised: it fires when a
  Testing-mode account goes 5+ days WITHOUT a successful refresh — an
  actively-syncing account gets no pre-warning. Guide, skill, CHANGELOG
  wording, and both recipes (which still said "day ~6") aligned.
- cold-start no longer forbids OAuth outright: the native connector is the
  sanctioned path (tokens in gbrain's vault, never in the agent's context),
  consistent with the skill's own safety principle; ClawVisor and Takeout
  remain as alternatives. README cold-start paragraph matches.
- gbrain google --help now lists --timeout-ms and setup's --account /
  --history-days / --sync-budget-ms (the guide pointed at --help for flags
  it didn't show).
- The relay design doc's error-code row dropped its stale count and gained
  relay_disabled.
- --consent-state production documented as a re-consent run (pair with
  --reauth), not a metadata-only stamp.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: CI gate wave — GCM tag length, bigint-id parity, cross-engine hot-memory cache leak, skills lockfile

Four CI failures on PR #4590, each fixed at the root:

- semgrep (gcm-no-tag-length): bundle import now pins authTagLength: 16 on
  createDecipheriv and rejects truncated tags as tampering — without the pin,
  Node accepts attacker-supplied tags down to 4 bytes, weakening forgery
  resistance. Regression test added.

- Tier 1 engine parity (open_loops round-trip): postgres.js returns
  BIGSERIAL/BIGINT columns as STRINGS while PGLite returns numbers, so
  close-by-id equality (`closed.id === first.id`) and `loops show <id>`
  silently failed on real Postgres only. normalizeRow now coerces
  id/fact_id/confidence.

- test (7) remote-privacy-sweep phase R: the hot-memory meta cache
  (src/core/facts/meta-hook.ts) keyed on source/tier/session but NOT the
  engine — one process serving two brains (test shards, hosted multi-tenant,
  mounts) could serve brain A's cached facts to brain B's caller within the
  30s TTL. CI's shard packing put the verbs-conformance suite seconds before
  the sweep and its fact surfaced in the sweep's _meta while the expected
  markers vanished. The key now folds a WeakMap-issued engine serial;
  bumpHotMemoryCache prunes engine-agnostically (safe over-invalidation).
  Cross-engine isolation pinned; the expired-eviction pin updated to
  same-engine semantics (pre-existing bug surfaced by this branch's shard
  reshuffle, v0.45.7-era).

- verify (check:skills-manifest): skills/skills.lock.json regenerated after
  the round-3 skill doc edits (plugin-tree regen alone does not cover it).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: post-merge regen — plugin trees, template repo, skills lockfile, flag registry, llms bundles

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: post-merge regen + v143 renumber artifacts — schema mirrors, plugin trees, skills lockfile, flag registry, llms

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: post-merge regen — plugin trees, template repo, skills lockfile, flag registry, llms bundles

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(google): pluggable access modes + open_loops scope params + honest no-source copy

Generic Google access (--access vault|command|env): a stack that already
holds Google access — a Google CLI with its own auth store, gcloud, or a
credential gateway that mints tokens — can drive the native source and the
open-loop engine without gbrain's OAuth flow. CommandAccessProvider runs a
local token-printing command (bare token or JSON w/ expiry; cached with a
60s margin; 30s timeout); EnvAccessProvider reads a live token from a named
env var. Non-vault modes synthesize the identity entry (scope preflight
trusts the configured services; send-as aliases fetched live best-effort).
Secrets never enter sources.config (command string / env NAME only; keys
unreachable over MCP). Two typed catalog codes: access_command_failed,
access_env_missing. The --token-env flag is parsed once and routed by kind
(an earlier draft shadowed github's flag; regression-pinned).

open_loops gains source_id / all_sources through the canonical grant
resolver, tightened for remote callers (loops carry no visibility tiering,
so a scalar-scoped caller cannot widen via source_id — summaries derive
from private email). An MCP client whose transport is bound to another
source can now reach the google source's loops within its grant.

gbrain waiting on a brain with no google source in scope now says the
engine has nothing to read (naming both connect paths) instead of a false
"You are clean"; results carry no_google_sources.

63 new tests (access providers, command/env-mode sweeps end-to-end, scope
params incl. scalar-grant denial, CLI flag validation, no-source copy).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: post-merge regen — plugin trees, template repo, skills lockfile, flag registry, llms bundles

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: post-merge regen — schema mirrors (open_loops → v144), plugin trees, skills lockfile, flag registry, llms

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-27 17:33:07 -07:00
..