Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: pre-landing review fixes
garrytan1616fcd7e34e
diff --git a/src/core/google/loops-extract.ts b/src/core/google/loops-extract.tsindex b4d69e0a9d..a8347809b1 100644--- a/src/core/google/loops-extract.ts+++ b/src/core/google/loops-extract.ts@@ -315,13 +315,17 @@ 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();-/** #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[] {+/** 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[] {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]);+ const key = JSON.stringify([direction(item), quote, who(item)]);if (seen.has(key)) return false;seen.add(key);return true;@@ -329,22 +333,27 @@ function uniqueByQuote<T extends { quote: string }>(items: T[], direction: (item}/**- * #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.+ * #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.*/async function loopDedupKey(engine: BrainEngine, sourceId: string, threadId: string, loopType: LoopType,- direction: string, text: string, quote: string): Promise<string> {+ direction: string, text: string, quote: string, who: string, claimed: Set<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 (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 }))}`;+ 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;}export async function runLoopsExtract(@@ -488,10 +497,11 @@ 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);- extraction.decisions_pending = uniqueByQuote(extraction.decisions_pending, () => 'decision');+ extraction.commitments = uniqueByQuote(extraction.commitments, (c) => c.direction, counterpartyKey);+ 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.@@ -551,7 +561,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);+ const dedupKey = await loopDedupKey(engine, payload.sourceId, threadId, loopType, c.direction, c.text, c.quote, counterpartyKey(c), claimedKeys);const { id } = await upsertOpenLoop(engine, {sourceId: payload.sourceId,dedupKey,@@ -594,7 +604,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);+ const dedupKey = await loopDedupKey(engine, payload.sourceId, threadId, 'decision_pending', 'decision', d.text, d.quote, '', claimedKeys);const { id } = await upsertOpenLoop(engine, {sourceId: payload.sourceId,dedupKey,diff --git a/src/core/persistence/physical-root-record.ts b/src/core/persistence/physical-root-record.tsindex c74298a780..b663f1d8eb 100644--- a/src/core/persistence/physical-root-record.ts+++ b/src/core/persistence/physical-root-record.ts@@ -252,6 +252,8 @@ export interface MovedPhysicalRoot {/*** #8625: reads only the stamp in `root` and the reservation of the root it records: beside that old root when the checkout* itself moved, or beside `root` (still named for the old root) when a parent folder was renamed and carried both along.+ * The moved parent is the deepest one the paths share a tail below that no longer exists, so a folder moved under another+ * folder of the same name names itself, never the folders that held it.* A recorded root that still exists (a copy), a stamp and reservation that disagree on token, brain or worktree, or a* parent rename that also renamed the checkout is no move (null). An ownership record other users can read keeps its own refusal.*/@@ -264,6 +266,7 @@ export function describeMovedPhysicalRoot(root: string): MovedPhysicalRoot | nulconst recorded = stamp.root.split(sep), current = root.split(sep);let shared = 0;while (shared < Math.min(recorded.length, current.length) - 2 && recorded[recorded.length - 1 - shared] === current[current.length - 1 - shared]) shared++;+ while (shared && existsSync(recorded.slice(0, -shared).join(sep))) shared--;if (!shared) return null;reservation = readReservationRecord(stamp.root, false, dirname(root));from = recorded.slice(0, -shared).join(sep); to = current.slice(0, -shared).join(sep);diff --git a/test/loops-extract-run.serial.test.ts b/test/loops-extract-run.serial.test.tsindex 70cd7685a8..44cbb91098 100644--- a/test/loops-extract-run.serial.test.ts+++ b/test/loops-extract-run.serial.test.ts@@ -893,6 +893,35 @@ 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';diff --git a/test/physical-root-moved-8625.test.ts b/test/physical-root-moved-8625.test.tsindex 72c0204d64..027bd7e146 100644--- a/test/physical-root-moved-8625.test.ts+++ b/test/physical-root-moved-8625.test.ts@@ -188,6 +188,20 @@ for (const kind of testBackends()) describe(`#8625 a moved managed checkout nameexpect(existsSync(from)).toBe(!bound);}), 120_000);+ for (const bound of [true, false]) test(`a parent moved under another folder with the same name (${bound ? 'bound' : 'removed source'}) names that parent, never the folders that held it`, () => fixture({ parent: join('left', 'group') }, async f => {+ if (!bound) await remove(f.source);+ const from = join(f.base, 'left', 'group'), to = join(f.base, 'right', 'group'), moved = join(to, 'root'), sourceId = bound ? f.source : `${f.source}-b`;+ mkdirSync(join(f.base, 'right'));+ renameSync(from, to);+ const error = await refusal(bound ? setPath(sourceId, moved, true) : add(sourceId, moved, true));+ expectMoved(error, f.root, f.worktreeId);+ expect(error!.message).toContain(`'${from}'`);+ expect(error!.fix!.argv).toEqual(bound ? ['ln', '-s', to, from] : ['mv', to, from]);+ await runFix(error!.fix);+ expect(await getWorktreeBinding(engine, sourceId)).toMatchObject({ worktree_id: f.worktreeId, local_path: bound ? moved : f.root });+ expect(existsSync(join(f.base, 'right'))).toBe(true);+ }), 120_000);+test('a copy with a new inode whose original was deleted names restore or deactivate, never a move back', () => fixture({}, async f => {await remove(f.source);const copy = join(f.base, 'copied-root');