Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(loops): warn on partially stale sources
masashiono06118e71545c09b5
diff --git a/docs/architecture/key-files/google-and-loops.md b/docs/architecture/key-files/google-and-loops.mdindex 604e19f982..6cbee5aa06 100644--- a/docs/architecture/key-files/google-and-loops.md+++ b/docs/architecture/key-files/google-and-loops.md@@ -28,10 +28,10 @@ Historical Gmail repair selects explicit nested MIME metadata fields, excluding- `src/core/google/loop-detect.ts` — the zero-LLM thread-state machine: last substantive message inbound + user in To: + unanswered ≥24h → `unanswered_inbound`; last outbound + contains a question + unanswered ≥72h → `unanswered_outbound` (both grace windows measured from the oldest owed message in the trailing run since the last turn flip, so a nudge or follow-up never restarts the clock — gbrain-evals N7-1); a reply closes the loop (`closed_by: reply_detected`), except that my acknowledgement-only reply to their question (`isAcknowledgementOnly`: "Thanks!", "Got it, thanks.") is dropped from the substantive run so it neither closes nor restarts the loop (N7-2); `asksQuestion` ignores a `?` inside a link (N7-7); each spec carries `openedMs`, the oldest obligation-carrying message in the run, which the apply step writes as `opened_at` (N7-6). Precision IS the product: noise senders, list mail (List-Unsubscribe), CC-only delivery, FYI/forwards without a question, self-threads, and muted senders/threads never open loops — pinned by the labeled fixture corpus in `test/google-loop-detect.test.ts` (every false-positive class gets a fixture before its fix). Pure verdict function + a thin apply step called per touched thread from the sync; the apply step must never fail the sync. A grace-window hold returns `held: { untilMs, spec }` (the loop it would open) and `applyThreadLoopVerdict` returns the verdict, so the sweep can record it (`loop-catchup.ts`); `openDueGraceHold` opens a stored spec after re-reading suppressions.- `src/core/google/loops-extract.ts` — the LLM half of the open-loop engine: ONE extractor per recent thread page projects each commitment into THREE substrates in the same pass — the `open_loops` row (dedup `commit:<sha8>`), a facts row via writeSingleFact (kind=commitment, fence-first, deduped; its id lands on `open_loops.fact_id` so entity cards / recall / context_pack see the commitment through existing read paths with zero new read code), and a typed edge thread-page → person-page (`owes_to` / `awaiting_reply_from`) for relational search. `extract_facts` never runs separately on google-source email pages. Guardrails: injection-hardened input, ALL-or-nothing parse barrier (a malformed model response writes NOTHING), a structural eligibility gate (`loopExtractionEligibility` — Gmail labels, `List-Unsubscribe`, calendar part, who wrote the message; no vendor lists) plus the per-source waiting-depth enqueue budget (`LOOPS_EXTRACT_ENQUEUE_CEILING`, a spend backstop — see `google-source.ts`), only the last `LOOPS_EXTRACT_WINDOW_DAYS` (30) of mail (the deep backfill is never extracted), kill switch `loops.extraction_enabled` (default ON for google sources). Suppressions gate the lane before any model/facts/edge write: a muted thread id, or a muted SENDER — `fm.from` ∪ `fm.senders`, every address that AUTHORED a message, so a muted counterparty who wrote earlier in the thread still suppresses — returns `reason: 'suppressed'`; recipients/CC never count (muting one person must not hide everyone else's commitments in a group thread, and an outside sender must not be able to dodge extraction by CC'ing a muted address). Pages without a `senders:` field fall back to `fm.from` alone until their next re-render. Eligibility computes the substantive (non-noise, non-calendar) message set FIRST and `owner_participated` requires the owner to have written a SUBSTANTIVE message — a pure-calendar thread the owner RSVP'd to stays `no_substantive_messages`. When the chat provider is unavailable, `runLoopsExtract` throws `LoopsExtractRetryableError` (reason `llm_unavailable`) rather than returning a skipped result: a completed no-work row would hold the revision-keyed idempotency slot forever, while a retried-then-dead row frees it so the same revision re-enqueues on the next sweep. On a managed brain `managedFactWritePreflight` checks the managed fact authority and canonical owner before chat (an unaccepted writer refuses with `writer_coordinator_required`), and the commitment fact publishes through writeSingleFact's coordinator path; disabled, missing-page and suppressed cases retain their existing no-work outcomes.- `src/core/loops/loops-store.ts` — SQL accessors for the `open_loops` + `loop_suppressions` tables over `engine.executeRaw` with IDENTICAL SQL text on both engines (parity by construction, the sources-ops.ts pattern — no per-engine method twins). JSONB discipline: evidence binds through `$N::text::jsonb`, never a bare `::jsonb` cast over JSON.stringify. Loops close by state transition, never delete: reply-driven auto-close flips status to `done` and stamps `closed_by`, keeping the audit trail. `openedAt` sets `opened_at` (default now()); an open row keeps the earlier of its stored and incoming value, a reopened row takes the incoming one. The upsert's DO UPDATE carries a manual-close guard in its WHERE: a closed row (done/dropped/stale) only reopens on GENUINELY newer activity, so a routine sweep re-seeing the same thread never resurrects a hand-closed loop, and the staleness auto-close (`closed_by: 'staleness'`) is likewise guarded against the upsert's reopen. `removeSuppression(engine, sourceId, kind, value)` is the exact inverse of the mute write — deletes the one `(source_id, kind, value)` row with the same lower-casing, returns `{removed: boolean}` (false = was not muted, callers treat it as a no-op success), and never reopens loops: suppressions gate NEW detection only.-- `src/core/ops/loops.ts` — the op surface: `open_loops` (read), `loops_close` (write), `loops_mute` (write). `loops_close` retires a commitment loop's fact through `persistence/loop-fact-retirement.ts` and returns `{ closed, id, status, fact_expired, retryable, reason? }` from the real publication outcome; a loop already closed whose fact is still active re-attempts the retirement. `open_loops` is deliberately NOT localOnly (hosted serves it over HTTP to the authenticated owner); instead it applies fail-closed evidence redaction for `ctx.remote !== false` — counts, counterparty, summary, due date only; verbatim quotes, Gmail deep links, and the injectable `text` digest are trusted-local only. Ranking and rendered ages use one reference time, `as_of` (ISO, default now, echoed in the grouped result; `gbrain waiting --as-of`), so a published order is reproducible (N7-5). The result carries the google sources' last-successful-sync ages + a `stale` flag (>24h) so callers can refuse stale-but-confident output on a trust-critical surface. Per-call scope params `source_id`/`all_sources` resolve through `resolveRequestedScope` (an MCP client bound to another source can reach the google source's loops; remote callers stay in-grant, out-of-grant `source_id` is denied); a scope with NO google source returns `no_google_sources: true` and the digest says the engine has nothing to read instead of a false "You are clean". Scope is fail-closed too: an UNSCOPED remote `open_loops` read is refused outright (the op must not rely on transports to enforce it — an unscoped remote read would span every source), and the write ops (`loops_close`, `loops_mute`, `loops_unmute`) require a single-source remote scope that matches the caller's grants — trusting a caller-supplied `source_id` for a remote write would let any remote client plant (or lift) suppression rows cross-source; `loops_unmute` reverses a suppression via `removeSuppression` and reports `{removed}` honestly.+- `src/core/ops/loops.ts` — the op surface: `open_loops` (read), `loops_close` (write), `loops_mute` (write). `loops_close` retires a commitment loop's fact through `persistence/loop-fact-retirement.ts` and returns `{ closed, id, status, fact_expired, retryable, reason? }` from the real publication outcome; a loop already closed whose fact is still active re-attempts the retirement. `open_loops` is deliberately NOT localOnly (hosted serves it over HTTP to the authenticated owner); instead it applies fail-closed evidence redaction for `ctx.remote !== false` — counts, counterparty, summary, due date only; verbatim quotes, Gmail deep links, and the injectable `text` digest are trusted-local only. Ranking and rendered ages use one reference time, `as_of` (ISO, default now, echoed in the grouped result; `gbrain waiting --as-of`), so a published order is reproducible (N7-5). The result carries per-source last-successful-sync ages + a `stale` flag (>24h): all stale sources remain a refusal condition for `gbrain waiting`, while a mixed fresh/stale set continues with a warning naming stale sources (`stale_sources` in JSON). Per-call scope params `source_id`/`all_sources` resolve through `resolveRequestedScope` (an MCP client bound to another source can reach the google source's loops; remote callers stay in-grant, out-of-grant `source_id` is denied); a scope with NO google source returns `no_google_sources: true` and the digest says the engine has nothing to read instead of a false "You are clean". Scope is fail-closed too: an UNSCOPED remote `open_loops` read is refused outright (the op must not rely on transports to enforce it — an unscoped remote read would span every source), and the write ops (`loops_close`, `loops_mute`, `loops_unmute`) require a single-source remote scope that matches the caller's grants — trusting a caller-supplied `source_id` for a remote write would let any remote client plant (or lift) suppression rows cross-source; `loops_unmute` reverses a suppression via `removeSuppression` and reports `{removed}` honestly.- `src/commands/google.ts` — `gbrain google connect|status|calendars|disconnect` (+ `setup` and `attachments` dispatch). Agent-first contract: every subcommand supports `--json` emitting `{ ok, status, next_action: { command?, user_message? }, error? }` (`calendars` adds `account` + `calendars[]` — id/summary/primary/accessRole — and carries the `sources add --calendar-id` template in `next_action.command`; it resolves a lone connected account, exits 2 when there are none or several without `--account`, and throws `not_connected` for an unknown `--account`); human copy the harness must relay verbatim is fenced in `[SHOW USER] ... [/SHOW USER]` blocks; secret intake is `--client-json <path|->` (preferred) / env `GOOGLE_CLIENT_ID`+`GOOGLE_CLIENT_SECRET` / TTY prompt, with raw argv flags accepted but documented last-resort; connect is an idempotent state machine (detects what exists, performs only the missing step — re-running is the documented fix for most errors). Credential commands are engine-free; `status` has a best-effort linked-sources listing, while `attachments backfill` requires the explicitly selected local managed brain. Funnel events append to `~/.gbrain/integrations/google/heartbeat.jsonl`; account addresses are hashed to a short non-reversible tag, never raw. The vault entry's `meta.scopes` records what Google ACTUALLY granted (the token response's `scope` — the consent screen lets users uncheck scopes; the requested set is only the fallback), which is what lets downstream preflights report `scope_missing` instead of opaque per-sweep 403s.- `src/commands/creds.ts` — `gbrain creds list|remove|export|import`: the provider-agnostic vault surface; never prints a secret (list is always redacted). Provider-SPECIFIC connect flows live in their own commands. Export custody: a loud per-credential warning when a byo Google entry's consent screen is not known published-to-Production (its 7-day Testing expiry travels with the tokens).-- `src/commands/loops.ts` — `gbrain waiting [--top N] [--json] [--stale-ok]` + `gbrain loops list|show|done|drop|mute`: all paths dispatch through the trusted-local op layer (`handleToolCall`, remote:false) so CLI and MCP share one behavior. `waiting` REFUSES when EVERY google source has gone >24h without a successful sync and prints the exact fix (`--stale-ok` bypasses; per-source sync ages are always reported) — stale-but-confident output is worse than none. Output per counterparty: what's owed, evidence quotes, Gmail deep links, entity-card context, a paste-ready digest. Reads default to the `__all__` brain span (loops live in google sources, not `default` — a default-scoped read would say "all clean" while people wait); `--source <id>` narrows explicitly. An unqualified `mute`/`unmute` resolves the brain's google source (never `default`) through the SAME resolution — an unmute can never aim at a different source than the mute it reverses — and refuses with the exact fix when none or multiple exist. `unmute sender <email> | thread <id>` is exact and forward-only; a repeated unmute is a no-op success (`removed: false`, exit 0) so scripts can call it unconditionally.+- `src/commands/loops.ts` — `gbrain waiting [--top N] [--json] [--stale-ok]` + `gbrain loops list|show|done|drop|mute`: all paths dispatch through the trusted-local op layer (`handleToolCall`, remote:false) so CLI and MCP share one behavior. `waiting` REFUSES when EVERY google source has gone >24h without a successful sync and prints the exact fix (`--stale-ok` bypasses; per-source sync ages are always reported); when only some sources are stale, it continues with the warning and source ids from `open_loops`. Output per counterparty: what's owed, evidence quotes, Gmail deep links, entity-card context, a paste-ready digest. Reads default to the `__all__` brain span (loops live in google sources, not `default` — a default-scoped read would say "all clean" while people wait); `--source <id>` narrows explicitly. An unqualified `mute`/`unmute` resolves the brain's google source (never `default`) through the SAME resolution — an unmute can never aim at a different source than the mute it reverses — and refuses with the exact fix when none or multiple exist. `unmute sender <email> | thread <id>` is exact and forward-only; a repeated unmute is a no-op success (`removed: false`, exit 0) so scripts can call it unconditionally.- `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.diff --git a/docs/guides/open-loops.md b/docs/guides/open-loops.mdindex b6a56ff661..207172affe 100644--- a/docs/guides/open-loops.md+++ b/docs/guides/open-loops.md@@ -163,7 +163,9 @@ gbrain waiting [--top N] [--json] [--stale-ok]REFUSES when every google source has gone >24h without a successfulsync, printing the exact fix — stale-but-confident output is worse thannone. (One fresh account keeps output flowing; per-source sync ages are- always reported.) When a Gmail thread from the last 14 days is held+ always reported. If only some sources are stale, output continues with a+ warning naming those sources; JSON includes their ids in `stale_sources`.)+ When a Gmail thread from the last 14 days is heldafter repeated import failures, the answer carriescompleteness: "partial" and names each held thread with its retrycommand (gbrain sources retry-held <id>); an empty partial answer saysdiff --git a/src/core/ops/loops.ts b/src/core/ops/loops.tsindex 979425ba8f..234faecc84 100644--- a/src/core/ops/loops.ts+++ b/src/core/ops/loops.ts@@ -64,7 +64,7 @@ interface GoogleSourceFreshness {async function googleSourceFreshness(ctx: OperationContext,scope: { sourceId?: string; sourceIds?: string[] },-): Promise<{ sources: GoogleSourceFreshness[]; stale: boolean }> {+): Promise<{ sources: GoogleSourceFreshness[]; stale: boolean; staleSources: string[] }> {try {const rows = await ctx.engine.executeRaw<{ id: string; last_sync_at: string | null; config: unknown }>(`SELECT id, last_sync_at, config FROM sources WHERE archived IS NOT TRUE`,@@ -87,12 +87,16 @@ async function googleSourceFreshness(stale:r.last_sync_at === null || Date.now() - Date.parse(r.last_sync_at) > STALE_AFTER_MS,}));- return { sources, stale: sources.length > 0 && sources.every((s) => s.stale) };+ return {+ sources,+ stale: sources.length > 0 && sources.every((s) => s.stale),+ staleSources: sources.filter((s) => s.stale).map((s) => s.id),+ };} catch {// Fail TOWARD stale: this surface's invariant is "stale-but-confident is// worse than nothing" — a DB error must not present confident output// with the stale warning suppressed.- return { sources: [], stale: true };+ return { sources: [], stale: true, staleSources: [] };}}@@ -252,10 +256,16 @@ function rankGroups(groups: CounterpartyGroup[], backlinks: Map<string, number>,}function renderText(groups: CounterpartyGroup[], stale: boolean, noGoogleSources: boolean,- coverage: { completeness: 'complete' | 'partial'; held: HeldItemView[] }, nowMs: number): string {+ coverage: { completeness: 'complete' | 'partial'; held: HeldItemView[] }, nowMs: number,+ partialStaleSources: string[]): string {const lines: string[] = [];const { held } = coverage;if (stale) lines.push('⚠ google sources have not synced recently — this may be out of date.');+ else if (partialStaleSources.length > 0) {+ lines.push(+ `⚠ some google sources have not synced recently — this may be out of date: ${partialStaleSources.join(', ')}.`,+ );+ }const partial = coverage.completeness === 'partial';const what = held.length ? `${held.length} held item(s) could not be imported:` : 'the held-item state could not be read.';if (partial && groups.length === 0) {@@ -375,6 +385,7 @@ const open_loops: Operation = {});const freshness = await googleSourceFreshness(ctx, scope);const noGoogleSources = freshness.sources.length === 0;+ const partialStaleSources = freshness.stale ? [] : freshness.staleSources;const coverage = await heldCoverage(ctx, freshness.sources, trusted);const deepLinks = trusted ? await deepLinksFor(ctx, loops) : new Map<string, string>();@@ -387,6 +398,7 @@ const open_loops: Operation = {truncated,stale: freshness.stale,sources: freshness.sources,+ ...(partialStaleSources.length > 0 ? { stale_sources: partialStaleSources } : {}),completeness: coverage.completeness,held: coverage.held,no_google_sources: noGoogleSources,@@ -468,12 +480,13 @@ const open_loops: Operation = {truncated,stale: freshness.stale,sources: freshness.sources,+ ...(partialStaleSources.length > 0 ? { stale_sources: partialStaleSources } : {}),completeness: coverage.completeness,held: coverage.held,no_google_sources: noGoogleSources,redacted: !trusted,as_of: new Date(nowMs).toISOString(),- ...(trusted ? { text: renderText(groups, freshness.stale, noGoogleSources, coverage, nowMs) } : {}),+ ...(trusted ? { text: renderText(groups, freshness.stale, noGoogleSources, coverage, nowMs, partialStaleSources) } : {}),};},};diff --git a/test/loops-cli.test.ts b/test/loops-cli.test.tsindex 58b4824479..30c511bbd2 100644--- a/test/loops-cli.test.ts+++ b/test/loops-cli.test.ts@@ -193,6 +193,40 @@ describe('runWaiting', () => {expect(r.verdict).toBe(0);});+ test('partially stale google sources warn with source ids without refusing, including JSON', async () => {+ await engine.executeRaw(+ `INSERT INTO sources (id, name, config, last_sync_at)+ VALUES ('g-stale', 'g-stale', '{"kind":"google"}'::jsonb, NULL)`,+ );++ const text = await captured(() => runWaiting(engine, []));+ expect(text.out).toContain('⚠ some google sources have not synced recently');+ expect(text.out).toContain('g-stale');+ expect(text.out).toBe(+ '⚠ some google sources have not synced recently — this may be out of date: g-stale.\n' ++ 'No open loops — no unanswered threads older than 24h and no tracked promises. You are clean.\n',+ );+ expect(text.err).toBe('');+ expect(text.verdict).toBe(0);++ const json = await captured(() => runWaiting(engine, ['--json']));+ const envelope = JSON.parse(json.out) as {+ ok: boolean;+ status: string;+ stale: boolean;+ stale_sources?: string[];+ sources: Array<{ id: string; stale: boolean }>;+ text: string;+ };+ expect(envelope.ok).toBe(true);+ expect(envelope.status).toBe('ok');+ expect(envelope.stale).toBe(false);+ expect(envelope.stale_sources).toEqual(['g-stale']);+ expect(envelope.sources).toHaveLength(2);+ expect(envelope.text).toContain('g-stale');+ expect(json.verdict).toBe(0);+ });+test('fresh --json → { ok:true, status:"ok" } envelope carrying groups + text', async () => {await upsertOpenLoop(engine, loop());const r = await captured(() => runWaiting(engine, ['--json']));