Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
44.6 KB
Raw Blame
/**
 * THE PRECISION GATE for the zero-LLM thread-state machine
 * (src/core/google/loop-detect.ts:detectThreadLoop).
 *
 * Labeled fixture corpus: every row asserts the EXACT verdict — either no
 * loop at all or exactly one loop of the expected type with the expected
 * counterparty. Zero false positives on this corpus is the assertion; every
 * new false-positive class gets a fixture row before its fix (per the
 * contract in loop-detect.ts's header).
 *
 * Pure function — no engine, no I/O. Synthetic data only.
 */
import { describe, expect, test } from 'bun:test';

import {
  asksQuestion,
  detectThreadLoop,
  isAcknowledgementOnly,
  INBOUND_GRACE_HOURS,
  OUTBOUND_GRACE_HOURS,
  type ThreadLoopVerdict,
} from '../src/core/google/loop-detect.ts';
import type { SuppressionSet } from '../src/core/loops/loops-store.ts';
import { BULK_CATEGORY_LABELS } from '../src/core/google/gmail-categories.ts';
import { BULK_CATEGORY_LABELS as EXTRACT_LANE_BULK_CATEGORY_LABELS } from '../src/core/google/loops-extract.ts';
import { trimQuotedReply } from '../src/core/google/google-render.ts';
import type { GmailMessageMeta, GmailThreadData } from '../src/core/google/types.ts';

// Frozen clock — every age below is relative to this instant, so the corpus
// is fully deterministic (no wall-clock flake at grace boundaries).
const NOW = new Date('2026-08-25T12:00:00Z');

const MY = new Set(['[email protected]', '[email protected]']);

const THREAD_ID = '18c2f4a9b3d21e07';

let msgSeq = 0;

interface MsgSpec {
  from: string;
  to?: string[];
  cc?: string[];
  ageHours: number;
  sent?: boolean;
  body?: string;
  subject?: string;
  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;
  /** Extra Gmail label ids (categories) beside SENT/INBOX. */
  labels?: string[];
  /** #5012 automated-mail headers (fields a master mapper did not capture). */
  headers?: { precedence?: string; listId?: boolean; replyTo?: string[] };
}

function msg(spec: MsgSpec): GmailMessageMeta {
  const internalDateMs =
    spec.dateMs !== undefined ? spec.dateMs : NOW.getTime() - spec.ageHours * 3_600_000;
  msgSeq += 1;
  return {
    id: `18c2f4a9b3d2${(0x1000 + msgSeq).toString(16)}`,
    threadId: THREAD_ID,
    from: spec.from,
    fromAddress: spec.from.toLowerCase(),
    to: (spec.to ?? []).map((a) => a.toLowerCase()),
    cc: (spec.cc ?? []).map((a) => a.toLowerCase()),
    subject: spec.subject ?? 'Quarterly plan',
    dateIso: new Date(Math.max(internalDateMs, 0)).toISOString(),
    internalDateMs,
    calendarMethod: spec.calendarMethod ?? null,
    ...(spec.autoSubmitted !== undefined ? { autoSubmitted: spec.autoSubmitted } : {}),
    labelIds: [spec.sent ? 'SENT' : 'INBOX', ...(spec.labels ?? [])],
    listUnsubscribe: spec.listUnsub ?? false,
    bodyText: spec.body ?? 'Can you review the plan?',
    ...(spec.headers ?? {}),
  };
}

function thread(messages: GmailMessageMeta[], threadId = THREAD_ID): GmailThreadData {
  return { threadId, account: '[email protected]', messages };
}

function sup(over: Partial<SuppressionSet> = {}): SuppressionSet {
  return { senders: new Set<string>(), threads: new Set<string>(), ...over };
}

interface CorpusCase {
  name: string;
  messages: GmailMessageMeta[];
  suppressions?: SuppressionSet;
  expect:
    | null
    | { type: 'unanswered_inbound' | 'unanswered_outbound'; counterparty: string };
}

