Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

24.0 KB
Raw Blame
import { describe, it, expect, vi, beforeEach } from 'vitest';

// Mock the DB layer so the SQL builders and row mappers can be tested without a
// live Postgres — the route test mocks the whole service away, so this is the
// only coverage for the contract-dense SQL↔JS mapping code.
vi.mock('../lib/db.js', () => ({
  ensureSchema: vi.fn().mockResolvedValue(undefined),
  query: vi.fn(),
  withTransaction: vi.fn(),
}));

// Fixed, mockable timezone for autoCreateTouchpoint's user-local-day derivation
// (#8451) — otherwise it would read the real (or unset) `settings.json` and make
// the last-contact-day assertions depend on this machine's configured timezone.
vi.mock('./userTimezone.js', () => ({
  getUserTimezone: vi.fn().mockResolvedValue('America/Los_Angeles'),
}));

vi.mock('./calendarSync.js', () => ({
  getEvent: vi.fn(),
}));

import { query, withTransaction } from '../lib/db.js';
import { getUserTimezone } from './userTimezone.js';
import { getEvent } from './calendarSync.js';
import {
  listPeople,
  getPerson,
  createPerson,
  createTouchpoint,
  createCalendarTouchpoint,
  normalizeTags,
  normalizeEmails,
  isoDate,
  isoDateTime,
  rowToPerson,
  rowToTouchpoint,
  personCadenceStatus,
  getCareSummary,
  autoCreateTouchpoint,
  autoLogTouchpoints,
  findDuplicateTribeIdentifiers,
  checkDuplicateTribeIdentifiers,
} from './tribe.js';
import { DEFAULT_RING_CADENCE } from '../lib/tribeCadence.js';

// ISO date (YYYY-MM-DD) `n` whole days before local today.
function daysAgo(n) {
  const d = new Date();
  d.setDate(d.getDate() - n);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}

describe('tribe service — pure helpers', () => {
  describe('normalizeTags', () => {
    it('splits a comma string, trimming and dropping empties', () => {
      expect(normalizeTags('a, b , ,c')).toEqual(['a', 'b', 'c']);
    });

    it('maps and trims an array, dropping empties', () => {
      expect(normalizeTags([' a ', '', 'b'])).toEqual(['a', 'b']);
    });

    it('returns [] for nullish input', () => {
      expect(normalizeTags(null)).toEqual([]);
      expect(normalizeTags(undefined)).toEqual([]);
    });
  });

  describe('isoDate / isoDateTime', () => {
    it('isoDate slices a Date to YYYY-MM-DD', () => {
      expect(isoDate(new Date('2026-06-18T15:00:00.000Z'))).toBe('2026-06-18');
    });

    it('isoDate keeps the date head of a string', () => {
      expect(isoDate('2026-06-18')).toBe('2026-06-18');
    });

    it('isoDate returns null for empty', () => {
      expect(isoDate(null)).toBeNull();
    });

    it('isoDateTime returns null for an unparseable string instead of throwing', () => {
      expect(isoDateTime('not-a-date')).toBeNull();
    });

    it('isoDateTime renders a valid Date', () => {
      expect(isoDateTime(new Date('2026-06-18T15:00:00.000Z'))).toBe('2026-06-18T15:00:00.000Z');
    });
  });

  describe('rowToPerson', () => {
    it('maps a full DB row to the API shape and coerces counts to numbers', () => {
      const row = {
        id: 'p1',
        name: 'Ada',
        relationship: 'mentor',
        ring: 'core',
        cadence_days: 21,
        last_contact_on: '2026-06-01',
        channel: 'sms',
        energy: 'steady',
        tags: ['x'],
        next_move: 'call',
        notes: 'n',
        touchpoint_count: '3',
        linked_memory_count: '2',
        created_at: '2026-05-01T00:00:00.000Z',
        updated_at: '2026-05-02T00:00:00.000Z',
      };
      expect(rowToPerson(row)).toMatchObject({
        id: 'p1',
        name: 'Ada',
        ring: 'core',
        cadenceDays: 21,
        lastContact: '2026-06-01',
        tags: ['x'],
        touchpointCount: 3,
        linkedMemoryCount: 2,
      });
    });

    it('defaults absent optional columns', () => {
      const r = rowToPerson({ id: 'p2', name: 'B', ring: 'tribe', cadence_days: 45 });
      expect(r.relationship).toBe('');
      expect(r.tags).toEqual([]);
      expect(r.touchpointCount).toBe(0);
      expect(r.lastContact).toBeNull();
    });
  });

  describe('rowToTouchpoint', () => {
    it('maps a touchpoint row and defaults nullable calendar fields', () => {
      const r = rowToTouchpoint({
        id: 't1',
        person_id: 'p1',
        happened_at: new Date('2026-06-18T15:00:00.000Z'),
        summary: 'Walk',
      });
      expect(r).toMatchObject({
        id: 't1',
        personId: 'p1',
        happenedAt: '2026-06-18T15:00:00.000Z',
        summary: 'Walk',
        calendarAccountId: null,
        calendarEventId: null,
        metadata: {},
      });
    });
  });
});

