Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
45.1 KB
Raw Blame
/**
 * loops ops — the open-loop engine's read/write surface.
 *
 *   open_loops  (read)  — the killer output: who is waiting on you, what you
 *                         promised, and the context needed to respond.
 *   loops_close (write) — mark a loop done/dropped.
 *   loops_mute  (write) — suppress a sender/thread from future detection.
 *   loops_unmute (write) — remove a suppression so detection can resume.
 *
 * Remote posture (approved D4-A): open_loops is NOT localOnly — hosted
 * gbrain.io serves it over HTTP to its authenticated owner. Fail-closed
 * evidence redaction instead: `ctx.remote !== false` gets counts +
 * counterparty + summary + due; verbatim quotes, Gmail deep links, and the
 * injectable text block are trusted-local only.
 *
 * Trust-critical freshness (outside-voice F2): the result carries the google
 * sources' last-successful-sync ages and a `stale` flag — stale-but-confident
 * "you owe Alice a reply" is worse than no output, so the CLI refuses on
 * stale unless --stale-ok.
 */

import { opError, type Operation, type OperationContext, type OperationError } from './contract.ts';
import type { Action, Notice } from '../agent-output.ts';
import { hostFix, invalidParam, opTransport, paramUse, readFix } from './op-fix.ts';
import { resolveRequestedScope, sourceScopeOpts } from './context.ts';
import { validateSourceId } from '../utils.ts';
import { isGmailHoldKey } from '../google/types.ts';
import { closedLoopWithActiveFact, retireLoopFact } from '../persistence/loop-fact-retirement.ts';
import {
  addSuppression,
  closeMutedLoops,
  closeOpenLoop,
  listOpenLoops,
  removeSuppression,
  requeueMutedLoops,
  type LoopStatus,
  type LoopType,
  type OpenLoopRow,
} from '../loops/loops-store.ts';

const STALE_AFTER_MS = 24 * 3_600_000;

/** Does this source carry Google content? A loops suppression row is only
 *  ever consulted by the detector inside a google source — a mute written
 *  anywhere else can never match. */
async function sourceHasGoogleContent(ctx: OperationContext, sourceId: string): Promise<boolean> {
  try {
    const rows = await ctx.engine.executeRaw<{ config: unknown }>(
      `SELECT config FROM sources WHERE id = $1`,
      [sourceId],
    );
    const c = rows[0]?.config;
    const cfg =
      typeof c === 'string'
        ? (JSON.parse(c) as Record<string, unknown>)
        : ((c ?? {}) as Record<string, unknown>);
    return cfg.kind === 'google';
  } catch {
    return false;
  }
}

interface GoogleSourceFreshness {
  id: string;
  last_sync_at: string | null;
  stale: boolean;
}