const CASES: CorpusCase[] = [
  // ── Inbound: I owe the reply ───────────────────────────────────────────────
  {
    name: 'inbound to me in To:, 48h old → unanswered_inbound',
    messages: [msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 })],
    expect: { type: 'unanswered_inbound', counterparty: '[email protected]' },
  },
  {
    name: 'inbound 2h old → none (grace window)',
    messages: [msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 2 })],
    expect: null,
  },
  {
    name: 'inbound exactly at the 24h grace boundary → opens',
    messages: [msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 24 })],
    expect: { type: 'unanswered_inbound', counterparty: '[email protected]' },
  },
  {
    name: 'inbound 23h old (just inside grace) → none',
    messages: [msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 23 })],
    expect: null,
  },
  {
    name: 'inbound where I am only in Cc → none',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], cc: ['[email protected]'], ageHours: 48 }),
    ],
    expect: null,
  },
  {
    name: 'inbound not addressed to me at all (bcc/list delivery) → none',
    messages: [msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 })],
    expect: null,
  },
  {
    name: 'inbound with empty To: (pure bcc) → none',
    messages: [msg({ from: '[email protected]', to: [], cc: ['[email protected]'], ageHours: 48 })],
    expect: null,
  },
  {
    name: 'inbound with List-Unsubscribe → none (list mail)',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48, listUnsub: true }),
    ],
    expect: null,
  },
  {
    name: 'inbound from noreply@ → none (noise)',
    messages: [msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 })],
    expect: null,
  },
  {
    name: 'inbound from no-reply@ → none (noise)',
    messages: [msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 })],
    expect: null,
  },
  {
    name: 'inbound from notifications@ → none (noise)',
    messages: [msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 })],
    expect: null,
  },
  {
    name: 'inbound from notification@ → none (noise)',
    messages: [msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 })],
    expect: null,
  },
  {
    name: 'inbound from mailer-daemon@ → none (bounce noise)',
    messages: [msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 })],
    expect: null,
  },
  {
    name: 'inbound from postmaster@ → none (noise)',
    messages: [msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 })],
    expect: null,
  },
  {
    name: 'inbound from donotreply@ → none (noise)',
    messages: [msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 })],
    expect: null,
  },
  {
    name: 'inbound from do-not-reply@ → none (noise)',
    messages: [msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 })],
    expect: null,
  },
  {
    name: 'inbound from calendar-notification@ → none (noise)',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 }),
    ],
    expect: null,
  },
  {
    name: 'inbound addressed to my alias in To: → unanswered_inbound',
    messages: [msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 })],
    expect: { type: 'unanswered_inbound', counterparty: '[email protected]' },
  },
  {
    name: 'inbound to me AND others in To: → unanswered_inbound on the sender',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]', '[email protected]'], ageHours: 48 }),
    ],
    expect: { type: 'unanswered_inbound', counterparty: '[email protected]' },
  },
  {
    name: 'mixed: inbound 48h, my reply 36h, their reply 30h → unanswered_inbound on the latest inbound sender',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 }),
      msg({ from: '[email protected]', to: ['[email protected]', '[email protected]'], ageHours: 36, sent: true, body: 'Here you go.' }),
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 30 }),
    ],
    expect: { type: 'unanswered_inbound', counterparty: '[email protected]' },
  },
  {
    name: 'inbound 48h followed by a fresh noise notification → still unanswered_inbound on the human',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 }),
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 1 }),
    ],
    expect: { type: 'unanswered_inbound', counterparty: '[email protected]' },
  },
  {
    name: 'earlier list mail, latest personal message without List-Unsubscribe → opens',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 72, listUnsub: true }),
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 }),
    ],
    expect: { type: 'unanswered_inbound', counterparty: '[email protected]' },
  },
  {
    name: 'thread where the LAST message is MY reply (SENT) with no "?" → none (answered)',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 }),
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 20, sent: true, body: 'Done, see attached.' }),
    ],
    expect: null,
  },
  {
    name: 'suppressed sender → none (mute wins)',
    messages: [msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 })],
    suppressions: sup({ senders: new Set(['[email protected]']) }),
    expect: null,
  },
  {
    name: 'suppressed thread → none (mute wins)',
    messages: [msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 })],
    suppressions: sup({ threads: new Set([THREAD_ID]) }),
    expect: null,
  },
  {
    name: 'a DIFFERENT suppressed sender does not mute this one → opens',
    messages: [msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 })],
    suppressions: sup({ senders: new Set(['[email protected]']) }),
    expect: { type: 'unanswered_inbound', counterparty: '[email protected]' },
  },
  {
    name: 'a DIFFERENT suppressed thread does not mute this one → opens',
    messages: [msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 })],
    suppressions: sup({ threads: new Set(['18c2f4a9b3d2ffff']) }),
    expect: { type: 'unanswered_inbound', counterparty: '[email protected]' },
  },

  // ── Outbound: I'm waiting on them ─────────────────────────────────────────
  {
    name: 'my outbound with "?" 96h old → unanswered_outbound',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 96, sent: true, body: 'Any update on the contract?' }),
    ],
    expect: { type: 'unanswered_outbound', counterparty: '[email protected]' },
  },
  {
    name: 'my outbound with "?" 24h old → none (72h grace)',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 24, sent: true, body: 'Any update?' }),
    ],
    expect: null,
  },
  {
    name: 'my outbound with "?" exactly at the 72h boundary → opens',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 72, sent: true, body: 'Any update?' }),
    ],
    expect: { type: 'unanswered_outbound', counterparty: '[email protected]' },
  },
  {
    name: 'my outbound with "?" 71h old (just inside grace) → none',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 71, sent: true, body: 'Any update?' }),
    ],
    expect: null,
  },
  {
    name: 'my outbound WITHOUT "?" 96h old → none (FYI rule)',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 96, sent: true, body: 'FYI, deck attached.' }),
    ],
    expect: null,
  },
  {
    name: 'my outbound only to my own alias → none (self-thread)',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 96, sent: true, body: 'Note to self: renew domain?' }),
    ],
    expect: null,
  },
  {
    name: 'all-mine thread (notes to self, several messages) → none',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 120, sent: true, body: 'Draft one?' }),
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 96, sent: true, body: 'Draft two?' }),
    ],
    expect: null,
  },
  {
    name: 'sent-label detection: from address NOT in MY but labeled SENT → treated as mine (outbound)',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 96, sent: true, body: 'Did you get my note?' }),
    ],
    expect: { type: 'unanswered_outbound', counterparty: '[email protected]' },
  },
  {
    name: 'sent-label detection: SENT message without "?" → none (FYI rule still applies)',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 96, sent: true, body: 'FYI only.' }),
    ],
    expect: null,
  },
  {
    name: 'outbound "?" with me AND bob in To: → counterparty is the first non-mine recipient',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]', '[email protected]'], ageHours: 96, sent: true, body: 'Thoughts?' }),
    ],
    expect: { type: 'unanswered_outbound', counterparty: '[email protected]' },
  },
  {
    name: 'outbound "?" addressed only to me with an external Cc → none (Cc is not a counterparty)',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], cc: ['[email protected]'], ageHours: 96, sent: true, body: 'Thoughts?' }),
    ],
    expect: null,
  },
  {
    name: 'outbound "?" to two external recipients → counterparty is the first',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]', '[email protected]'], ageHours: 96, sent: true, body: 'Can one of you take this?' }),
    ],
    expect: { type: 'unanswered_outbound', counterparty: '[email protected]' },
  },
  {
    name: 'outbound with suppressed counterparty → none',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 96, sent: true, body: 'Any update?' }),
    ],
    suppressions: sup({ senders: new Set(['[email protected]']) }),
    expect: null,
  },
  {
    name: 'outbound on a suppressed thread → none',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 96, sent: true, body: 'Any update?' }),
    ],
    suppressions: sup({ threads: new Set([THREAD_ID]) }),
    expect: null,
  },
  {
    name: 'inbound then my old follow-up question → unanswered_outbound (last word is my ask)',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 100 }),
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 96, sent: true, body: 'Does Tuesday work?' }),
    ],
    expect: { type: 'unanswered_outbound', counterparty: '[email protected]' },
  },
  {
    name: 'inbound then my FRESH reply with "?" (20h) → none (outbound grace)',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 }),
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 20, sent: true, body: 'Does Tuesday work?' }),
    ],
    expect: null,
  },

  // ── Degenerate threads ────────────────────────────────────────────────────
  {
    name: 'empty thread → none',
    messages: [],
    expect: null,
  },
  {
    name: 'all-zero internalDate → none',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48, dateMs: 0 }),
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 30, dateMs: 0 }),
    ],
    expect: null,
  },
  {
    name: 'zero-date message alongside a valid inbound → the valid one still opens',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 200, dateMs: 0 }),
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 }),
    ],
    expect: { type: 'unanswered_inbound', counterparty: '[email protected]' },
  },
  {
    name: 'thread of nothing but noise senders → none',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 96 }),
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 }),
    ],
    expect: null,
  },
  // ── Grace runs from the oldest unanswered message (gbrain-evals N7-1) ─────
  // First sight of a thread (backfill, sync gap): a fresh nudge must not
  // restart the clock on a request that has waited past the window.
  {
    name: 'request 40h + nudge 5h, first sight → unanswered_inbound (clock starts at the request)',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 40, body: 'Can you send the deck?' }),
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 5, body: 'Bumping this. Any news?' }),
    ],
    expect: { type: 'unanswered_inbound', counterparty: '[email protected]' },
  },
  {
    name: 'my ask 100h + my follow-up 10h, first sight → unanswered_outbound (clock starts at the ask)',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 100, sent: true, body: 'Could you confirm the date?' }),
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 10, sent: true, body: 'Following up on this. Any update?' }),
    ],
    expect: { type: 'unanswered_outbound', counterparty: '[email protected]' },
  },
  {
    name: 'fresh request 10h + nudge 2h → none (the whole run is inside grace)',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 10 }),
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 2 }),
    ],
    expect: null,
  },
  {
    name: 'inbound 40h, my reply 30h, their nudge 5h → none (the run starts after my reply)',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 40 }),
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 30, sent: true, body: 'Will do.' }),
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 5 }),
    ],
    expect: null,
  },
  {
    name: 'CC-only mail 40h + direct ask 5h → none (the reply is owed from the To: message)',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], cc: ['[email protected]'], ageHours: 40 }),
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 5 }),
    ],
    expect: null,
  },
  {
    name: 'my FYI 100h + my question 10h → none (the ask is fresh)',
    messages: [
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 100, sent: true, body: 'Notes attached.' }),
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 10, sent: true, body: 'Can you review?' }),
    ],
    expect: null,
  },
];

