Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(loops): RFC 3834 auto-submitted mail opens no loops; log the swallowed fact-projection failure (#5586)
time-attack7c8fc566951a
diff --git a/src/core/google/google-clients.ts b/src/core/google/google-clients.tsindex 24eaf13f50..f80534c966 100644--- a/src/core/google/google-clients.ts+++ b/src/core/google/google-clients.ts@@ -233,6 +233,17 @@ function header(msg: RawGmailMessage, name: string): string {return partHeader(msg.payload, name);}+/**+ * RFC 3834 `Auto-Submitted`: any keyword other than `no` (`auto-generated`,+ * `auto-replied`, `auto-notified`, extensions) marks machine mail, matched+ * case-insensitively with parameters and comments ignored. An absent or empty+ * header is human mail.+ */+function isAutoSubmittedHeader(value: string): boolean {+ const keyword = value.replace(/\([^)]*\)/g, ' ').split(';')[0]!.trim().toLowerCase();+ return keyword !== '' && keyword !== 'no';+}+/** iCalendar METHOD parameter of a Content-Type value (quoted or bare). */const CALENDAR_METHOD_RE = /method\s*=\s*"?([a-z]+)"?/i;@@ -439,6 +450,7 @@ export class GmailClient extends GoogleApiClient {internalDateMs,labelIds: m.labelIds ?? [],listUnsubscribe: header(m, 'List-Unsubscribe') !== '',+ autoSubmitted: isAutoSubmittedHeader(header(m, 'Auto-Submitted')),calendarMethod: extractCalendarMethod(m.payload),bodyText,attachmentInspection,diff --git a/src/core/google/loop-detect.ts b/src/core/google/loop-detect.tsindex 47ddf25552..944953cfe3 100644--- a/src/core/google/loop-detect.ts+++ b/src/core/google/loop-detect.ts@@ -15,6 +15,8 @@* closes loops — it comes FROM a real colleague, so no mute could* exclude it without silencing that person's genuine email* - list mail (List-Unsubscribe) never opens loops+ * - auto-submitted mail (RFC 3834 Auto-Submitted other than "no": tracker+ * notices, auto-replies) neither opens nor closes loops* - self-threads (all participants are my addresses) never open loops* - CC-only inbound does not owe a reply (must be in To:)* - outbound without a question mark is FYI, not an ask; a question mark@@ -131,7 +133,9 @@ export function detectThreadLoop(// to, and it arrives from the colleague's real address so no sender mute// could exclude it without silencing that person entirely. And they must// not CLOSE one either: a calendar invite is not a reply, so letting it- // flip the turn would silently answer a real outbound loop.+ // flip the turn would silently answer a real outbound loop. RFC 3834+ // auto-submitted mail declares itself machine mail and is excluded the same+ // way: an out-of-office auto-reply is not the answer to my outbound ask.// My acknowledgement-only reply to their question is not an answer: drop// it so the turn stays theirs and the reply-owed loop neither closes nor// restarts its clock. An acknowledgement of a message that asked nothing@@ -139,7 +143,7 @@ export function detectThreadLoop(const substantive: GmailMessageMeta[] = [];let theirQuestionPending = false;for (const m of messages) {- if (isNoiseSender(m.fromAddress) || isCalendarSystemMail(m)) continue;+ if (isNoiseSender(m.fromAddress) || isCalendarSystemMail(m) || m.autoSubmitted) continue;if (!isMine(m, myAddresses)) {theirQuestionPending = asksQuestion(m.bodyText);} else if (theirQuestionPending && isAcknowledgementOnly(m.bodyText)) {diff --git a/src/core/google/loops-extract.ts b/src/core/google/loops-extract.tsindex db1b99b2c6..af4e834d15 100644--- a/src/core/google/loops-extract.ts+++ b/src/core/google/loops-extract.ts@@ -118,8 +118,10 @@ export function loopExtractionEligibility(// below only counts messages the owner actually wrote — an "Accepted:" RSVP// Calendar sends on the owner's behalf (SENT label, METHOD:REPLY) is still// calendar mail, so a pure invitation exchange never pays for a model call.+ // RFC 3834 auto-submitted mail (tracker notices, auto-replies) is machine+ // mail by its own declaration and counts exactly like a noise sender.const substantive = messages.filter(- (m) => !isNoiseSender(m.fromAddress) && !isCalendarSystemMail(m),+ (m) => !isNoiseSender(m.fromAddress) && !isCalendarSystemMail(m) && !m.autoSubmitted,);if (substantive.length === 0) return { eligible: false, reason: 'no_substantive_messages' };@@ -432,8 +434,13 @@ export async function runLoopsExtract(confidence: 0.85,});factId = result.id;- } catch {- /* the loop row still lands; facts projection is best-effort */+ } catch (err) {+ // The loop row still lands; the facts projection is best-effort, but its+ // failure is logged. Slug, source and a bounded error only: the+ // commitment text and quote stay out of logs.+ const code = (err as { code?: unknown })?.code;+ console.warn(`[loops_extract] fact projection failed slug=${payload.slug} source=${payload.sourceId}` ++ ` (${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'sdiff --git a/src/core/google/types.ts b/src/core/google/types.tsindex a1f3ad65aa..ee13a77e00 100644--- a/src/core/google/types.ts+++ b/src/core/google/types.ts@@ -177,6 +177,8 @@ export interface GmailMessageMeta {internalDateMs: number;labelIds: string[];listUnsubscribe: boolean;+ /** RFC 3834 `Auto-Submitted` other than `no` (tracker notices, auto-replies); absent means human mail. */+ autoSubmitted?: boolean;/*** iCalendar method when the message carries a `text/calendar` part or an* `.ics` attachment — 'REQUEST' | 'REPLY' | 'CANCEL' | 'COUNTER' | '' when adiff --git a/test/google-clients.test.ts b/test/google-clients.test.tsindex 1db8f39ed2..880cdfd28f 100644--- a/test/google-clients.test.ts+++ b/test/google-clients.test.ts@@ -668,6 +668,36 @@ describe('GmailClient', () => {expect(third.labelIds).toEqual(['SENT']);});+ test('#5586: getThread stamps RFC 3834 Auto-Submitted: any keyword but "no", case-insensitive, parameters and comments ignored', async () => {+ const cases: Array<[string | null, boolean]> = [+ ['auto-generated', true], ['Auto-Replied', true], [' AUTO-NOTIFIED ; owner-email="[email protected]"', true],+ ['auto-generated (tracker)', true], ['x-custom-robot', true],+ ['no', false], ['No', false], [' no ; reason=human', false], ['no (sent by a person)', false], ['', false], [null, false],+ ];+ const rawThread = {+ id: '17aa9999ffff0000',+ messages: cases.map(([value], i) => ({+ id: `18c2f4a9b3d21f${String(i).padStart(2, '0')}`,+ threadId: '17aa9999ffff0000',+ labelIds: [],+ internalDate: String(Date.parse('2026-08-10T09:00:00Z') + i * 60_000),+ payload: {+ mimeType: 'text/plain',+ headers: [+ { name: 'From', value: 'Tracker <[email protected]>' },+ { name: 'To', value: '[email protected]' },+ { name: 'Subject', value: `Issue #${i}` },+ ...(value === null ? [] : [{ name: i % 2 ? 'auto-submitted' : 'Auto-Submitted', value }]),+ ],+ body: { data: b64url('Status changed.') },+ },+ })),+ };+ const h = makeHarness(() => json(rawThread));+ const thread = await new GmailClient(h.tokens, h.fetchImpl, () => {}, CLIENT_ID).getThread('17aa9999ffff0000', '[email protected]');+ expect(thread.messages.map((m) => m.autoSubmitted)).toEqual(cases.map(([, expected]) => expected));+ });+test('getThread stamps calendarMethod from a real-shape text/calendar part; plain messages get null', async () => {const rawThread = {id: '17aa7777eeee8888',diff --git a/test/google-loop-detect.test.ts b/test/google-loop-detect.test.tsindex 0a9d283851..a176bc3e6b 100644--- a/test/google-loop-detect.test.ts+++ b/test/google-loop-detect.test.ts@@ -44,6 +44,8 @@ interface MsgSpec {listUnsub?: boolean;/** iCalendar method — non-null marks Google Calendar system mail. */calendarMethod?: string | null;+ /** RFC 3834 Auto-Submitted other than "no". */+ autoSubmitted?: boolean;/** Explicit internalDateMs override (0 = the all-zero-date case). */dateMs?: number;}@@ -63,6 +65,7 @@ function msg(spec: MsgSpec): GmailMessageMeta {dateIso: new Date(Math.max(internalDateMs, 0)).toISOString(),internalDateMs,calendarMethod: spec.calendarMethod ?? null,+ ...(spec.autoSubmitted !== undefined ? { autoSubmitted: spec.autoSubmitted } : {}),labelIds: spec.sent ? ['SENT'] : ['INBOX'],listUnsubscribe: spec.listUnsub ?? false,bodyText: spec.body ?? 'Can you review the plan?',@@ -620,6 +623,30 @@ describe('N7 open-loops wave regressions', () => {});});+describe('#5586: RFC 3834 auto-submitted mail', () => {+ const detect = (messages: GmailMessageMeta[]): ThreadLoopVerdict =>+ detectThreadLoop(thread(messages), MY, NOW);++ test('a tracker notice addressed to me opens no inbound loop', () => {+ const v = detect([msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 100, autoSubmitted: true })]);+ expect(v.open).toEqual([]);+ });++ test('an auto-reply does NOT close my real outbound loop', () => {+ const v = detect([+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 200, sent: true, body: 'Can you confirm the budget?' }),+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 100, body: 'I am out of office until Monday.', autoSubmitted: true }),+ ]);+ expect(v.open.map((o) => o.loopType)).toEqual(['unanswered_outbound']);+ expect(v.close).toEqual(['unanswered_inbound']);+ });++ test('the same sender writing by hand (Auto-Submitted: no) still opens a loop', () => {+ const v = detect([msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 100, autoSubmitted: false })]);+ expect(v.open.map((o) => o.loopType)).toEqual(['unanswered_inbound']);+ });+});+describe('google calendar system mail', () => {const detect = (messages: GmailMessageMeta[]): ThreadLoopVerdict =>detectThreadLoop(thread(messages), MY, NOW);diff --git a/test/loops-extract-eligibility.test.ts b/test/loops-extract-eligibility.test.tsindex ae3fdbe903..11bb9ee1ef 100644--- a/test/loops-extract-eligibility.test.ts+++ b/test/loops-extract-eligibility.test.ts@@ -27,6 +27,7 @@ interface MsgSpec {labels?: string[];listUnsub?: boolean;calendarMethod?: string | null;+ autoSubmitted?: boolean;body?: string;subject?: string;}@@ -46,6 +47,7 @@ function msg(spec: MsgSpec): GmailMessageMeta {labelIds: spec.labels ?? ['INBOX'],listUnsubscribe: spec.listUnsub ?? false,calendarMethod: spec.calendarMethod ?? null,+ ...(spec.autoSubmitted !== undefined ? { autoSubmitted: spec.autoSubmitted } : {}),bodyText: spec.body ?? 'Some body text.',};}@@ -103,6 +105,24 @@ const ROWS: Row[] = [eligible: false,reason: 'no_substantive_messages',},+ {+ name: '#5586: a tracker thread marked Auto-Submitted (no List-Unsubscribe) is not eligible',+ messages: [msg({ from: '[email protected]', autoSubmitted: true }), msg({ from: '[email protected]', autoSubmitted: true })],+ eligible: false,+ reason: 'no_substantive_messages',+ },+ {+ name: '#5586: my own auto-reply is not owner participation',+ messages: [msg({ from: '[email protected]', autoSubmitted: true }), msg({ from: '[email protected]', labels: ['SENT'], autoSubmitted: true })],+ eligible: false,+ reason: 'no_substantive_messages',+ },+ {+ name: '#5586: a human message beside an auto-submitted one keeps the thread eligible',+ messages: [msg({ from: '[email protected]', autoSubmitted: true }), msg({ from: '[email protected]', autoSubmitted: false })],+ eligible: true,+ reason: 'human_correspondence',+ },{name: 'a human "Notification: ..." thread with no calendar part is eligible',messages: [msg({ from: '[email protected]', subject: 'Notification: your invoice is ready' })],diff --git a/test/loops-extract-run.serial.test.ts b/test/loops-extract-run.serial.test.tsindex 5c469a7cd8..9cf5b5e04a 100644--- a/test/loops-extract-run.serial.test.ts+++ b/test/loops-extract-run.serial.test.ts@@ -16,7 +16,7 @@* Synthetic data only — every person/email/company below is a placeholder.*/-import { describe, test, expect, beforeAll, afterAll, mock } from 'bun:test';+import { describe, test, expect, beforeAll, afterAll, mock, spyOn } from 'bun:test';// ── Gateway mock (must precede every import that can reach ai/gateway.ts) ──interface ChatReq {@@ -722,3 +722,41 @@ describe('runLoopsExtract', () => {for (const e of edges) expect(e.context).not.toContain('compliance checklist by Tuesday');});});++describe('#5586: fact projection failure', () => {+ test('a failed facts write is logged with slug, source and error only; the loop row still lands', async () => {+ const slug = 'emails/2026/08/2026-08-23-projection-thread-5586aaaa';+ await engine.putPage(slug, {+ type: 'email', title: 'Re: acme-example renewal',+ compiled_truth: 'Me: I will send the acme-example renewal terms by Monday.\n',+ frontmatter: { thread_id: 'thread-5586aaaa', date: '2026-08-23T10:00:00Z' },+ effective_date: new Date('2026-08-23T10:00:00Z'),+ }, { sourceId: SRC });+ chatImpl = async () => ({ text: JSON.stringify({+ commitments: [{ direction: 'owed_by_me', text: 'Send the acme-example renewal terms', counterparty_name: 'Alice Example',+ counterparty_email: '[email protected]', due_iso: '2026-08-31', quote: 'I will send the acme-example renewal terms by Monday.' }],+ decisions_pending: [],+ }), stopReason: 'end' });+ await engine.executeRaw(`CREATE OR REPLACE FUNCTION test_5586_refuse_fact() RETURNS trigger LANGUAGE plpgsql AS $$+ BEGIN RAISE EXCEPTION 'synthetic facts write failure'; END $$`);+ await engine.executeRaw('CREATE TRIGGER test_5586_refuse_fact BEFORE INSERT ON facts FOR EACH ROW EXECUTE FUNCTION test_5586_refuse_fact()');+ const warn = spyOn(console, 'warn').mockImplementation(() => {});+ try {+ const r = await runLoopsExtract(engine, { slug, sourceId: SRC });+ expect(r.status).toBe('extracted');+ const [loop] = await engine.executeRaw<{ fact_id: number | null }>(+ 'SELECT fact_id FROM open_loops WHERE source_id = $1 AND page_slug = $2', [SRC, slug]);+ expect(loop).toBeDefined();+ expect(loop!.fact_id).toBeNull();+ const lines = warn.mock.calls.map((call) => String(call[0])).filter((line) => line.startsWith('[loops_extract] fact projection failed'));+ expect(lines.length).toBe(1);+ expect(lines[0]).toContain(`slug=${slug} source=${SRC}`);+ expect(lines[0]).toContain('synthetic facts write failure');+ expect(lines[0]).not.toContain('renewal terms');+ } finally {+ warn.mockRestore();+ await engine.executeRaw('DROP TRIGGER test_5586_refuse_fact ON facts');+ await engine.executeRaw('DROP FUNCTION test_5586_refuse_fact()');+ }+ });+});