describe('tribe service — listPeople query builder', () => {
  beforeEach(() => {
    query.mockReset();
    query.mockResolvedValue({ rows: [] });
  });

  // The list view renders contact status/tags/energy/next move — never the
  // touchpoint or memory-link counts — so the per-row correlated counts were
  // pure overhead (2N index scans per request). getPerson() still carries them.
  it('does not run correlated touchpoint/memory-link count subqueries', async () => {
    await listPeople();
    const [sql] = query.mock.calls[0];
    expect(sql).not.toContain('COUNT(*)');
    expect(sql).not.toContain('tribe_touchpoints');
    expect(sql).not.toContain('tribe_memory_links');
    expect(sql).toContain('FROM tribe_people');
  });

  it('keeps the ring-rank, oldest-contact, name ordering', async () => {
    await listPeople();
    const [sql] = query.mock.calls[0];
    expect(sql).toContain("CASE ring WHEN 'support' THEN 1");
    expect(sql).toContain("COALESCE(last_contact_on, DATE '1900-01-01') ASC");
    expect(sql).toContain('name ASC');
  });

  it('maps rows to full person objects with counts defaulted to 0', async () => {
    query.mockResolvedValue({ rows: [
      { id: 'p1', name: 'Ada', ring: 'core', cadence_days: 21, tags: ['x'], notes: 'n' },
    ] });
    const [person] = await listPeople();
    expect(person).toMatchObject({ id: 'p1', name: 'Ada', ring: 'core', tags: ['x'], notes: 'n' });
    expect(person.touchpointCount).toBe(0);
    expect(person.linkedMemoryCount).toBe(0);
  });

  it('getPerson still hydrates the touchpoint and memory-link counts', async () => {
    query.mockResolvedValue({ rows: [
      { id: 'p1', name: 'Ada', ring: 'core', cadence_days: 21, touchpoint_count: '3', linked_memory_count: '2' },
    ] });
    const person = await getPerson('p1');
    const [sql, params] = query.mock.calls[0];
    expect(sql).toContain('FROM tribe_touchpoints t');
    expect(sql).toContain('FROM tribe_memory_links ml');
    expect(params).toEqual(['p1']);
    expect(person).toMatchObject({ id: 'p1', touchpointCount: 3, linkedMemoryCount: 2 });
  });

  it('filters by ring with a single $1 parameter', async () => {
    await listPeople({ ring: 'core' });
    const [sql, params] = query.mock.calls[0];
    expect(sql).toContain('ring = $1');
    expect(params).toEqual(['core']);
  });

  it('does not add a ring filter when ring is "all"', async () => {
    await listPeople({ ring: 'all' });
    const [sql, params] = query.mock.calls[0];
    expect(sql).not.toContain('ring = $');
    expect(params).toEqual([]);
  });

  it('reuses one parameter across every search column, wrapped in %%', async () => {
    await listPeople({ search: 'ada' });
    const [sql, params] = query.mock.calls[0];
    expect(sql).toContain('ILIKE $1');
    expect(params).toEqual(['%ada%']);
  });

  it('assigns sequential parameter indices for ring + search together', async () => {
    await listPeople({ ring: 'core', search: 'ada' });
    const [sql, params] = query.mock.calls[0];
    expect(sql).toContain('ring = $1');
    expect(sql).toContain('ILIKE $2');
    expect(params).toEqual(['core', '%ada%']);
  });
});