describe('detectThreadLoop precision corpus', () => {
  test('grace constants are the documented values', () => {
    expect(INBOUND_GRACE_HOURS).toBe(24);
    expect(OUTBOUND_GRACE_HOURS).toBe(72);
  });

  test(`corpus has at least 40 labeled cases (${CASES.length})`, () => {
    expect(CASES.length).toBeGreaterThanOrEqual(40);
  });

  for (const c of CASES) {
    test(c.name, () => {
      const verdict: ThreadLoopVerdict = detectThreadLoop(
        thread(c.messages),
        MY,
        NOW,
        c.suppressions,
      );
      if (c.expect === null) {
        // ZERO false positives: the corpus assertion is exact emptiness.
        expect(verdict.open).toEqual([]);
      } else {
        expect(verdict.open).toHaveLength(1);
        expect(verdict.open[0].loopType).toBe(c.expect.type);
        expect(verdict.open[0].counterpartyEmail).toBe(c.expect.counterparty);
      }
    });
  }

  test('open verdict carries subject in the summary and a body quote + message id in evidence', () => {
    const m = msg({
      from: '[email protected]',
      to: ['[email protected]'],
      ageHours: 48,
      subject: 'Budget review',
      body: '  Can you   send\nover the numbers?  ',
    });
    const verdict = detectThreadLoop(thread([m]), MY, NOW);
    expect(verdict.open).toHaveLength(1);
    const spec = verdict.open[0];
    expect(spec.summary).toContain('Budget review');
    expect(spec.summary).toContain('[email protected]');
    expect(spec.evidence).toHaveLength(1);
    expect(spec.evidence[0].message_id).toBe(m.id);
    // Whitespace-collapsed quote from the body.
    expect(spec.evidence[0].quote).toBe('Can you send over the numbers?');
    expect(spec.lastActivityMs).toBe(m.internalDateMs);
  });

  test('Re:/Fwd: prefixes are stripped from the summary subject', () => {
    const verdict = detectThreadLoop(
      thread([
        msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48, subject: 'Re: Re: Budget' }),
      ]),
      MY,
      NOW,
    );
    expect(verdict.open[0].summary).toContain('"Budget"');
    expect(verdict.open[0].summary).not.toContain('Re:');

    const fwd = detectThreadLoop(
      thread([
        msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48, subject: 'Fwd: Offsite' }),
      ]),
      MY,
      NOW,
    );
    expect(fwd.open[0].summary).toContain('"Offsite"');
    expect(fwd.open[0].summary).not.toContain('Fwd:');
  });

  test('empty subject falls back to (no subject)', () => {
    const verdict = detectThreadLoop(
      thread([msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48, subject: '' })]),
      MY,
      NOW,
    );
    expect(verdict.open[0].summary).toContain('(no subject)');
  });

  test('quote is capped at 200 chars', () => {
    const verdict = detectThreadLoop(
      thread([
        msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48, body: `${'x'.repeat(500)}?` }),
      ]),
      MY,
      NOW,
    );
    expect(verdict.open[0].evidence[0].quote?.length).toBe(200);
  });
});

