Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

migration: open_loops_counterparty_source takes v235 (v234 is wave 14 PR2's git-durability migration)

garrytanc24cdd633efe
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9076c045b4..e23b4723c0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,7 +16,7 @@ identifiers and attribution are available in the pre-removal Git revision
### Google connector and open loops
-- **Loops find the person across sources (#5504).** A Gmail source's loop names someone whose page lives in `default:people/<slug>`; resolution now runs in the mail's own source first and then across sources by identity only (the exact email as a page alias, or an `entity_identities` canonical member; names never cross, ties stay unresolved). The loop row records the page's source (`open_loops.counterparty_source_id`, migration `open_loops_counterparty_source`, provisional v233), the `owes_to` / `awaiting_reply_from` edge points there, and the entity card, `gbrain waiting` and `open_loops` read the loop from that page and never from a namesake in another source. The commitment fact stays in the connector source.
+- **Loops find the person across sources (#5504).** A Gmail source's loop names someone whose page lives in `default:people/<slug>`; resolution now runs in the mail's own source first and then across sources by identity only (the exact email as a page alias, or an `entity_identities` canonical member; names never cross, ties stay unresolved). The loop row records the page's source (`open_loops.counterparty_source_id`, migration `open_loops_counterparty_source`, v235), the `owes_to` / `awaiting_reply_from` edge points there, and the entity card, `gbrain waiting` and `open_loops` read the loop from that page and never from a namesake in another source. The commitment fact stays in the connector source.
- **Daily spend cap on loop extraction.** `loops.extraction_max_usd_per_day` (default $2.00, per UTC day, brain-wide): every `loops_extract` job a sweep or the managed catch-up queues shares the day's spend group through the job spend envelope; an attempt the cap cannot admit is refused before the provider call and a sweep at the cap queues nothing (`daily_spend_cap`; `spend_cap_zero` when the user set 0).
- **Your own label exclusions (#5445).** Per-source `g_loops_exclude_labels` (`gbrain sources add … --loops-exclude-labels`) with the brain-wide `loops.extraction_exclude_labels` as the fallback; label names are resolved once per sweep and gate all three eligibility sites, the execution-time check and grace-hold publication, plus the deterministic detector. A name that does not resolve fails closed for new paid extraction (`excluded_label_unresolved`, visible in the sweep counters and retried every sweep). Contributed by @furuchanchan. Supersedes #5524.
- **Contacts next to your own people (#4845, #6158).** `g_contacts_dir` (default `people`, `--contacts-dir`) decides where a Google contact page renders; an existing page is renamed in place (import the new path, then retire the old one). A connector stub yields to its canonical twin in another source under `link_resolution.cross_source`, and doctor `junk_entity_hubs` names the twin and the exact remedy instead of an open policy question.
@@ -45,7 +45,6 @@ identifiers and attribution are available in the pre-removal Git revision
- `test/db-lock-fencing.test.ts` and `test/cycle-lock-steal.serial.test.ts` simulate a steal by rotating the acquisition token (what a real successor does) instead of only moving `acquired_at`; a rewrite of `acquired_at` under a live holder is now, deliberately, not a steal.
- `test/junk-entity-guards.test.ts`'s #6158 pin changed from "open policy question" (`operator_judgement`) to a concrete remedy; `test/google-source-reconcile.test.ts`'s calendar reconcile pin flipped from "events outside the window stay" to "they reconcile on `--full`".
- `test/lint-3958.test.ts`, `test/managed-lint.test.ts`, `test/managed-phase-matrix.test.ts` and `test/cycle-lint-durability.test.ts` relied on the `created:` promotion as their one fixable issue and were updated deliberately (#5433).
-- `test/migrations-golden.test.ts` carries 232 as a provisional gap until the integrator renumbers the migration at merge-slot time.
### For contributors
diff --git a/docs/architecture/key-files/open-loops-engine.md b/docs/architecture/key-files/open-loops-engine.md
index 8e2da74e46..ef99ca2a77 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 v234 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 v235 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.ts
index 05abc320fa..274b6e990d 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 v234 has no counterparty source and is read
+ * join with: a row written before v235 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.ts
index 35c21073e5..ed8310a0ad 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 v234).
+ * column (rows written before v235).
*/
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-v234 rows (read as `source_id`). */
+ /** Source of the counterparty page; NULL on pre-v235 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-v234 row) is this one. An email match is unaffected.
+ * source for a pre-v235 row) is this one. An email match is unaffected.
*/
counterpartySourceId?: string;
/**
diff --git a/src/core/ops/loops.ts b/src/core/ops/loops.ts
index a9b822fca0..b2e77fda33 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-v234 row reads as its own source. */
+ * the loops' source. A pre-v235 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.ts
index 663df87dfd..d98387962c 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 = 234;
+export const LATEST_SCHEMA_VERSION = 235;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index 4cd755c3f0..7c65bd7caf 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -234,7 +234,7 @@ import { v230 } from './v230-trust-generation.ts';
import { v231 } from './v231-fact-purge-lookup-indexes.ts';
import { v232 } from './v232-fts-cjk-boundary.ts';
import { v233 } from './v233-oauth-client-registered-via.ts';
-import { v234 } from './v234-open-loops-counterparty-source.ts';
+import { v235 } from './v235-open-loops-counterparty-source.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -467,5 +467,5 @@ export const MIGRATIONS: Migration[] = [
v231,
v232,
v233,
- v234,
+ v235,
];
diff --git a/src/core/schema-migrations/v234-open-loops-counterparty-source.ts b/src/core/schema-migrations/v235-open-loops-counterparty-source.ts
similarity index 89%
rename from src/core/schema-migrations/v234-open-loops-counterparty-source.ts
rename to src/core/schema-migrations/v235-open-loops-counterparty-source.ts
index 0f3ad2c94a..1d02e2b0f9 100644
--- a/src/core/schema-migrations/v234-open-loops-counterparty-source.ts
+++ b/src/core/schema-migrations/v235-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-v234 row) read as the loop's own source. Nullable, no default,
+// NULL (pre-v235 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 v234: Migration = {
- version: 234,
+export const v235: Migration = {
+ version: 235,
name: 'open_loops_counterparty_source',
idempotent: true,
sql: `${OPEN_LOOPS_COUNTERPARTY_SOURCE_COLUMN_SQL};`,
handler: async engine => {
- await buildIndexOnline(engine, 234, OPEN_LOOPS_COUNTERPARTY_SOURCE_INDEX, { notice: migrationNotice });
+ await buildIndexOnline(engine, 235, OPEN_LOOPS_COUNTERPARTY_SOURCE_INDEX, { notice: migrationNotice });
},
};
diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.ts
index e01084cb29..bde1ad6bf4 100644
--- a/src/core/verbs/entity-card.ts
+++ b/src/core/verbs/entity-card.ts
@@ -473,7 +473,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-v234 row (NULL counterparty source) on its own
+ // default card, a pre-v235 row (NULL counterparty source) on its own
// source's card (#5504).
const loopRows = await engine.executeRaw<{
id: number;
diff --git a/test/loops-counterparty-null-entity.test.ts b/test/loops-counterparty-null-entity.test.ts
index e2385b6670..8a3e8380f5 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-v234 row (NULL counterparty source) reads as its own source.
+ // A pre-v235 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']);
}