Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Keep open-loop keys as they are on master until the counterparty fix is reviewed
garrytanc91b0329e166
diff --git a/src/core/google/loops-extract.ts b/src/core/google/loops-extract.tsindex a8347809b1..b4d69e0a9d 100644--- a/src/core/google/loops-extract.ts+++ b/src/core/google/loops-extract.ts@@ -315,17 +315,13 @@ export class LoopsExtractRetryableError extends Error {/** #7289: a verbatim quote compared case- and whitespace-insensitively; '' when the item has none. */const quoteKey = (quote: string): string => quote.toLowerCase().replace(/\s+/g, ' ').trim();-/** The person an obligation is to or from, compared case-insensitively; '' when the item names nobody. */-const counterpartyKey = (item: { counterparty_name?: string; counterparty_email?: string }): string =>- (item.counterparty_email || item.counterparty_name || '').toLowerCase().trim();--/** #7289: items of one response that quote the same sentence in the same direction to the same person are one loop; the first wins. */-function uniqueByQuote<T extends { quote: string }>(items: T[], direction: (item: T) => string, who: (item: T) => string): T[] {+/** #7289: items of one response that quote the same sentence in the same direction are one loop; the first wins. */+function uniqueByQuote<T extends { quote: string }>(items: T[], direction: (item: T) => string): T[] {const seen = new Set<string>();return items.filter((item) => {const quote = quoteKey(item.quote);if (!quote) return true;- const key = JSON.stringify([direction(item), quote, who(item)]);+ const key = JSON.stringify([direction(item), quote]);if (seen.has(key)) return false;seen.add(key);return true;@@ -333,27 +329,22 @@ function uniqueByQuote<T extends { quote: string }>(items: T[], direction: (item}/**- * #7289: a loop is its thread, direction, verbatim quote and counterparty, so- * every pass over a growing thread updates the loop its quote opened instead of- * opening one per paraphrase, and one sentence that promises two people two- * things stays two loops. A row already keyed that way wins; otherwise a row- * recorded for that quote keeps its key (rows written before this keyed on the- * model's text), open rows first, unless another item of this pass already took- * it (`claimed`). An item without a verified quote keys on its text.+ * #7289: a loop is its thread, direction and verbatim quote, so every pass over+ * a growing thread updates the loop its quote opened instead of opening one per+ * paraphrase. A row already recorded for that quote keeps its key (rows written+ * before this keyed on the model's text), open rows first. An item without a+ * verified quote keys on its text.*/async function loopDedupKey(engine: BrainEngine, sourceId: string, threadId: string, loopType: LoopType,- direction: string, text: string, quote: string, who: string, claimed: Set<string>): Promise<string> {+ direction: string, text: string, quote: string): Promise<string> {const q = quoteKey(quote);if (!q) return `commit:${sha8(JSON.stringify({ t: threadId, d: direction, x: text.toLowerCase() }))}`;- const fresh = `commit:${sha8(JSON.stringify({ t: threadId, d: direction, q, ...(who ? { c: who } : {}) }))}`;const rows = await engine.executeRaw<{ dedup_key: string; quote: string }>(`SELECT dedup_key, evidence->0->>'quote' AS quote FROM open_loopsWHERE source_id = $1 AND thread_id = $2 AND loop_type = $3 AND detector = 'llm_extract'AND COALESCE(evidence->0->>'quote', '') <> ''- ORDER BY (dedup_key = $4) DESC, (status = 'open') DESC, id`, [sourceId, threadId, loopType, fresh]);- const key = rows.find((row) => quoteKey(row.quote) === q && !claimed.has(row.dedup_key))?.dedup_key ?? fresh;- claimed.add(key);- return key;+ ORDER BY (status = 'open') DESC, id`, [sourceId, threadId, loopType]);+ return rows.find((row) => quoteKey(row.quote) === q)?.dedup_key ?? `commit:${sha8(JSON.stringify({ t: threadId, d: direction, q }))}`;}export async function runLoopsExtract(@@ -497,11 +488,10 @@ export async function runLoopsExtract(};for (const c of extraction.commitments) { c.text = restore(c.text); c.quote = verbatim(c.quote); }for (const d of extraction.decisions_pending) { d.text = restore(d.text); d.quote = verbatim(d.quote); }- extraction.commitments = uniqueByQuote(extraction.commitments, (c) => c.direction, counterpartyKey);- extraction.decisions_pending = uniqueByQuote(extraction.decisions_pending, () => 'decision', () => '');+ extraction.commitments = uniqueByQuote(extraction.commitments, (c) => c.direction);+ extraction.decisions_pending = uniqueByQuote(extraction.decisions_pending, () => 'decision');const loopIds: number[] = [];- const claimedKeys = new Set<string>();const messageDate = typeof fm.date === 'string' ? fm.date : new Date().toISOString();// #5575 I2/B3: the model read only this email page, so its commitment facts carry the page's tier// (a connector page is external_untrusted) and pass the write gate at that tier.@@ -561,7 +551,7 @@ export async function runLoopsExtract(}// Projection 2 — the loop row itself.- const dedupKey = await loopDedupKey(engine, payload.sourceId, threadId, loopType, c.direction, c.text, c.quote, counterpartyKey(c), claimedKeys);+ const dedupKey = await loopDedupKey(engine, payload.sourceId, threadId, loopType, c.direction, c.text, c.quote);const { id } = await upsertOpenLoop(engine, {sourceId: payload.sourceId,dedupKey,@@ -604,7 +594,7 @@ export async function runLoopsExtract(}for (const d of extraction.decisions_pending) {- const dedupKey = await loopDedupKey(engine, payload.sourceId, threadId, 'decision_pending', 'decision', d.text, d.quote, '', claimedKeys);+ const dedupKey = await loopDedupKey(engine, payload.sourceId, threadId, 'decision_pending', 'decision', d.text, d.quote);const { id } = await upsertOpenLoop(engine, {sourceId: payload.sourceId,dedupKey,diff --git a/test/loops-extract-run.serial.test.ts b/test/loops-extract-run.serial.test.tsindex 44cbb91098..70cd7685a8 100644--- a/test/loops-extract-run.serial.test.ts+++ b/test/loops-extract-run.serial.test.ts@@ -893,35 +893,6 @@ describe('#7289 the dedup key is the thread, direction and verbatim quote, not texpect(new Set(r.loop_ids).size).toBe(3);});- test('two obligations quoting one sentence to different people stay two loops, and a reordered pass keeps each on its own row', async () => {- const slug = 'emails/2026/08/2026-08-24-deck-invoice-7289eeee';- const threadId = 'thread-7289eeee';- const sentence = 'I will send Alice the deck and Bob the invoice by Friday.';- await engine.putPage(slug, {- type: 'email', title: 'Re: deck and invoice', compiled_truth: `Alice: Any update?\n\nMe: ${sentence}\n`,- frontmatter: { thread_id: threadId, date: '2026-08-24T10:00:00Z' },- }, { sourceId: SRC });- const alice = { direction: 'owed_by_me', text: 'Send Alice the deck by Friday', counterparty_name: 'Alice Example', counterparty_email: '[email protected]', due_iso: null, quote: sentence };- const bob = { direction: 'owed_by_me', text: 'Send Bob the invoice by Friday', counterparty_name: 'Bob Example', counterparty_email: '[email protected]', due_iso: null, quote: sentence };- const byEmail = async () => (await engine.executeRaw<{ id: number; counterparty_email: string; summary: string }>(- `SELECT id, counterparty_email, summary FROM open_loops WHERE source_id = $1 AND thread_id = $2 AND status = 'open' ORDER BY id`, [SRC, threadId]))- .map((row) => [Number(row.id), row.counterparty_email, row.summary]);- chatImpl = reply([alice, bob]);- const r = await runLoopsExtract(engine, { slug, sourceId: SRC });- expect(r.commitments).toBe(2);- const first = await byEmail();- expect(first.map(([, email, summary]) => [email, summary])).toEqual([- ['[email protected]', 'Send Alice the deck by Friday'],- ['[email protected]', 'Send Bob the invoice by Friday'],- ]);- chatImpl = reply([{ ...bob, text: 'Invoice to Bob by Friday' }, { ...alice, text: 'Deck to Alice by Friday' }]);- await runLoopsExtract(engine, { slug, sourceId: SRC });- expect(await byEmail()).toEqual([- [first[0]![0], '[email protected]', 'Deck to Alice by Friday'],- [first[1]![0], '[email protected]', 'Invoice to Bob by Friday'],- ]);- });-test('an open loop keyed on the old paraphrase key gets no twin: the next pass updates it', async () => {const slug = 'emails/2026/08/2026-08-24-budget-thread-7289cccc';const threadId = 'thread-7289cccc';