describe('tribe service — createTouchpoint', () => {
  beforeEach(() => {
    query.mockReset();
    withTransaction.mockReset();
  });

  it('persists the browser-local date independently from the UTC timestamp', async () => {
    query.mockResolvedValue({ rows: [{ id: 'person-1', name: 'Example Person', ring: 'tribe', cadence_days: 45 }] });
    const clientQuery = vi.fn()
      .mockResolvedValueOnce({ rows: [{ id: 'touch-1', person_id: 'person-1', happened_at: '2026-01-02T04:00:00.000Z' }] })
      .mockResolvedValueOnce({ rows: [] });
    withTransaction.mockImplementation(async (fn) => fn({ query: clientQuery }));

    await createTouchpoint('person-1', {
      happenedAt: '2026-01-02T04:00:00.000Z',
      localDate: '2026-01-01',
    });

    expect(clientQuery).toHaveBeenNthCalledWith(
      2,
      expect.stringContaining('SET last_contact_on'),
      ['person-1', '2026-01-01', ''],
    );
  });
});

describe('tribe service — createCalendarTouchpoint (#8451 UTC-offset day shift)', () => {
  beforeEach(() => {
    query.mockReset();
    withTransaction.mockReset();
    getEvent.mockReset();
    getUserTimezone.mockClear();
  });

  it('stores the user-local day for an evening calendar event, not its UTC day', async () => {
    getEvent.mockResolvedValue({
      title: 'Dinner',
      startTime: '2026-09-11T01:00:00.000Z', // 2026-09-10 18:00 America/Los_Angeles
      endTime: '2026-09-11T02:00:00.000Z',
    });
    query.mockResolvedValue({ rows: [{ id: 'person-1', name: 'Example Person', ring: 'tribe', cadence_days: 45 }] });
    const clientQuery = vi.fn()
      .mockResolvedValueOnce({ rows: [{ id: 'touch-1', person_id: 'person-1' }] })
      .mockResolvedValueOnce({ rows: [] });
    withTransaction.mockImplementation(async (fn) => fn({ query: clientQuery }));

    await createCalendarTouchpoint('person-1', { accountId: 'acct-1', eventId: 'evt-1' });

    expect(clientQuery).toHaveBeenNthCalledWith(
      2,
      expect.stringContaining('SET last_contact_on'),
      ['person-1', '2026-09-10', 'Calendar'],
    );
  });
});

describe('tribe service — createCalendarTouchpoint idempotency', () => {
  beforeEach(() => {
    query.mockReset();
    withTransaction.mockReset();
    getEvent.mockReset();
  });

  it('keys the insert on the same cal:<account>:<externalId> the sync auto-logger uses, and returns the existing row on conflict', async () => {
    getEvent.mockResolvedValue({ id: 'local-id', externalId: 'provider-evt', title: 'Dinner', startTime: '2026-09-11T01:00:00.000Z' });
    query.mockResolvedValue({ rows: [{ id: 'person-1', name: 'Example Person', ring: 'tribe', cadence_days: 45 }] });
    const clientQuery = vi.fn()
      .mockResolvedValueOnce({ rows: [] }) // ON CONFLICT DO NOTHING — row already logged by sync or a prior click
      .mockResolvedValueOnce({ rows: [{ id: 'touch-existing', person_id: 'person-1' }] });
    withTransaction.mockImplementation(async (fn) => fn({ query: clientQuery }));

    const result = await createCalendarTouchpoint('person-1', { accountId: 'acct-1', eventId: 'local-id' });

    expect(clientQuery.mock.calls[0][0]).toContain('ON CONFLICT (person_id, dedupe_key)');
    expect(clientQuery.mock.calls[0][1][8]).toBe('cal:acct-1:provider-evt');
    expect(clientQuery).toHaveBeenCalledTimes(2); // no last_contact_on / channel rewrite for a duplicate
    expect(result.id).toBe('touch-existing');
  });
});