async function googleSourceFreshness(
  ctx: OperationContext,
  scope: { sourceId?: string; sourceIds?: string[] },
): Promise<{ sources: GoogleSourceFreshness[]; stale: boolean; staleSources: string[]; failed?: true }> {
  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`,
      [],
    );
    const sources = rows
      .filter((r) => {
        const c =
          typeof r.config === 'string'
            ? (JSON.parse(r.config) as Record<string, unknown>)
            : ((r.config ?? {}) as Record<string, unknown>);
        if (c.kind !== 'google') return false;
        if (scope.sourceIds && !scope.sourceIds.includes(r.id)) return false;
        if (scope.sourceId && scope.sourceId !== r.id) return false;
        return true;
      })
      .map((r) => ({
        id: r.id,
        last_sync_at: r.last_sync_at,
        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),
      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, staleSources: [], failed: true };
  }
}

/**
 * Fix wave 4: held Gmail threads whose newest message falls inside this window
 * (or whose date is unknown) make the answer's coverage partial.
 */
const HELD_WINDOW_MS = 14 * 86_400_000;

interface HeldItemView { source_id: string; key: string; sender: string | null; subject?: string | null; retry_command: string }

/**
 * Held items do not block freshness, so completeness is reported separately:
 * `partial` whenever a held Gmail thread in scope falls inside the window.
 * Remote callers get the sender and the retry command, never the subject.
 */
async function heldCoverage(ctx: OperationContext, sources: GoogleSourceFreshness[], trusted: boolean): Promise<{ completeness: 'complete' | 'partial'; held: HeldItemView[] }> {
  if (!sources.length) return { completeness: 'complete', held: [] };
  try {
    const { readAllSourceHolds } = await import('../connectors/item-holds-store.ts');
    const now = Date.now();
    const held: HeldItemView[] = [];
    for (const entry of await readAllSourceHolds(ctx.engine, { sourceIds: sources.map((s) => s.id) })) {
      // Contacts and Calendar holds (GBRA-130 A-3) say nothing about mail coverage.
      for (const record of entry.held.filter((held) => isGmailHoldKey(held.key))) {
        const at = record.meta.upstream_at ? Date.parse(record.meta.upstream_at) : NaN;
        if (Number.isFinite(at) && now - at > HELD_WINDOW_MS) continue;
        held.push({ source_id: entry.sourceId, key: record.key, sender: record.meta.sender, ...(trusted ? { subject: record.meta.subject } : {}),
          retry_command: `gbrain sources retry-held ${entry.sourceId}` });
      }
    }
    return { completeness: held.length ? 'partial' : 'complete', held };
  } catch {
    // Fail toward partial: an unreadable hold state must not read as complete coverage.
    return { completeness: 'partial', held: [] };
  }
}

interface WithheldNoiseSender { source_id: string; email: string; open_loops: number; reason: string; preview_command: string }

/**
 * #5012: open reply-owed loops from senders the detector now withholds (the
 * `loop_withheld_senders` record in each google source's connector state):
 * loops the automated-mail rule would not have opened. Null when there are
 * none or the record cannot be read (advisory; never blocks the answer).
 */
async function withheldNoise(ctx: OperationContext, sources: GoogleSourceFreshness[]): Promise<{ loop_count: number; sender_count: number; senders: WithheldNoiseSender[] } | null> {
  if (!sources.length) return null;
  try {
    const { managedBrain, readConnectorCursorState } = await import('../connectors/item-holds-store.ts');
    const rows = await ctx.engine.executeRaw<{ id: string; incarnation: string; local_path: string | null; config: Record<string, unknown> }>(
      `SELECT id, incarnation::text AS incarnation, local_path, config FROM sources WHERE id = ANY(string_to_array($1, E'\n'))`,
      [sources.map((x) => x.id).join('\n')]);
    const managed = await managedBrain(ctx.engine);
    const senders: WithheldNoiseSender[] = [];
    for (const row of rows) {
      const record = ((await readConnectorCursorState(ctx.engine, row, managed))?.loop_withheld_senders ?? {}) as Record<string, { reason?: string }>;
      const emails = Object.keys(record);
      if (!emails.length) continue;
      const counts = await ctx.engine.executeRaw<{ email: string; n: number }>(
        `SELECT counterparty_email AS email, count(*)::int AS n FROM open_loops
          WHERE source_id = $1 AND status = 'open' AND loop_type = 'unanswered_inbound'
            AND counterparty_email = ANY(string_to_array($2, E'\n'))
          GROUP BY counterparty_email`, [row.id, emails.join('\n')]);
      for (const c of counts) {
        senders.push({ source_id: row.id, email: c.email, open_loops: Number(c.n), reason: record[c.email]?.reason ?? 'automated_mail',
          preview_command: `gbrain loops drop sender ${c.email} --source ${row.id} --dry-run` });
      }
    }
    if (!senders.length) return null;
    senders.sort((a, b) => b.open_loops - a.open_loops || a.email.localeCompare(b.email));
    return { loop_count: senders.reduce((n, x) => n + x.open_loops, 0), sender_count: senders.length, senders };
  } catch {
    return null;
  }
}

function partialLines(held: HeldItemView[]): string[] {
  const lines = held.slice(0, 10).map((h) => `  - ${h.key}${h.sender ? ` from ${h.sender}` : ''}${h.subject ? `: ${h.subject}` : ''}`);
  if (held.length > 10) lines.push(`  +${held.length - 10} more`);
  for (const command of [...new Set(held.map((h) => h.retry_command))]) lines.push(`  Re-attempt them: ${command}`);
  return lines;
}

/** Regenerate Gmail deep links (code, never stored LLM text) for evidence. */
async function deepLinksFor(
  ctx: OperationContext,
  loops: OpenLoopRow[],
): Promise<Map<string, string>> {
  // account lives in the thread page's frontmatter; batch one query.
  const slugs = [...new Set(loops.map((l) => l.page_slug).filter((s): s is string => s !== null))];
  const accounts = new Map<string, string>();
  if (slugs.length > 0) {
    try {
      // source-scoped so the composite (source_id, slug) unique index serves
      // the lookup — a slug-only predicate would sequential-scan pages.
      const sourceIds = [...new Set(loops.map((l) => l.source_id))];
      const rows = await ctx.engine.executeRaw<{ slug: string; account: string | null; source_id: string }>(
        `SELECT slug, source_id, frontmatter->>'account' AS account FROM pages
         WHERE source_id = ANY(string_to_array($2, E'\\n'))
           AND slug = ANY(string_to_array($1, E'\\n')) AND deleted_at IS NULL`,
        [slugs.join('\n'), sourceIds.join('\n')],
      );
      for (const r of rows) if (r.account) accounts.set(`${r.source_id}:${r.slug}`, r.account);
    } catch { /* links degrade to none */ }
  }
  const out = new Map<string, string>();
  const { emailCitation } = await import('../output/scaffold.ts');
  for (const l of loops) {
    const account = l.page_slug ? accounts.get(`${l.source_id}:${l.page_slug}`) : undefined;
    const messageId = l.evidence.find((e) => e.message_id)?.message_id;
    if (!account || !messageId) continue;
    try {
      out.set(
        `${l.id}`,
        emailCitation({
          account,
          messageId,
          subject: l.summary.slice(0, 80),
          dateISO: l.last_activity_at.slice(0, 10),
        }),
      );
    } catch { /* invalid message id — no link */ }
  }
  return out;
}

interface LoopView {
  id: number;
  loop_type: LoopType;
  status: LoopStatus;
  summary: string;
  due_at: string | null;
  opened_at: string;
  last_activity_at: string;
  counterparty_slug: string | null;
  counterparty_email: string | null;
  detector: string;
  confidence: number;
  page_slug: string | null;
  /** Trusted-local only. */
  quote?: string;
  deep_link?: string;
}

function loopView(l: OpenLoopRow, trusted: boolean, deepLinks: Map<string, string>): LoopView {
  const base: LoopView = {
    id: l.id,
    loop_type: l.loop_type,
    status: l.status,
    summary: l.summary,
    due_at: l.due_at,
    opened_at: l.opened_at,
    last_activity_at: l.last_activity_at,
    counterparty_slug: l.counterparty_slug,
    counterparty_email: l.counterparty_email,
    detector: l.detector,
    confidence: l.confidence,
    page_slug: l.page_slug,
  };
  if (trusted) {
    const q = l.evidence.find((e) => e.quote)?.quote;
    if (q) base.quote = q;
    const link = deepLinks.get(`${l.id}`);
    if (link) base.deep_link = link;
  }
  return base;
}

interface CounterpartyGroup {
  counterparty: string;
  counterparty_slug: string | null;
  counterparty_email: string | null;
  /** The loops' home source. */
  source_id: string;
  /** Where the counterparty page lives (#5504): entity cards/aliases live
   *  THERE, not in the caller's (often 'default') scope and not always in
   *  the loops' source. A pre-v236 row reads as its own source. */
  counterparty_source_id: string;
  loop_count: number;
  oldest_opened_at: string;
  nearest_due_at: string | null;
  loops: LoopView[];
  /** #5871: loops beyond the LOOPS_PER_GROUP shown; loop_count stays the total. */
  loops_omitted: number;
  context?: unknown;
}

/** #5871: loops with neither a counterparty slug nor an email. Not a person, so never ranked. */
interface NoCounterpartyLoops {
  loop_count: number;
  by_type: Partial<Record<LoopType, number>>;
  loops: LoopView[];
  loops_omitted: number;
}

/** Loops shown per group (and in the no-counterparty section); the rest are counted in loops_omitted. */
const LOOPS_PER_GROUP = 5;

/** Due-soonest first (undated last), then the most recently active; keeps the first LOOPS_PER_GROUP. */
function capLoops(loops: LoopView[]): { loops: LoopView[]; loops_omitted: number } {
  const time = (v: string | null) => v === null ? Infinity : Date.parse(v);
  const sorted = [...loops].sort((a, b) => time(a.due_at) - time(b.due_at) || Date.parse(b.last_activity_at) - Date.parse(a.last_activity_at));
  return { loops: sorted.slice(0, LOOPS_PER_GROUP), loops_omitted: Math.max(0, loops.length - LOOPS_PER_GROUP) };
}

function rankGroups(groups: CounterpartyGroup[], backlinks: Map<string, number>, nowMs: number): CounterpartyGroup[] {
  const score = (g: CounterpartyGroup): number => {
    let s = g.loop_count * 10;
    if (g.nearest_due_at) {
      const days = (Date.parse(g.nearest_due_at) - nowMs) / 86_400_000;
      s += days <= 0 ? 50 : days <= 3 ? 30 : days <= 7 ? 15 : 5;
    }
    const ageDays = (nowMs - Date.parse(g.oldest_opened_at)) / 86_400_000;
    s += Math.min(20, ageDays);
    if (g.counterparty_slug) s += Math.min(20, backlinks.get(g.counterparty_slug) ?? 0);
    return s;
  };
  return [...groups].sort((a, b) => score(b) - score(a) || a.counterparty.localeCompare(b.counterparty));
}

function renderLoopLine(lines: string[], l: LoopView, nowMs: number): void {
  const due = l.due_at ? ` — due ${l.due_at.slice(0, 10)}` : '';
  // Age renders at READ time from last_activity_at — stored summaries
  // deliberately carry no age (it would freeze at detection time).
  const ageDays = Math.max(0, Math.floor((nowMs - Date.parse(l.last_activity_at)) / 86_400_000));
  const age = Number.isFinite(ageDays) ? ` (${ageDays}d)` : '';
  lines.push(`- [${l.loop_type}] ${l.summary}${age}${due}`);
  if (l.quote) lines.push(`  > "${l.quote}"`);
  if (l.deep_link) lines.push(`  ${l.deep_link}`);
}

function renderNoCounterparty(lines: string[], none: NoCounterpartyLoops | null, nowMs: number): void {
  if (!none) return;
  const types = Object.entries(none.by_type).map(([type, n]) => `${type} ${n}`).join(', ');
  lines.push('', `## No counterparty (${none.loop_count} open: ${types})`);
  for (const l of none.loops) renderLoopLine(lines, l, nowMs);
  if (none.loops_omitted > 0) lines.push(`+${none.loops_omitted} more`);
}