// gbrain-evals N7 (2026-10-02 receipt, repros n7-2, n7-6, n7-7).
describe('N7 open-loops wave regressions', () => {
  test('N7-7: a question mark inside a link is not an ask', () => {
    expect(asksQuestion('FYI, the doc: https://docs.example.com/view?id=42')).toBe(false);
    expect(asksQuestion('See www.example.com/a?b=c for details.')).toBe(false);
    expect(asksQuestion('Can you check https://docs.example.com/view?id=42 ?')).toBe(true);
    const v = detectThreadLoop(
      thread([msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 100, sent: true, body: 'FYI, the doc: https://docs.example.com/view?id=42' })]),
      MY,
      NOW,
    );
    expect(v.open).toEqual([]);
  });

  test('N7-2: "Thanks!" to a question neither closes nor restarts the reply-owed loop', () => {
    const ask = msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 40, body: 'Can you send the deck?' });
    const v = detectThreadLoop(
      thread([ask, msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 30, sent: true, body: 'Thanks!' })]),
      MY,
      NOW,
    );
    expect(v.close).not.toContain('unanswered_inbound');
    expect(v.open).toHaveLength(1);
    expect(v.open[0].loopType).toBe('unanswered_inbound');
    expect(v.open[0].openedMs).toBe(ask.internalDateMs);
  });

  test('N7-2: an acknowledgement of a message that asked nothing is still a reply', () => {
    const v = detectThreadLoop(
      thread([
        msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 40, body: 'Here is the deck.' }),
        msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 30, sent: true, body: 'Thanks!' }),
      ]),
      MY,
      NOW,
    );
    expect(v.open).toEqual([]);
    expect(v.close).toEqual(['unanswered_inbound']);
  });

  test('N7-2: a substantive reply still closes', () => {
    const v = detectThreadLoop(
      thread([
        msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 40, body: 'Can you send the deck?' }),
        msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 30, sent: true, body: 'Thanks! Attached is the deck.' }),
      ]),
      MY,
      NOW,
    );
    expect(v.open).toEqual([]);
    expect(v.close).toEqual(['unanswered_inbound']);
  });

  test('acknowledgement detection is narrow', () => {
    for (const t of ['Thanks!', 'thank you', 'Got it, thanks.', 'Thanks, Bob!', 'ok']) expect(isAcknowledgementOnly(t)).toBe(true);
    for (const t of ['Yes', 'No, not this week.', 'Thanks! Attached.', 'Thanks, sending it tomorrow.', 'Will do.', '']) expect(isAcknowledgementOnly(t)).toBe(false);
  });

  test('N7-6: the loop opens at the oldest message that carries the obligation', () => {
    const first = msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 720, body: 'Can you review this?' });
    const v = detectThreadLoop(
      thread([first, msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 30, body: 'Bumping this.' })]),
      MY,
      NOW,
    );
    expect(v.open[0].openedMs).toBe(first.internalDateMs);
    const ask = msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 200, sent: true, body: 'Can you review?' });
    const out = detectThreadLoop(
      thread([ask, msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 100, sent: true, body: 'Any news?' })]),
      MY,
      NOW,
    );
    expect(out.open[0].openedMs).toBe(ask.internalDateMs);
  });
});

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);

  // Structural: Calendar attaches a text/calendar part to every one of these.
  // The address is the colleague's REAL address in each case — that is the
  // whole point, and why a sender mute is not an available fix.
  const CAL = [
    { method: 'REQUEST', subject: 'Invitation: Team sync @ Fri Aug 21, 2026 1pm' },
    { method: 'REQUEST', subject: 'Updated invitation: Team sync @ Fri Aug 21, 2026 1pm' },
    { method: 'REPLY', subject: 'Accepted: 1:1 Alice / Bob' },
    { method: 'REPLY', subject: 'Declined: 1:1 Alice / Bob' },
    { method: 'REPLY', subject: 'Tentative: 1:1 Alice / Bob' },
    { method: 'CANCEL', subject: 'Canceled event: Alice / Bob @ Fri Jun 26' },
  ];

  for (const c of CAL) {
    test(`${c.subject.split(':')[0]} (method=${c.method}) opens no inbound loop`, () => {
      const v = detect([
        msg({
          from: '[email protected]',
          to: ['[email protected]'],
          ageHours: 100,
          subject: c.subject,
          calendarMethod: c.method,
        }),
      ]);
      expect(v.open).toEqual([]);
    });
  }

  test('my own calendar response opens no outbound loop even with a question mark', () => {
    const v = detect([
      msg({
        from: '[email protected]',
        to: ['[email protected]'],
        ageHours: 200,
        sent: true,
        subject: 'Accepted: Team sync',
        body: 'Does this time still work?',
        calendarMethod: 'REPLY',
      }),
    ]);
    expect(v.open).toEqual([]);
  });

  test('a calendar invite does NOT close a real outbound loop', () => {
    // A colleague sending an invite has not answered my question. If the
    // invite were treated as their turn, it would silently close the 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,
        subject: 'Invitation: Budget sync',
        calendarMethod: 'REQUEST',
      }),
    ]);
    expect(v.open.map((o) => o.loopType)).toEqual(['unanswered_outbound']);
    expect(v.close).toEqual(['unanswered_inbound']);
  });

  test('a real human email from the SAME colleague still opens a loop', () => {
    const v = detect([
      msg({
        from: '[email protected]',
        to: ['[email protected]'],
        ageHours: 100,
        subject: 'Invitation: Team sync',
        calendarMethod: 'REQUEST',
      }),
      msg({
        from: '[email protected]',
        to: ['[email protected]'],
        ageHours: 50,
        subject: 'Budget question',
        body: 'Can you approve the Q3 number?',
      }),
    ]);
    expect(v.open.map((o) => o.loopType)).toEqual(['unanswered_inbound']);
    expect(v.open[0].counterpartyEmail).toBe('[email protected]');
  });

  test('subject fallback applies when MIME was not captured', () => {
    const v = detect([
      msg({
        from: '[email protected]',
        to: ['[email protected]'],
        ageHours: 100,
        subject: 'Updated invitation: Team sync @ Fri Aug 21',
        calendarMethod: null,
      }),
    ]);
    expect(v.open).toEqual([]);
  });

  test('a localized calendar subject is covered by the fallback', () => {
    const v = detect([
      msg({
        from: '[email protected]',
        to: ['[email protected]'],
        ageHours: 100,
        subject: 'Приглашение: Team sync',
        calendarMethod: null,
      }),
    ]);
    expect(v.open).toEqual([]);
  });

  test('a human "Notification: ..." email with no calendar part still opens a loop', () => {
    // 'Notification:' is a generic vendor/human prefix, not a Calendar header —
    // classifying it as system mail dropped real inbound questions from BOTH
    // detectors (ship-review fix).
    const v = detect([
      msg({
        from: '[email protected]',
        to: ['[email protected]'],
        ageHours: 100,
        subject: 'Notification: your invoice is ready',
        body: 'Can you confirm receipt?',
        calendarMethod: null,
      }),
    ]);
    expect(v.open.map((o) => o.loopType)).toEqual(['unanswered_inbound']);
  });

  test('an unrecognised MIME method is not trusted as a Calendar stamp', () => {
    const v = detect([
      msg({
        from: '[email protected]',
        to: ['[email protected]'],
        ageHours: 100,
        subject: 'Quarterly plan',
        body: 'Can you review the plan?',
        calendarMethod: 'BOGUS',
      }),
    ]);
    expect(v.open.map((o) => o.loopType)).toEqual(['unanswered_inbound']);
  });

  test('a forwarded human question is NOT lost just because it says Invitation', () => {
    // The fallback refuses anything carrying a Re:/Fwd: prefix, so a human
    // forward of an invite thread still owes a reply.
    const v = detect([
      msg({
        from: '[email protected]',
        to: ['[email protected]'],
        ageHours: 100,
        subject: 'Fwd: Invitation: Team sync',
        body: 'Should I accept this on your behalf?',
        calendarMethod: null,
      }),
    ]);
    expect(v.open.map((o) => o.loopType)).toEqual(['unanswered_inbound']);
  });

  test("a human email attaching a bare .ics (calendarMethod '') still opens a loop", () => {
    // calendarMethod '' means "an .ics-ish thing was present but NO iCalendar
    // METHOD was found" — that is a human attaching an invite file, not
    // Calendar system mail. Pre-fix, '' classified as system mail and the
    // question below could neither open nor close a loop.
    const v = detect([
      msg({
        from: '[email protected]',
        to: ['[email protected]'],
        ageHours: 100,
        subject: 'Venue contract and invite file',
        body: 'Attached the invite file — can you confirm the venue works?',
        calendarMethod: '',
      }),
    ]);
    expect(v.open.map((o) => o.loopType)).toEqual(['unanswered_inbound']);
    expect(v.open[0].counterpartyEmail).toBe('[email protected]');
  });

  test("a reply carrying a bare .ics (calendarMethod '') still CLOSES my outbound loop", () => {
    const v = detect([
      msg({
        from: '[email protected]',
        to: ['[email protected]'],
        ageHours: 200,
        sent: true,
        body: 'Can you send over the invite file?',
      }),
      msg({
        from: '[email protected]',
        to: ['[email protected]'],
        ageHours: 100,
        subject: 'Re: invite file',
        body: 'Here it is.',
        calendarMethod: '',
      }),
    ]);
    // Alice's human reply is her turn: nothing stays open on my side.
    expect(v.open.map((o) => o.loopType)).not.toContain('unanswered_outbound');
  });

  test('a human subject merely containing the word invitation still opens a loop', () => {
    const v = detect([
      msg({
        from: '[email protected]',
        to: ['[email protected]'],
        ageHours: 100,
        subject: 'Your invitation: what should we do about the venue?',
        calendarMethod: null,
      }),
    ]);
    expect(v.open.map((o) => o.loopType)).toEqual(['unanswered_inbound']);
  });
});