describe('tribe service — autoCreateTouchpoint (#8451 UTC-offset day shift)', () => {
  beforeEach(() => {
    withTransaction.mockReset();
    getUserTimezone.mockClear();
  });

  it('advances last_contact_on to the user-LOCAL day, not the UTC day, for a late-evening instant', async () => {
    // 2026-09-11T01:00:00Z is 2026-09-10 18:00 in America/Los_Angeles (mocked
    // above) — an evening touchpoint that must not be dated tomorrow.
    const clientQuery = vi.fn()
      .mockResolvedValueOnce({ rows: [{ id: 'touch-1', person_id: 'person-1' }] })
      .mockResolvedValueOnce({ rows: [] });
    withTransaction.mockImplementation(async (fn) => fn({ query: clientQuery }));

    await autoCreateTouchpoint('person-1', {
      happenedAt: '2026-09-11T01:00:00.000Z',
      source: 'calendar',
      dedupeKey: 'cal:a:e1',
    });

    expect(clientQuery).toHaveBeenNthCalledWith(
      2,
      expect.stringContaining('SET last_contact_on'),
      ['person-1', '2026-09-10'],
    );
  });

  it('stores happened_at as the full raw instant (unaffected by the local-day derivation)', async () => {
    const clientQuery = vi.fn()
      .mockResolvedValueOnce({ rows: [{ id: 'touch-1', person_id: 'person-1' }] })
      .mockResolvedValueOnce({ rows: [] });
    withTransaction.mockImplementation(async (fn) => fn({ query: clientQuery }));

    await autoCreateTouchpoint('person-1', {
      happenedAt: '2026-09-11T01:00:00.000Z',
      source: 'calendar',
      dedupeKey: 'cal:a:e1',
    });

    const [, insertParams] = clientQuery.mock.calls[0];
    expect(insertParams[2]).toBe('2026-09-11T01:00:00.000Z'); // happened_at column
  });
});

describe('tribe service — personCadenceStatus', () => {
  it('external people are never overdue', () => {
    expect(personCadenceStatus({ ring: 'external', lastContact: daysAgo(999), cadenceDays: 7 }))
      .toMatchObject({ state: 'external', daysOverdue: 0 });
  });

  it('no touchpoint → missing with null daysOverdue', () => {
    const s = personCadenceStatus({ ring: 'core', lastContact: null, cadenceDays: 21 });
    expect(s.state).toBe('missing');
    expect(s.daysOverdue).toBeNull();
  });

  it('elapsed beyond cadence → overdue with positive daysOverdue', () => {
    const s = personCadenceStatus({ ring: 'support', lastContact: daysAgo(10), cadenceDays: 7 });
    expect(s.state).toBe('overdue');
    expect(s.daysOverdue).toBe(3);
  });

  it('within a week of cadence → soon', () => {
    expect(personCadenceStatus({ ring: 'core', lastContact: daysAgo(18), cadenceDays: 21 }).state).toBe('soon');
  });

  it('comfortably inside cadence → steady', () => {
    expect(personCadenceStatus({ ring: 'village', lastContact: daysAgo(2), cadenceDays: 90 }).state).toBe('steady');
  });
});

