Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(loops): keep no-counterparty loops out of the waiting ranking, cap groups at 5 (#5871)
garrytan18a6db458658
diff --git a/docs/architecture/key-files/google-and-loops.md b/docs/architecture/key-files/google-and-loops.mdindex 52771bbce2..8f76120664 100644--- a/docs/architecture/key-files/google-and-loops.md+++ b/docs/architecture/key-files/google-and-loops.md@@ -29,7 +29,7 @@ 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), auto-submitted mail (RFC 3834 `Auto-Submitted` other than `no`, which also never closes a loop, so an auto-reply is not an answer), 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; a failed facts write is logged with slug, source and a bounded error, never the commitment text, and the loop row still lands), 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`, `Auto-Submitted`, 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. A judge response cut off at the 2048-token cap (`stopReason: length`) is retried once at 8192; still truncated, the job fails retryable (`truncated`) with the ceiling named. Non-length errors and refusals are never escalated.- `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. `listOpenLoops` takes an optional `id` that composes with the status/type/counterparty filters and never replaces the source scope. `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). An optional `id` (positive safe integer, else `invalid_params` through `invalidParam` without echoing the value) finds one loop at any status unless `status` is given; explicit filters still intersect, scope and redaction are unchanged, so an out-of-scope id returns exactly what a missing id returns, and an id lookup carries no `text` digest. 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/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). An optional `id` (positive safe integer, else `invalid_params` through `invalidParam` without echoing the value) finds one loop at any status unless `status` is given; explicit filters still intersect, scope and redaction are unchanged, so an out-of-scope id returns exactly what a missing id returns, and an id lookup carries no `text` digest. 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. #5871: grouped output ranks people only; loops with neither a counterparty slug nor an email return in `no_counterparty` (`loop_count`, `by_type`, shown loops, `loops_omitted`; null when none), never ranked or counted by `limit`, and the digest lists them last and never says "You are clean" while they exist; each group shows at most `LOOPS_PER_GROUP` (5) loops, due-soonest then most recently active, with `loops_omitted` (`test/ops-loops.test.ts`, `test/loops-cli.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.- `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); 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. `loops show <id>` passes the id to `open_loops` (any status and rank); a missing positive id is a usage error (exit 2) and an unknown id renders `not_found` with the `gbrain loops list` fix (exit 1). 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.diff --git a/docs/guides/open-loops.md b/docs/guides/open-loops.mdindex 207172affe..2c571ae017 100644--- a/docs/guides/open-loops.md+++ b/docs/guides/open-loops.md@@ -218,6 +218,26 @@ source's suppression is as much a targeted write as planting one). `open_loops`point the read at the google source, grant-checked for remote callers) and`all_sources` (trusted local spans the brain; remote stays in-grant).+**Who counts as a person.** Grouped output ranks counterparties only. A loop+with neither a counterparty page nor an email (a `decision_pending` the+extractor could not attribute, say) is not a person, so it never takes a+ranked slot or counts toward `--top`/`limit`: it comes back in+`no_counterparty` and the digest lists it last under+`## No counterparty (N open: <type> N, …)`. When only such loops exist, the+digest says no person is waiting and lists them; it never says "You are+clean". Each group (and the no-counterparty section) shows at most 5 loops,+due-soonest first and then the most recently active; `loop_count` stays the+total and `loops_omitted` counts the rest (`+N more` in the digest).++```json+// before+{ "groups": [{ "counterparty": "unknown", "loop_count": 9, "loops": [/* all 9 */] },+ { "counterparty": "[email protected]", "loop_count": 8, "loops": [/* all 8 */] }] }+// after+{ "groups": [{ "counterparty": "[email protected]", "loop_count": 8, "loops": [/* 5 */], "loops_omitted": 3 }],+ "no_counterparty": { "loop_count": 9, "by_type": { "decision_pending": 9 }, "loops": [/* 5 */], "loops_omitted": 4 } }+```+When the scope holds **no google source at all**, the result carries`no_google_sources: true` and the digest says so explicitly instead of "Youare clean" — a brain whose email arrives through a gateway or agent-authoreddiff --git a/plugin/skills/google-loops/SKILL.md b/plugin/skills/google-loops/SKILL.mdindex 38055b6ae6..e6531f7885 100644--- a/plugin/skills/google-loops/SKILL.md+++ b/plugin/skills/google-loops/SKILL.md@@ -153,7 +153,7 @@ unanswered-thread detector is free and unaffected.## Output Format-When relaying `gbrain waiting`, present per counterparty, most urgent first:+When relaying `gbrain waiting`, present per counterparty, most urgent first, then the `## No counterparty` section (loops that name no person) last:```## <Counterparty> (<N> open)diff --git a/skills/google-loops/SKILL.md b/skills/google-loops/SKILL.mdindex c3afdac71e..222e863ada 100644--- a/skills/google-loops/SKILL.md+++ b/skills/google-loops/SKILL.md@@ -152,7 +152,7 @@ unanswered-thread detector is free and unaffected.## Output Format-When relaying `gbrain waiting`, present per counterparty, most urgent first:+When relaying `gbrain waiting`, present per counterparty, most urgent first, then the `## No counterparty` section (loops that name no person) last:```## <Counterparty> (<N> open)diff --git a/src/commands/loops.ts b/src/commands/loops.tsindex 4306205879..d612ae435f 100644--- a/src/commands/loops.ts+++ b/src/commands/loops.ts@@ -66,6 +66,8 @@ interface WaitingResult {}>;context?: { summary?: string; last_touched?: { last_timeline_date?: string | null } };}>;+ /** #5871: loops that name no counterparty, listed apart from the people; null when none. */+ no_counterparty?: { loop_count: number } | null;count: number;stale: boolean;sources: Array<{ id: string; last_sync_at: string | null; stale: boolean }>;@@ -133,7 +135,7 @@ export async function runWaiting(engine: BrainEngine, args: string[]): Promise<vreturn;}process.stdout.write((result.text ?? 'No open loops.') + '\n');- if (result.groups.length > 0) {+ if (result.groups.length > 0 || result.no_counterparty) {process.stdout.write(`\n(close: gbrain loops done <id> · mute a sender: gbrain loops mute sender <email> · details: gbrain loops list)\n`,);diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 68bbb3d116..1ba64ba102 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -259,6 +259,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.99.0', text: 'Fixable facts and takes fences are now rewritten instead of held or refused: managed sync, put_page and the fact and take writers normalize a fence whose meaning is unambiguous (a missing end marker after the table, two-dash takes markers, zero or duplicate row numbers, header aliases, invented kinds and enum synonyms, assistant holders, percent confidences) without changing a claim or an existing row number, and managed sync commits the rewritten file. Results report `fences_normalized`; `gbrain sync --dry-run` lists `would_normalize`. `gbrain config set fences.normalize false` turns it off (such fences are then held or refused).' },{ since: '0.0.0-wave11', text: 'Frontmatter validation and `--fix` no longer flag or rewrite valid YAML (a block-scalar line shaped like `Key: "a", then "b"`); a file an earlier `gbrain frontmatter validate --fix` rewrote can be restored from its backup under ~/.gbrain/backups/frontmatter/.' },{ since: '0.0.0-wave11', text: 'Facts the sweep extracts from a saved session file are dated when the file was written, not when the sweep ran; facts saved earlier keep their dates.' },+ { since: '0.0.0-wave11', text: '`gbrain waiting --json` and MCP `open_loops` changed shape: loops that name no counterparty are no longer ranked as the person "unknown" but returned in `no_counterparty`, and each group lists at most 5 loops with `loops_omitted` counting the rest (`loop_count` stays the total).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/ops/loops.ts b/src/core/ops/loops.tsindex 7b0c7cdb58..3fea493107 100644--- a/src/core/ops/loops.ts+++ b/src/core/ops/loops.ts@@ -239,9 +239,29 @@ interface CounterpartyGroup {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;@@ -257,7 +277,26 @@ function rankGroups(groups: CounterpartyGroup[], backlinks: Map<string, number>,return [...groups].sort((a, b) => score(b) - score(a) || a.counterparty.localeCompare(b.counterparty));}-function renderText(groups: CounterpartyGroup[], stale: boolean, noGoogleSources: boolean,+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,coverage: { completeness: 'complete' | 'partial'; held: HeldItemView[] }, nowMs: number,partialStaleSources: string[]): string {const lines: string[] = [];@@ -270,11 +309,16 @@ function renderText(groups: CounterpartyGroup[], stale: boolean, noGoogleSources}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) {+ 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@@ -293,17 +337,10 @@ function renderText(groups: CounterpartyGroup[], stale: boolean, noGoogleSourceslines.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) {- 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}`);- }+ 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');}@@ -314,7 +351,9 @@ const open_loops: Operation = {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) or flat. Loops come from the ' ++ '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 ' +@@ -420,8 +459,15 @@ const open_loops: Operation = {}const byKey = new Map<string, CounterpartyGroup>();+ const unattributed: LoopView[] = [];+ const byType: NoCounterpartyLoops['by_type'] = {};for (const l of loops) {- const key = l.counterparty_slug ?? l.counterparty_email ?? 'unknown';+ const key = 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 = {@@ -433,6 +479,7 @@ const open_loops: Operation = {oldest_opened_at: l.opened_at,nearest_due_at: null,loops: [],+ loops_omitted: 0,};byKey.set(key, g);}@@ -469,7 +516,10 @@ const open_loops: Operation = {} 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);+ 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) {@@ -489,6 +539,7 @@ const open_loops: Operation = {return {groups,+ no_counterparty: noCounterparty,count: loops.length,truncated,stale: freshness.stale,@@ -500,7 +551,7 @@ const open_loops: Operation = {redacted: !trusted,as_of: new Date(nowMs).toISOString(),...(trusted && loopId === undefined- ? { text: renderText(groups, freshness.stale, noGoogleSources, coverage, nowMs, partialStaleSources) }+ ? { text: renderText(groups, noCounterparty, freshness.stale, noGoogleSources, coverage, nowMs, partialStaleSources) }: {}),};},diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 6f48ce401d..01d54fe88e 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 207947,- "stdoutSha256": "e701d9d6ea58a198e29b939eba243b90349890cb3713631c940fbcbe6781e06d",+ "stdoutBytes": 208130,+ "stdoutSha256": "06ae73add41b18eedf984fd14f85603ad1aa57af46eb7597f05b27da457397a4","toolNames": ["remember","entity",@@ -6379,7 +6379,7 @@"scope": "admin"},{- "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) or flat. 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; present the answer as partial and name the held items and their retry command.",+ "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; present the answer as partial and name the held items and their retry command.","idempotent": true,"local_only": false,"mutating": false,diff --git a/test/loops-cli.test.ts b/test/loops-cli.test.tsindex 6aed76c6e7..b0cdb1c0d5 100644--- a/test/loops-cli.test.ts+++ b/test/loops-cli.test.ts@@ -194,6 +194,18 @@ describe('runWaiting', () => {expect(r.verdict).toBe(0);});+ // #5871: no-counterparty loops are listed in their own section, never as a person.+ test('only no-counterparty loops → their section and the management hint, never "You are clean"', async () => {+ await upsertOpenLoop(engine, loop({ dedupKey: 'decision:solo', loopType: 'decision_pending', counterpartyEmail: null, threadId: null,+ summary: 'Decide on the offsite venue', detector: 'llm_extract' }));+ const r = await captured(() => runWaiting(engine, []));+ expect(r.out).toContain('## No counterparty (1 open: decision_pending 1)');+ expect(r.out).not.toContain('You are clean');+ expect(r.out).toContain('gbrain loops done <id>');+ const j = await captured(() => runWaiting(engine, ['--json']));+ expect(JSON.parse(j.out)).toMatchObject({ ok: true, groups: [], no_counterparty: { loop_count: 1, loops_omitted: 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)diff --git a/test/ops-loops.test.ts b/test/ops-loops.test.tsindex 8bb77bd0cb..31c2819c83 100644--- a/test/ops-loops.test.ts+++ b/test/ops-loops.test.ts@@ -1124,3 +1124,62 @@ describe('loops_unmute', () => {).rejects.toThrow(/no Google content|invalid_params/);});});++// #5871: loops with no counterparty (decision_pending and the like) are not a+// person. They used to group under 'unknown' and rank first by sheer count.+describe('open_loops no-counterparty loops and the per-group cap (#5871)', () => {+ interface CappedResult extends GroupsResult {+ groups: Array<GroupsResult['groups'][number] & { loops_omitted: number }>;+ no_counterparty: { loop_count: number; by_type: Record<string, number>; loops: Array<Record<string, unknown>>; loops_omitted: number } | null;+ }+ async function seedPile(): Promise<void> {+ for (let i = 0; i < 9; i++) {+ await upsertOpenLoop(engine, loop({ dedupKey: `decision:${i}`, loopType: 'decision_pending', counterpartyEmail: null,+ threadId: null, summary: `Decide on vendor option ${i}`, detector: 'llm_extract' }));+ }+ for (let i = 0; i < 8; i++) {+ await upsertOpenLoop(engine, loop({ threadId: `18c2f4a9b3d21f${String(i).padStart(2, '0')}`, counterpartyEmail: '[email protected]',+ summary: `Reply owed to [email protected]: thread ${i}` }));+ }+ await upsertOpenLoop(engine, loop({ threadId: '18c2f4a9b3d21e99', counterpartyEmail: '[email protected]', summary: 'Reply owed to [email protected]' }));+ }++ for (const remote of [false, true]) {+ test(`${remote ? 'remote' : 'trusted'}: no-counterparty loops sit beside the people, never ranked, and each group shows at most 5`, async () => {+ await seedPile();+ const r = (await openLoopsOp.handler(ctx({ remote }), {})) as CappedResult;+ expect(r.groups.map((g) => g.counterparty)).toEqual(['[email protected]', '[email protected]']);+ expect(r.groups[0]).toMatchObject({ loop_count: 8, loops_omitted: 3 });+ expect(r.groups[0].loops).toHaveLength(5);+ expect(r.no_counterparty).toMatchObject({ loop_count: 9, by_type: { decision_pending: 9 }, loops_omitted: 4 });+ expect(r.no_counterparty!.loops).toHaveLength(5);+ expect(r.count).toBe(18);+ if (!remote) {+ expect(r.text).toContain('2 people are waiting on you');+ expect(r.text).not.toContain('## unknown');+ expect(r.text).toContain('+3 more');+ expect(r.text).toContain('## No counterparty (9 open: decision_pending 9)');+ }+ });+ }++ test('the group cap shows the due-soonest loop first', async () => {+ for (let i = 0; i < 6; i++) {+ await upsertOpenLoop(engine, loop({ threadId: `18c2f4a9b3d21a${String(i).padStart(2, '0')}`, summary: `Reply ${i}`,+ ...(i === 5 ? { dueAt: new Date(Date.now() + 86_400_000).toISOString() } : {}) }));+ }+ const r = (await openLoopsOp.handler(ctx({ remote: true }), {})) as CappedResult;+ expect(r.groups[0].loops[0].summary).toBe('Reply 5');+ expect(r.groups[0].loops_omitted).toBe(1);+ });++ test('only no-counterparty loops: no person is waiting, and the digest never says you are clean', async () => {+ await upsertOpenLoop(engine, loop({ dedupKey: 'decision:solo', loopType: 'decision_pending', counterpartyEmail: null, threadId: null,+ summary: 'Decide on the offsite venue', detector: 'llm_extract' }));+ const r = (await openLoopsOp.handler(ctx(), {})) as CappedResult;+ expect(r.groups).toEqual([]);+ expect(r.no_counterparty).toMatchObject({ loop_count: 1, loops_omitted: 0 });+ expect(r.text).not.toContain('You are clean');+ expect(r.text).toContain('## No counterparty (1 open: decision_pending 1)');+ });+});