function renderText(groups: CounterpartyGroup[], none: NoCounterpartyLoops | null, stale: boolean, noGoogleSources: boolean | null,
  coverage: { completeness: 'complete' | 'partial'; held: HeldItemView[] }, nowMs: number,
  partialStaleSources: string[]): string {
  const lines: string[] = [];
  const { held } = coverage;
  if (noGoogleSources === null) lines.push('⚠ the sources could not be read — whether a google source exists and when it last synced are unknown.');
  else 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 = noGoogleSources === null ? 'the sources could not be read, so held mail is unknown.'
    : held.length ? `${held.length} held item(s) could not be imported:` : 'the held-item state could not be read.';
  if (partial && groups.length === 0 && !none) {
    lines.push(`No open loops found, but coverage is partial: ${what}`, ...partialLines(held));
    return lines.join('\n');
  }
  if (partial) lines.push(`⚠ Coverage is partial: ${what}`, ...partialLines(held), '');
  if (groups.length === 0 && none) {
    lines.push('No person is waiting on you; these open loops name no counterparty:');
    renderNoCounterparty(lines, none, nowMs);
    return lines.join('\n');
  }
  if (groups.length === 0) {
    if (noGoogleSources) {
      // Trust-critical copy: on a brain whose email arrives some other way
      // (a gateway, an agent-authored collector), "You are clean" would be a
      // confident lie — the engine has nothing to read.
      lines.push(
        'No google source is connected in this scope — the open-loop engine has nothing to read, ' +
          'so this is NOT "inbox clean". Connect one with: gbrain google setup ' +
          '(existing gateway/CLI access works too: gbrain sources add <id> --kind google --access command|env — see docs/guides/google-connect.md).',
      );
      return lines.join('\n');
    }
    lines.push('No open loops — no unanswered threads older than 24h and no tracked promises. You are clean.');
    return lines.join('\n');
  }
  lines.push(`${groups.length} ${groups.length === 1 ? 'person is' : 'people are'} waiting on you:`);
  for (const g of groups) {
    lines.push('', `## ${g.counterparty} (${g.loop_count} open)`);
    for (const l of g.loops) renderLoopLine(lines, l, nowMs);
    if (g.loops_omitted > 0) lines.push(`+${g.loops_omitted} more`);
  }
  renderNoCounterparty(lines, none, nowMs);
  return lines.join('\n');
}