describe('tribe service — getCareSummary', () => {
  beforeEach(() => {
    query.mockReset();
  });

  // The care query projects only the cadence + response columns, so mock rows
  // carry exactly those snake_case columns and no full person entity.
  const row = (over) => ({
    id: over.id, name: over.name, ring: over.ring,
    cadence_days: over.cadence_days, last_contact_on: over.last_contact_on ?? null,
    channel: '',
  });

  it('projects only the cadence columns and excludes external people in SQL', async () => {
    query.mockResolvedValue({ rows: [] });
    await getCareSummary();
    const [sql] = query.mock.calls[0];
    expect(sql).toContain('SELECT id, name, ring, cadence_days, last_contact_on, channel');
    expect(sql).toContain("ring <> 'external'");
    expect(sql).toContain('deleted = FALSE');
    // Never the full entity, and never the 2N correlated counts (#6024).
    expect(sql).not.toContain('notes');
    expect(sql).not.toContain('COUNT(*)');
  });

  it('sorts missing first, then most-overdue', async () => {
    query.mockResolvedValue({ rows: [
      row({ id: 'a', name: 'Overdue Small', ring: 'support', cadence_days: 7, last_contact_on: daysAgo(10) }), // 3d overdue
      row({ id: 'b', name: 'Never', ring: 'core', cadence_days: 21, last_contact_on: null }),                  // missing
      row({ id: 'c', name: 'Overdue Big', ring: 'core', cadence_days: 21, last_contact_on: daysAgo(60) }),     // 39d overdue
      row({ id: 'd', name: 'Steady', ring: 'village', cadence_days: 90, last_contact_on: daysAgo(1) }),        // steady
    ] });

    const summary = await getCareSummary();
    expect(summary.hasPeople).toBe(true);
    expect(summary.peopleCount).toBe(4);
    expect(summary.overdueCount).toBe(3); // missing + 2 overdue
    expect(summary.overdue.map((p) => p.id)).toEqual(['b', 'c', 'a']);
    // Response shape the dashboard widget + proactive alert consume.
    expect(Object.keys(summary.overdue[1]).sort()).toEqual(
      ['channel', 'daysOverdue', 'id', 'lastContact', 'name', 'ring', 'state'],
    );
    expect(summary.overdue[1]).toMatchObject({ ring: 'core', state: 'overdue', daysOverdue: 39 });
  });

  it('renders a Date last_contact_on as an ISO date string', async () => {
    query.mockResolvedValue({ rows: [
      { id: 'a', name: 'A', ring: 'core', cadence_days: 21, last_contact_on: new Date('2020-01-02T00:00:00.000Z'), channel: 'sms' },
    ] });
    const summary = await getCareSummary();
    expect(summary.overdue[0].lastContact).toBe('2020-01-02');
    expect(summary.overdue[0].channel).toBe('sms');
  });

  it('respects the limit while still reporting the full overdueCount', async () => {
    query.mockResolvedValue({ rows: [
      row({ id: 'a', name: 'A', ring: 'core', cadence_days: 21, last_contact_on: daysAgo(60) }),
      row({ id: 'b', name: 'B', ring: 'core', cadence_days: 21, last_contact_on: daysAgo(50) }),
    ] });
    const summary = await getCareSummary(1);
    expect(summary.overdueCount).toBe(2);
    expect(summary.overdue).toHaveLength(1);
  });

  it('reports hasPeople false for an empty tribe', async () => {
    query.mockResolvedValue({ rows: [] });
    const summary = await getCareSummary();
    expect(summary.hasPeople).toBe(false);
    expect(summary.overdueCount).toBe(0);
  });
});