describe('#5103: Google system senders and bulk categories in the deterministic lane', () => {
  const detect = (messages: GmailMessageMeta[]): ThreadLoopVerdict => detectThreadLoop(thread(messages), MY, NOW);

  test('both lanes read one bulk-category constant', () => {
    expect(EXTRACT_LANE_BULK_CATEGORY_LABELS).toBe(BULK_CATEGORY_LABELS);
    expect([...BULK_CATEGORY_LABELS]).toEqual(['CATEGORY_PROMOTIONS', 'CATEGORY_SOCIAL', 'CATEGORY_FORUMS']);
  });

  test('a Meet notes digest from [email protected] opens no inbound loop', () => {
    const v = detect([msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48, subject: 'Notes: weekly sync', body: 'Here are the notes. Any corrections?' })]);
    expect(v.open).toEqual([]);
  });

  test('a lookalike address is matched by equality only, so it still opens a loop', () => {
    const v = detect([msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 })]);
    expect(v.open.map((o) => o.loopType)).toEqual(['unanswered_inbound']);
  });

  for (const label of BULK_CATEGORY_LABELS) {
    test(`${label} inbound the owner never joined → no loop`, () => {
      const v = detect([msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48, labels: [label] })]);
      expect(v.open).toEqual([]);
    });
  }

  test('a PROMOTIONS thread the owner wrote a substantive message in still opens the reply-owed loop', () => {
    const v = detect([
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 200, labels: ['CATEGORY_PROMOTIONS'], body: 'Spring sale is on.' }),
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 150, sent: true, labels: ['CATEGORY_PROMOTIONS'], body: 'Is the blue model still available in size 10?' }),
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48, labels: ['CATEGORY_PROMOTIONS'], body: 'Yes, could you confirm your shipping address?' }),
    ]);
    expect(v.open.map((o) => [o.loopType, o.counterpartyEmail])).toEqual([['unanswered_inbound', '[email protected]']]);
  });

  test('CATEGORY_UPDATES without an owner reply still opens (invoices and document requests live there)', () => {
    const v = detect([msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48, labels: ['CATEGORY_UPDATES'], body: 'Could you approve the attached invoice?' })]);
    expect(v.open.map((o) => o.loopType)).toEqual(['unanswered_inbound']);
  });

  test('a bulk category never fabricates a close: my reply still closes, and their reply still closes my outbound loop', () => {
    const v = detect([
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 100, labels: ['CATEGORY_PROMOTIONS'] }),
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 2, sent: true, labels: ['CATEGORY_PROMOTIONS'], body: 'Done, thanks for the details.' }),
    ]);
    expect(v.close).toEqual(['unanswered_inbound']);
    expect(v.open).toEqual([]);
  });

  test('a mixed thread: the system digest is ignored and the human message to me opens the loop', () => {
    const v = detect([
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 60, subject: 'Notes: planning' }),
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48, subject: 'Re: planning', body: 'Can you send the budget sheet?' }),
    ]);
    expect(v.open.map((o) => [o.loopType, o.counterpartyEmail])).toEqual([['unanswered_inbound', '[email protected]']]);
  });
});