const OPEN_LOOPS_ROW_CAP = 500;

const open_loops: Operation = {
  name: 'open_loops',
  mutating: false,
  idempotent: true,
  outputRedaction: 'retrieval',
  description:
    'The open-loop engine\'s killer output: who is waiting on you, what you promised, and the context ' +
    'needed to respond. Grouped by counterparty (default, ranked; each group shows at most 5 loops, the rest counted in ' +
    'loops_omitted) or flat. Loops that name no counterparty are never ranked as a person: they come back in ' +
    'no_counterparty (null when none). Loops come from the ' +
    'deterministic Gmail thread-state detector and the LLM commitment extractor. Remote callers get ' +
    'redacted evidence (no verbatim quotes); trusted local callers also get quotes, Gmail deep links, ' +
    'entity-card context, and a pre-rendered text digest. Carries google-source freshness (stale flag) and ' +
    'completeness: when it is "partial", some mail in the window is held after repeated import failures (or, with ' +
    'no_google_sources: null, the sources could not be read); present the ' +
    'answer as partial and name the held items and their retry command. The grouped view also returns withheld_noise ' +
    '(null when none): open reply-owed loops from senders whose mail the detector now treats as automated, with a ' +
    'per-sender preview_command for closing them.',
  params: {
    group_by: { type: 'string', enum: ['counterparty', 'none'], description: "Default 'counterparty' (ranked groups)." },
    status: { type: 'string', enum: ['open', 'done', 'dropped', 'stale'], description: "Default 'open', except with `id`, where any status matches." },
    id: { type: 'number', minimum: 1, description: 'Fetch the single loop with this id (ids come from earlier open_loops results). Matches any status unless `status` is passed; the source scope still applies, and the grouped view omits `text`.' },
    loop_type: { type: 'string', enum: ['commitment_owed_by_me', 'commitment_owed_to_me', 'unanswered_inbound', 'unanswered_outbound', 'decision_pending'], description: 'Filter to one loop type.' },
    counterparty: { type: 'string', description: 'Filter to one counterparty (slug or email).' },
    limit: { type: 'number', description: 'Grouped: max groups (default 3). Flat: max loops (default 50); `count` is the number matched (at most 500) and `truncated: true` marks a list cut by this limit or by the 500-row internal cap (then `count` is a lower bound).' },
    include_context: { type: 'boolean', description: 'Attach the counterparty entity card per group (trusted local only). Default true.' },
    source_id: { type: 'string', description: "Scope to one source (e.g. the google source, when the caller's transport is bound elsewhere). Remote callers must hold a grant covering it." },
    all_sources: { type: 'boolean', description: 'Trusted local: span every source in the brain. Remote callers stay inside their grant.' },
    as_of: { type: 'string', description: 'Reference time (ISO 8601) for due-date proximity, loop age and rendered ages. Default: now. Pin it to reproduce a ranking.' },
  },
  scope: 'read',
  annotations: { readOnlyHint: true },
  handler: async (ctx, p) => {
    const trusted = ctx.remote === false;
    const nowMs = p.as_of === undefined ? Date.now() : Date.parse(String(p.as_of));
    if (!Number.isFinite(nowMs)) {
      throw invalidParam(ctx, 'open_loops', 'as_of', `open_loops: as_of must be an ISO 8601 timestamp, got ${JSON.stringify(p.as_of)}`,
        { def: open_loops.params.as_of, example: '2026-04-03T09:00:00Z' });
    }
    const groupBy = (p.group_by as string | undefined) ?? 'counterparty';
    const loopId = requestedLoopId(ctx, p.id);
    let status = (p.status ?? undefined) as LoopStatus | undefined;
    if (status === undefined && loopId === undefined) status = 'open';
    // Per-call scope via the canonical trust+grant resolver: an MCP caller
    // whose transport is bound to another source can point this read at the
    // google source (`source_id`) or, trusted-local, span the brain
    // (`all_sources`) — remote callers stay inside their grant and an
    // out-of-grant source_id is denied there.
    const scope = resolveRequestedScope(
      ctx,
      p.source_id as string | undefined,
      p.all_sources === true,
    );
    // Tighter than the shared resolver for REMOTE callers: resolveRequestedScope
    // honors an explicit source_id for scalar-scoped callers (its other
    // consumers apply page-visibility filtering, so a cross-source read there
    // exposes world rows only). Loops have NO visibility tiering — summaries
    // derive from private email — so a remote source_id must sit inside the
    // caller's grant, scalar or federated.
    if (!trusted && typeof p.source_id === 'string') {
      const allowed = ctx.auth?.allowedSources;
      const inGrant =
        (allowed && allowed.length > 0 && allowed.includes(p.source_id)) ||
        (!(allowed && allowed.length > 0) && ctx.sourceId === p.source_id);
      if (!inGrant) {
        throw opError(
          'permission_denied',
          `open_loops: source '${p.source_id}' is outside your granted sources`,
          `Pass source_id as one of your granted sources (${grantedSources(ctx).join(', ') || 'none'}), or omit it to read your default scope.`,
          { fix: sourcesFix('Lists the sources this connection can read.') },
        );
      }
    }
    // Fail-closed invariant: an untrusted caller must arrive with a resolved
    // scope. Shipped transports refuse unscoped remote calls upstream, but
    // the op must not rely on them — an unscoped remote read here would span
    // every source (the cross-source leak class).
    if (!trusted && !scope.sourceId && !scope.sourceIds) {
      throw opError(
        'permission_denied',
        'open_loops: remote callers need a resolved source scope',
        'Pass source_id naming one of your granted sources (fix lists them).',
        { fix: sourcesFix('Lists the sources this connection can read.') },
      );
    }
    const loops = await listOpenLoops(ctx.engine, {
      ...(scope.sourceIds ? { sourceIds: scope.sourceIds } : {}),
      ...(scope.sourceId ? { sourceIds: [scope.sourceId] } : {}),
      status,
      ...(p.loop_type ? { loopType: p.loop_type as LoopType } : {}),
      ...(p.counterparty ? { counterparty: p.counterparty as string } : {}),
      ...(loopId === undefined ? {} : { loopId }),
      limit: OPEN_LOOPS_ROW_CAP + 1,
    });
    const capped = loops.length > OPEN_LOOPS_ROW_CAP;
    if (capped) loops.length = OPEN_LOOPS_ROW_CAP;
    const freshness = await googleSourceFreshness(ctx, scope);
    // #8452: a failed sources read proves neither that no google source exists nor that coverage is complete.
    const noGoogleSources = freshness.failed ? null : freshness.sources.length === 0;
    if (freshness.failed) ctx.emitNotice?.(SOURCES_UNREADABLE_NOTICE);
    else if (!trusted && noGoogleSources && loops.length === 0) ctx.emitNotice?.(noGoogleInScopeNotice(scope.sourceIds ?? (scope.sourceId ? [scope.sourceId] : [])));
    const partialStaleSources = freshness.stale ? [] : freshness.staleSources;
    const coverage = freshness.failed ? { completeness: 'partial' as const, held: [] } : await heldCoverage(ctx, freshness.sources, trusted);
    const deepLinks = trusted ? await deepLinksFor(ctx, loops) : new Map<string, string>();

    if (groupBy === 'none') {
      const limit = Math.min(Math.max((p.limit as number | undefined) ?? 50, 1), 500);
      return {
        loops: loops.slice(0, limit).map((l) => loopView(l, trusted, deepLinks)),
        count: loops.length,
        truncated: capped || loops.length > limit,
        stale: freshness.stale,
        sources: freshness.sources,
        ...(partialStaleSources.length > 0 ? { stale_sources: partialStaleSources } : {}),
        completeness: coverage.completeness,
        held: coverage.held,
        no_google_sources: noGoogleSources,
        redacted: !trusted,
      };
    }

    const byKey = new Map<string, CounterpartyGroup>();
    const unattributed: LoopView[] = [];
    const byType: NoCounterpartyLoops['by_type'] = {};
    for (const l of loops) {
      const counterpartySource = l.counterparty_source_id ?? l.source_id;
      // Two people with the same slug in different sources are two groups.
      const key = l.counterparty_slug ? `${counterpartySource}:${l.counterparty_slug}` : l.counterparty_email;
      if (key === null) {
        unattributed.push(loopView(l, trusted, deepLinks));
        byType[l.loop_type] = (byType[l.loop_type] ?? 0) + 1;
        continue;
      }
      let g = byKey.get(key);
      if (!g) {
        g = {
          counterparty: l.counterparty_slug ?? key,
          counterparty_slug: l.counterparty_slug,
          counterparty_email: l.counterparty_email,
          source_id: l.source_id,
          counterparty_source_id: counterpartySource,
          loop_count: 0,
          oldest_opened_at: l.opened_at,
          nearest_due_at: null,
          loops: [],
          loops_omitted: 0,
        };
        byKey.set(key, g);
      }
      g.loop_count++;
      if (l.opened_at < g.oldest_opened_at) g.oldest_opened_at = l.opened_at;
      if (l.due_at && (!g.nearest_due_at || l.due_at < g.nearest_due_at)) g.nearest_due_at = l.due_at;
      g.loops.push(loopView(l, trusted, deepLinks));
    }

    const backlinks = new Map<string, number>();
    try {
      // Backlink counts span every source, so they rank trusted-local reads
      // only: an untrusted caller's order must not depend on pages outside its grant.
      const slugs = !trusted ? [] : [...byKey.values()]
        .map((g) => g.counterparty_slug)
        .filter((s): s is string => s !== null);
      if (slugs.length > 0) {
        // getBacklinkCounts takes numeric page ids (v0.46.35) — resolve the
        // counterparty slugs within the counterparty pages' sources first
        // (same composite-key discipline as deepLinksFor), then fold back to slugs.
        const srcIds = [...new Set([...byKey.values()].map((g) => g.counterparty_source_id))];
        const rows = await ctx.engine.executeRaw<{ id: number; slug: string }>(
          `SELECT id, slug FROM pages
           WHERE source_id = ANY(string_to_array($2, E'\\n'))
             AND slug = ANY(string_to_array($1, E'\\n')) AND deleted_at IS NULL`,
          [slugs.join('\n'), srcIds.join('\n')],
        );
        if (rows.length > 0) {
          const counts = await ctx.engine.getBacklinkCounts(rows.map((r) => Number(r.id)));
          for (const r of rows) {
            const c = counts.get(Number(r.id));
            if (c !== undefined) backlinks.set(r.slug, Math.max(backlinks.get(r.slug) ?? 0, c));
          }
        }
      }
    } catch { /* rank without backlinks */ }

    const limit = Math.min(Math.max((p.limit as number | undefined) ?? 3, 1), 50);
    const groups = rankGroups([...byKey.values()], backlinks, nowMs).slice(0, limit)
      .map((g) => ({ ...g, ...capLoops(g.loops) }));
    const noCounterparty: NoCounterpartyLoops | null = unattributed.length === 0 ? null
      : { loop_count: unattributed.length, by_type: byType, ...capLoops(unattributed) };

    // Entity-card context (zero-LLM, trusted local only).
    if (trusted && (p.include_context as boolean | undefined) !== false) {
      const { buildEntityCard } = await import('../verbs/entity-card.ts');
      for (const g of groups) {
        if (!g.counterparty_slug) continue;
        try {
          // The card resolves in the COUNTERPARTY PAGE's source (where the
          // person page + alias rows live), never the caller's scope — an
          // unqualified `gbrain waiting` would otherwise look in 'default'
          // and silently never attach context (same bug class as
          // deepLinksFor's fix); since #5504 that source can differ from the
          // loop's.
          const card = await buildEntityCard(ctx.engine, g.counterparty_source_id, g.counterparty_slug, { remote: false });
          if (card.found) g.context = card.card;
        } catch { /* context is best-effort */ }
      }
    }

    return {
      groups,
      no_counterparty: noCounterparty,
      ...(loopId === undefined ? { withheld_noise: await withheldNoise(ctx, freshness.sources) } : {}),
      count: loops.length,
      truncated: capped,
      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 && loopId === undefined
        ? { text: renderText(groups, noCounterparty, freshness.stale, noGoogleSources, coverage, nowMs, partialStaleSources) }
        : {}),
    };
  },
};