describe('tribe service — createPerson', () => {
  beforeEach(() => {
    query.mockReset();
  });

  it('resolves the ring-aware default cadence and normalizes a tag string', async () => {
    query.mockResolvedValue({
      rows: [{ id: 'p1', name: 'Ada', ring: 'core', cadence_days: 21, tags: ['a', 'b'] }],
    });
    await createPerson({ name: 'Ada', ring: 'core', tags: 'a, b' });

    const [, params] = query.mock.calls[0];
    // INSERT param order: id,name,relationship,ring,cadence_days,last_contact,
    // channel,energy,tags,emails,next_move,notes
    expect(params[3]).toBe('core');
    expect(params[4]).toBe(DEFAULT_RING_CADENCE.core); // 21, not the flat SQL default
    expect(params[8]).toEqual(['a', 'b']);
  });

  it('normalizes emails to a lowercased de-duplicated array on insert', async () => {
    query.mockResolvedValue({ rows: [{ id: 'p1', name: 'Ada', ring: 'tribe', cadence_days: 45 }] });
    await createPerson({ name: 'Ada', emails: [' [email protected] ', '[email protected]', '[email protected]'] });
    const [, params] = query.mock.calls[0];
    expect(params[9]).toEqual(['[email protected]', '[email protected]']); // emails at $10
  });
});

describe('tribe service — normalizeEmails', () => {
  it('lowercases, trims, splits a comma string, and de-dupes', () => {
    expect(normalizeEmails('[email protected], [email protected] , ,[email protected]')).toEqual(['[email protected]', '[email protected]']);
  });
  it('handles an array and drops empties', () => {
    expect(normalizeEmails([' [email protected] ', '', '[email protected]'])).toEqual(['[email protected]']);
  });
  it('returns [] for nullish', () => {
    expect(normalizeEmails(null)).toEqual([]);
    expect(normalizeEmails(undefined)).toEqual([]);
  });
});

describe('tribe service — rowToPerson emails', () => {
  it('maps the emails array and defaults to []', () => {
    expect(rowToPerson({ id: 'p', name: 'N', ring: 'tribe', cadence_days: 45, emails: ['[email protected]'] }).emails)
      .toEqual(['[email protected]']);
    expect(rowToPerson({ id: 'p', name: 'N', ring: 'tribe', cadence_days: 45 }).emails).toEqual([]);
  });
});

describe('tribe service — autoLogTouchpoints', () => {
  beforeEach(() => {
    query.mockReset();
    withTransaction.mockReset();
  });

  // One tracked person "Ada" with a known email; listPeople() is the first query.
  function mockPeople() {
    query.mockResolvedValue({ rows: [
      { id: 'ada', name: 'Ada', ring: 'tribe', cadence_days: 45, emails: ['[email protected]'] },
    ] });
  }

  it('matches identities and inserts one deduped touchpoint per matched person', async () => {
    mockPeople();
    // INSERT returns a row (new); UPDATE returns nothing.
    withTransaction.mockImplementation(async (fn) => fn({
      query: vi.fn()
        .mockResolvedValueOnce({ rows: [{ id: 't1', person_id: 'ada', source: 'calendar' }] })
        .mockResolvedValueOnce({ rows: [] }),
    }));

    const result = await autoLogTouchpoints([
      { identities: [{ email: '[email protected]' }], source: 'calendar', dedupeKey: 'cal:a:e1', happenedAt: '2026-06-01T10:00:00Z' },
      { identities: [{ email: '[email protected]' }], source: 'calendar', dedupeKey: 'cal:a:e2' },
    ]);

    expect(result).toEqual({ created: 1, matched: 1 });
  });

  it('counts a matched-but-duplicate insert (ON CONFLICT no row) as matched, not created', async () => {
    mockPeople();
    // INSERT returns no row → duplicate; UPDATE must not run.
    const clientQuery = vi.fn().mockResolvedValueOnce({ rows: [] });
    withTransaction.mockImplementation(async (fn) => fn({ query: clientQuery }));

    const result = await autoLogTouchpoints([
      { identities: [{ email: '[email protected]' }], source: 'message', dedupeKey: 'msg:a:t:2026-06-01' },
    ]);

    expect(result).toEqual({ created: 0, matched: 1 });
    expect(clientQuery).toHaveBeenCalledTimes(1); // no last_contact_on UPDATE on a dup
  });

  it('skips candidates without a dedupeKey (idempotency required)', async () => {
    mockPeople();
    const result = await autoLogTouchpoints([{ identities: [{ email: '[email protected]' }], source: 'calendar' }]);
    expect(result).toEqual({ created: 0, matched: 0 });
    expect(withTransaction).not.toHaveBeenCalled();
  });

  it('is a no-op when nothing is tracked', async () => {
    query.mockResolvedValue({ rows: [] });
    const result = await autoLogTouchpoints([
      { identities: [{ email: '[email protected]' }], dedupeKey: 'cal:a:e1' },
    ]);
    expect(result).toEqual({ created: 0, matched: 0 });
  });

  it('returns zeros for an empty batch without touching the DB', async () => {
    const result = await autoLogTouchpoints([]);
    expect(result).toEqual({ created: 0, matched: 0 });
    expect(query).not.toHaveBeenCalled();
  });
});