describe('#5012 positively automated mail and the opt-in Updates reciprocity rule', () => {
  const alert = (headers: MsgSpec['headers'], labels: string[] = []) =>
    msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48, labels, headers,
      subject: 'Your balance alert', body: 'Your available balance is below the threshold you set. Review it?' });

  const automatedHeaders: Array<[string, NonNullable<MsgSpec['headers']>]> = [
    ['Precedence: bulk', { precedence: 'bulk' }],
    ['Precedence: list', { precedence: 'list' }],
    ['Precedence: junk', { precedence: 'junk' }],
    ['a List-Id header', { listId: true }],
    ['a no-reply Reply-To', { replyTo: ['[email protected]'] }],
  ];
  for (const [name, headers] of automatedHeaders) {
    test(`a bank alert with ${name} opens no reply-owed loop and records why`, () => {
      const v = detectThreadLoop(thread([alert(headers)]), MY, NOW, sup());
      expect(v.open).toEqual([]);
      expect(v.held).toBeUndefined();
      expect(v.withheld).toEqual({ reason: 'automated_mail', counterpartyEmail: '[email protected]' });
    });
  }

  test('withholding never fabricates a close: my earlier outbound ask is still closed by their reply', () => {
    const v = detectThreadLoop(thread([
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 100, sent: true, body: 'Can you raise my limit?' }),
      alert({ precedence: 'bulk' }),
    ]), MY, NOW, sup());
    expect(v.close).toEqual(['unanswered_outbound']);
    expect(v.open).toEqual([]);
  });

  test('a cold founder intro in Primary still opens a loop', () => {
    const v = detectThreadLoop(thread([msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48,
      labels: ['CATEGORY_PERSONAL'], subject: 'Intro: seed round', body: 'Would you have 20 minutes next week to hear about what we are building?' })]), MY, NOW, sup());
    expect(v.open.map((o) => [o.loopType, o.counterpartyEmail])).toEqual([['unanswered_inbound', '[email protected]']]);
    expect(v.withheld).toBeUndefined();
  });

  const updatesIntro = () => thread([msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48,
    labels: ['CATEGORY_UPDATES'], subject: 'Intro: seed round', body: 'Would you have 20 minutes next week?' })]);

  test('a cold founder intro in Updates opens a loop by default (the category alone never withholds)', () => {
    const v = detectThreadLoop(updatesIntro(), MY, NOW, sup());
    expect(v.open.map((o) => o.counterpartyEmail)).toEqual(['[email protected]']);
  });

  test('with the reciprocity rule on, Updates mail opens only for a sender the owner wrote to', () => {
    const off = detectThreadLoop(updatesIntro(), MY, NOW, sup(), { ownerWroteTo: new Set() });
    expect(off.open).toEqual([]);
    expect(off.withheld).toEqual({ reason: 'updates_without_reciprocity', counterpartyEmail: '[email protected]' });
    const known = detectThreadLoop(updatesIntro(), MY, NOW, sup(), { ownerWroteTo: new Set(['[email protected]']) });
    expect(known.open.map((o) => o.counterpartyEmail)).toEqual(['[email protected]']);
  });

  test('with the reciprocity rule on, an Updates thread the owner already wrote in still opens', () => {
    const v = detectThreadLoop(thread([
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 100, sent: true, labels: ['CATEGORY_UPDATES'], body: 'Please resend the invoice.' }),
      msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48, labels: ['CATEGORY_UPDATES'], body: 'Attached. Can you approve it?' }),
    ]), MY, NOW, sup(), { ownerWroteTo: new Set() });
    expect(v.open.map((o) => o.counterpartyEmail)).toEqual(['[email protected]']);
  });
});