/**
 * open_loops `id`: absent or null means a list read (over the tool paths, 0
 * reads as absent too: `minimum: 1`, GST-927). Anything else must be a
 * positive safe integer. The refusal never echoes the raw value. The digest
 * stays off for a lookup because it describes the open list ("waiting on
 * you", "You are clean"), which is false for a closed or missing loop.
 */
function requestedLoopId(ctx: OperationContext, raw: unknown): number | undefined {
  if (raw === undefined || raw === null) return undefined;
  if (typeof raw === 'number' && Number.isSafeInteger(raw) && raw >= 1) return raw;
  throw invalidParam(ctx, 'open_loops', 'id', 'open_loops: id must be a whole number of 1 or more.',
    { def: open_loops.params.id, example: 42 });
}

function grantedSources(ctx: OperationContext): string[] {
  const allowed = ctx.auth?.allowedSources;
  if (allowed && allowed.length > 0) return [...allowed];
  return ctx.sourceId ? [ctx.sourceId] : [];
}

function sourcesFix(why: string): Action {
  return readFix(why, { argv: ['gbrain', 'sources', 'list', '--json'], mcp: { tool: 'sources_list', arguments: {} } });
}

/** #8452: carries no database error text; the answer is partial until a read succeeds. */
const SOURCES_UNREADABLE_NOTICE: Notice = {
  code: 'loops_source_read_failed',
  kind: 'degraded',
  why: 'open_loops could not read the sources table, so whether a google source is in scope, when it last synced and which mail is held ' +
    'are unknown (no_google_sources: null, completeness: "partial"). An empty answer is not "inbox clean"; repeat the call.',
};

