Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
P4.1: carry the counterparty_source_id migration as provisional v233
garrytan0e5ea08a6546
diff --git a/docs/architecture/key-files/open-loops-engine.md b/docs/architecture/key-files/open-loops-engine.mdindex 5674108eed..024711d9c1 100644--- a/docs/architecture/key-files/open-loops-engine.md+++ b/docs/architecture/key-files/open-loops-engine.md@@ -8,7 +8,7 @@ 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/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 v233 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; `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.diff --git a/src/core/google/counterparty.ts b/src/core/google/counterparty.tsindex 115963309e..eb97dafa20 100644--- a/src/core/google/counterparty.ts+++ b/src/core/google/counterparty.ts@@ -94,7 +94,7 @@ export async function resolveCounterparty(/*** The `(counterparty_slug, source)` predicate readers confine a loop → entity- * join with: a row written before v232 has no counterparty source and is read+ * join with: a row written before v233 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/loops/loops-store.ts b/src/core/loops/loops-store.tsindex 72aceb03aa..3552ddec44 100644--- a/src/core/loops/loops-store.ts+++ b/src/core/loops/loops-store.ts@@ -38,7 +38,7 @@ export interface OpenLoopUpsert {/*** 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).+ * column (rows written before v233).*/counterpartySourceId?: string | null;counterpartyEmail?: string | null;@@ -66,7 +66,7 @@ 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`). */+ /** Source of the counterparty page; NULL on pre-v233 rows (read as `source_id`). */counterparty_source_id: string | null;counterparty_email: string | null;summary: string;@@ -234,7 +234,7 @@ export interface ListLoopsOpts {/*** 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.+ * source for a pre-v233 row) is this one. An email match is unaffected.*/counterpartySourceId?: string;/**diff --git a/src/core/ops/loops.ts b/src/core/ops/loops.tsindex 1030b776f5..1f5e20335c 100644--- a/src/core/ops/loops.ts+++ b/src/core/ops/loops.ts@@ -236,7 +236,7 @@ interface CounterpartyGroup {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. */+ * the loops' source. A pre-v233 row reads as its own source. */counterparty_source_id: string;loop_count: number;oldest_opened_at: string;diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex ed00b02841..7cdcfafcf0 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 = 232;+export const LATEST_SCHEMA_VERSION = 233;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 0cdde7acc1..e8c67fa149 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -232,7 +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';+import { v233 } from './v233-open-loops-counterparty-source.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -463,5 +463,5 @@ export const MIGRATIONS: Migration[] = [v229,v230,v231,- v232,+ v233,];diff --git a/src/core/schema-migrations/v232-open-loops-counterparty-source.ts b/src/core/schema-migrations/v233-open-loops-counterparty-source.tssimilarity index 89%rename from src/core/schema-migrations/v232-open-loops-counterparty-source.tsrename to src/core/schema-migrations/v233-open-loops-counterparty-source.tsindex 9af4dc4551..53a3554044 100644--- a/src/core/schema-migrations/v232-open-loops-counterparty-source.ts+++ b/src/core/schema-migrations/v233-open-loops-counterparty-source.ts@@ -12,17 +12,17 @@ import { buildIndexOnline, migrationNotice } from './helpers.ts';// 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,+// NULL (pre-v233 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,+export const v233: Migration = {+ version: 233,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 });+ await buildIndexOnline(engine, 233, OPEN_LOOPS_COUNTERPARTY_SOURCE_INDEX, { notice: migrationNotice });},};diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.tsindex 6e99b6b1d7..c968d988ca 100644--- a/src/core/verbs/entity-card.ts+++ b/src/core/verbs/entity-card.ts@@ -470,7 +470,7 @@ async function assembleCard(// 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+ // default card, a pre-v233 row (NULL counterparty source) on its own// source's card (#5504).const loopRows = await engine.executeRaw<{id: number;diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 454df2fd6a..a02e2cd3bb 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -5,7 +5,8 @@17,18,19,- 100+ 100,+ 232],"helpers": {"ALIAS_TABLES": "cddd37c636af42d862c08ca7754a57dfe9d12576b769fa8f74a5f02c803f67a0",@@ -42,7 +43,7 @@"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5","verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"},- "latest": 232,+ "latest": 233,"records": [{"handler": {@@ -3467,7 +3468,7 @@"migrationNotice","quietMigrationNotices"],- "sha256": "3cc85accec244596bd36b032d658121ae3c3b8fc48b3e8d52d918813433de225"+ "sha256": "6aa0ec5da80beb3ee59b46ac273e3109062befad63aa7ec6fba4919f72720964"},"idempotent": true,"name": "open_loops_counterparty_source",@@ -3478,7 +3479,7 @@"sqlFor": "absent","transaction": "absent","verify": "absent",- "version": 232+ "version": 233}],"versions": [@@ -3708,7 +3709,7 @@229,230,231,- 232+ 233]},"normalizer": "migrations-record-v1"diff --git a/test/loops-counterparty-null-entity.test.ts b/test/loops-counterparty-null-entity.test.tsindex 0db6833e9c..a575f61e09 100644--- a/test/loops-counterparty-null-entity.test.ts+++ b/test/loops-counterparty-null-entity.test.ts@@ -217,7 +217,7 @@ describe('(b) readers confine on (slug, counterparty source)', () => {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.+ // A pre-v233 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']);}diff --git a/test/migrations-golden.test.ts b/test/migrations-golden.test.tsindex 5eb1bcd0e9..7c7b345ed6 100644--- a/test/migrations-golden.test.ts+++ b/test/migrations-golden.test.ts@@ -33,7 +33,10 @@ describe('migrations full-record golden', () => {expect(new Set(versions).size).toBe(versions.length);const sorted = [...versions].sort((a, b) => a - b);const golden = buildMigrationsGolden(MIGRATIONS);- expect(golden.gaps).toEqual([17, 18, 19, 100]);+ // 232 is provisional (wave 14 PR4 carries its migration as v233 while wave 13+ // PR4 takes v232/v233 and wave 14 PR2 v234); the integrator renumbers at+ // merge-slot time and restores the [17, 18, 19, 100] expectation.+ expect(golden.gaps).toEqual([17, 18, 19, 100, 232]);expect(sorted[0]).toBe(2);expect(sorted[sorted.length - 1]).toBe(LATEST_VERSION);}, 60_000);