Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(loops): link question marks, acknowledgement-only replies, request-time loop age, pinnable ranking clock (N7-2, N7-5, N7-6, N7-7)
garrytan09e1f905e1f5
diff --git a/docs/architecture/key-files/google-and-loops.md b/docs/architecture/key-files/google-and-loops.mdindex 67e85c7059..289a64b82d 100644--- a/docs/architecture/key-files/google-and-loops.md+++ b/docs/architecture/key-files/google-and-loops.md@@ -25,10 +25,10 @@ Historical Gmail repair selects explicit nested MIME metadata fields, excluding- `src/core/google/google-render.ts` — pure render functions (`{relPath, markdown}` out; no I/O, no engine): thread pages under `emails/YYYY/MM/` (type email), events under `calendar/YYYY/MM/` (type meeting), contacts under `people/` (type person). Gmail deep links are code-generated via the typed `emailCitation` scaffold, never LLM-composed. The noise/signature rules `recipes/email-to-brain.md` specifies as prose for agent-authored collectors are implemented here — keep the recipe and this module in sync. `isCalendarSystemMail({calendarMethod, subject})` gates BOTH loop detectors: the PRIMARY signal is a `calendarMethod` in the `CALENDAR_METHODS` allowlist (RFC 5546 — REQUEST, REPLY, CANCEL, PUBLISH, COUNTER, DECLINECOUNTER, REFRESH, ADD; case-insensitive); an empty or unrecognised method is NOT a stamp and falls to the subject fallback, which is anchored to the start of the subject, refuses any Re:/Fwd: prefix, and matches only Calendar's OWN localised headers (`Invitation:`, `Updated invitation:`, `Accepted:`, `Declined:`, `Tentative:`, `Canceled event:` + localised equivalents) — a generic word like `Notification:` is a human/vendor subject and never matches. `renderThreadPage` stamps `participants:` (every address on the thread) AND `senders:` (sorted unique message AUTHORS only — the list `loops mute sender` gates on, so muting one person cannot silence a whole group thread). Pinned by `test/google-render.test.ts`.- `src/core/google/google-source.ts` — the Google API source sweep. Unmanaged mode materializes Markdown under the source directory and imports through the standard chunks/aliases/links pipeline; managed mode uses journaled connector admission. Sweep order contacts → calendar → gmail: alias rows must exist before the loop detector resolves counterparties. Per-service independent cursors: contacts/calendar syncToken commits only after that service's fully-successful sweep (410 GONE drops the token and re-runs windowed); gmail delta rides history.list with an expired-history windowed fallback; the INITIAL backfill drains newest→oldest with a batch-committed floor cursor so a killed 50k-message backfill resumes at the floor instead of restarting, and the historyId anchor is captured BEFORE the backfill so the delta lane takes over with zero gap (overlap re-renders are idempotent). Emits the `sync.google_materialize` progress phase (docs/progress-events.md). Access resolves per source config: the vault (default), a token-printing command (`g_access: command` — gog/gcloud/gateway; identity entry synthesized, scope preflight trusts the configured services, send-as aliases fetched live best-effort), or a named env var (`g_access: env`). Secrets never land in `sources.config` (the command/env NAME is config; tokens are not). Honesty invariants: `last_sync_at` is gated on the GMAIL sweep's success (it feeds `gbrain waiting`'s trust-critical staleness gate, which protects loop freshness — a gmail sweep with real thread failures must not advance it); contacts/calendar failures mark the run `partial` but do not block the stamp, and a source without gmail in its services stamps unconditionally. A thread whose fetch fails on consecutive sweeps lands in the poison ledger and is skipped (steady-state runs honor the ledger; `--full` retries with a fresh one), so one bad thread can't wedge the sync while a poison-skip alone doesn't count as failure. Contact reconcile resolves by contact resourceName (DB lookup by contact id FIRST): deletion tombstones carry only `resourceName + deleted` (no names — slug derivation yields null) and a renamed contact derives a DIFFERENT slug, so both must land on the existing page by id, never by slug. The calendar sweep binds its sync token to its calendar: `sweepCalendar` compares `state.calendar_id` (legacy state without it is treated as primary's) with the configured `calendarId`; on a mismatch it logs `[google] calendar changed (<old> → <new>)`, discards the token and takes the windowed first-sync path (no `syncToken` on the wire), and a freshly banked token stores the calendar id beside it — pairing a re-pointed source with the previous calendar's cursor would import a foreign delta. Pages from the previous calendar are not reconciled on the switch (logged; a filed follow-up). `enqueueLoopsExtraction` enqueues EVERY eligible thread (newest first) under a waiting-depth budget `LOOPS_EXTRACT_ENQUEUE_CEILING − waiting` that counts only THIS source's waiting `loops_extract` jobs (`data->>'sourceId'`), so one account's stalled backlog cannot pin another source's budget at 0; overflow is a logged deferral (a deferred thread re-candidates when it changes) and a failed probe fails open. The budget probe counts PENDING rows — `status IN ('waiting','delayed','active')` — so a retry backlog parked in `delayed` during a flapping provider cannot stack past the ceiling. With no chat provider available (`isAvailable('chat')` false) the enqueue is skipped entirely and one stderr line per sweep names the reason and the count; pages still import and the threads re-candidate on their next touch or a `--full` sweep. Managed Google API sync uses journaled connector checkpoints; an unbound source is explicitly `connector_database`, while a bound source publishes canonical files. Identity-query storage failures do not become successful absence or advance the checkpoint. Unsupported Git/dry-run flags refuse before credentials/network; legacy materialization remains the unmanaged path. FILE MODES (every write, both paths): `writeGoogleState` writes `.google-source.json` through `atomicWriteFileSync(..., { mode: 0o600 })` under `mkdirPrivate(dir)`; a corrupt state file is chmod-ed 0600 and then renamed to `.corrupt`, and if either step fails stderr names the path, the failed step, the exposure and the fix (`chmod 600 <path>` or delete it) while the sync continues with empty cursors. A legacy page goes through `writePrivateTemp`: a stale `<page>.tmp` is removed with `lstat` (never followed; a stale `.tmp` directory fails that item with `Stale temporary path <path> is a directory; remove it and re-run the sync.`), the temp file is created `wx` at 0600 and fchmod-ed past the umask, imported, then renamed over the page; page directories come from `mkdirPrivate(dirname(page), cfg.dir)`. 0600 is reasserted on every rewrite, so a looser mode set by hand is reverted on the next rewrite (unchanged pages are not rewritten). Managed pages get the same modes through `publishMode` (see the persistence coordinator). Mode assertions are skipped on win32. Tests: `test/google-file-modes.test.ts` (child process under umask 0000, `test/helpers/google-file-modes-child.ts`).- `src/core/google/file-modes.ts` — detection and tightening for group/world-readable files gbrain wrote under a Google source directory outside `~/.gbrain` (inside it the 0700 home already protects them). `scanGoogleFileModes(engine, { sourceIds? })` reads non-archived Google sources, skips dirs inside the home (`outsideGbrainHome`, realpath-aware), and inspects only gbrain's own layout: `.google-source.json*` in the root, every recorded page `source_path` under `emails/`, `calendar/`, `people/` (malformed paths ignored), each page's `.tmp`, and the directories between the root and those pages. Each path is `lstat`-ed component by component (a symlink anywhere on the path, another owner, or the wrong file type is counted in `skipped`, never followed); an entry is loose when `mode & 0o077`. `tightenGoogleEntry(root, entry)` re-checks the path, opens the leaf `O_NOFOLLOW` (`O_DIRECTORY` for dirs), re-checks the owner on the fd and `fchmod`s `mode & ~0o077`, so a swap after the scan is refused, not followed; the user-chosen root is never in the candidate set. `googleFileModesPreviewCommand`/`googleFileModesApplyCommand` build the `gbrain repair google-file-modes --source <id> [--apply]` strings every surface prints. win32: scan returns nothing. Tests: `test/google-file-modes-repair.test.ts`.-- `src/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`). 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.+- `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.- `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. 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). `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. 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/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). `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/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.diff --git a/docs/guides/open-loops.md b/docs/guides/open-loops.mdindex 82889baaa5..be1146a315 100644--- a/docs/guides/open-loops.md+++ b/docs/guides/open-loops.md@@ -24,10 +24,17 @@ zero LLM, free, always on). For every synced Gmail thread:≥72h → `unanswered_outbound` — *you are waiting on them*.- a reply lands → the loop **closes itself** (`closed_by: reply_detected`).Loops close by state transition, never delete — the audit trail stays.+ A reply of yours that only acknowledges their question ("Thanks!",+ "Got it, thanks.") is not an answer: the loop stays open and its clock+ keeps running. "Will do" counts as a reply.+- a question mark inside a link (`https://docs.example.com/view?id=42`) is+ not a question, so an FYI that only shares a link opens nothing.- "unanswered" is measured from the oldest unanswered message since thelast turn flip (the first one addressed to you, or your first question),so a nudge or follow-up never restarts the clock — a request that waited- 40h and got a "bumping this" 5h ago opens on the first sync.+ 40h and got a "bumping this" 5h ago opens on the first sync. The loop's+ `opened_at` is that message's time, not the time gbrain noticed it, so a+ first sync of an old inbox ranks a 30-day wait as older than yesterday's.Precision rules (pinned by a labeled fixture corpus in`test/google-loop-detect.test.ts` — every false-positive class gets a@@ -197,7 +204,8 @@ carry additive optional fields (`direction`, `due`, `counterparty`,## Close semantics-- Thread loops close deterministically when a reply lands.+- Thread loops close deterministically when a reply lands (an+ acknowledgement-only reply to a question does not count).- Commitment loops close manually (`gbrain loops done`) or by staleness(overdue >14 days AND no activity in 14 days — an actively-discussedoverdue commitment stays open — or >90 days without any activity →@@ -212,4 +220,7 @@ carry additive optional fields (`direction`, `due`, `counterparty`,Counterparties rank by open-loop count, due-date proximity, age of theoldest loop, and how connected the person is in your brain (backlink-count). Deterministic — same data, same order.+count). Deterministic — same data and same reference time, same order. Due+dates and ages are relative to the reference time, which defaults to now;+pin it with `gbrain waiting --as-of <iso>` (MCP: `open_loops` `as_of`) to+reproduce a ranking. The result echoes it as `as_of`.diff --git a/src/commands/loops.ts b/src/commands/loops.tsindex f2d99a92d3..5095497f5a 100644--- a/src/commands/loops.ts+++ b/src/commands/loops.ts@@ -82,6 +82,7 @@ export async function runWaiting(engine: BrainEngine, args: string[]): Promise<v' --source <id> scope to one source (default: every source in the brain)',' --json agent envelope (groups, staleness, completeness, held items, sources)',' --stale-ok show possibly-outdated loops even when google sources have not synced in 24h',+ ' --as-of <iso> rank and age loops as of this time (default: now), to reproduce an order','','Manage loops: gbrain loops --help · Setup: gbrain google setup · Docs: docs/guides/open-loops.md',].join('\n') + '\n',@@ -92,11 +93,12 @@ export async function runWaiting(engine: BrainEngine, args: string[]): Promise<vconst staleOk = args.includes('--stale-ok');const topIdx = args.indexOf('--top');const top = topIdx !== -1 ? Number(args[topIdx + 1]) || 3 : 3;+ const asOfIdx = args.indexOf('--as-of');const result = (await handleToolCall(engine,'open_loops',- { group_by: 'counterparty', limit: top, include_context: true },+ { group_by: 'counterparty', limit: top, include_context: true, ...(asOfIdx !== -1 ? { as_of: args[asOfIdx + 1] } : {}) },{ sourceId: sourceFlag(args) ?? ALL_SOURCES },)) as WaitingResult;diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 6b9da0a73d..0addb69b86 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -72,7 +72,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'integrity': ['--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url'],'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--image', '--images', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--older-than', '--once', '--order', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--prune-orphans', '--queue', '--quiet', '--reason', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--vectors', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--abort', '--all', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-cron', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all'],- 'loops': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],+ 'loops': ['--all', '--as-of', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],'maintain': ['--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--explain', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--older-than', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],@@ -123,7 +123,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],'transcripts': ['--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout'],'upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],- 'waiting': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],+ 'waiting': ['--all', '--as-of', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],'whoknows': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--explain', '--federated-read', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--trusted-extraction', '--types', '--url', '--yes'],};diff --git a/src/core/google/loop-detect.ts b/src/core/google/loop-detect.tsindex 2d76f52e35..eae436eb60 100644--- a/src/core/google/loop-detect.ts+++ b/src/core/google/loop-detect.ts@@ -17,7 +17,11 @@* - list mail (List-Unsubscribe) never opens loops* - self-threads (all participants are my addresses) never open loops* - CC-only inbound does not owe a reply (must be in To:)- * - outbound without a question mark is FYI, not an ask+ * - outbound without a question mark is FYI, not an ask; a question mark+ * inside a link (?id=42) is not a question+ * - my acknowledgement-only reply ("Thanks!", "Got it") to a question is+ * not an answer: it neither closes the reply-owed loop nor flips the turn+ * ("Will do" is a commitment and still counts as the reply)* - suppressed senders/threads (gbrain loops mute) never open NEW loops;* existing loops keep their state* - grace windows: inbound 24h, outbound 72h — fresh mail is not a loop yet;@@ -48,6 +52,8 @@ export interface ThreadLoopSpec {summary: string;evidence: LoopEvidence[];lastActivityMs: number;+ /** When the obligation began: the oldest message in the trailing run that carries it. */+ openedMs: number;}export interface ThreadLoopVerdict {@@ -73,6 +79,24 @@ function ageHours(ms: number, now: Date): number {return (now.getTime() - ms) / 3_600_000;}+const URL_RE = /\b(?:https?:\/\/|www\.)\S+/gi;++/** A question mark outside any link. */+export function asksQuestion(text: string): boolean {+ return text.replace(URL_RE, '').includes('?');+}++const ACK_ONLY_RE =+ /^(?:(?:thanks|thank you|thx|ty|many thanks|thanks so much|thank you so much|got it|noted|received|ack|ok|okay|sounds good|cheers)[\s!.,]*)+$/i;+const SIGN_OFF_NAME_RE = /(?:,\s*|\s+[-–—]\s*)\p{Lu}[\p{Ll}.]{0,19}[\s!.]*$/u;++/** A short reply that only acknowledges ("Thanks!", "Got it, thanks.", "Thanks, Bob!"). */+export function isAcknowledgementOnly(text: string): boolean {+ const t = text.replace(/\s+/g, ' ').trim();+ if (t.length === 0 || t.length > 60) return false;+ return ACK_ONLY_RE.test(t) || ACK_ONLY_RE.test(t.replace(SIGN_OFF_NAME_RE, ''));+}+function quote(m: GmailMessageMeta): string {const q = m.bodyText.replace(/\s+/g, ' ').trim().slice(0, 200);return q;@@ -102,9 +126,23 @@ export function detectThreadLoop(// could exclude it without silencing that person entirely. And they must// not CLOSE one either: a calendar invite is not a reply, so letting it// flip the turn would silently answer a real outbound loop.- const substantive = messages.filter(- (m) => !isNoiseSender(m.fromAddress) && !isCalendarSystemMail(m),- );+ // My acknowledgement-only reply to their question is not an answer: drop+ // it so the turn stays theirs and the reply-owed loop neither closes nor+ // restarts its clock. An acknowledgement of a message that asked nothing+ // ("Here is the deck" / "Thanks!") still counts as the reply it is.+ const substantive: GmailMessageMeta[] = [];+ let theirQuestionPending = false;+ for (const m of messages) {+ if (isNoiseSender(m.fromAddress) || isCalendarSystemMail(m)) continue;+ if (!isMine(m, myAddresses)) {+ theirQuestionPending = asksQuestion(m.bodyText);+ } else if (theirQuestionPending && isAcknowledgementOnly(m.bodyText)) {+ continue;+ } else {+ theirQuestionPending = false;+ }+ substantive.push(m);+ }if (substantive.length === 0) return { open: [], close: [] };const last = substantive[substantive.length - 1];@@ -161,6 +199,7 @@ export function detectThreadLoop(counterpartyEmail: last.fromAddress,evidence: [{ message_id: last.id, quote: quote(last) }],lastActivityMs: last.internalDateMs,+ openedMs: owedSince.internalDateMs,},],close,@@ -168,13 +207,13 @@ export function detectThreadLoop(}// ── Last word is mine: am I waiting on them? ──- // No question mark → FYI/forward, not an ask.- if (!last.bodyText.includes('?')) return { open: [], close };+ // No question mark outside a link → FYI/forward, not an ask.+ if (!asksQuestion(last.bodyText)) return { open: [], close };const recipients = last.to.filter((a) => !myAddresses.has(a));if (recipients.length === 0) return { open: [], close };const counterparty = recipients[0];if (threadSuppressed || suppressions?.senders.has(counterparty)) return { open: [], close };- const askedSince = run.find((m) => m.bodyText.includes('?')) ?? last;+ const askedSince = run.find((m) => asksQuestion(m.bodyText)) ?? last;if (ageHours(askedSince.internalDateMs, now) < OUTBOUND_GRACE_HOURS) return { open: [], close };return {open: [@@ -184,6 +223,7 @@ export function detectThreadLoop(summary: `Waiting on ${counterparty}: "${subject}"`,evidence: [{ message_id: last.id, quote: quote(last) }],lastActivityMs: last.internalDateMs,+ openedMs: askedSince.internalDateMs,},],close,@@ -272,6 +312,7 @@ export async function applyThreadLoopVerdict(pageSlug,detector: 'deterministic_thread',lastActivityAt: new Date(spec.lastActivityMs).toISOString(),+ openedAt: new Date(spec.openedMs).toISOString(),});}}diff --git a/src/core/loops/loops-store.ts b/src/core/loops/loops-store.tsindex 62795e50b2..a33aa00d46 100644--- a/src/core/loops/loops-store.ts+++ b/src/core/loops/loops-store.ts@@ -46,6 +46,12 @@ export interface OpenLoopUpsert {factId?: number | null;/** Loop activity time (newest evidence message), ISO. Defaults to now(). */lastActivityAt?: string | null;+ /**+ * When the obligation began (the oldest unanswered message), ISO. Defaults+ * to now(). An open row keeps the earlier of its stored and the incoming+ * value; a reopened row takes the incoming one.+ */+ openedAt?: string | null;}export interface OpenLoopRow {@@ -111,12 +117,15 @@ export async function upsertOpenLoop(`INSERT INTO open_loops (source_id, dedup_key, loop_type, counterparty_slug, counterparty_email,summary, evidence, thread_id, page_slug, due_at, detector, confidence,- fact_id, last_activity_at+ fact_id, last_activity_at, opened_at) VALUES ($1, $2, $3, $4, $5, $6, $7::text::jsonb, $8, $9, $10::timestamptz, $11, $12,- $13, COALESCE($14::timestamptz, now())+ $13, COALESCE($14::timestamptz, now()), COALESCE($15::timestamptz, now()))ON CONFLICT (source_id, dedup_key) DO UPDATE SET+ opened_at = CASE WHEN open_loops.status = 'open'+ THEN LEAST(open_loops.opened_at, EXCLUDED.opened_at)+ ELSE EXCLUDED.opened_at END,status = 'open',loop_type = EXCLUDED.loop_type,counterparty_slug = COALESCE(EXCLUDED.counterparty_slug, open_loops.counterparty_slug),@@ -149,6 +158,7 @@ export async function upsertOpenLoop(loop.confidence ?? 1.0,loop.factId ?? null,loop.lastActivityAt ?? null,+ loop.openedAt ?? null,],);// The DO UPDATE's WHERE is the manual-close guard: a closed (done/dropped/diff --git a/src/core/ops/loops.ts b/src/core/ops/loops.tsindex af47558418..aec5673894 100644--- a/src/core/ops/loops.ts+++ b/src/core/ops/loops.ts@@ -215,14 +215,14 @@ interface CounterpartyGroup {context?: unknown;}-function rankGroups(groups: CounterpartyGroup[], backlinks: Map<string, number>): CounterpartyGroup[] {+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) - Date.now()) / 86_400_000;+ 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 = (Date.now() - Date.parse(g.oldest_opened_at)) / 86_400_000;+ 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;@@ -231,7 +231,7 @@ function rankGroups(groups: CounterpartyGroup[], backlinks: Map<string, number>)}function renderText(groups: CounterpartyGroup[], stale: boolean, noGoogleSources: boolean,- coverage: { completeness: 'complete' | 'partial'; held: HeldItemView[] } = { completeness: 'complete', held: [] }): string {+ coverage: { completeness: 'complete' | 'partial'; held: HeldItemView[] }, nowMs: number): string {const lines: string[] = [];const { held } = coverage;if (stale) lines.push('⚠ google sources have not synced recently — this may be out of date.');@@ -264,7 +264,7 @@ function renderText(groups: CounterpartyGroup[], stale: boolean, noGoogleSourcesconst 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((Date.now() - Date.parse(l.last_activity_at)) / 86_400_000));+ 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}"`);@@ -294,11 +294,16 @@ const open_loops: Operation = {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 new OperationError('invalid_params', `open_loops: as_of must be an ISO 8601 timestamp, got ${JSON.stringify(p.as_of)}`);+ }const groupBy = (p.group_by as string | undefined) ?? 'counterparty';const status = ((p.status as string | undefined) ?? 'open') as LoopStatus;// Per-call scope via the canonical trust+grant resolver: an MCP caller@@ -418,7 +423,7 @@ 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).slice(0, limit);+ const groups = rankGroups([...byKey.values()], backlinks, nowMs).slice(0, limit);// Entity-card context (zero-LLM, trusted local only).if (trusted && (p.include_context as boolean | undefined) !== false) {@@ -446,7 +451,8 @@ const open_loops: Operation = {held: coverage.held,no_google_sources: noGoogleSources,redacted: !trusted,- ...(trusted ? { text: renderText(groups, freshness.stale, noGoogleSources, coverage) } : {}),+ as_of: new Date(nowMs).toISOString(),+ ...(trusted ? { text: renderText(groups, freshness.stale, noGoogleSources, coverage, nowMs) } : {}),};},};diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 76a2907a26..440f2435e9 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": 202985,- "stdoutSha256": "bd0de8ec965e91bfc419afeccf1983ff9bc1d2590e38ec76d3b751dd53e3fe47",+ "stdoutBytes": 203219,+ "stdoutSha256": "e07561286578badf4a4d0fbf7c4d1099ca3a90a938e578a2cfedb439ddf8501f","toolNames": ["remember","entity",@@ -5116,6 +5116,7 @@"name": "open_loops","parameters": {"all_sources": "boolean?",+ "as_of": "string?","counterparty": "string?","group_by": "string?","include_context": "boolean?",@@ -5130,6 +5131,10 @@"description": "Trusted local: span every source in the brain. Remote callers stay inside their grant.","type": "boolean"},+ "as_of": {+ "description": "Reference time (ISO 8601) for due-date proximity, loop age and rendered ages. Default: now. Pin it to reproduce a ranking.",+ "type": "string"+ },"counterparty": {"description": "Filter to one counterparty (slug or email).","type": "string"diff --git a/test/google-loop-detect.test.ts b/test/google-loop-detect.test.tsindex 512c775275..079bfacadd 100644--- a/test/google-loop-detect.test.ts+++ b/test/google-loop-detect.test.ts@@ -13,7 +13,9 @@import { describe, expect, test } from 'bun:test';import {+ asksQuestion,detectThreadLoop,+ isAcknowledgementOnly,INBOUND_GRACE_HOURS,OUTBOUND_GRACE_HOURS,type ThreadLoopVerdict,@@ -542,6 +544,82 @@ describe('detectThreadLoop precision corpus', () => {});});+// gbrain-evals N7 (2026-10-02 receipt, repros n7-2, n7-6, n7-7).+describe('N7 eval regressions', () => {+ test('N7-7: a question mark inside a link is not an ask', () => {+ expect(asksQuestion('FYI, the doc: https://docs.example.com/view?id=42')).toBe(false);+ expect(asksQuestion('See www.example.com/a?b=c for details.')).toBe(false);+ expect(asksQuestion('Can you check https://docs.example.com/view?id=42 ?')).toBe(true);+ const v = detectThreadLoop(+ thread([msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 100, sent: true, body: 'FYI, the doc: https://docs.example.com/view?id=42' })]),+ MY,+ NOW,+ );+ expect(v.open).toEqual([]);+ });++ test('N7-2: "Thanks!" to a question neither closes nor restarts the reply-owed loop', () => {+ const ask = msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 40, body: 'Can you send the deck?' });+ const v = detectThreadLoop(+ thread([ask, msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 30, sent: true, body: 'Thanks!' })]),+ MY,+ NOW,+ );+ expect(v.close).not.toContain('unanswered_inbound');+ expect(v.open).toHaveLength(1);+ expect(v.open[0].loopType).toBe('unanswered_inbound');+ expect(v.open[0].openedMs).toBe(ask.internalDateMs);+ });++ test('N7-2: an acknowledgement of a message that asked nothing is still a reply', () => {+ const v = detectThreadLoop(+ thread([+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 40, body: 'Here is the deck.' }),+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 30, sent: true, body: 'Thanks!' }),+ ]),+ MY,+ NOW,+ );+ expect(v.open).toEqual([]);+ expect(v.close).toEqual(['unanswered_inbound']);+ });++ test('N7-2: a substantive reply still closes', () => {+ const v = detectThreadLoop(+ thread([+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 40, body: 'Can you send the deck?' }),+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 30, sent: true, body: 'Thanks! Attached is the deck.' }),+ ]),+ MY,+ NOW,+ );+ expect(v.open).toEqual([]);+ expect(v.close).toEqual(['unanswered_inbound']);+ });++ test('acknowledgement detection is narrow', () => {+ for (const t of ['Thanks!', 'thank you', 'Got it, thanks.', 'Thanks, Bob!', 'ok']) expect(isAcknowledgementOnly(t)).toBe(true);+ for (const t of ['Yes', 'No, not this week.', 'Thanks! Attached.', 'Thanks, sending it tomorrow.', 'Will do.', '']) expect(isAcknowledgementOnly(t)).toBe(false);+ });++ test('N7-6: the loop opens at the oldest message that carries the obligation', () => {+ const first = msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 720, body: 'Can you review this?' });+ const v = detectThreadLoop(+ thread([first, msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 30, body: 'Bumping this.' })]),+ MY,+ NOW,+ );+ expect(v.open[0].openedMs).toBe(first.internalDateMs);+ const ask = msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 200, sent: true, body: 'Can you review?' });+ const out = detectThreadLoop(+ thread([ask, msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 100, sent: true, body: 'Any news?' })]),+ MY,+ NOW,+ );+ expect(out.open[0].openedMs).toBe(ask.internalDateMs);+ });+});+describe('google calendar system mail', () => {const detect = (messages: GmailMessageMeta[]): ThreadLoopVerdict =>detectThreadLoop(thread(messages), MY, NOW);diff --git a/test/loop-apply.test.ts b/test/loop-apply.test.tsindex 1e486f680a..9a93785f95 100644--- a/test/loop-apply.test.ts+++ b/test/loop-apply.test.ts@@ -80,6 +80,25 @@ function inboundThread(from: string, threadId = '18c2f4a9b3d21e07'): GmailThread}describe('applyThreadLoopVerdict', () => {+ test('N7-6: opened_at is the request time, so a backfill ranks a 30-day wait older than a 30-hour one', async () => {+ for (const [tid, age] of [['18c2f4a9b3d21e01', 720], ['18c2f4a9b3d21e02', 30]] as const) {+ await applyThreadLoopVerdict(engine, 'g1', thread([msg({ from: `${tid}@example.com`, to: ['[email protected]'], ageHours: age, threadId: tid })], tid), MY, null, NOW);+ }+ const rows = await listOpenLoops(engine, { sourceIds: ['g1'], status: 'open' });+ const opened = new Map(rows.map((r) => [r.thread_id, Date.parse(r.opened_at)]));+ expect(opened.get('18c2f4a9b3d21e01')).toBe(NOW.getTime() - 720 * 3_600_000);+ expect(opened.get('18c2f4a9b3d21e02')).toBe(NOW.getTime() - 30 * 3_600_000);+ });++ test('N7-6: a re-apply keeps the earlier opened_at and repairs a detection-time one', async () => {+ const t = thread([msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 300 })]);+ await applyThreadLoopVerdict(engine, 'g1', t, MY, null, NOW);+ await engine.executeRaw(`UPDATE open_loops SET opened_at = now()`);+ await applyThreadLoopVerdict(engine, 'g1', t, MY, null, NOW);+ const [row] = await listOpenLoops(engine, { sourceIds: ['g1'], status: 'open' });+ expect(Date.parse(row.opened_at)).toBe(NOW.getTime() - 300 * 3_600_000);+ });+test('creates the loop row with dedup thread:<tid>:unanswered_inbound and merges page_slug into evidence', async () => {await applyThreadLoopVerdict(engine,diff --git a/test/ops-loops.test.ts b/test/ops-loops.test.tsindex 2d57b6dd09..93b8d23368 100644--- a/test/ops-loops.test.ts+++ b/test/ops-loops.test.ts@@ -164,6 +164,25 @@ describe('open_loops grouped', () => {);});+ test('N7-5: as_of pins the ranking clock, so the same rows give the same order at any wall-clock time', async () => {+ const T = Date.parse('2026-10-01T12:00:00Z');+ const D = 86_400_000;+ await upsertOpenLoop(engine, loop({ dedupKey: 'a', loopType: 'commitment_owed_by_me', counterpartyEmail: '[email protected]', detector: 'llm_extract', dueAt: new Date(T + 8 * D).toISOString() }));+ await upsertOpenLoop(engine, loop({ dedupKey: 'b', loopType: 'commitment_owed_to_me', counterpartyEmail: '[email protected]', detector: 'llm_extract' }));+ await engine.executeRaw(+ `UPDATE open_loops SET opened_at = CASE dedup_key WHEN 'a' THEN $1::timestamptz ELSE $2::timestamptz END`,+ [new Date(T).toISOString(), new Date(T - 10 * D).toISOString()],+ );+ const order = async (asOf: string) =>+ ((await openLoopsOp.handler(ctx({ remote: true }), { as_of: asOf })) as GroupsResult & { as_of: string });+ const atT = await order(new Date(T).toISOString());+ const later = await order(new Date(T + 2 * D).toISOString());+ expect(atT.groups.map((g) => g.counterparty)).not.toEqual(later.groups.map((g) => g.counterparty));+ expect((await order(new Date(T).toISOString())).groups.map((g) => g.counterparty)).toEqual(atT.groups.map((g) => g.counterparty));+ expect(atT.as_of).toBe(new Date(T).toISOString());+ await expect(openLoopsOp.handler(ctx(), { as_of: 'yesterday' })).rejects.toThrow('as_of');+ });+test('limit caps GROUPS (default 3) while count reports total loops', async () => {await seedRanked();// A fourth counterparty that ranks last.