/** #7286: names only the sources this read covered, all inside the grant, so the text is the same whether or not a google source exists outside it. */
function noGoogleInScopeNotice(readSources: string[]): Notice {
  return {
    code: 'loops_no_google_in_scope',
    kind: 'info',
    why: `open_loops read only ${readSources.join(', ') || 'none'}, inside this connection's grant, and none of them is a google source, ` +
      'so it had nothing to read: this is not "inbox clean", and it says nothing about sources outside the grant. ' +
      "Pass source_id naming a google source this connection is granted, or ask the brain's owner to grant one.",
    fix: sourcesFix('Lists the sources this connection can read; pass a google one as source_id.'),
  };
}

function closeFix(ctx: OperationContext, p: Record<string, unknown>): { fix?: Action } {
  if (typeof p.id !== 'number' || !Number.isSafeInteger(p.id)) return {};
  return { fix: hostFix(ctx, ['gbrain', 'loops', p.status === 'dropped' ? 'drop' : 'done', String(p.id)],
    'The trusted local CLI closes loops in any source; a remote caller closes only inside its bound write source.') };
}

const MUTE_VALUE = /^[A-Za-z0-9][A-Za-z0-9._%+@-]{0,253}$/;

function muteScopeError(ctx: OperationContext, verb: 'mute' | 'unmute', p: Record<string, unknown>,
  sourceId: string, writeSource: string | undefined): OperationError {
  const kind = p.kind === 'sender' || p.kind === 'thread' ? p.kind : undefined;
  const value = typeof p.value === 'string' && MUTE_VALUE.test(p.value) ? p.value : undefined;
  return opError('permission_denied', `loops_${verb}: source "${sourceId}" is outside the caller's write scope`,
    writeSource
      ? `Nothing changed. This connection writes only to source '${writeSource}': pass source_id '${writeSource}', or have the user run the ${verb} from the trusted local CLI (command in fix).`
      : `Nothing changed. This connection has no bound write source; the user can run the ${verb} from the trusted local CLI (command in fix).`,
    kind && value ? { fix: hostFix(ctx, ['gbrain', 'loops', verb, kind, value, '--source', sourceId],
      'A suppression is a write; remote callers write only inside their bound source.') } : {});
}