describe('tribe service — findDuplicateTribeIdentifiers (#5908)', () => {
  it('flags an email shared by two people, case-insensitively', () => {
    const report = findDuplicateTribeIdentifiers([
      { id: 'p1', name: 'Ada', emails: ['[email protected]'], phones: [] },
      { id: 'p2', name: 'Bea', emails: ['[email protected]'], phones: [] },
    ]);
    expect(report.emails).toEqual([
      { identifier: '[email protected]', people: [{ id: 'p1', name: 'Ada' }, { id: 'p2', name: 'Bea' }] },
    ]);
    expect(report.phones).toEqual([]);
  });

  it('flags a phone shared by two people despite different formatting', () => {
    const report = findDuplicateTribeIdentifiers([
      { id: 'p1', name: 'Ada', emails: [], phones: ['(555) 010-0199'] },
      { id: 'p2', name: 'Bea', emails: [], phones: ['+15550100199'] },
    ]);
    expect(report.phones).toEqual([
      { identifier: '+15550100199', people: [{ id: 'p1', name: 'Ada' }, { id: 'p2', name: 'Bea' }] },
    ]);
  });

  it('does not flag a person against themself, even with a near-duplicate raw value', () => {
    const report = findDuplicateTribeIdentifiers([
      { id: 'p1', name: 'Ada', emails: ['[email protected]', '[email protected]'], phones: [] },
    ]);
    expect(report.emails).toEqual([]);
  });

  it('reports nothing for a unique roster', () => {
    const report = findDuplicateTribeIdentifiers([
      { id: 'p1', name: 'Ada', emails: ['[email protected]'], phones: ['+15551234567'] },
      { id: 'p2', name: 'Bea', emails: ['[email protected]'], phones: ['+15557654321'] },
    ]);
    expect(report).toEqual({ emails: [], phones: [] });
  });

  it('handles an empty roster', () => {
    expect(findDuplicateTribeIdentifiers([])).toEqual({ emails: [], phones: [] });
    expect(findDuplicateTribeIdentifiers(undefined)).toEqual({ emails: [], phones: [] });
  });
});

describe('tribe service — checkDuplicateTribeIdentifiers', () => {
  beforeEach(() => {
    query.mockReset();
  });

  it('loads through listPeople (soft-deleted people already excluded) and reduces to a report', async () => {
    query.mockResolvedValue({ rows: [
      { id: 'p1', name: 'Ada', ring: 'core', cadence_days: 21, emails: ['[email protected]'] },
      { id: 'p2', name: 'Bea', ring: 'core', cadence_days: 21, emails: ['[email protected]'] },
    ] });
    const report = await checkDuplicateTribeIdentifiers();
    const [sql] = query.mock.calls[0];
    expect(sql).toContain('deleted = FALSE');
    expect(report.emails).toEqual([
      { identifier: '[email protected]', people: [{ id: 'p1', name: 'Ada' }, { id: 'p2', name: 'Bea' }] },
    ]);
  });
});