describe('forwarded mail is judged by the note above the forward (#8941 keeps the forwarded body)', () => {
  // Bodies go through the same trim the Gmail client applies, so these rows
  // pin both halves: the forward keeps its whole body, and only the sender's
  // own note decides whether it asks anything.
  const GMAIL_FORWARD = [
    '---------- Forwarded message ---------',
    'From: Carol Example <[email protected]>',
    'Date: Mon, Aug 17, 2026 at 9:00 AM',
    'Subject: Venue for the offsite',
    'To: Me Example <[email protected]>',
    '',
    'Which venue did we settle on for the offsite? I need a headcount by Friday.',
  ].join('\n');
  const APPLE_FORWARD = [
    'Begin forwarded message:',
    '',
    'From: Carol Example <[email protected]>',
    'Subject: Venue for the offsite',
    '',
    'Which venue did we settle on for the offsite?',
  ].join('\n');
  const forwardBody = (note: string, forwarded = GMAIL_FORWARD) => trimQuotedReply(note ? `${note}\n\n${forwarded}` : forwarded);
  const myForward = (note: string, ageHours = 96, forwarded = GMAIL_FORWARD) =>
    msg({ from: '[email protected]', to: ['[email protected]'], ageHours, sent: true, subject: 'Fwd: Venue for the offsite', body: forwardBody(note, forwarded) });

  test('the forward keeps the forwarded message in its body', () => {
    expect(forwardBody('FYI, see below.')).toContain('Which venue did we settle on');
    expect(forwardBody('See below.', APPLE_FORWARD)).toContain('Which venue did we settle on');
  });

  for (const [name, m] of [
    ['a Gmail forward with an FYI note over someone else\'s question', myForward('FYI, see below.')],
    ['an Apple Mail forward with a "See below." note', myForward('See below.', 96, APPLE_FORWARD)],
    ['a forward with no note at all', myForward('')],
    ['an FYI note that only shares a link', myForward('FYI, context here: https://docs.example.com/view?id=42')],
  ] as const) {
    test(`${name} opens no waiting-on-them loop`, () => {
      const v = detectThreadLoop(thread([m]), MY, NOW);
      expect(v.open).toEqual([]);
      expect(v.held).toBeUndefined();
    });
  }

  test('a forward whose own note asks a question still opens the loop', () => {
    const v = detectThreadLoop(thread([myForward('Can you take this one?')]), MY, NOW);
    expect(v.open).toHaveLength(1);
    expect(v.open[0].loopType).toBe('unanswered_outbound');
    expect(v.open[0].counterpartyEmail).toBe('[email protected]');
  });

  test('my question after an FYI forward opens at the question, not at the forward', () => {
    const ask = msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 80, sent: true, body: 'Did you get a chance to look?' });
    const v = detectThreadLoop(thread([myForward('FYI, see below.', 400), ask]), MY, NOW);
    expect(v.open).toHaveLength(1);
    expect(v.open[0].openedMs).toBe(ask.internalDateMs);
  });

  test('their FYI forward to me is answered by my "Thanks!"', () => {
    const v = detectThreadLoop(
      thread([
        msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 40, subject: 'Fwd: Venue for the offsite', body: forwardBody('FYI, see below.') }),
        msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 30, sent: true, body: 'Thanks!' }),
      ]),
      MY,
      NOW,
    );
    expect(v.open).toEqual([]);
    expect(v.close).toEqual(['unanswered_inbound']);
  });

  test('their forward that asks me in its note still owes a real answer', () => {
    const v = detectThreadLoop(
      thread([
        msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 40, subject: 'Fwd: Venue for the offsite', body: forwardBody('Can you answer Carol?') }),
        msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 30, sent: true, body: 'Thanks!' }),
      ]),
      MY,
      NOW,
    );
    expect(v.open).toHaveLength(1);
    expect(v.open[0].loopType).toBe('unanswered_inbound');
  });

  test('asksQuestion reads only the text above a forward separator', () => {
    expect(asksQuestion(forwardBody('FYI, see below.'))).toBe(false);
    expect(asksQuestion(forwardBody('Thoughts?'))).toBe(true);
    expect(asksQuestion('Is "---------- Forwarded message ---------" the separator Gmail writes?')).toBe(true);
  });
});