function noGoogleContent(ctx: OperationContext, message: string): OperationError {
  const param = opTransport(ctx) === 'cli' ? paramUse(ctx, 'source') : '`source_id`';
  return opError('invalid_params', message,
    `Nothing changed. Pass ${param} naming the google source (fix lists sources with their kind).`,
    { fix: sourcesFix('Lists sources with their kind, so you can pick the google one.') });
}

const loops_close: Operation = {
  name: 'loops_close',
  idempotent: true,
  outputRedaction: 'no_stored_text',
  description:
    "Close an open loop by id: status 'done' (handled) or 'dropped' (not going to). Closing is a state " +
    'transition with an audit trail, never a delete. Thread loops also close automatically when a reply lands.',
  params: {
    id: { type: 'number', required: true, description: 'Loop id (from open_loops).' },
    status: { type: 'string', required: true, enum: ['done', 'dropped'], description: 'Terminal state.' },
    note: { type: 'string', description: 'Optional closed_by note (default: manual).' },
    source_id: {
      type: 'string',
      description:
        "The loop's home source (e.g. the google source, when the caller's transport is bound " +
        'elsewhere). Remote callers must be write-bound to it — a federated read grant does not ' +
        'authorize the close. When omitted, the caller\'s bound write source is used.',
    },
  },
  mutating: true,
  scope: 'write',
  handler: async (ctx, p) => {
    const requested = p.source_id as string | undefined;
    if (requested) validateSourceId(requested);
    // Remote callers stay inside their bound write source; trusted local
    // closes across sources (null = unscoped).
    let sourceId: string | null = null;
    if (ctx.remote !== false) {
      // Write authority is the caller's bound write source
      // (auth.sourceId, dual-written to ctx.sourceId) ONLY — the federated
      // allowedSources array is a READ grant and must never authorize a
      // close+fact-expiry write in a sibling source (contract.ts).
      const writeSource = (ctx.auth?.sourceId ?? ctx.sourceId) as string | undefined;
      if (!writeSource) {
        // Enumerated error envelope (dispatch classifies + request-logs it),
        // never a success-shaped { closed:false } payload.
        throw opError(
          'permission_denied',
          'loops_close: remote callers need a bound write source',
          'Nothing was closed. This connection has no bound write source; the user can close the loop from the trusted local CLI (command in fix).',
          closeFix(ctx, p),
        );
      }
      if (requested && requested !== writeSource) {
        throw opError(
          'permission_denied',
          `loops_close: source "${requested}" is outside the caller's write scope`,
          `Nothing was closed. This connection writes only to source '${writeSource}': omit source_id to close there, or have the user close it from the trusted local CLI (command in fix).`,
          closeFix(ctx, p),
        );
      }
      // No cross-source SELECT: the close runs scoped to the write source,
      // so a loop living in a grant-adjacent source is indistinguishable
      // from a missing id — both answer closed:false, and neither the row's
      // existence nor its home source name ever leaves the boundary.
      sourceId = writeSource;
    } else {
      sourceId = requested ?? null;
    }
    if (ctx.dryRun) return { dry_run: true, action: 'loops_close', id: p.id, status: p.status };
    const row = await closeOpenLoop(
      ctx.engine,
      sourceId,
      p.id as number,
      p.status as 'done' | 'dropped',
      (p.note as string | undefined)?.slice(0, 200) || 'manual',
    ) ?? await closedLoopWithActiveFact(ctx.engine, sourceId, p.id as number);
    if (!row) return { closed: false, reason: 'not_found_or_already_closed' };
    // #5869: a closed commitment loop retires its fact (expired + fence row
    // struck) through one coordinated publication. A loop already closed whose
    // fact is still active re-attempts it, so a refused retirement is retryable.
    if (row.fact_id === null) return { closed: true, id: row.id, status: row.status, fact_expired: false, retryable: false };
    const retired = await retireLoopFact(ctx, row.id);
    return { closed: true, id: row.id, status: row.status, fact_expired: retired.fact_expired, retryable: retired.retryable,
      ...(retired.reason && retired.reason !== 'already_expired' ? { reason: retired.reason } : {}) };
  },
};

/** #5012: the CLI command that reverses a mute or unmute. */
function undoCommand(verb: 'mute' | 'unmute', kind: unknown, value: string, sourceId: string): string {
  return `gbrain loops ${verb} ${String(kind)} ${value} --source ${sourceId}`;
}

