Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
P4.1 #5504: loops resolve their counterparty across sources by identity and record its source
garrytanb69d4ff9402b
diff --git a/docs/architecture/key-files/open-loops-engine.md b/docs/architecture/key-files/open-loops-engine.mdindex b87089146d..5674108eed 100644--- a/docs/architecture/key-files/open-loops-engine.md+++ b/docs/architecture/key-files/open-loops-engine.md@@ -8,8 +8,9 @@ close semantics). The Gmail sweep that feeds both lanes is in- `src/core/google/loops-exclusion.ts` — the user's own label exclusion for the open-loop engine (#5445). `excludedLabelTokens` reads the source's `g_loops_exclude_labels`, else the brain-wide `loops.extraction_exclude_labels` (no merge); `resolveExcludedLabels` matches tokens against the account's label catalog (id verbatim, name case-insensitively; with no catalog only id-shaped tokens resolve) into a `LoopsExclusionPolicy { tokens, ids, unresolved }`, where a non-empty `unresolved` means FAIL CLOSED for new paid extraction. `resolveSweepExclusion` (`loops-enqueue.ts`) runs it once per Gmail sweep (one `GmailClient.getLabels` call when anything is configured), logs each unresolved name, and `storeLoopsExclusion` keeps the resolution in `op_checkpoints` (op `loops-exclusion`, keyed like the loop outcomes) so `loadLoopsExclusionPolicy` can apply the policy without a Gmail client at the two late sites: `runLoopsExtract` (skips `excluded_label`, throws retryable `excluded_label_unresolved`) and `openDueGraceHold` (`'excluded'` drops the hold, `'deferred'` keeps it). A stored resolution is reused only for the same token list; changed tokens fall back to id-only until the next sweep. The policy gates `loopExtractionEligibility` right after SPAM/TRASH and before the owner override (reasons `excluded_label` / `excluded_label_unresolved` in the sweep's counters), `withLabelExclusion` strips the opens from a `detectThreadLoop` verdict (closes untouched), `recordGraceVerdict` records no hold for an excluded thread, `runLoopsCatchup` skips with `excluded_label_unresolved`, and `enqueueLoopsExtraction` reports the same `skipped_reason` ahead of `no_candidates`. The leaf is `excluded` from connector identity. Tests: `test/loops-exclusion.test.ts`, `test/google-source-reconcile.test.ts` ("label exclusion (#5445)"), `test/loops-extract-run.serial.test.ts` ("#5445 execution-time").- `src/core/google/loops-spend.ts` — the daily spend cap on loop extraction (wave 14 P4.6b): `loops.extraction_max_usd_per_day` (default $2.00, validated at `config set` by `validateLoopsSpendConfigValue`; a stored value is `user`-sourced). `loopsSpendGate` is what both enqueue sites call: it reads the cap and the day's group spend (`readGroupSpend` on `group:<day group>`) and returns the `SpendAuthorization` to stamp (`loopsExtractSpendAuthorization`: kind `authorized`, command `loops_extract`, via `preapproval`, one deterministic UUID per UTC day from `loopsSpendGroupId`) or the reason to queue nothing (`daily_spend_cap` at the cap, `spend_cap_zero` at 0). The sweep's `enqueueLoopsExtraction` and the catch-up's enqueue pass that record through `MinionQueue.add`'s trusted `spendAuthorization` option, so the worker runs each job under `runWithJobSpend` (spend-authorization.ts): every provider attempt reserves against the group and settles its usage; refusal before the call is `cost_cap_exceeded`, recorded on the row. An unreadable meter admits the enqueue (the worker still enforces). Tests: `test/loops-extract-spend-cap.test.ts`.+- `src/core/google/counterparty.ts` — where a loop's counterparty page is (#5504, wave 14 P4.1). `resolveCounterparty(engine, sourceId, { name, email })` tries the loop's OWN source first through `resolveEntitySlugWithSource` (name, then email; never the slugify fallback), and only then crosses a source boundary by identity: an `entity_identities` canonical member in another source (`identity_canonical`, which also redirects an own-source stub to its canonical twin) or the exact email as a `page_aliases` row on exactly one live page in exactly one other source (`email_alias`). A display name never crosses, a tie (two other sources) stays unresolved and the loop keeps a NULL counterparty rather than a guess. Both writers (`loop-detect.ts` `upsertThreadLoop`, `loops-extract.ts`) stamp the result into `open_loops.counterparty_source_id` and point the `owes_to` / `awaiting_reply_from` edge at the page's source; the commitment fact stays in the connector source. Readers confine with `COALESCE(counterparty_source_id, source_id)` (`COUNTERPARTY_SOURCE_SQL`): a row written before v232 reads as its own source. `src/core/loops/loops-schema.ts` is the leaf the migration and the store share (column DDL + the partial index `open_loops_counterparty_source_idx`).- `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/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; `counterpartySourceId` narrows a `counterparty` slug match to the source the page lives in (`COALESCE(counterparty_source_id, source_id)`), leaving an email match untouched (#5504). `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. #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/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 a1662ca2be..0925f6db50 100644--- a/docs/guides/open-loops.md+++ b/docs/guides/open-loops.md@@ -79,6 +79,19 @@ decisions. One extractor, three projections per item:- a typed edge thread-page → person-page (`owes_to` / `awaiting_reply_from`)— so relational search can traverse it+The person page a loop points at may live in another source than the mail:+on a federated brain the Gmail source holds the threads while+`people/<slug>` lives in `default`. Both detectors resolve the counterparty+in the mail's own source first and then across sources by identity only:+the exact email address as an alias of one page in one other source, or an+`entity_identities` group whose canonical member sits elsewhere. A display+name alone never crosses a source and a tie stays unresolved, so a loop is+either attached to a real page or carries no counterparty page at all. The+loop row records which source that page is in (`counterparty_source_id`),+the typed edge points there, and the entity card, `gbrain waiting` and+`open_loops` read the loop from that page, never from a namesake in another+source. The commitment fact itself stays in the mail's source.+Guardrails: injection-hardened input (the model sees the NEWEST 12k of thethread, so the latest reply is always visible to the judge), ALL-or-nothingparse barrier (a malformed model response writes nothing), only the last 30diff --git a/src/core/google/counterparty.ts b/src/core/google/counterparty.tsnew file mode 100644index 0000000000..115963309e--- /dev/null+++ b/src/core/google/counterparty.ts@@ -0,0 +1,100 @@+/**+ * Counterparty resolution for open loops (#5504, wave 14 P4.1).+ *+ * A loop's counterparty is a person named in a connector source (a Gmail+ * sweep), while the person's page often lives in another source (`default`+ * on a federated brain). Resolution runs in two steps and records the source+ * it landed in, so `open_loops.counterparty_source_id` can confine every+ * later read to one (source, slug) page:+ *+ * 1. the loop's OWN source, through the ordinary resolver, any+ * high-confidence arm (never the slugify fallback);+ * 2. failing that, ACROSS sources by identity only (T8): the exact email+ * as a page alias (one live page in one other source), or a page the+ * own-source hit belongs to through `entity_identities` whose canonical+ * member sits elsewhere. A display name never crosses a source+ * boundary, and a tie (two sources match) stays unresolved.+ *+ * Facts stay in the connector source (T5): this module only decides where+ * the loop row and its typed edge point.+ */+import type { BrainEngine } from '../engine.ts';+import { normalizeAlias } from '../search/alias-normalize.ts';+import { isUndefinedTableError } from '../utils.ts';++export interface ResolvedCounterparty {+ slug: string;+ sourceId: string;+ via: 'same_source' | 'identity_canonical' | 'email_alias';+}++/** The identity group's canonical member when the page has one in ANOTHER source. */+async function canonicalTwin(engine: BrainEngine, sourceId: string, slug: string): Promise<{ slug: string; sourceId: string } | null> {+ try {+ const rows = await engine.executeRaw<{ slug: string; source_id: string }>(+ `SELECT c.slug, ei.source_id+ FROM entity_identities me+ JOIN pages p ON p.id = me.page_id AND p.source_id = $1 AND p.slug = $2 AND p.deleted_at IS NULL+ JOIN entity_identities ei ON ei.entity_id = me.entity_id AND ei.canonical AND ei.source_id <> $1+ JOIN pages c ON c.id = ei.page_id AND c.deleted_at IS NULL+ LIMIT 2`,+ [sourceId, slug],+ );+ return rows.length === 1 ? { slug: rows[0]!.slug, sourceId: rows[0]!.source_id } : null;+ } catch (err) {+ if (isUndefinedTableError(err)) return null;+ throw err;+ }+}++/** A live page in exactly one other source that declares the exact email as an alias. */+async function emailAliasElsewhere(engine: BrainEngine, sourceId: string, email: string): Promise<{ slug: string; sourceId: string } | null> {+ const norm = normalizeAlias(email);+ if (!norm || !norm.includes('@')) return null;+ try {+ const rows = await engine.executeRaw<{ slug: string; source_id: string }>(+ `SELECT DISTINCT pa.slug, pa.source_id+ FROM page_aliases pa+ JOIN pages p ON p.slug = pa.slug AND p.source_id = pa.source_id AND p.deleted_at IS NULL+ WHERE pa.alias_norm = $1 AND pa.source_id <> $2+ LIMIT 2`,+ [norm, sourceId],+ );+ return rows.length === 1 ? { slug: rows[0]!.slug, sourceId: rows[0]!.source_id } : null;+ } catch (err) {+ if (isUndefinedTableError(err)) return null;+ throw err;+ }+}++/**+ * Where the loop's counterparty page is, or null when nothing resolves with+ * confidence. `name` and `email` are what the detector or the model saw;+ * either may be empty.+ */+export async function resolveCounterparty(+ engine: BrainEngine,+ sourceId: string,+ ref: { name?: string | null; email?: string | null },+): Promise<ResolvedCounterparty | null> {+ const own = [ref.name?.trim(), ref.email?.trim()].filter((v): v is string => Boolean(v));+ if (own.length === 0) return null;+ const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts');+ for (const raw of own) {+ const resolved = await resolveEntitySlugWithSource(engine, sourceId, raw);+ if (!resolved || resolved.source === 'fallback_slugify') continue;+ const canonical = await canonicalTwin(engine, sourceId, resolved.slug);+ return canonical ? { ...canonical, via: 'identity_canonical' } : { slug: resolved.slug, sourceId, via: 'same_source' };+ }+ const elsewhere = ref.email ? await emailAliasElsewhere(engine, sourceId, ref.email) : null;+ if (!elsewhere) return null;+ const canonical = await canonicalTwin(engine, elsewhere.sourceId, elsewhere.slug);+ return canonical ? { ...canonical, via: 'identity_canonical' } : { ...elsewhere, via: 'email_alias' };+}++/**+ * The `(counterparty_slug, source)` predicate readers confine a loop → entity+ * join with: a row written before v232 has no counterparty source and is read+ * as its own source, the posture it was written under.+ */+export const COUNTERPARTY_SOURCE_SQL = 'COALESCE(counterparty_source_id, source_id)';diff --git a/src/core/google/loop-detect.ts b/src/core/google/loop-detect.tsindex 28585001cf..f7820f3975 100644--- a/src/core/google/loop-detect.ts+++ b/src/core/google/loop-detect.ts@@ -42,6 +42,7 @@ import {type LoopEvidence,type SuppressionSet,} from '../loops/loops-store.ts';+import { resolveCounterparty, type ResolvedCounterparty } from './counterparty.ts';import { isCalendarSystemMail, isNoiseSender } from './google-render.ts';import { hasBulkCategory } from './gmail-categories.ts';import { isExcludedByLabels, NO_EXCLUSION, pageLabelIds, type LoopsExclusionPolicy } from './loops-exclusion.ts';@@ -281,7 +282,8 @@ export function __clearSuppressionCacheForTests(engine?: BrainEngine): void {/*** Apply the verdict: close thread loops that no longer hold, upsert the ones* that do (dedup key 'thread:<threadId>:<loop_type>' — reopen on conflict).- * Counterparty slug resolution is alias-exact within the same source.+ * Counterparty resolution: own source first, then identity-only across+ * sources (google/counterparty.ts, #5504).*/export async function applyThreadLoopVerdict(engine: BrainEngine,@@ -354,13 +356,12 @@ async function upsertThreadLoop(spec: ThreadLoopSpec,pageSlug: string | null,): Promise<void> {- let counterpartySlug: string | null = null;+ // Own source first, then across sources by identity only (#5504); a+ // slugify fallback would fabricate a person that doesn't exist, so an+ // unresolved counterparty stays NULL.+ let counterparty: ResolvedCounterparty | null = null;try {- const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts');- const resolved = await resolveEntitySlugWithSource(engine, sourceId, spec.counterpartyEmail);- // Only alias-exact/high-confidence resolutions count — a slugify- // fallback would fabricate a person that doesn't exist.- if (resolved && resolved.source !== 'fallback_slugify') counterpartySlug = resolved.slug;+ counterparty = await resolveCounterparty(engine, sourceId, { email: spec.counterpartyEmail });} catch {/* resolution is best-effort */}@@ -368,7 +369,8 @@ async function upsertThreadLoop(sourceId,dedupKey: `thread:${threadId}:${spec.loopType}`,loopType: spec.loopType,- counterpartySlug,+ counterpartySlug: counterparty?.slug ?? null,+ counterpartySourceId: counterparty?.sourceId ?? null,counterpartyEmail: spec.counterpartyEmail,summary: spec.summary,evidence: spec.evidence.map((e) => ({ ...e, ...(pageSlug ? { page_slug: pageSlug } : {}) })),diff --git a/src/core/google/loops-extract.ts b/src/core/google/loops-extract.tsindex d19e6948bf..20ed21d45c 100644--- a/src/core/google/loops-extract.ts+++ b/src/core/google/loops-extract.ts@@ -31,6 +31,7 @@ import { isCalendarSystemMail, isNoiseSender, sha8 } from './google-render.ts';import { hasBulkCategory } from './gmail-categories.ts';import { isExcludedByLabels, loadLoopsExclusionPolicy, NO_EXCLUSION, pageLabelIds, type LoopsExclusionPolicy } from './loops-exclusion.ts';import { bareAddress, type GmailMessageMeta, type GmailThreadData } from './types.ts';+import { resolveCounterparty, type ResolvedCounterparty } from './counterparty.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';import { deriveTrust } from '../trust/taint.ts';import { applyGateDecision, derivedGateConfig, derivedGateInput } from '../trust/derived-gate.ts';@@ -487,16 +488,15 @@ export async function runLoopsExtract(` (${typeof code === 'string' ? code : err instanceof Error ? err.name : 'error'}): ${(err instanceof Error ? err.message : String(err)).slice(0, 200)}`);}- // Counterparty slug: high-confidence resolutions only. The facts layer's- // slugify holding fallback is fine for facts, but a phantom slug on the- // loop row would group `gbrain waiting` under a person that doesn't- // exist and miss every entity-card lookup.- let counterpartySlug: string | null = null;+ // Counterparty page: high-confidence resolutions only, own source first+ // and then across sources by identity (#5504; google/counterparty.ts).+ // The facts layer's slugify holding fallback is fine for facts, but a+ // phantom slug on the loop row would group `gbrain waiting` under a+ // person that doesn't exist and miss every entity-card lookup.+ let counterparty: ResolvedCounterparty | null = null;if (counterpartyRef) {try {- const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts');- const resolved = await resolveEntitySlugWithSource(engine, payload.sourceId, counterpartyRef);- if (resolved && resolved.source !== 'fallback_slugify') counterpartySlug = resolved.slug;+ counterparty = await resolveCounterparty(engine, payload.sourceId, { name: c.counterparty_name, email: c.counterparty_email });} catch {/* resolution is best-effort */}@@ -508,7 +508,8 @@ export async function runLoopsExtract(sourceId: payload.sourceId,dedupKey,loopType,- counterpartySlug,+ counterpartySlug: counterparty?.slug ?? null,+ counterpartySourceId: counterparty?.sourceId ?? null,counterpartyEmail: c.counterparty_email || null,summary: c.text,evidence: [{ page_slug: payload.slug, ...(c.quote ? { quote: c.quote } : {}) }],@@ -523,18 +524,20 @@ export async function runLoopsExtract(loopIds.push(id);// Projection 3 — typed edge thread-page → person-page, so the relational- // arm ("who owes me", "who am I waiting on") can traverse it.- if (counterpartySlug) {+ // arm ("who owes me", "who am I waiting on") can traverse it. The edge+ // points at the page's own source; the fact above stays in the connector+ // source (#5504).+ if (counterparty) {try {await engine.addLink( // gbrain-allow-direct-insert: loops-extract writes its own provenance-tagged edges (link_source google-loops); auto-link reconciliation never manages thesepayload.slug,- counterpartySlug,+ counterparty.slug,(c.quote || c.text).slice(0, 200),c.direction === 'owed_by_me' ? 'owes_to' : 'awaiting_reply_from','google-loops',undefined,undefined,- { fromSourceId: payload.sourceId, toSourceId: payload.sourceId },+ { fromSourceId: payload.sourceId, toSourceId: counterparty.sourceId },);} catch {/* edge is best-effort */diff --git a/src/core/loops/loops-schema.ts b/src/core/loops/loops-schema.tsnew file mode 100644index 0000000000..d6b0d40a0d--- /dev/null+++ b/src/core/loops/loops-schema.ts@@ -0,0 +1,16 @@+/**+ * Schema pieces of the open-loop store that a migration and the store share+ * (leaf module: no engine import). `open_loops.counterparty_source_id`+ * (#5504, wave 14 P4.1) records which source the counterparty page the loop+ * resolved to lives in; NULL on rows written before it existed, which readers+ * treat as the loop's own source (the posture those rows were written under).+ */+export const OPEN_LOOPS_COUNTERPARTY_SOURCE_COLUMN_SQL =+ 'ALTER TABLE open_loops ADD COLUMN IF NOT EXISTS counterparty_source_id TEXT';++export const OPEN_LOOPS_COUNTERPARTY_SOURCE_INDEX = {+ name: 'open_loops_counterparty_source_idx',+ table: 'open_loops',+ sql: `CREATE INDEX IF NOT EXISTS open_loops_counterparty_source_idx+ ON open_loops (counterparty_source_id, counterparty_slug) WHERE status = 'open' AND counterparty_source_id IS NOT NULL`,+} as const;diff --git a/src/core/loops/loops-store.ts b/src/core/loops/loops-store.tsindex deec074aed..72aceb03aa 100644--- a/src/core/loops/loops-store.ts+++ b/src/core/loops/loops-store.ts@@ -35,6 +35,12 @@ export interface OpenLoopUpsert {dedupKey: string;loopType: LoopType;counterpartySlug?: string | null;+ /**+ * Source of the page `counterpartySlug` names (#5504). Omitted or null+ * means the loop's own source, which is how every reader treats a NULL+ * column (rows written before v232).+ */+ counterpartySourceId?: string | null;counterpartyEmail?: string | null;summary: string;evidence: LoopEvidence[];@@ -60,6 +66,8 @@ export interface OpenLoopRow {dedup_key: string;loop_type: LoopType;counterparty_slug: string | null;+ /** Source of the counterparty page; NULL on pre-v232 rows (read as `source_id`). */+ counterparty_source_id: string | null;counterparty_email: string | null;summary: string;evidence: LoopEvidence[];@@ -94,6 +102,7 @@ function normalizeRow(r: Record<string, unknown>): OpenLoopRow {// returns numbers — without coercion, id equality (`loops show <id>`,// close-by-id checks) silently fails on real Postgres only.id: Number(r.id),+ counterparty_source_id: typeof r.counterparty_source_id === 'string' ? r.counterparty_source_id : null,fact_id: r.fact_id === null || r.fact_id === undefined ? null : Number(r.fact_id),confidence: Number(r.confidence ?? 1),evidence:@@ -117,10 +126,10 @@ 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, opened_at+ fact_id, last_activity_at, opened_at, counterparty_source_id) VALUES ($1, $2, $3, $4, $5, $6, $7::text::jsonb, $8, $9, $10::timestamptz, $11, $12,- $13, COALESCE($14::timestamptz, now()), COALESCE($15::timestamptz, now())+ $13, COALESCE($14::timestamptz, now()), COALESCE($15::timestamptz, now()), $16)ON CONFLICT (source_id, dedup_key) DO UPDATE SETopened_at = CASE WHEN open_loops.status = 'open'@@ -129,6 +138,9 @@ export async function upsertOpenLoop(status = 'open',loop_type = EXCLUDED.loop_type,counterparty_slug = COALESCE(EXCLUDED.counterparty_slug, open_loops.counterparty_slug),+ counterparty_source_id = CASE WHEN EXCLUDED.counterparty_slug IS NULL+ THEN open_loops.counterparty_source_id+ ELSE EXCLUDED.counterparty_source_id END,counterparty_email = COALESCE(EXCLUDED.counterparty_email, open_loops.counterparty_email),summary = EXCLUDED.summary,evidence = EXCLUDED.evidence,@@ -159,6 +171,7 @@ export async function upsertOpenLoop(loop.factId ?? null,loop.lastActivityAt ?? null,loop.openedAt ?? null,+ loop.counterpartySlug ? (loop.counterpartySourceId ?? null) : null,],);// The DO UPDATE's WHERE is the manual-close guard: a closed (done/dropped/@@ -218,6 +231,12 @@ export interface ListLoopsOpts {status?: LoopStatus;loopType?: LoopType;counterparty?: string;+ /**+ * With `counterparty`, the source the counterparty page lives in (#5504):+ * a slug match counts only when the loop's counterparty source (its own+ * source for a pre-v232 row) is this one. An email match is unaffected.+ */+ counterpartySourceId?: string;/*** Restrict the read to the loop with this primary key. It is ANDed with* every other filter, so the source scope above still bounds the result.@@ -236,7 +255,9 @@ export async function listOpenLoops(WHERE ($1::text IS NULL OR source_id = ANY(string_to_array($1, ',')))AND ($2::text IS NULL OR status = $2)AND ($3::text IS NULL OR loop_type = $3)- AND ($4::text IS NULL OR counterparty_slug = $4 OR counterparty_email = $4)+ AND ($4::text IS NULL+ OR (counterparty_slug = $4 AND ($6::text IS NULL OR COALESCE(counterparty_source_id, source_id) = $6))+ OR counterparty_email = $4)AND ($5::bigint IS NULL OR id = $5::bigint)ORDER BY last_activity_at DESC, id DESCLIMIT ${limit}`,@@ -246,6 +267,7 @@ export async function listOpenLoops(opts.loopType ?? null,opts.counterparty ?? null,opts.loopId === undefined ? null : opts.loopId,+ opts.counterpartySourceId ?? null,],);return rows.map(normalizeRow);diff --git a/src/core/ops/loops.ts b/src/core/ops/loops.tsindex 3fea493107..1030b776f5 100644--- a/src/core/ops/loops.ts+++ b/src/core/ops/loops.ts@@ -232,9 +232,12 @@ interface CounterpartyGroup {counterparty: string;counterparty_slug: string | null;counterparty_email: string | null;- /** The loops' home source — entity cards/aliases live THERE, not in the- * caller's (often 'default') scope. */+ /** 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-v232 row reads as its own source. */+ counterparty_source_id: string;loop_count: number;oldest_opened_at: string;nearest_due_at: string | null;@@ -462,7 +465,9 @@ const open_loops: Operation = {const unattributed: LoopView[] = [];const byType: NoCounterpartyLoops['by_type'] = {};for (const l of loops) {- const key = l.counterparty_slug ?? l.counterparty_email;+ 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;@@ -471,10 +476,11 @@ const open_loops: Operation = {let g = byKey.get(key);if (!g) {g = {- counterparty: key,+ 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,@@ -496,9 +502,9 @@ const open_loops: Operation = {.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 loops' home sources first (same- // composite-key discipline as deepLinksFor), then fold back to slugs.- const srcIds = [...new Set([...byKey.values()].map((g) => g.source_id))];+ // 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 pagesWHERE source_id = ANY(string_to_array($2, E'\\n'))@@ -527,11 +533,13 @@ const open_loops: Operation = {for (const g of groups) {if (!g.counterparty_slug) continue;try {- // The card resolves in the LOOP'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).- const card = await buildEntityCard(ctx.engine, g.source_id, g.counterparty_slug, { remote: false });+ // 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 */ }}diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex f08dfeeffd..ed00b02841 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 231;+export const LATEST_SCHEMA_VERSION = 232;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 7b020ce4dc..0cdde7acc1 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -232,6 +232,7 @@ import { v228 } from './v228-memory-purge.ts';import { v229 } from './v229-trust-allow-rules.ts';import { v230 } from './v230-trust-generation.ts';import { v231 } from './v231-fact-purge-lookup-indexes.ts';+import { v232 } from './v232-open-loops-counterparty-source.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -462,4 +463,5 @@ export const MIGRATIONS: Migration[] = [v229,v230,v231,+ v232,];diff --git a/src/core/schema-migrations/v232-open-loops-counterparty-source.ts b/src/core/schema-migrations/v232-open-loops-counterparty-source.tsnew file mode 100644index 0000000000..9af4dc4551--- /dev/null+++ b/src/core/schema-migrations/v232-open-loops-counterparty-source.ts@@ -0,0 +1,28 @@+import type { Migration } from './types.ts';+import { OPEN_LOOPS_COUNTERPARTY_SOURCE_COLUMN_SQL, OPEN_LOOPS_COUNTERPARTY_SOURCE_INDEX } from '../loops/loops-schema.ts';+import { buildIndexOnline, migrationNotice } from './helpers.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// #5504 (wave 14 P4.1): `open_loops.counterparty_source_id` names the source of+// the person page a loop's counterparty resolved to. loops_extract and the+// deterministic detector resolve a counterparty in the loop's own source first+// and, failing that, across sources by identity only (an entity_identities+// canonical member or an exact-email alias; google/counterparty.ts), so a+// Gmail source's loop can point at `default:people/<slug>`. Readers that join a+// loop to an entity page confine on both predicates (slug AND source), with a+// NULL (pre-v232 row) read as the loop's own source. Nullable, no default,+// metadata-only on Postgres 11+ and PGLite; not in schema.sql's CREATE TABLE,+// so fresh and upgraded brains share column ordinals (the v180/v221 pattern).+// The partial index serves the entity card's lookup; Postgres builds it+// CONCURRENTLY on a dedicated connection, PGLite inline (buildIndexOnline).+export const v232: Migration = {+ version: 232,+ name: 'open_loops_counterparty_source',+ idempotent: true,+ sql: `${OPEN_LOOPS_COUNTERPARTY_SOURCE_COLUMN_SQL};`,+ handler: async engine => {+ await buildIndexOnline(engine, 232, OPEN_LOOPS_COUNTERPARTY_SOURCE_INDEX, { notice: migrationNotice });+ },+};diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.tsindex b066566e10..6e99b6b1d7 100644--- a/src/core/verbs/entity-card.ts+++ b/src/core/verbs/entity-card.ts@@ -467,7 +467,11 @@ async function assembleCard(const openThreads: EntityOpenThread[] = [];const loopFactIds = new Set<number>();try {- // Zero-LLM, indexed lookup — stays inside the p99<100ms budget.+ // Zero-LLM, indexed lookup — stays inside the p99<100ms budget. A loop+ // belongs to this card when its counterparty page is THIS (source, slug):+ // a Gmail-source loop whose person page lives in `default` shows on the+ // default card, a pre-v232 row (NULL counterparty source) on its own+ // source's card (#5504).const loopRows = await engine.executeRaw<{id: number;loop_type: string;@@ -478,7 +482,8 @@ async function assembleCard(}>(`SELECT id, loop_type, summary, due_at, last_activity_at, fact_idFROM open_loops- WHERE status = 'open' AND counterparty_slug = $1 AND source_id = $2+ WHERE status = 'open' AND counterparty_slug = $1+ AND COALESCE(counterparty_source_id, source_id) = $2ORDER BY last_activity_at DESCLIMIT ${OPEN_THREADS_CAP}`,[pageSlug, sourceId],diff --git a/test/e2e/loops-counterparty-null-entity-postgres.test.ts b/test/e2e/loops-counterparty-null-entity-postgres.test.tsnew file mode 100644index 0000000000..16164beafb--- /dev/null+++ b/test/e2e/loops-counterparty-null-entity-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../loops-counterparty-null-entity.test.ts'));diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex e7d9d1a1a8..751d1c1e1e 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -1110,6 +1110,7 @@"op_checkpoints_sync_hold_page_idx": "CREATE INDEX op_checkpoints_sync_hold_page_idx ON public.op_checkpoints USING btree ((((completed_keys -> 0) ->> 'page_id'::text))) WHERE (op = 'sync-hold'::text)","op_checkpoints_updated_at_idx": "CREATE INDEX op_checkpoints_updated_at_idx ON public.op_checkpoints USING btree (updated_at)","open_loops_counterparty_idx": "CREATE INDEX open_loops_counterparty_idx ON public.open_loops USING btree (source_id, counterparty_slug) WHERE (status = 'open'::text)",+ "open_loops_counterparty_source_idx": "CREATE INDEX open_loops_counterparty_source_idx ON public.open_loops USING btree (counterparty_source_id, counterparty_slug) WHERE ((status = 'open'::text) AND (counterparty_source_id IS NOT NULL))","open_loops_dedup": "CREATE UNIQUE INDEX open_loops_dedup ON public.open_loops USING btree (source_id, dedup_key)","open_loops_pkey": "CREATE UNIQUE INDEX open_loops_pkey ON public.open_loops USING btree (id)","open_loops_status_idx": "CREATE INDEX open_loops_status_idx ON public.open_loops USING btree (source_id, status, last_activity_at DESC)",@@ -2474,7 +2475,8 @@"18 closed_at timestamp with time zone/timestamptz NULL","19 closed_by text/text NULL","20 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",- "21 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "21 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "22 counterparty_source_id text/text NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex 15fbc1cf0c..14c78c022e 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -1110,6 +1110,7 @@"op_checkpoints_sync_hold_page_idx": "CREATE INDEX op_checkpoints_sync_hold_page_idx ON public.op_checkpoints USING btree ((((completed_keys -> 0) ->> 'page_id'::text))) WHERE (op = 'sync-hold'::text)","op_checkpoints_updated_at_idx": "CREATE INDEX op_checkpoints_updated_at_idx ON public.op_checkpoints USING btree (updated_at)","open_loops_counterparty_idx": "CREATE INDEX open_loops_counterparty_idx ON public.open_loops USING btree (source_id, counterparty_slug) WHERE (status = 'open'::text)",+ "open_loops_counterparty_source_idx": "CREATE INDEX open_loops_counterparty_source_idx ON public.open_loops USING btree (counterparty_source_id, counterparty_slug) WHERE ((status = 'open'::text) AND (counterparty_source_id IS NOT NULL))","open_loops_dedup": "CREATE UNIQUE INDEX open_loops_dedup ON public.open_loops USING btree (source_id, dedup_key)","open_loops_pkey": "CREATE UNIQUE INDEX open_loops_pkey ON public.open_loops USING btree (id)","open_loops_status_idx": "CREATE INDEX open_loops_status_idx ON public.open_loops USING btree (source_id, status, last_activity_at DESC)",@@ -2474,7 +2475,8 @@"18 closed_at timestamp with time zone/timestamptz NULL","19 closed_by text/text NULL","20 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",- "21 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "21 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "22 counterparty_source_id text/text NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex 60b2f16aef..115f674fe7 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -1106,6 +1106,7 @@"op_checkpoints_sync_hold_page_idx": "CREATE INDEX op_checkpoints_sync_hold_page_idx ON public.op_checkpoints USING btree ((((completed_keys -> 0) ->> 'page_id'::text))) WHERE (op = 'sync-hold'::text)","op_checkpoints_updated_at_idx": "CREATE INDEX op_checkpoints_updated_at_idx ON public.op_checkpoints USING btree (updated_at)","open_loops_counterparty_idx": "CREATE INDEX open_loops_counterparty_idx ON public.open_loops USING btree (source_id, counterparty_slug) WHERE (status = 'open'::text)",+ "open_loops_counterparty_source_idx": "CREATE INDEX open_loops_counterparty_source_idx ON public.open_loops USING btree (counterparty_source_id, counterparty_slug) WHERE ((status = 'open'::text) AND (counterparty_source_id IS NOT NULL))","open_loops_dedup": "CREATE UNIQUE INDEX open_loops_dedup ON public.open_loops USING btree (source_id, dedup_key)","open_loops_pkey": "CREATE UNIQUE INDEX open_loops_pkey ON public.open_loops USING btree (id)","open_loops_status_idx": "CREATE INDEX open_loops_status_idx ON public.open_loops USING btree (source_id, status, last_activity_at DESC)",@@ -2470,7 +2471,8 @@"18 closed_at timestamp with time zone/timestamptz NULL","19 closed_by text/text NULL","20 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",- "21 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "21 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "22 counterparty_source_id text/text NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex b29dec1fcf..454df2fd6a 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 226,+ "count": 227,"gaps": [17,18,@@ -14,6 +14,7 @@"FACT_RELINK_TABLE_SQL": "1fdde4b99d0077365274096f294be64a992961c7b4544af794224de238b03630","FACT_UNLINKED_INDEX_SQL": "87dcf23c3fa570d93bfb214b6bbb024faa9ff9bff227aa78869a29580be03298","ISSUANCE_CLOCK_SLACK_SECONDS": "8f36c80392df6f9b9c754826289b63969d9d41ca8955213291e4413d614dce35",+ "OPEN_LOOPS_COUNTERPARTY_SOURCE_INDEX": "e9b472d9db37733e908ea40512ad3f9520d7a6729ce207b0d279d43d3beb5b2f","PAGES_RECONCILE_NAME_INDEXES": "8805e35341b22324b932b1cc05030cc8f2bfc95532bf810ec35330783f29c59a","PERSISTENCE_COMMITTED_WATERMARK_INDEX": "f472fa0acb542c1caebaaa3bc69fb2da1647e5e201239429fc02ccef0d669533","PERSISTENCE_COMPACTABLE_INDEX": "25ee657878efb41ba9ea3a7624464ddcf66407d861659456c230366e57f230a0",@@ -41,7 +42,7 @@"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5","verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"},- "latest": 231,+ "latest": 232,"records": [{"handler": {@@ -3455,6 +3456,29 @@"transaction": "absent","verify": "absent","version": 231+ },+ {+ "handler": {+ "form": "arrow",+ "helpers": [+ "OPEN_LOOPS_COUNTERPARTY_SOURCE_INDEX",+ "buildIndexOnline",+ "dropInvalidConcurrentIndex",+ "migrationNotice",+ "quietMigrationNotices"+ ],+ "sha256": "3cc85accec244596bd36b032d658121ae3c3b8fc48b3e8d52d918813433de225"+ },+ "idempotent": true,+ "name": "open_loops_counterparty_source",+ "sql": {+ "length": 76,+ "sha256": "1976b6a28a5078fa1879722e27fdd7778d9524810212c1e4953a6b9cf0b78d70"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 232}],"versions": [@@ -3683,7 +3707,8 @@228,229,230,- 231+ 231,+ 232]},"normalizer": "migrations-record-v1"diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.jsonindex 314db54966..e42c16f9d0 100644--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json@@ -1110,6 +1110,7 @@"op_checkpoints_sync_hold_page_idx": "CREATE INDEX op_checkpoints_sync_hold_page_idx ON public.op_checkpoints USING btree ((((completed_keys -> 0) ->> 'page_id'::text))) WHERE (op = 'sync-hold'::text)","op_checkpoints_updated_at_idx": "CREATE INDEX op_checkpoints_updated_at_idx ON public.op_checkpoints USING btree (updated_at)","open_loops_counterparty_idx": "CREATE INDEX open_loops_counterparty_idx ON public.open_loops USING btree (source_id, counterparty_slug) WHERE (status = 'open'::text)",+ "open_loops_counterparty_source_idx": "CREATE INDEX open_loops_counterparty_source_idx ON public.open_loops USING btree (counterparty_source_id, counterparty_slug) WHERE ((status = 'open'::text) AND (counterparty_source_id IS NOT NULL))","open_loops_dedup": "CREATE UNIQUE INDEX open_loops_dedup ON public.open_loops USING btree (source_id, dedup_key)","open_loops_pkey": "CREATE UNIQUE INDEX open_loops_pkey ON public.open_loops USING btree (id)","open_loops_status_idx": "CREATE INDEX open_loops_status_idx ON public.open_loops USING btree (source_id, status, last_activity_at DESC)",@@ -2474,7 +2475,8 @@"18 closed_at timestamp with time zone/timestamptz NULL","19 closed_by text/text NULL","20 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",- "21 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "21 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "22 counterparty_source_id text/text NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/loops-counterparty-null-entity.test.ts b/test/loops-counterparty-null-entity.test.tsnew file mode 100644index 0000000000..0db6833e9c--- /dev/null+++ b/test/loops-counterparty-null-entity.test.ts@@ -0,0 +1,241 @@+/**+ * #5504 (wave 14 P4.1): a loop's counterparty page may live in another+ * source than the loop. On a federated brain the Gmail source carries the+ * thread pages while `people/<slug>` lives in `default`.+ *+ * (a) A counterparty nothing resolves with confidence leaves the loop row+ * with a NULL slug and a NULL counterparty source, fabricates no page in+ * any source and writes no edge.+ * (b) The resolver (google/counterparty.ts) crosses a source boundary by+ * identity only: an exact-email alias in exactly one other source, or an+ * entity_identities canonical member. A display name never crosses, a tie+ * stays unresolved. Both writers stamp `counterparty_source_id`, the+ * typed edge points at the page's source, and every reader confines on+ * (slug, counterparty source): the entity card in `default` shows the+ * Gmail loop, a namesake page in the Gmail source does not inherit it.+ *+ * Runs on PGLite and, with DATABASE_URL, on an isolated Postgres database+ * (test/e2e/loops-counterparty-null-entity-postgres.test.ts registers the+ * Postgres arm; the E2E matrix adds the PgBouncer transaction-mode pass).+ * Synthetic data only.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { configureGateway, resetGateway, __setChatTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';+import { runLoopsExtract } from '../src/core/google/loops-extract.ts';+import { applyThreadLoopVerdict } from '../src/core/google/loop-detect.ts';+import { resolveCounterparty } from '../src/core/google/counterparty.ts';+import { listOpenLoops } from '../src/core/loops/loops-store.ts';+import { buildEntityCard } from '../src/core/verbs/entity-card.ts';+import { loopsOperations } from '../src/core/ops/loops.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import type { GmailThreadData } from '../src/core/google/types.ts';+import { normalizeAlias } from '../src/core/search/alias-normalize.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const G1 = 'g1';+const OTHER = 'other';+const engines: Array<{ engine: BrainEngine; close: () => Promise<void> }> = [];+const usage = { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 };++async function seed(engine: BrainEngine): Promise<void> {+ for (const id of [G1, OTHER]) {+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ($1, $1, '{"kind":"google"}'::jsonb) ON CONFLICT (id) DO NOTHING`, [id]);+ }+ const person = (title: string) => ({ type: 'person', title, compiled_truth: `# ${title}\n` });+ const alias = (sourceId: string, raw: string, slug: string) =>+ engine.executeRaw(`INSERT INTO page_aliases (source_id, alias_norm, slug) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`, [sourceId, normalizeAlias(raw), slug]);+ // Alice: page and email alias in default only (the federated-brain case).+ await engine.putPage('people/alice-example', person('Alice Example'), { sourceId: 'default' });+ await alias('default', '[email protected]', 'people/alice-example');+ await alias('default', 'Alice Example', 'people/alice-example');+ // A namesake slug in the Gmail source: a stub that must not inherit Alice's loops.+ await engine.putPage('people/alice-example', { ...person('Alice (stub)'), frontmatter: { google_contact_id: 'c1' } }, { sourceId: OTHER });+ // Bob: name alias in default, no email alias anywhere (names never cross).+ await engine.putPage('people/bob-example', person('Bob Example'), { sourceId: 'default' });+ await alias('default', 'Bob Example', 'people/bob-example');+ // Carol: email alias in two other sources (a tie).+ await engine.putPage('people/carol-example', person('Carol Example'), { sourceId: 'default' });+ await engine.putPage('people/carol-example', person('Carol Example'), { sourceId: OTHER });+ await alias('default', '[email protected]', 'people/carol-example');+ await alias(OTHER, '[email protected]', 'people/carol-example');+ // Dave: connector stub in g1 with its alias, identity group canonical in default.+ await engine.putPage('people/dave-stub', person('Dave Example'), { sourceId: G1 });+ await alias(G1, 'Dave Example', 'people/dave-stub');+ await engine.putPage('people/dave-example', person('Dave Example'), { sourceId: 'default' });+ const ids = await engine.executeRaw<{ id: number; source_id: string }>(+ `SELECT id, source_id FROM pages WHERE slug IN ('people/dave-stub', 'people/dave-example') AND source_id IN ($1, 'default')`, [G1]);+ for (const r of ids) {+ await engine.executeRaw(`INSERT INTO entity_identities (entity_id, source_id, page_id, canonical) VALUES ('ent-dave', $1, $2, $3)`,+ [r.source_id, r.id, r.source_id === 'default']);+ }+ // Erin: resolvable in the Gmail source itself.+ await engine.putPage('people/erin-example', person('Erin Example'), { sourceId: G1 });+ await alias(G1, '[email protected]', 'people/erin-example');+}++beforeAll(async () => {+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });+ for (const backend of testBackends()) {+ if (backend === 'pglite') {+ const engine = new PGLiteEngine();+ await engine.connect({ database_url: '' });+ await engine.initSchema();+ engines.push({ engine, close: () => engine.disconnect() });+ } else {+ engines.push(await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ }+ }+ for (const { engine } of engines) await seed(engine);+}, 120_000);++afterAll(async () => {+ __setChatTransportForTests(null);+ resetGateway();+ for (const e of engines) await e.close();+});++function chatReturns(commitments: Array<Record<string, unknown>>): void {+ __setChatTransportForTests(async (): Promise<ChatResult> => ({+ text: JSON.stringify({ commitments, decisions_pending: [] }), blocks: [], stopReason: 'end', usage,+ model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic',+ }));+}++async function emailPage(engine: BrainEngine, slug: string, threadId: string, from: string, body: string): Promise<void> {+ await engine.putPage(slug, {+ type: 'email', title: `Re: ${threadId}`, compiled_truth: `From: ${from}\n\n${body}\n`,+ frontmatter: { thread_id: threadId, date: '2026-09-20T10:00:00Z', from },+ effective_date: new Date('2026-09-20T10:00:00Z'),+ }, { sourceId: G1 });+}++async function extract(engine: BrainEngine, slug: string, threadId: string, c: Record<string, unknown>) {+ await emailPage(engine, slug, threadId, String(c.counterparty_email || '[email protected]'), 'I will send you the deck by Friday.');+ chatReturns([{ direction: 'owed_by_me', text: `Send the deck (${threadId})`, due_iso: null, quote: 'I will send you the deck by Friday.', ...c }]);+ const r = await runLoopsExtract(engine, { slug, sourceId: G1 });+ expect(r).toMatchObject({ status: 'extracted', commitments: 1 });+ const [row] = await engine.executeRaw<{ counterparty_slug: string | null; counterparty_source_id: string | null }>(+ `SELECT counterparty_slug, counterparty_source_id FROM open_loops WHERE source_id = $1 AND thread_id = $2`, [G1, threadId]);+ return row;+}++async function edgesFrom(engine: BrainEngine, slug: string) {+ return engine.executeRaw<{ to_slug: string; to_source: string; link_type: string }>(+ `SELECT t.slug AS to_slug, t.source_id AS to_source, l.link_type FROM links l+ JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id+ WHERE f.slug = $1 AND f.source_id = $2 AND l.link_source = 'google-loops'`, [slug, G1]);+}++describe('(a) an unresolvable counterparty', () => {+ test('writes a NULL-counterparty loop, no page in any source and no edge', async () => {+ for (const { engine } of engines) {+ const row = await extract(engine, 'emails/nobody', 'thread-nobody', { counterparty_name: 'Nobody Known', counterparty_email: '[email protected]' });+ expect(row).toEqual({ counterparty_slug: null, counterparty_source_id: null });+ const pages = await engine.executeRaw<{ slug: string }>(`SELECT slug FROM pages WHERE slug <> 'emails/nobody' AND (slug LIKE '%nobody%' OR slug LIKE '%known%') AND deleted_at IS NULL`);+ expect(pages).toEqual([]);+ expect(await edgesFrom(engine, 'emails/nobody')).toEqual([]);+ }+ }, 60_000);+});++describe('(b) resolver: identity-only cross-source matching', () => {+ test('own source first, then an exact-email alias in exactly one other source', async () => {+ for (const { engine } of engines) {+ expect(await resolveCounterparty(engine, G1, { name: 'Erin Example', email: '[email protected]' }))+ .toEqual({ slug: 'people/erin-example', sourceId: G1, via: 'same_source' });+ expect(await resolveCounterparty(engine, G1, { name: 'Alice Example', email: '[email protected]' }))+ .toEqual({ slug: 'people/alice-example', sourceId: 'default', via: 'email_alias' });+ }+ });++ test('a display name never crosses a source; a tie stays unresolved', async () => {+ for (const { engine } of engines) {+ expect(await resolveCounterparty(engine, G1, { name: 'Bob Example', email: '[email protected]' })).toBeNull();+ expect(await resolveCounterparty(engine, G1, { name: 'Bob Example' })).toBeNull();+ expect(await resolveCounterparty(engine, G1, { name: 'Carol Example', email: '[email protected]' })).toBeNull();+ }+ });++ test('an entity_identities canonical member in another source wins over the local stub', async () => {+ for (const { engine } of engines) {+ expect(await resolveCounterparty(engine, G1, { name: 'Dave Example', email: '[email protected]' }))+ .toEqual({ slug: 'people/dave-example', sourceId: 'default', via: 'identity_canonical' });+ }+ });+});++describe('(b) writers stamp counterparty_source_id', () => {+ test('loops_extract: the row names the page source and the owes_to edge points there', async () => {+ for (const { engine } of engines) {+ const row = await extract(engine, 'emails/alice', 'thread-alice', { counterparty_name: 'Alice Example', counterparty_email: '[email protected]' });+ expect(row).toEqual({ counterparty_slug: 'people/alice-example', counterparty_source_id: 'default' });+ expect(await edgesFrom(engine, 'emails/alice')).toEqual([{ to_slug: 'people/alice-example', to_source: 'default', link_type: 'owes_to' }]);+ const same = await extract(engine, 'emails/erin', 'thread-erin', { counterparty_name: 'Erin Example', counterparty_email: '[email protected]' });+ expect(same).toEqual({ counterparty_slug: 'people/erin-example', counterparty_source_id: G1 });+ }+ }, 60_000);++ test('deterministic detector: an unanswered inbound from Alice resolves across sources', async () => {+ for (const { engine } of engines) {+ const thread: GmailThreadData = {+ threadId: 'thread-alice-inbound', account: '[email protected]',+ messages: [{+ id: 'm1', threadId: 'thread-alice-inbound', from: 'Alice Example <[email protected]>', fromAddress: '[email protected]',+ to: ['[email protected]'], cc: [], subject: 'Quarterly plan', bodyText: 'Can you review the plan?', dateIso: '2026-09-10T10:00:00Z',+ internalDateMs: Date.parse('2026-09-10T10:00:00Z'), labelIds: ['INBOX'], listUnsubscribe: false,+ }],+ };+ const verdict = await applyThreadLoopVerdict(engine, G1, thread, new Set(['[email protected]']), null, new Date('2026-09-20T10:00:00Z'));+ expect(verdict.open.map((s) => s.loopType)).toEqual(['unanswered_inbound']);+ const [row] = await engine.executeRaw<{ counterparty_slug: string | null; counterparty_source_id: string | null }>(+ `SELECT counterparty_slug, counterparty_source_id FROM open_loops WHERE source_id = $1 AND thread_id = $2`, [G1, 'thread-alice-inbound']);+ expect(row).toEqual({ counterparty_slug: 'people/alice-example', counterparty_source_id: 'default' });+ }+ }, 60_000);+});++describe('(b) readers confine on (slug, counterparty source)', () => {+ test("Alice's card in default shows the Gmail loops; the namesake stub in another source does not", async () => {+ for (const { engine } of engines) {+ const card = await buildEntityCard(engine, 'default', 'people/alice-example', { remote: false });+ expect(card.found).toBe(true);+ const threads = (card.card!.open_threads ?? []).filter((t) => t.loop_id !== undefined);+ expect(threads.map((t) => t.direction).sort()).toEqual(['my_turn', 'owed_by_me']);+ const stub = await buildEntityCard(engine, OTHER, 'people/alice-example', { remote: false });+ expect(stub.found).toBe(true);+ expect((stub.card!.open_threads ?? []).filter((t) => t.loop_id !== undefined)).toEqual([]);+ }+ });++ test('listOpenLoops counterpartySourceId filters the slug to one source', async () => {+ for (const { engine } of engines) {+ const inDefault = await listOpenLoops(engine, { sourceIds: [G1], status: 'open', counterparty: 'people/alice-example', counterpartySourceId: 'default' });+ expect(inDefault.map((l) => l.thread_id).sort()).toEqual(['thread-alice', 'thread-alice-inbound']);+ expect(inDefault.every((l) => l.counterparty_source_id === 'default')).toBe(true);+ const inOther = await listOpenLoops(engine, { sourceIds: [G1], status: 'open', counterparty: 'people/alice-example', counterpartySourceId: OTHER });+ expect(inOther).toEqual([]);+ // A pre-v232 row (NULL counterparty source) reads as its own source.+ const legacy = await listOpenLoops(engine, { sourceIds: [G1], status: 'open', counterparty: 'people/erin-example', counterpartySourceId: G1 });+ expect(legacy.map((l) => l.thread_id)).toEqual(['thread-erin']);+ }+ });++ test('open_loops groups carry counterparty_source_id and attach the card from that source', async () => {+ for (const { engine } of engines) {+ const op = loopsOperations.find((o) => o.name === 'open_loops')!;+ const ctx = { engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId: G1, remote: false, dryRun: false,+ logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext;+ const res = await op.handler(ctx, { group_by: 'counterparty', source_id: G1, limit: 50 }) as {+ groups: Array<{ counterparty_slug: string | null; source_id: string; counterparty_source_id: string; context?: { slug?: string } }>;+ };+ const alice = res.groups.find((g) => g.counterparty_slug === 'people/alice-example');+ expect(alice).toMatchObject({ source_id: G1, counterparty_source_id: 'default' });+ expect(alice?.context).toBeDefined();+ const erin = res.groups.find((g) => g.counterparty_slug === 'people/erin-example');+ expect(erin).toMatchObject({ source_id: G1, counterparty_source_id: G1 });+ }+ });+});diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.tsindex 46c2f9de8d..51e903830b 100644--- a/test/schema-bootstrap-coverage.test.ts+++ b/test/schema-bootstrap-coverage.test.ts@@ -903,6 +903,11 @@ const COLUMN_EXEMPTIONS = new Set<string>([// the schema blob carries a comment, no CREATE TABLE column and no index// reads it, so there is no forward reference for the bootstrap to trip on.'content_chunks.embedding_pending_since',+ // #5504 (wave 14 P4.1) open_loops.counterparty_source_id (migration+ // open_loops_counterparty_source): same posture as embedding_pending_since,+ // migration-only so fresh and upgraded brains share column ordinals; the+ // partial index is built by the migration handler, never by the blob.+ 'open_loops.counterparty_source_id',// T7 — search_telemetry rank-1 drift columns (migration v111). search_telemetry// is created entirely by migration v57 (not in the schema blob), so the v57+v111// chain handles fresh + upgrade; no CREATE INDEX references these columns, so