const loops_mute: Operation = {
  name: 'loops_mute',
  idempotent: true,
  outputRedaction: 'no_stored_text',
  description:
    'Suppress a sender (email address) or thread id from opening NEW loops — the detector feedback ' +
    'primitive behind "never track this sender". It also closes that sender\'s (or thread\'s) open reply-owed ' +
    '(unanswered_inbound) loops as dropped with closed_by "muted" and lists their ids in `closed`; other loop types ' +
    'keep their state. dry_run lists `would_close` and changes nothing. loops_unmute re-checks the closed loops.',
  params: {
    kind: { type: 'string', required: true, enum: ['sender', 'thread'], description: 'What to mute.' },
    value: { type: 'string', required: true, description: 'The sender email or Gmail thread id.' },
    source_id: { type: 'string', description: 'Google source to scope the mute to (default: routed source).' },
  },
  mutating: true,
  scope: 'write',
  handler: async (ctx, p) => {
    const sourceId = (p.source_id as string | undefined) ?? ctx.sourceId ?? 'default';
    validateSourceId(sourceId);
    // Remote callers stay strictly inside their bound write source (mirrors
    // loops_close): the federated allowedSources array is a READ grant and
    // never authorizes the write. Trusting it (or p.source_id alone) for a
    // remote WRITE would let any remote client plant suppression rows into
    // arbitrary sources (targeted denial-of-loop-detection).
    if (ctx.remote !== false) {
      const writeSource = (ctx.auth?.sourceId ?? ctx.sourceId) as string | undefined;
      if (!writeSource || sourceId !== writeSource) {
        throw muteScopeError(ctx, 'mute', p, sourceId, writeSource);
      }
    }
    // A suppression is only consulted inside a google source — when the
    // caller omits source_id and the resolved target holds no Google
    // content, the row can never match. Refuse instead of planting a dead
    // mute (remote callers bound to a non-google source hit exactly this).
    if (p.source_id === undefined && !(await sourceHasGoogleContent(ctx, sourceId))) {
      throw noGoogleContent(ctx, `loops_mute: source "${sourceId}" holds no Google content — a suppression there can never match; pass source_id naming the google source`);
    }
    const kind = p.kind as 'sender' | 'thread';
    const value = (p.value as string).toLowerCase();
    const undo = undoCommand('unmute', kind, value, sourceId);
    if (ctx.dryRun) {
      const wouldClose = await closeMutedLoops(ctx.engine, sourceId, kind, value, false);
      return { dry_run: true, action: 'loops_mute', kind, value, source_id: sourceId, would_close: wouldClose, count: wouldClose.length, undo_command: undo };
    }
    await addSuppression(ctx.engine, sourceId, kind, value);
    const closed = await closeMutedLoops(ctx.engine, sourceId, kind, value, true);
    (await import('../google/loop-detect.ts')).invalidateSuppressionCache(ctx.engine);
    return { muted: true, kind, value, source_id: sourceId, closed, count: closed.length, undo_command: undo };
  },
};

const loops_unmute: Operation = {
  name: 'loops_unmute',
  idempotent: true,
  outputRedaction: 'no_stored_text',
  description:
    'Remove a sender/thread suppression added by loops_mute, so the detector can open NEW loops for ' +
    'it again. Exact-match only. The reply-owed loops the mute closed (unless another mute still covers them) are queued ' +
    'for re-check on the next Gmail sync and listed in `requeued`: a loop reopens only when nothing answered its thread ' +
    'since the mute. `unverifiable` lists closed loops with no thread to re-check (they stay closed); `stale_source` ' +
    'means the re-check waits on a sync that has not run in 24h. Manually closed loops are never touched. dry_run lists ' +
    '`would_requeue` and changes nothing.',
  params: {
    kind: { type: 'string', required: true, enum: ['sender', 'thread'], description: 'What to unmute.' },
    value: { type: 'string', required: true, description: 'The sender email or Gmail thread id.' },
    source_id: { type: 'string', description: 'Google source the mute was scoped to (default: routed source).' },
  },
  mutating: true,
  scope: 'write',
  handler: async (ctx, p) => {
    const sourceId = (p.source_id as string | undefined) ?? ctx.sourceId ?? 'default';
    validateSourceId(sourceId);
    // Same write-source check as loops_mute — an unmute is equally a targeted
    // write, and a federated read grant does not confer it: letting a remote
    // caller lift another source's suppression would re-open the very noise
    // channel its owner silenced.
    if (ctx.remote !== false) {
      const writeSource = (ctx.auth?.sourceId ?? ctx.sourceId) as string | undefined;
      if (!writeSource || sourceId !== writeSource) {
        throw muteScopeError(ctx, 'unmute', p, sourceId, writeSource);
      }
    }
    // Mirrors loops_mute: an omitted source_id resolving to a source with no
    // Google content can never hold a live suppression — refuse rather than
    // answer removed:false on a row that should never have existed.
    if (p.source_id === undefined && !(await sourceHasGoogleContent(ctx, sourceId))) {
      throw noGoogleContent(ctx, `loops_unmute: source "${sourceId}" holds no Google content — pass source_id naming the google source`);
    }
    const kind = p.kind as 'sender' | 'thread';
    const value = (p.value as string).toLowerCase();
    const undo = undoCommand('mute', kind, value, sourceId);
    if (ctx.dryRun) {
      const preview = await requeueMutedLoops(ctx.engine, sourceId, kind, value, false);
      return { dry_run: true, action: 'loops_unmute', kind, value, source_id: sourceId, would_requeue: preview.requeued,
        unverifiable: preview.unverifiable, count: preview.requeued.length, undo_command: undo };
    }
    const removed = await removeSuppression(ctx.engine, sourceId, kind, value);
    const { requeued, unverifiable } = await requeueMutedLoops(ctx.engine, sourceId, kind, value, true);
    (await import('../google/loop-detect.ts')).invalidateSuppressionCache(ctx.engine);
    const fresh = (await googleSourceFreshness(ctx, { sourceId })).sources[0];
    const stale = requeued.length > 0 && (fresh?.stale ?? true);
    // removed:false is the ordinary "was not muted" answer, never an error —
    // a retried unmute must be safe.
    return {
      removed: removed > 0,
      kind,
      value,
      source_id: sourceId,
      requeued,
      unverifiable,
      count: requeued.length,
      ...(stale ? { stale_source: true, recheck_command: `gbrain sync --source ${sourceId}` } : {}),
      undo_command: undo,
      ...(removed > 0 ? {} : { reason: 'no matching suppression' }),
    };
  },
};

export const loopsOperations: Operation[] = [open_loops, loops_close, loops_mute, loops_unmute];