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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
Sync macOS Contacts to resolve iMessage names and enrich Tribe (#2415)
[._.]/ Adam Eivy77cf11dfd501
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 423a58d234..7005c5b4bc 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Features+- **[issue-2415] macOS Contacts sync resolves iMessage names and enriches Tribe.** Settings → Contacts reads AddressBook SQLite (read-only, multi-source) into a machine-local cache. Comms → iMessage conversation titles resolve at read time: **Tribe person name first**, then Contacts (people/companies), then the raw handle. **Fill Tribe phones/emails** matches Contacts to existing people; **Suggest Tribe imports** ranks frequent iMessage counterparts for opt-in add — never dump-all. No write-back to Apple Contacts or Messages.+- **[issue-2413] Comms → iMessage manager for ingested Messages activity.** After Settings → iMessage sync lands events in PortOS, you can browse them under **Comms → iMessage** (`/imessage`): conversation list + short summaries, PortOS-side purge (per event or whole chat), and a handle blocklist that future syncs honor. Deletes never write Apple's `chat.db` (read-only boundary unchanged). Settings → iMessage links to the manager and surfaces when more history remains to drain.- **A never-run cron task no longer fires an immediate "catch-up" for a scheduled slot that predates when the task was set up.** `shouldRunTask`'s cron catch-up bounded a never-run task only by "the occurrence before the most recent slot" — which is always earlier than that slot, so the guard was vacuous and *every* never-run cron task reported `cron-catch-up` for its most recent past slot. For long periods this was jarring: a weekly `branch-cleanup` scheduled `0 9 * * 0` (Sunday 09:00) that was enabled mid-week immediately showed as **due now (catch-up)** on the Schedule Timeline for *last* Sunday's slot — a slot that elapsed before the task existed and was never actually missed. Tasks now carry a `createdAt` timestamp (stamped when first configured; `loadSchedule` backfills existing installs to "now", which only suppresses catch-up for already-past slots and never affects future cadence), and never-run catch-up only fires for a slot that elapsed *after* `createdAt`. So a weekly task enabled on a Friday now waits for the coming Sunday instead of running immediately, while a task that was genuinely configured before a missed slot (daemon down / check window missed) still catches up as before.diff --git a/client/src/components/settings/ContactsTab.jsx b/client/src/components/settings/ContactsTab.jsxnew file mode 100644index 0000000000..a76d61b7bc--- /dev/null+++ b/client/src/components/settings/ContactsTab.jsx@@ -0,0 +1,287 @@+import { useEffect, useState } from 'react';+import { Link } from 'react-router-dom';+import {+ Contact, Loader2, RefreshCw, ShieldCheck, ShieldAlert,+ Users, UserPlus, ExternalLink,+} from 'lucide-react';+import toast from '../ui/Toast';+import BrailleSpinner from '../BrailleSpinner';+import {+ getContactsStatus,+ checkContactsSetup,+ syncContacts,+ enrichTribeFromContacts,+ suggestTribeFromContacts,+ importContactToTribe,+} from '../../services/api';++// Settings → Contacts (#2415). Opt-in read of macOS AddressBook → local cache+// for iMessage name resolution + Tribe phone/email fill. Never writes Contacts.+export function ContactsTab() {+ const [loading, setLoading] = useState(true);+ const [status, setStatus] = useState(null);+ const [setup, setSetup] = useState(null);+ const [checking, setChecking] = useState(false);+ const [syncing, setSyncing] = useState(false);+ const [enriching, setEnriching] = useState(false);+ const [suggestions, setSuggestions] = useState([]);+ const [loadingSuggest, setLoadingSuggest] = useState(false);+ const [importingId, setImportingId] = useState(null);++ const reload = async () => {+ const st = await getContactsStatus({ silent: true }).catch(() => null);+ setStatus(st);+ };++ useEffect(() => {+ reload().finally(() => setLoading(false));+ }, []);++ const handleCheck = async () => {+ setChecking(true);+ const report = await checkContactsSetup({ silent: true }).catch(() => ({ ok: false, error: 'Setup check failed' }));+ setChecking(false);+ setSetup(report);+ if (report?.ok) toast.success(`AddressBook OK — ${report.sourceCount ?? 0} source(s), ${report.rawContactRows ?? 0} row(s)`);+ else toast.error(report?.fullDiskAccessRequired ? 'Full Disk Access required' : (report?.error || 'Contacts not reachable'));+ };++ const handleSync = async () => {+ setSyncing(true);+ const result = await syncContacts({ silent: true }).catch(() => ({ ok: false, error: 'Sync failed' }));+ setSyncing(false);+ if (result?.ok) {+ toast.success(`Synced ${result.contactCount} contact(s) from ${result.sourceCount} source(s)`);+ await reload();+ } else {+ toast.error(result?.fullDiskAccessRequired ? 'Full Disk Access required' : (result?.error || 'Sync failed'));+ setSetup(result);+ }+ };++ const handleEnrich = async ({ dryRun }) => {+ setEnriching(true);+ const result = await enrichTribeFromContacts({ dryRun, silent: true }).catch(() => null);+ setEnriching(false);+ if (!result) {+ toast.error('Tribe enrich failed');+ return;+ }+ if (dryRun) {+ toast.success(`Would update ${result.matched} Tribe person/people`);+ } else {+ toast.success(`Updated phones/emails on ${result.updated} Tribe person/people`);+ }+ };++ const loadSuggestions = async () => {+ setLoadingSuggest(true);+ const res = await suggestTribeFromContacts({ limit: 30, silent: true }).catch(() => null);+ setLoadingSuggest(false);+ setSuggestions(res?.suggestions || []);+ if (!res) toast.error('Failed to load suggestions');+ };++ const handleImport = async (s) => {+ const key = s.contactId || s.handle || s.displayName;+ setImportingId(key);+ const result = await importContactToTribe({+ contactId: s.contactId || undefined,+ name: s.displayName,+ phones: s.phones,+ emails: s.emails,+ organization: s.organization || undefined,+ ring: 'tribe',+ }, { silent: true }).catch(() => null);+ setImportingId(null);+ if (!result) {+ toast.error('Import failed');+ return;+ }+ toast.success(result.created ? `Added ${result.person?.name} to Tribe` : `${result.person?.name} already in Tribe`);+ setSuggestions((prev) => prev.filter((x) => (x.contactId || x.handle) !== (s.contactId || s.handle)));+ };++ if (loading) return <BrailleSpinner />;++ const cache = status?.cache;+ const last = status?.state?.lastResult;++ return (+ <div className="space-y-6">+ <div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6">+ <div className="flex items-center gap-2 mb-2">+ <Contact size={16} className="text-port-accent" />+ <h3 className="text-lg font-semibold text-white">macOS Contacts</h3>+ </div>+ <p className="text-sm text-gray-400 mb-4">+ Reads your local AddressBook databases read-only into a machine-local cache.+ Used to show names (and companies) on{' '}+ <Link to="/imessage" className="text-port-accent hover:underline">Comms → iMessage</Link>+ {' '}and to fill missing phones/emails on{' '}+ <Link to="/tribe" className="text-port-accent hover:underline">Tribe</Link>+ {' '}people. Never writes Apple Contacts. Requires{' '}+ <strong>Full Disk Access</strong> for the PortOS process (same as iMessage).+ </p>++ <div className="flex flex-wrap gap-2">+ <button+ type="button"+ onClick={handleCheck}+ disabled={checking}+ className="inline-flex items-center justify-center gap-2 min-h-[40px] px-4 py-2 bg-port-bg border border-port-border hover:border-port-accent text-gray-200 rounded-lg text-sm transition-colors disabled:opacity-40"+ >+ {checking ? <Loader2 size={14} className="animate-spin" /> : <ShieldCheck size={14} />}+ Check setup+ </button>+ <button+ type="button"+ onClick={handleSync}+ disabled={syncing}+ className="inline-flex items-center justify-center gap-2 min-h-[40px] px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors disabled:opacity-40"+ >+ {syncing ? <Loader2 size={14} className="animate-spin" /> : <RefreshCw size={14} />}+ Sync Contacts now+ </button>+ </div>+ </div>++ {setup && (+ <div className={`bg-port-card border rounded-lg p-4 sm:p-6 ${setup.ok ? 'border-port-success/40' : 'border-port-error/40'}`}>+ <div className="flex items-center gap-2 mb-2">+ {setup.ok+ ? <ShieldCheck size={16} className="text-port-success" />+ : <ShieldAlert size={16} className="text-port-error" />}+ <h3 className="text-sm font-semibold text-white">{setup.ok ? 'Setup OK' : 'Setup blocked'}</h3>+ </div>+ {setup.ok ? (+ <p className="text-sm text-gray-300">+ {setup.sourceCount} AddressBook source(s), {setup.rawContactRows ?? 0} raw row(s) under{' '}+ <code className="text-gray-400 text-xs">{setup.root}</code>+ </p>+ ) : (+ <div className="text-sm text-gray-300 space-y-2">+ <p className="text-port-error">{setup.error}</p>+ {setup.remediation && <p className="text-gray-400">{setup.remediation}</p>}+ </div>+ )}+ </div>+ )}++ <div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6">+ <h3 className="text-sm font-semibold text-white mb-2">Cache</h3>+ <dl className="grid grid-cols-2 sm:grid-cols-3 gap-3 text-sm">+ <div>+ <dt className="text-gray-500 text-xs uppercase">Contacts</dt>+ <dd className="text-gray-200">{cache?.contactCount ?? 0}</dd>+ </div>+ <div>+ <dt className="text-gray-500 text-xs uppercase">Sources (last sync)</dt>+ <dd className="text-gray-200">{cache?.sourceCount ?? last?.sourceCount ?? '—'}</dd>+ </div>+ <div>+ <dt className="text-gray-500 text-xs uppercase">Last synced</dt>+ <dd className="text-gray-200">+ {cache?.syncedAt ? new Date(cache.syncedAt).toLocaleString() : 'Never'}+ </dd>+ </div>+ </dl>+ {(cache?.contactCount || 0) === 0 && (+ <p className="mt-3 text-xs text-gray-500">+ Run <strong className="text-gray-400">Sync Contacts now</strong>, then open Comms → iMessage —+ conversation titles resolve at read time (no iMessage re-sync required).+ </p>+ )}+ </div>++ <div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6 space-y-3">+ <div className="flex items-center gap-2">+ <Users size={16} className="text-port-accent" />+ <h3 className="text-sm font-semibold text-white">Tribe phones & emails</h3>+ </div>+ <p className="text-sm text-gray-400">+ Match cached Contacts to existing Tribe people (by phone, email, or exact unique name)+ and fill missing <code className="text-gray-300">phones[]</code> / <code className="text-gray-300">emails[]</code>.+ Does not create new Tribe people.+ </p>+ <div className="flex flex-wrap gap-2">+ <button+ type="button"+ onClick={() => handleEnrich({ dryRun: true })}+ disabled={enriching || !(cache?.contactCount)}+ className="inline-flex items-center gap-2 min-h-[40px] px-4 py-2 bg-port-bg border border-port-border hover:border-port-accent text-gray-200 rounded-lg text-sm disabled:opacity-40"+ >+ Preview matches+ </button>+ <button+ type="button"+ onClick={() => handleEnrich({ dryRun: false })}+ disabled={enriching || !(cache?.contactCount)}+ className="inline-flex items-center gap-2 min-h-[40px] px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm disabled:opacity-40"+ >+ {enriching ? <Loader2 size={14} className="animate-spin" /> : <Users size={14} />}+ Fill Tribe phones/emails+ </button>+ <Link+ to="/tribe"+ className="inline-flex items-center gap-1 min-h-[40px] px-3 py-2 text-sm text-port-accent hover:underline"+ >+ Open Tribe <ExternalLink size={12} />+ </Link>+ </div>+ </div>++ <div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6 space-y-3">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <div className="flex items-center gap-2">+ <UserPlus size={16} className="text-port-accent" />+ <h3 className="text-sm font-semibold text-white">Suggest Tribe imports</h3>+ </div>+ <button+ type="button"+ onClick={loadSuggestions}+ disabled={loadingSuggest}+ className="inline-flex items-center gap-2 px-3 py-1.5 text-xs rounded border border-port-border bg-port-bg hover:border-port-accent text-gray-200 disabled:opacity-40"+ >+ {loadingSuggest ? <Loader2 size={12} className="animate-spin" /> : <RefreshCw size={12} />}+ Load suggestions+ </button>+ </div>+ <p className="text-sm text-gray-400">+ Frequent iMessage counterparts (and unmatched contacts) not yet in Tribe.+ Import only people you want in your relationship graph — not the whole address book.+ </p>+ {suggestions.length > 0 && (+ <ul className="divide-y divide-port-border rounded border border-port-border max-h-80 overflow-y-auto">+ {suggestions.map((s) => {+ const key = s.contactId || s.handle || s.displayName;+ return (+ <li key={key} className="flex items-center justify-between gap-2 px-3 py-2 text-sm">+ <div className="min-w-0">+ <div className="font-medium text-gray-100 truncate">{s.displayName}</div>+ <div className="text-xs text-gray-500 truncate">+ {[s.organization, s.phones?.[0], s.emails?.[0], s.eventCount ? `${s.eventCount} msgs` : null]+ .filter(Boolean)+ .join(' · ')}+ </div>+ </div>+ <button+ type="button"+ onClick={() => handleImport(s)}+ disabled={importingId === key}+ className="shrink-0 inline-flex items-center gap-1 rounded border border-port-border px-2 py-1 text-xs text-gray-200 hover:border-port-accent disabled:opacity-40"+ >+ {importingId === key ? <Loader2 size={12} className="animate-spin" /> : <UserPlus size={12} />}+ Add to Tribe+ </button>+ </li>+ );+ })}+ </ul>+ )}+ </div>+ </div>+ );+}++export default ContactsTab;diff --git a/client/src/components/settings/IMessageTab.jsx b/client/src/components/settings/IMessageTab.jsxindex 81c101d98f..db3ea1c6b5 100644--- a/client/src/components/settings/IMessageTab.jsx+++ b/client/src/components/settings/IMessageTab.jsx@@ -101,6 +101,9 @@ export function IMessageTab() {Comms → iMessage <ExternalLink size={12} /></Link>{' '}— deletes there remove PortOS copies only, never Apple Messages.+ For names instead of phone numbers, sync{' '}+ <Link to="/settings/contacts" className="text-port-accent hover:underline">Settings → Contacts</Link>+ {' '}(and optionally fill Tribe phones/emails).</p><div className="space-y-3">diff --git a/client/src/components/settings/SettingsTabsHeader.jsx b/client/src/components/settings/SettingsTabsHeader.jsxindex e677854189..d7208dd268 100644--- a/client/src/components/settings/SettingsTabsHeader.jsx+++ b/client/src/components/settings/SettingsTabsHeader.jsx@@ -15,6 +15,7 @@ export const TABS = [{ id: 'autofixer', label: 'Autofixer', to: '/settings/autofixer' },{ id: 'backup', label: 'Backup', to: '/settings/backup' },{ id: 'catalog', label: 'Catalog', to: '/settings/catalog' },+ { id: 'contacts', label: 'Contacts', to: '/settings/contacts' },{ id: 'database', label: 'Database', to: '/settings/database' },{ id: 'embeddings', label: 'Embeddings', to: '/settings/embeddings' },{ id: 'general', label: 'General', to: '/settings/general' },diff --git a/client/src/pages/IMessage.jsx b/client/src/pages/IMessage.jsxindex 4c49c6bec9..296a219dd9 100644--- a/client/src/pages/IMessage.jsx+++ b/client/src/pages/IMessage.jsx@@ -91,16 +91,32 @@ function ConversationList({ conversations, selectedKey, onSelect, query, onQuery<div className="flex items-start justify-between gap-2"><div className="min-w-0 flex-1"><div className="flex items-center gap-1.5">- <span className="truncate font-medium text-sm text-gray-100">{c.title}</span>+ <span className="truncate font-medium text-sm text-gray-100">+ {c.displayName || c.title}+ </span>+ {c.identitySource === 'tribe' && (+ <span className="shrink-0 rounded bg-port-accent/15 px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-port-accent">+ Tribe+ </span>+ )}+ {c.identitySource === 'contacts' && (+ <span className="shrink-0 rounded bg-port-bg px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-gray-500 border border-port-border">+ Contact+ </span>+ )}{c.blocked && (<span className="shrink-0 rounded bg-port-error/15 px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-port-error">Blocked</span>)}</div>- {c.lastSummary && (- <div className="mt-0.5 truncate text-xs text-gray-500">{c.lastSummary}</div>- )}+ <div className="mt-0.5 truncate text-xs text-gray-500">+ {[+ c.organization && c.organization !== (c.displayName || c.title) ? c.organization : null,+ c.handle && c.handle !== (c.displayName || c.title) ? c.handle : null,+ c.lastSummary,+ ].filter(Boolean).join(' · ')}+ </div></div><div className="shrink-0 text-right"><div className="text-[10px] text-gray-500">{formatWhen(c.lastAt)}</div>@@ -122,6 +138,7 @@ function ConversationDetail({chatKey,conversation,events,+ identity,loading,timezone,onBack,@@ -133,6 +150,12 @@ function ConversationDetail({const [busy, setBusy] = useState(false);const handle = conversation?.handle;+ const displayTitle = conversation?.displayName+ || identity?.displayName+ || conversation?.title+ || 'Conversation';+ const organization = conversation?.organization || identity?.organization;+ const personId = conversation?.personId || identity?.personId;const runPurge = async () => {setBusy(true);@@ -210,13 +233,19 @@ function ConversationDetail({</button><div className="min-w-0 flex-1"><h2 className="truncate text-base font-semibold text-white">- {conversation?.title || 'Conversation'}+ {displayTitle}</h2><div className="mt-0.5 flex flex-wrap items-center gap-2 text-xs text-gray-500">+ {organization && <span>{organization}</span>}{handle && <span className="font-mono">{handle}</span>}{conversation?.eventCount != null && (<span>{conversation.eventCount} event(s)</span>)}+ {(conversation?.identitySource || identity?.identitySource) && (+ <span className="rounded bg-port-bg border border-port-border px-1.5 py-0.5 text-[10px] uppercase">+ {conversation?.identitySource || identity?.identitySource}+ </span>+ )}{conversation?.blocked && (<span className="rounded bg-port-error/15 px-1.5 py-0.5 text-[10px] uppercase text-port-error">Blocked@@ -292,13 +321,23 @@ function ConversationDetail({<ExternalLink size={10} className="opacity-60" /></Link>)}- <Link- to="/tribe"- className="inline-flex items-center gap-1.5 rounded border border-port-border bg-port-bg px-2.5 py-1.5 text-xs text-gray-200 hover:border-port-accent"- >- <Users size={12} />- Tribe phones- </Link>+ {personId ? (+ <Link+ to="/tribe"+ className="inline-flex items-center gap-1.5 rounded border border-port-border bg-port-bg px-2.5 py-1.5 text-xs text-gray-200 hover:border-port-accent"+ >+ <Users size={12} />+ Open Tribe+ </Link>+ ) : (+ <Link+ to="/settings/contacts"+ className="inline-flex items-center gap-1.5 rounded border border-port-border bg-port-bg px-2.5 py-1.5 text-xs text-gray-200 hover:border-port-accent"+ >+ <Users size={12} />+ Resolve names+ </Link>+ )}</div>)}</div>@@ -355,6 +394,7 @@ export default function IMessage() {const [query, setQuery] = useState('');const [debouncedQ, setDebouncedQ] = useState('');const [events, setEvents] = useState([]);+ const [conversationIdentity, setConversationIdentity] = useState(null);const [eventsLoading, setEventsLoading] = useState(false);const [syncing, setSyncing] = useState(false);@@ -381,17 +421,22 @@ export default function IMessage() {useEffect(() => {if (!selectedKey) {setEvents([]);+ setConversationIdentity(null);return undefined;}let active = true;setEventsLoading(true);api.getImessageConversationEvents(selectedKey, { limit: 200, silent: true }).then((res) => {- if (active) setEvents(res?.events || []);+ if (active) {+ setEvents(res?.events || []);+ setConversationIdentity(res?.identity || null);+ }}).catch(() => {if (active) {setEvents([]);+ setConversationIdentity(null);toast.error('Failed to load conversation');}})@@ -474,6 +519,13 @@ export default function IMessage() {subtitle="Browse and manage PortOS copies of your local Messages activity. Full bodies stay in Apple's chat.db — deletes never write back."actions={(<div className="flex flex-wrap items-center gap-2">+ <Link+ to="/settings/contacts"+ className="inline-flex items-center gap-1.5 rounded border border-port-border bg-port-card px-3 py-1.5 text-xs text-gray-300 hover:border-port-accent"+ >+ <Users size={12} />+ Contacts+ </Link><Linkto="/settings/imessage"className="inline-flex items-center gap-1.5 rounded border border-port-border bg-port-card px-3 py-1.5 text-xs text-gray-300 hover:border-port-accent"@@ -542,6 +594,7 @@ export default function IMessage() {chatKey={selectedKey}conversation={selectedConversation}events={events}+ identity={conversationIdentity}loading={eventsLoading}timezone={undefined}onBack={() => select(null)}diff --git a/client/src/pages/Settings.jsx b/client/src/pages/Settings.jsxindex de1b72b822..2edfed52e5 100644--- a/client/src/pages/Settings.jsx+++ b/client/src/pages/Settings.jsx@@ -12,6 +12,7 @@ import { LocalLlmTab } from '../components/settings/LocalLlmTab';import { TelegramTab } from '../components/settings/TelegramTab';import { GeneralTab } from '../components/settings/GeneralTab';import { IMessageTab } from '../components/settings/IMessageTab';+import { ContactsTab } from '../components/settings/ContactsTab';import { MortalLoomTab } from '../components/settings/MortalLoomTab';import { SecurityTab } from '../components/settings/SecurityTab';import { SharingTab } from '../components/settings/SharingTab';@@ -40,6 +41,7 @@ export default function Settings() {switch (activeTab) {case 'general': return <GeneralTab />;case 'imessage': return <IMessageTab />;+ case 'contacts': return <ContactsTab />;case 'ai-assignments': return <AiAssignmentsTab />;case 'api-access': return <ApiAccessTab />;case 'autofixer': return <AutofixerTab />;diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 0b246ad922..ec3033c5b7 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -77,6 +77,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiTribe.js` | Tribe people (relationship rings + contacts). || `apiCalendar.js` | Calendar events. || `apiMessages.js` | Messages / notifications + iMessage manager (#2413). |+| `apiContacts.js` | macOS Contacts sync + identity resolve + Tribe enrich (#2415). || `apiSignal.js` | Signal Desktop ingestion status / setup-check / sync. || `apiSpotify.js` | Spotify OAuth + listening-history sync. || `apiYoutube.js` | YouTube watch-history scrape sync + setup check. |diff --git a/client/src/services/api.js b/client/src/services/api.jsindex dc7ec7841e..9d6db32625 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -23,6 +23,7 @@ export * from './apiPersonalities.js';export * from './apiAccounts.js';export * from './apiSchedules.js';export * from './apiMessages.js';+export * from './apiContacts.js';export * from './apiSignal.js';export * from './apiSpotify.js';export * from './apiYoutube.js';diff --git a/client/src/services/apiContacts.js b/client/src/services/apiContacts.jsnew file mode 100644index 0000000000..3250c8db97--- /dev/null+++ b/client/src/services/apiContacts.js@@ -0,0 +1,33 @@+import { request } from './apiCore.js';++// macOS Contacts ingestion + Tribe bridge (#2415).+export const getContactsStatus = (options = {}) => request('/contacts/status', options);+export const checkContactsSetup = (options = {}) => request('/contacts/setup-check', options);+export const syncContacts = (options = {}) => request('/contacts/sync', { method: 'POST', ...options });+export const searchContacts = ({ q, limit, silent } = {}) => {+ const params = new URLSearchParams();+ if (q) params.set('q', q);+ if (limit) params.set('limit', String(limit));+ const qs = params.toString();+ return request(`/contacts/search${qs ? `?${qs}` : ''}`, { silent });+};+export const resolveContactHandle = (handle, options = {}) =>+ request(`/contacts/resolve?handle=${encodeURIComponent(handle)}`, options);+export const enrichTribeFromContacts = ({ dryRun = false, ...options } = {}) =>+ request('/contacts/enrich-tribe', {+ method: 'POST',+ body: JSON.stringify({ dryRun }),+ ...options,+ });+export const suggestTribeFromContacts = ({ limit, silent } = {}) => {+ const params = new URLSearchParams();+ if (limit) params.set('limit', String(limit));+ const qs = params.toString();+ return request(`/contacts/suggest-tribe${qs ? `?${qs}` : ''}`, { silent });+};+export const importContactToTribe = (data, options = {}) =>+ request('/contacts/import-to-tribe', {+ method: 'POST',+ body: JSON.stringify(data),+ ...options,+ });diff --git a/server/index.js b/server/index.jsindex 55495393a1..811bedcdd4 100644--- a/server/index.js+++ b/server/index.js@@ -50,6 +50,7 @@ import memoryRoutes from './routes/memory.js';import tribeRoutes from './routes/tribe.js';import timelineRoutes from './routes/timeline.js';import imessageRoutes from './routes/imessage.js';+import contactsRoutes from './routes/contacts.js';import signalRoutes from './routes/signal.js';import spotifyRoutes from './routes/spotify.js';import youtubeRoutes from './routes/youtube.js';@@ -489,6 +490,7 @@ app.use('/api/memory', memoryRoutes);app.use('/api/tribe', tribeRoutes);app.use('/api/timeline', timelineRoutes);app.use('/api/imessage', imessageRoutes);+app.use('/api/contacts', contactsRoutes);app.use('/api/signal', signalRoutes);app.use('/api/spotify', spotifyRoutes);app.use('/api/youtube', youtubeRoutes);diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 327c39c929..b3ec4ea328 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -180,6 +180,7 @@ export const NAV_COMMANDS = [{ id: 'nav.settings.autofixer', path: '/settings/autofixer', label: 'Autofixer', section: 'Settings', aliases: ['autofixer', 'settings-autofixer', 'auto-fixer'], keywords: ['crash', 'fix', 'pm2', 'repair', 'ai provider', 'restart'] },{ id: 'nav.settings.backup', path: '/settings/backup', label: 'Backup', section: 'Settings', aliases: ['backup', 'settings-backup'] },{ id: 'nav.settings.catalog', path: '/settings/catalog', label: 'Catalog Types', section: 'Settings', aliases: ['settings-catalog', 'catalog-types'], keywords: ['catalog', 'types', 'character', 'place', 'object', 'taxonomy'] },+ { id: 'nav.settings.contacts', path: '/settings/contacts', label: 'Contacts', section: 'Settings', aliases: ['settings-contacts', 'contacts', 'address-book', 'contacts-settings'], keywords: ['contacts', 'address book', 'phone', 'email', 'tribe', 'imessage', 'names', 'resolve'] },{ id: 'nav.settings.database', path: '/settings/database', label: 'Database', section: 'Settings', aliases: ['settings-database', 'database'] },{ id: 'nav.settings.embeddings', path: '/settings/embeddings', label: 'Embeddings', section: 'Settings', aliases: ['settings-embeddings', 'embeddings', 'embedding'], keywords: ['vector', 'pgvector', 'semantic search', 'nomic', 'ollama', 'lm studio'] },{ id: 'nav.settings.general', path: '/settings/general', label: 'General', section: 'Settings', aliases: ['settings', 'settings-general', 'general'] },diff --git a/server/routes/contacts.js b/server/routes/contacts.jsnew file mode 100644index 0000000000..03068195a6--- /dev/null+++ b/server/routes/contacts.js@@ -0,0 +1,98 @@+import { Router } from 'express';+import { z } from 'zod';++import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import * as contactsSync from '../services/contactsSync.js';+import * as identityResolve from '../services/identityResolve.js';+import * as tribeContacts from '../services/tribeContacts.js';++const router = Router();++// Setup check — discover AddressBook DBs and report Full Disk Access issues.+router.get('/setup-check', asyncHandler(async (req, res) => {+ const report = await contactsSync.checkSetup();+ res.json(report);+}));++// Status — cache counts + last sync (no AddressBook open unless setup block).+router.get('/status', asyncHandler(async (req, res) => {+ const status = await contactsSync.getStatus();+ res.json(status);+}));++// Run a full Contacts → cache sync now.+router.post('/sync', asyncHandler(async (req, res) => {+ const result = await contactsSync.runSync();+ res.json(result);+}));++const searchQuerySchema = z.object({+ q: z.string().max(200).optional(),+ limit: z.coerce.number().int().min(1).max(500).optional(),+});++router.get('/search', asyncHandler(async (req, res) => {+ const q = validateRequest(searchQuerySchema, req.query);+ const contacts = await contactsSync.searchContacts(q);+ res.json({ contacts });+}));++const resolveQuerySchema = z.object({+ handle: z.string().min(1).max(200),+});++router.get('/resolve', asyncHandler(async (req, res) => {+ const { handle } = validateRequest(resolveQuerySchema, req.query);+ const ctx = await identityResolve.loadResolverContext();+ const resolution = identityResolve.resolveHandle(handle, ctx);+ res.json(resolution);+}));++const enrichBodySchema = z.object({+ dryRun: z.boolean().optional().default(false),+});++// Fill missing Tribe phones/emails from Contacts matches.+router.post('/enrich-tribe', asyncHandler(async (req, res) => {+ const body = validateRequest(enrichBodySchema, req.body || {});+ const result = await tribeContacts.enrichTribeFromContacts(body);+ res.json(result);+}));++const suggestQuerySchema = z.object({+ limit: z.coerce.number().int().min(1).max(200).optional(),+});++router.get('/suggest-tribe', asyncHandler(async (req, res) => {+ const q = validateRequest(suggestQuerySchema, req.query);+ const result = await tribeContacts.suggestTribeImports(q);+ res.json(result);+}));++const importBodySchema = z.object({+ contactId: z.string().min(1).max(300).optional(),+ name: z.string().min(1).max(200).optional(),+ phones: z.array(z.string().max(40)).max(20).optional(),+ emails: z.array(z.string().email().max(200)).max(20).optional(),+ organization: z.string().max(200).optional(),+ ring: z.enum(['support', 'core', 'tribe', 'village', 'external']).optional(),+ relationship: z.string().max(200).optional(),+}).refine((b) => b.contactId || b.name || (b.phones?.length) || (b.emails?.length), {+ message: 'contactId or name/phones/emails required',+});++router.post('/import-to-tribe', asyncHandler(async (req, res) => {+ const body = validateRequest(importBodySchema, req.body || {});+ try {+ const result = await tribeContacts.importContactToTribe(body);+ res.status(result.created ? 201 : 200).json(result);+ } catch (err) {+ if (err?.status === 400) {+ throw new ServerError(err.message, { status: 400, code: err.code || 'BAD_REQUEST' });+ }+ throw err;+ }+}));++export default router;diff --git a/server/routes/contacts.test.js b/server/routes/contacts.test.jsnew file mode 100644index 0000000000..c0fcbd93d2--- /dev/null+++ b/server/routes/contacts.test.js@@ -0,0 +1,73 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++vi.mock('../services/contactsSync.js', () => ({+ checkSetup: vi.fn(async () => ({ ok: true, sourceCount: 2, rawContactRows: 100 })),+ getStatus: vi.fn(async () => ({ cache: { contactCount: 50, syncedAt: null }, state: {}, setup: { ok: true } })),+ runSync: vi.fn(async () => ({ ok: true, contactCount: 50, sourceCount: 2 })),+ searchContacts: vi.fn(async () => [{ id: 'c1', displayName: 'Jane' }]),+}));++vi.mock('../services/identityResolve.js', () => ({+ loadResolverContext: vi.fn(async () => ({})),+ resolveHandle: vi.fn(() => ({ displayName: 'Jane', source: 'contacts', handle: '+1555' })),+}));++vi.mock('../services/tribeContacts.js', () => ({+ enrichTribeFromContacts: vi.fn(async ({ dryRun }) => ({ dryRun, matched: 3, updated: dryRun ? 0 : 3, changes: [] })),+ suggestTribeImports: vi.fn(async () => ({ suggestions: [{ displayName: 'Sam', eventCount: 5 }], contactsCached: 10, tribeCount: 2 })),+ importContactToTribe: vi.fn(async () => ({ person: { id: 'p1', name: 'Sam' }, created: true })),+}));++const { default: router } = await import('./contacts.js');++function makeApp() {+ const app = express();+ app.use(express.json());+ app.use('/api/contacts', router);+ app.use(errorMiddleware);+ return app;+}++describe('contacts routes (#2415)', () => {+ beforeEach(() => vi.clearAllMocks());++ it('GET /setup-check', async () => {+ const res = await request(makeApp()).get('/api/contacts/setup-check');+ expect(res.status).toBe(200);+ expect(res.body.ok).toBe(true);+ });++ it('POST /sync', async () => {+ const res = await request(makeApp()).post('/api/contacts/sync');+ expect(res.status).toBe(200);+ expect(res.body.contactCount).toBe(50);+ });++ it('GET /resolve', async () => {+ const res = await request(makeApp()).get('/api/contacts/resolve?handle=%2B15551234567');+ expect(res.status).toBe(200);+ expect(res.body.displayName).toBe('Jane');+ });++ it('POST /enrich-tribe dry run', async () => {+ const res = await request(makeApp()).post('/api/contacts/enrich-tribe').send({ dryRun: true });+ expect(res.status).toBe(200);+ expect(res.body.dryRun).toBe(true);+ expect(res.body.matched).toBe(3);+ });++ it('GET /suggest-tribe', async () => {+ const res = await request(makeApp()).get('/api/contacts/suggest-tribe');+ expect(res.status).toBe(200);+ expect(res.body.suggestions).toHaveLength(1);+ });++ it('POST /import-to-tribe', async () => {+ const res = await request(makeApp()).post('/api/contacts/import-to-tribe').send({ contactId: 'c1', name: 'Sam' });+ expect(res.status).toBe(201);+ expect(res.body.created).toBe(true);+ });+});diff --git a/server/services/contactsSync.js b/server/services/contactsSync.jsnew file mode 100644index 0000000000..c5a4c74c25--- /dev/null+++ b/server/services/contactsSync.js@@ -0,0 +1,543 @@+/**+ * macOS Contacts ingestion (#2415) — read-only scan of AddressBook SQLite DBs+ * (AddressBook root + Sources/.../AddressBook-v22.abcddb) into a machine-local+ * cache used to resolve phone/email → display name for iMessage and to enrich+ * Tribe phones/emails.+ *+ * Design constraints:+ * - Zero new dependencies. node:sqlite readOnly (same as imessageSync).+ * - Never write Apple's Contacts databases.+ * - Machine-local cache in data/contacts-cache.json (not federated).+ * - LLM-free. Pure normalize + index; Tribe wins over Contacts on resolve.+ */+import { DatabaseSync } from 'node:sqlite';+import { readdirSync, statSync, existsSync } from 'node:fs';+import { join } from 'node:path';++import { expandHome, dataPath, atomicWrite, tryReadFile, safeJSONParse } from '../lib/fileUtils.js';+import { identityFromHandle, normalizeIdentifier, normalizePhone } from '../lib/tribeMatch.js';++const DEFAULT_AB_ROOT = '~/Library/Application Support/AddressBook';+const CACHE_FILE = 'contacts-cache.json';+const STATE_FILE = 'contacts-sync-state.json';++// ---------------------------------------------------------------------------+// Pure helpers+// ---------------------------------------------------------------------------++/**+ * Build a human display name from contact name parts + organization.+ * Prefers "First Last" / nickname; falls back to organization (companies).+ */+export function contactDisplayName({+ firstName, lastName, middleName, nickname, organization, name,+} = {}) {+ const nick = String(nickname || '').trim();+ const first = String(firstName || '').trim();+ const middle = String(middleName || '').trim();+ const last = String(lastName || '').trim();+ const org = String(organization || '').trim();+ const full = String(name || '').trim();++ const parts = [first, middle, last].filter(Boolean).join(' ').replace(/\s+/g, ' ').trim();+ if (parts) return parts;+ if (nick) return nick;+ if (full) return full;+ if (org) return org;+ return '';+}++/**+ * Normalize a raw AddressBook row-group into a contact record, or null when+ * there is nothing usable (no name and no phones/emails).+ */+export function normalizeContactRecord(raw) {+ if (!raw) return null;+ const phones = [...new Set(+ (raw.phones || []).map((p) => normalizePhone(p)).filter(Boolean),+ )];+ const emails = [...new Set(+ (raw.emails || []).map((e) => normalizeIdentifier(e)).filter(Boolean),+ )];+ const displayName = contactDisplayName(raw);+ if (!displayName && phones.length === 0 && emails.length === 0) return null;+ const id = String(raw.id || raw.uniqueId || `${displayName}|${phones[0] || ''}|${emails[0] || ''}`);+ return {+ id,+ uniqueId: raw.uniqueId || id,+ displayName: displayName || phones[0] || emails[0] || 'Contact',+ firstName: String(raw.firstName || '').trim() || null,+ lastName: String(raw.lastName || '').trim() || null,+ organization: String(raw.organization || '').trim() || null,+ nickname: String(raw.nickname || '').trim() || null,+ phones,+ emails,+ sourcePath: raw.sourcePath || null,+ };+}++/**+ * Merge contacts from multiple AddressBook sources. Same uniqueId or same+ * phone/email set collapses; prefers the record with more fields.+ */+export function mergeContacts(lists = []) {+ const byKey = new Map();+ const score = (c) => (c.phones?.length || 0) + (c.emails?.length || 0) + (c.organization ? 1 : 0)+ + (c.firstName ? 1 : 0) + (c.lastName ? 1 : 0);++ for (const list of lists) {+ for (const raw of list || []) {+ const c = normalizeContactRecord(raw);+ if (!c) continue;+ // Prefer uniqueId; also index under each phone/email for dedupe across sources.+ const keys = new Set([`id:${c.uniqueId}`]);+ for (const p of c.phones) keys.add(`p:${p}`);+ for (const e of c.emails) keys.add(`e:${e}`);++ let existing = null;+ for (const k of keys) {+ if (byKey.has(k)) {+ existing = byKey.get(k);+ break;+ }+ }+ if (!existing) {+ for (const k of keys) byKey.set(k, c);+ continue;+ }+ // Merge phones/emails into the richer record.+ const merged = {+ ...existing,+ phones: [...new Set([...(existing.phones || []), ...(c.phones || [])])],+ emails: [...new Set([...(existing.emails || []), ...(c.emails || [])])],+ organization: existing.organization || c.organization,+ firstName: existing.firstName || c.firstName,+ lastName: existing.lastName || c.lastName,+ nickname: existing.nickname || c.nickname,+ displayName: score(c) > score(existing) ? c.displayName : existing.displayName,+ };+ // Re-point all keys for both records at the merged one.+ const allKeys = new Set([...keys]);+ for (const p of merged.phones) allKeys.add(`p:${p}`);+ for (const e of merged.emails) allKeys.add(`e:${e}`);+ allKeys.add(`id:${merged.uniqueId}`);+ for (const k of allKeys) byKey.set(k, merged);+ }+ }++ // De-dupe by uniqueId for the returned array.+ const seen = new Set();+ const out = [];+ for (const c of byKey.values()) {+ if (seen.has(c.uniqueId)) continue;+ seen.add(c.uniqueId);+ out.push(c);+ }+ out.sort((a, b) => a.displayName.localeCompare(b.displayName));+ return out;+}++/**+ * Build lookup maps from a contact list: byPhone, byEmail.+ * First claim wins (stable after sort).+ */+export function buildContactIndex(contacts = []) {+ const byPhone = new Map();+ const byEmail = new Map();+ for (const c of contacts) {+ for (const p of c.phones || []) {+ if (p && !byPhone.has(p)) byPhone.set(p, c);+ }+ for (const e of c.emails || []) {+ if (e && !byEmail.has(e)) byEmail.set(e, c);+ }+ }+ return { byPhone, byEmail };+}++/**+ * Resolve a raw handle (phone or email) against a contacts index.+ * Returns `{ displayName, organization, contactId, source: 'contacts' }` or null.+ */+export function resolveHandleAgainstContacts(handle, contactIndex) {+ if (!handle || !contactIndex) return null;+ const id = identityFromHandle(handle);+ if (id.phone && contactIndex.byPhone.has(id.phone)) {+ const c = contactIndex.byPhone.get(id.phone);+ return {+ displayName: c.displayName,+ organization: c.organization || null,+ contactId: c.id,+ source: 'contacts',+ };+ }+ if (id.email && contactIndex.byEmail.has(id.email)) {+ const c = contactIndex.byEmail.get(id.email);+ return {+ displayName: c.displayName,+ organization: c.organization || null,+ contactId: c.id,+ source: 'contacts',+ };+ }+ return null;+}++// ---------------------------------------------------------------------------+// Filesystem: discover AddressBook DBs+// ---------------------------------------------------------------------------++export function addressBookRoot() {+ return expandHome(process.env.CONTACTS_AB_ROOT || DEFAULT_AB_ROOT);+}++/**+ * List every AddressBook-v22.abcddb under the root (root + Sources/*).+ * Pure-ish: uses readdir/stat only.+ */+export function discoverAddressBookPaths(root = addressBookRoot()) {+ const paths = [];+ const rootDb = join(root, 'AddressBook-v22.abcddb');+ if (existsSync(rootDb)) paths.push(rootDb);+ const sourcesDir = join(root, 'Sources');+ if (!existsSync(sourcesDir)) return paths;+ let entries = [];+ try {+ entries = readdirSync(sourcesDir, { withFileTypes: true });+ } catch {+ return paths;+ }+ for (const ent of entries) {+ if (!ent.isDirectory()) continue;+ const db = join(sourcesDir, ent.name, 'AddressBook-v22.abcddb');+ if (existsSync(db)) paths.push(db);+ }+ return paths;+}++// ---------------------------------------------------------------------------+// SQLite read (try/catch sanctioned — outside Express request lifecycle)+// ---------------------------------------------------------------------------++function isPermissionError(err) {+ if (err?.code === 'EACCES' || err?.code === 'EPERM') return true;+ const msg = String(err?.message || '').toLowerCase();+ return msg.includes('unable to open')+ || msg.includes('not authorized')+ || msg.includes('operation not permitted');+}++/**+ * Read one AddressBook DB into raw contact groups (pre-normalize).+ * Groups phones/emails by owner Z_PK.+ */+export function readAddressBookDb(dbPath) {+ let db;+ try {+ db = new DatabaseSync(dbPath, { readOnly: true });+ } catch (err) {+ return { ok: false, path: dbPath, error: err?.message || String(err), permission: isPermissionError(err), contacts: [] };+ }+ try {+ // Presence check — older/empty DBs may lack phone tables.+ const tables = db.prepare(+ `SELECT name FROM sqlite_master WHERE type='table' AND name IN ('ZABCDRECORD','ZABCDPHONENUMBER','ZABCDEMAILADDRESS')`,+ ).all().map((r) => r.name);+ if (!tables.includes('ZABCDRECORD')) {+ return { ok: true, path: dbPath, contacts: [], empty: true };+ }++ const records = db.prepare(+ `SELECT Z_PK AS pk, ZUNIQUEID AS unique_id,+ ZFIRSTNAME AS first_name, ZLASTNAME AS last_name,+ ZMIDDLENAME AS middle_name, ZNICKNAME AS nickname,+ ZORGANIZATION AS organization, ZNAME AS name+ FROM ZABCDRECORD`,+ ).all();++ const phonesByOwner = new Map();+ if (tables.includes('ZABCDPHONENUMBER')) {+ const phoneRows = db.prepare(+ `SELECT ZOWNER AS owner, ZFULLNUMBER AS full_number FROM ZABCDPHONENUMBER WHERE ZFULLNUMBER IS NOT NULL AND ZFULLNUMBER <> ''`,+ ).all();+ for (const r of phoneRows) {+ const list = phonesByOwner.get(r.owner) || [];+ list.push(String(r.full_number));+ phonesByOwner.set(r.owner, list);+ }+ }++ const emailsByOwner = new Map();+ if (tables.includes('ZABCDEMAILADDRESS')) {+ const emailRows = db.prepare(+ `SELECT ZOWNER AS owner, ZADDRESS AS address FROM ZABCDEMAILADDRESS WHERE ZADDRESS IS NOT NULL AND ZADDRESS <> ''`,+ ).all();+ for (const r of emailRows) {+ const list = emailsByOwner.get(r.owner) || [];+ list.push(String(r.address));+ emailsByOwner.set(r.owner, list);+ }+ }++ const contacts = [];+ for (const r of records) {+ const phones = phonesByOwner.get(r.pk) || [];+ const emails = emailsByOwner.get(r.pk) || [];+ // Skip group-ish rows with no contact data (many ZABCDRECORD rows are groups/meta).+ if (!r.first_name && !r.last_name && !r.organization && !r.nickname && !r.name+ && phones.length === 0 && emails.length === 0) {+ continue;+ }+ contacts.push({+ id: r.unique_id || `ab:${dbPath}:${r.pk}`,+ uniqueId: r.unique_id || `ab:${r.pk}`,+ firstName: r.first_name,+ lastName: r.last_name,+ middleName: r.middle_name,+ nickname: r.nickname,+ organization: r.organization,+ name: r.name,+ phones,+ emails,+ sourcePath: dbPath,+ });+ }+ return { ok: true, path: dbPath, contacts };+ } catch (err) {+ return { ok: false, path: dbPath, error: err?.message || String(err), permission: isPermissionError(err), contacts: [] };+ } finally {+ try { db?.close(); } catch { /* noop */ }+ }+}++// ---------------------------------------------------------------------------+// Cache + state+// ---------------------------------------------------------------------------++function cachePath() {+ return dataPath(CACHE_FILE);+}++function statePath() {+ return dataPath(STATE_FILE);+}++export async function readContactCache() {+ const raw = await tryReadFile(cachePath());+ const parsed = raw ? safeJSONParse(raw, null, { allowArray: false }) : null;+ const contacts = Array.isArray(parsed?.contacts) ? parsed.contacts : [];+ return {+ contacts,+ syncedAt: parsed?.syncedAt || null,+ sourceCount: parsed?.sourceCount || 0,+ };+}++async function writeContactCache(contacts, meta = {}) {+ const payload = {+ contacts,+ syncedAt: new Date().toISOString(),+ sourceCount: meta.sourceCount || 0,+ contactCount: contacts.length,+ };+ await atomicWrite(cachePath(), JSON.stringify(payload));+ return payload;+}++export async function readSyncState() {+ const raw = await tryReadFile(statePath());+ const parsed = raw ? safeJSONParse(raw, null, { allowArray: false }) : null;+ return {+ lastRunAt: parsed?.lastRunAt || null,+ lastResult: parsed?.lastResult || null,+ };+}++async function writeSyncState(state) {+ await atomicWrite(statePath(), JSON.stringify(state, null, 2));+}++// ---------------------------------------------------------------------------+// Public API+// ---------------------------------------------------------------------------++/**+ * Setup check — discover DBs and attempt a read of the first one. Never throws.+ */+export async function checkSetup() {+ const root = addressBookRoot();+ let paths = [];+ try {+ paths = discoverAddressBookPaths(root);+ } catch (err) {+ return {+ ok: false,+ root,+ error: err?.message || 'Failed to scan AddressBook directory',+ fullDiskAccessRequired: isPermissionError(err),+ remediation: isPermissionError(err)+ ? 'Grant Full Disk Access to the process running PortOS (System Settings → Privacy & Security → Full Disk Access), then restart PortOS.'+ : `Could not scan ${root}: ${err?.message || 'unknown error'}`,+ };+ }+ if (paths.length === 0) {+ return {+ ok: false,+ root,+ paths: [],+ error: 'No AddressBook-v22.abcddb found',+ remediation: `No Contacts databases under ${root}. Open the macOS Contacts app at least once, or check CONTACTS_AB_ROOT.`,+ };+ }+ // Probe the largest source for a real permission signal.+ let best = { path: paths[0], n: 0 };+ for (const p of paths) {+ try {+ const n = statSync(p).size || 0;+ if (n > best.n) best = { path: p, n };+ } catch { /* skip */ }+ }+ const probe = readAddressBookDb(best.path);+ if (!probe.ok) {+ return {+ ok: false,+ root,+ paths,+ error: probe.error,+ fullDiskAccessRequired: probe.permission,+ remediation: probe.permission+ ? 'Grant Full Disk Access to the process running PortOS (System Settings → Privacy & Security → Full Disk Access), then restart PortOS.'+ : probe.error,+ };+ }+ // Count across all sources (cheap open).+ let totalRaw = 0;+ let sourcesOk = 0;+ for (const p of paths) {+ const r = readAddressBookDb(p);+ if (r.ok) {+ sourcesOk += 1;+ totalRaw += r.contacts.length;+ }+ }+ return {+ ok: true,+ root,+ paths,+ sourceCount: sourcesOk,+ rawContactRows: totalRaw,+ };+}++/**+ * Full sync: read all AddressBook sources, merge, write cache.+ */+let syncInFlight = null;+export async function runSync() {+ if (syncInFlight) return syncInFlight;+ syncInFlight = doRunSync().finally(() => { syncInFlight = null; });+ return syncInFlight;+}++async function doRunSync() {+ const setup = await checkSetup();+ if (!setup.ok) {+ const result = {+ ok: false,+ error: setup.error,+ fullDiskAccessRequired: setup.fullDiskAccessRequired,+ remediation: setup.remediation,+ };+ await writeSyncState({ lastRunAt: new Date().toISOString(), lastResult: result });+ return result;+ }++ const lists = [];+ const errors = [];+ for (const p of setup.paths || []) {+ const r = readAddressBookDb(p);+ if (r.ok) lists.push(r.contacts);+ else errors.push({ path: p, error: r.error });+ }+ const contacts = mergeContacts(lists);+ const cache = await writeContactCache(contacts, { sourceCount: lists.length });+ const result = {+ ok: true,+ contactCount: contacts.length,+ sourceCount: lists.length,+ phoneKeys: contacts.reduce((n, c) => n + (c.phones?.length || 0), 0),+ emailKeys: contacts.reduce((n, c) => n + (c.emails?.length || 0), 0),+ errors: errors.length ? errors : undefined,+ syncedAt: cache.syncedAt,+ };+ await writeSyncState({ lastRunAt: new Date().toISOString(), lastResult: result });+ console.log(`📇 Contacts sync: ${result.contactCount} contact(s) from ${result.sourceCount} source(s)`);+ return result;+}++export async function getStatus() {+ const [cache, state, setup] = await Promise.all([+ readContactCache(),+ readSyncState(),+ checkSetup().catch(() => ({ ok: false })),+ ]);+ return {+ cache: {+ contactCount: cache.contacts.length,+ syncedAt: cache.syncedAt,+ sourceCount: cache.sourceCount,+ },+ state,+ setup: {+ ok: setup.ok,+ sourceCount: setup.sourceCount,+ root: setup.root,+ fullDiskAccessRequired: setup.fullDiskAccessRequired,+ error: setup.error,+ },+ };+}++/**+ * Search the cached contacts (name / org / phone / email substring).+ */+export async function searchContacts({ q, limit } = {}) {+ const { contacts } = await readContactCache();+ const needle = String(q || '').trim().toLowerCase();+ const cap = Math.min(Math.max(Number(limit) || 50, 1), 500);+ if (!needle) return contacts.slice(0, cap);+ const out = [];+ for (const c of contacts) {+ const hay = [+ c.displayName,+ c.organization,+ c.firstName,+ c.lastName,+ ...(c.phones || []),+ ...(c.emails || []),+ ].filter(Boolean).join(' ').toLowerCase();+ if (hay.includes(needle)) {+ out.push(c);+ if (out.length >= cap) break;+ }+ }+ return out;+}++export async function getContactById(id) {+ const { contacts } = await readContactCache();+ return contacts.find((c) => c.id === id || c.uniqueId === id) || null;+}++/**+ * Load contacts + build index. Cached in-process for the duration of a request+ * batch via the returned object (caller holds it).+ */+export async function loadContactIndex() {+ const { contacts, syncedAt } = await readContactCache();+ return {+ contacts,+ syncedAt,+ index: buildContactIndex(contacts),+ };+}diff --git a/server/services/contactsSync.test.js b/server/services/contactsSync.test.jsnew file mode 100644index 0000000000..f10ed4947d--- /dev/null+++ b/server/services/contactsSync.test.js@@ -0,0 +1,73 @@+import { describe, it, expect } from 'vitest';+import {+ contactDisplayName,+ normalizeContactRecord,+ mergeContacts,+ buildContactIndex,+ resolveHandleAgainstContacts,+} from './contactsSync.js';++// Fixtures use reserved NANP 555 numbers only — never real contact data.++describe('contactsSync pure helpers', () => {+ describe('contactDisplayName', () => {+ it('prefers first + last over organization', () => {+ expect(contactDisplayName({+ firstName: 'Jane',+ lastName: 'Doe',+ organization: 'Acme',+ })).toBe('Jane Doe');+ });++ it('falls back to organization for company contacts', () => {+ expect(contactDisplayName({ organization: 'Acme Repair Co' })).toBe('Acme Repair Co');+ });++ it('uses nickname when no first/last', () => {+ expect(contactDisplayName({ nickname: 'Skip' })).toBe('Skip');+ });+ });++ describe('normalizeContactRecord', () => {+ it('normalizes phones and emails', () => {+ const c = normalizeContactRecord({+ id: '1',+ uniqueId: 'u1',+ firstName: 'Alex',+ lastName: 'Example',+ phones: ['15551234567', '+1 (555) 123-4567'],+ emails: ['[email protected]'],+ });+ expect(c.phones).toEqual(['+15551234567']);+ expect(c.emails).toEqual(['[email protected]']);+ expect(c.displayName).toBe('Alex Example');+ });++ it('returns null when empty', () => {+ expect(normalizeContactRecord({ phones: [], emails: [] })).toBeNull();+ });+ });++ describe('mergeContacts + resolve', () => {+ it('dedupes across sources by phone', () => {+ const merged = mergeContacts([+ [{ uniqueId: 'a', firstName: 'Jane', phones: ['5551234567'], emails: [] }],+ [{ uniqueId: 'b', firstName: 'Jane', lastName: 'Doe', phones: ['+1 555 123 4567'], emails: ['[email protected]'] }],+ ]);+ expect(merged).toHaveLength(1);+ expect(merged[0].emails).toContain('[email protected]');+ expect(merged[0].phones).toEqual(['+15551234567']);+ });++ it('resolves handle against contact index', () => {+ const contacts = mergeContacts([[+ { uniqueId: '1', firstName: 'Pat', lastName: 'Lee', phones: ['+1 (555) 987-6543'], emails: [] },+ ]]);+ const index = buildContactIndex(contacts);+ const hit = resolveHandleAgainstContacts('5559876543', index);+ expect(hit.displayName).toBe('Pat Lee');+ expect(hit.source).toBe('contacts');+ expect(resolveHandleAgainstContacts('+19999999999', index)).toBeNull();+ });+ });+});diff --git a/server/services/identityResolve.js b/server/services/identityResolve.jsnew file mode 100644index 0000000000..030d5e1386--- /dev/null+++ b/server/services/identityResolve.js@@ -0,0 +1,188 @@+/**+ * Identity resolution (#2415) — map a phone/email handle to a display name.+ *+ * Priority:+ * 1. Tribe person (phones[] / emails[]) — user-curated relationship graph+ * 2. macOS Contacts cache — AddressBook ingest+ * 3. null (caller falls back to raw handle)+ *+ * Pure given preloaded indexes; async helpers load Tribe + Contacts once.+ */+import {+ buildPersonMatchIndex,+ identityFromHandle,+ matchPerson,+ normalizeIdentifier,+ normalizePhone,+} from '../lib/tribeMatch.js';+import { loadContactIndex, resolveHandleAgainstContacts } from './contactsSync.js';++/**+ * Resolve one raw handle against tribe + contact indexes.+ * Returns:+ * {+ * displayName, organization?, personId?, contactId?,+ * source: 'tribe' | 'contacts' | null,+ * handle, phone?, email?+ * }+ */+export function resolveHandle(handle, { tribeIndex, contactIndex } = {}) {+ const raw = handle == null ? '' : String(handle).trim();+ const identity = identityFromHandle(raw);+ const base = {+ handle: raw,+ phone: identity.phone || null,+ email: identity.email || null,+ displayName: null,+ organization: null,+ personId: null,+ contactId: null,+ source: null,+ };+ if (!raw) return base;++ if (tribeIndex) {+ const personId = matchPerson(identity, tribeIndex);+ if (personId) {+ const person = tribeIndex.byId?.get(personId);+ return {+ ...base,+ displayName: person?.name || raw,+ personId,+ source: 'tribe',+ };+ }+ }++ const fromContacts = resolveHandleAgainstContacts(raw, contactIndex);+ if (fromContacts) {+ return {+ ...base,+ displayName: fromContacts.displayName,+ organization: fromContacts.organization,+ contactId: fromContacts.contactId,+ source: 'contacts',+ };+ }++ return base;+}++/**+ * Best label for UI: resolved displayName, else organization, else raw handle.+ */+export function displayLabel(resolution, fallback = '') {+ if (resolution?.displayName) {+ if (resolution.organization && resolution.source === 'contacts'+ && resolution.displayName !== resolution.organization) {+ // "Jane Doe · Acme" when both person name and company exist+ // Keep simple: only append org when the display name looks like a person+ // (not already the org).+ return resolution.displayName;+ }+ return resolution.displayName;+ }+ if (resolution?.organization) return resolution.organization;+ return fallback || resolution?.handle || '';+}++/**+ * Load Tribe people + Contacts cache and build a combined resolver context.+ * `tribeIndex` includes `byId` for name lookup after matchPerson.+ */+export async function loadResolverContext() {+ const [{ listPeople }, contactBundle] = await Promise.all([+ import('./tribe.js'),+ loadContactIndex(),+ ]);+ const people = await listPeople().catch(() => []);+ const base = buildPersonMatchIndex(people);+ const byId = new Map(people.map((p) => [p.id, p]));+ return {+ people,+ tribeIndex: { ...base, byId },+ contactIndex: contactBundle.index,+ contacts: contactBundle.contacts,+ contactsSyncedAt: contactBundle.syncedAt,+ };+}++/**+ * Resolve many handles with one shared context (avoids N Tribe loads).+ */+export function resolveHandles(handles = [], ctx) {+ const out = new Map();+ for (const h of handles) {+ if (h == null || h === '') continue;+ if (out.has(h)) continue;+ out.set(h, resolveHandle(h, ctx));+ }+ return out;+}++/**+ * Enrich a conversation-like row that has `handle` / `title` / `participants`.+ */+export function enrichConversationRow(row, ctx) {+ if (!row) return row;+ const handle = row.handle || '';+ // Also try title when it looks like a handle (phone/email) and handle is empty.+ const probe = handle || (row.title && (row.title.includes('@') || /^\+?\d[\d\s().-]{6,}$/.test(row.title))+ ? row.title+ : '');+ const res = resolveHandle(probe, ctx);+ const label = displayLabel(res, row.title || handle || 'iMessage');+ // Prefer resolved name over a title that is just the raw handle.+ const titleIsHandle = row.title && (+ row.title === handle+ || row.title === res.phone+ || row.title === res.email+ || row.title === probe+ );+ return {+ ...row,+ title: (titleIsHandle || !row.title) ? label : row.title,+ displayName: label,+ organization: res.organization || null,+ personId: res.personId || null,+ contactId: res.contactId || null,+ identitySource: res.source,+ resolvedHandle: res.phone || res.email || handle || null,+ };+}++/**+ * Enrich activity events: attach counterpart displayName on participants + title.+ */+export function enrichActivityEvent(event, ctx) {+ if (!event) return event;+ const handle = event.metadata?.handle || '';+ const res = resolveHandle(handle, ctx);+ const participants = (event.participants || []).map((p) => {+ const key = p.phone || p.email || '';+ if (!key) return p;+ const pr = resolveHandle(key, ctx);+ if (!pr.displayName) return p;+ return {+ ...p,+ name: p.name || pr.displayName,+ personId: p.personId || pr.personId || undefined,+ };+ });+ const titleIsHandle = event.title && handle && (+ event.title === handle || event.title === res.phone || event.title === res.email+ );+ const label = displayLabel(res, event.title || handle || '');+ return {+ ...event,+ title: (titleIsHandle || !event.title) ? (label || event.title) : event.title,+ displayName: label || null,+ personId: res.personId || null,+ contactId: res.contactId || null,+ identitySource: res.source,+ participants,+ };+}++// Re-export normalize helpers used by tribe enrich.+export { normalizeIdentifier, normalizePhone, identityFromHandle };diff --git a/server/services/identityResolve.test.js b/server/services/identityResolve.test.jsnew file mode 100644index 0000000000..25259c6ac9--- /dev/null+++ b/server/services/identityResolve.test.js@@ -0,0 +1,76 @@+import { describe, it, expect } from 'vitest';+import { buildPersonMatchIndex } from '../lib/tribeMatch.js';+import { buildContactIndex, mergeContacts } from './contactsSync.js';+import {+ resolveHandle,+ displayLabel,+ enrichConversationRow,+ enrichActivityEvent,+} from './identityResolve.js';++describe('identityResolve', () => {+ const people = [+ { id: 'p1', name: 'Tribe Friend', phones: ['+15551234567'], emails: ['[email protected]'] },+ ];+ const tribeIndex = {+ ...buildPersonMatchIndex(people),+ byId: new Map(people.map((p) => [p.id, p])),+ };+ const contacts = mergeContacts([[+ { uniqueId: 'c1', firstName: 'Contact', lastName: 'Only', phones: ['+15559876543'], emails: [] },+ { uniqueId: 'c2', firstName: 'Also', lastName: 'Friend', phones: ['+15551234567'], emails: [] },+ ]]);+ const contactIndex = buildContactIndex(contacts);+ const ctx = { tribeIndex, contactIndex };++ it('prefers Tribe over Contacts for the same phone', () => {+ const r = resolveHandle('+1 555 123 4567', ctx);+ expect(r.source).toBe('tribe');+ expect(r.personId).toBe('p1');+ expect(r.displayName).toBe('Tribe Friend');+ });++ it('falls back to Contacts when not in Tribe', () => {+ const r = resolveHandle('5559876543', ctx);+ expect(r.source).toBe('contacts');+ expect(r.displayName).toBe('Contact Only');+ });++ it('returns null source for unknown handles', () => {+ const r = resolveHandle('+19990001111', ctx);+ expect(r.source).toBeNull();+ expect(r.displayName).toBeNull();+ expect(displayLabel(r, '+19990001111')).toBe('+19990001111');+ });++ it('enriches conversation rows when title is a raw handle', () => {+ const row = enrichConversationRow({+ handle: '+15559876543',+ title: '+15559876543',+ lastSummary: 'hi',+ }, ctx);+ expect(row.displayName).toBe('Contact Only');+ expect(row.title).toBe('Contact Only');+ expect(row.identitySource).toBe('contacts');+ });++ it('keeps a custom chat title that is not the handle', () => {+ const row = enrichConversationRow({+ handle: '+15559876543',+ title: 'Family Group',+ }, ctx);+ expect(row.title).toBe('Family Group');+ expect(row.displayName).toBe('Contact Only');+ });++ it('enriches activity event participants', () => {+ const ev = enrichActivityEvent({+ title: '+15551234567',+ metadata: { handle: '+15551234567' },+ participants: [{ phone: '+15551234567' }],+ }, ctx);+ expect(ev.personId).toBe('p1');+ expect(ev.participants[0].name).toBe('Tribe Friend');+ expect(ev.participants[0].personId).toBe('p1');+ });+});diff --git a/server/services/imessageManage.js b/server/services/imessageManage.jsindex 184e19b046..ad600fe37b 100644--- a/server/services/imessageManage.js+++ b/server/services/imessageManage.js@@ -212,20 +212,59 @@ export function filterBlockedTouchpointCandidates(candidates = [], blockedKeys)// Browse / purge wrappers (source-scoped)// ---------------------------------------------------------------------------+/**+ * List iMessage conversations with identity enrichment (#2415): Tribe name+ * wins, then macOS Contacts cache, then raw handle. When `q` is set, filter+ * also matches resolved display names (not only stored titles).+ */export async function listConversations({ q, limit } = {}) {+ // When searching by resolved name, pull a wider raw set then filter after+ // enrich — SQL only sees stored titles/handles.+ const needle = q != null && String(q).trim() ? String(q).trim().toLowerCase() : '';+ const rawLimit = needle ? Math.min(Math.max(Number(limit) || 500, 1) * 4, 2000) : limit;const [rows, blocklist] = await Promise.all([- humanActivity.listConversations({ source: SOURCE, q, limit }),+ humanActivity.listConversations({+ source: SOURCE,+ // Skip SQL q when we will name-filter after resolve (SQL misses Contacts names).+ q: needle ? undefined : q,+ limit: rawLimit,+ }),readBlocklist(),]);const blocked = new Set(blocklist.handles);- return rows.map((row) => {+ let enrichConversationRow = (row) => row;+ try {+ const identity = await import('./identityResolve.js');+ const ctx = await identity.loadResolverContext();+ enrichConversationRow = (row) => identity.enrichConversationRow(row, ctx);+ } catch (err) {+ console.error(`⚠️ Identity resolve unavailable: ${err?.message || err}`);+ }++ const cap = Math.min(Math.max(Number(limit) || 500, 1), 2000);+ const enriched = [];+ for (const row of rows) {const handleKey = blocklistKey(row.handle);- return {+ const base = {...row,chatKey: encodeChatKey(row.chatGuid),blocked: !!(handleKey && blocked.has(handleKey)),};- });+ const withName = enrichConversationRow(base);+ if (needle) {+ const hay = [+ withName.title,+ withName.displayName,+ withName.handle,+ withName.organization,+ withName.lastSummary,+ ].filter(Boolean).join(' ').toLowerCase();+ if (!hay.includes(needle)) continue;+ }+ enriched.push(withName);+ if (enriched.length >= cap) break;+ }+ return enriched;}export async function listConversationEvents(chatKey, { limit, before } = {}) {@@ -237,10 +276,38 @@ export async function listConversationEvents(chatKey, { limit, before } = {}) {to: before || undefined,limit,});+ let enrichedEvents = events;+ let conversationMeta = null;+ try {+ const identity = await import('./identityResolve.js');+ const ctx = await identity.loadResolverContext();+ enrichedEvents = events.map((ev) => identity.enrichActivityEvent(ev, ctx));+ // Conversation header identity from the first event handle or chat title.+ const sampleHandle = events.find((e) => e.metadata?.handle)?.metadata?.handle+ || events[0]?.title+ || '';+ if (sampleHandle) {+ conversationMeta = identity.enrichConversationRow({+ handle: events.find((e) => e.metadata?.handle)?.metadata?.handle || null,+ title: events[0]?.title || '',+ }, ctx);+ }+ } catch (err) {+ console.error(`⚠️ Identity resolve unavailable: ${err?.message || err}`);+ }return {chatGuid,chatKey: encodeChatKey(chatGuid),- events,+ events: enrichedEvents,+ identity: conversationMeta+ ? {+ displayName: conversationMeta.displayName,+ personId: conversationMeta.personId,+ contactId: conversationMeta.contactId,+ organization: conversationMeta.organization,+ identitySource: conversationMeta.identitySource,+ }+ : null,};}diff --git a/server/services/tribeContacts.js b/server/services/tribeContacts.jsnew file mode 100644index 0000000000..85f056ca56--- /dev/null+++ b/server/services/tribeContacts.js@@ -0,0 +1,241 @@+/**+ * Tribe ↔ Contacts bridge (#2415).+ *+ * - enrichTribeFromContacts: fill missing phones/emails on existing people+ * when a Contacts record matches by phone, email, or exact unique name.+ * - suggestTribeImports: Contacts / iMessage handles not yet in Tribe.+ * - importContactToTribe: create a Tribe person from a cached contact.+ *+ * Never auto-dumps the whole address book into Tribe rings.+ */+import {+ buildPersonMatchIndex,+ matchPerson,+ normalizeIdentifier,+ normalizePhone,+ identityFromHandle,+} from '../lib/tribeMatch.js';+import { loadContactIndex } from './contactsSync.js';+import * as tribe from './tribe.js';+import * as humanActivity from './humanActivity.js';++function personMatchKeys(person) {+ const phones = new Set((person.phones || []).map(normalizePhone).filter(Boolean));+ const emails = new Set((person.emails || []).map(normalizeIdentifier).filter(Boolean));+ return { phones, emails };+}++/**+ * Match a contact to a tribe person: phone/email first, then exact unique name.+ */+export function matchContactToPerson(contact, tribeIndex) {+ for (const p of contact.phones || []) {+ const id = matchPerson({ phone: p }, tribeIndex);+ if (id) return id;+ }+ for (const e of contact.emails || []) {+ const id = matchPerson({ email: e }, tribeIndex);+ if (id) return id;+ }+ if (contact.displayName) {+ const id = matchPerson({ name: contact.displayName }, tribeIndex);+ if (id) return id;+ }+ return null;+}++/**+ * Compute phone/email fills for one person from a matched contact.+ * Returns null when nothing new would be added.+ */+export function computePhoneEmailFill(person, contact) {+ const { phones: haveP, emails: haveE } = personMatchKeys(person);+ const addPhones = (contact.phones || []).filter((p) => p && !haveP.has(p));+ const addEmails = (contact.emails || []).filter((e) => e && !haveE.has(e));+ if (addPhones.length === 0 && addEmails.length === 0) return null;+ return {+ phones: [...(person.phones || []), ...addPhones],+ emails: [...(person.emails || []), ...addEmails],+ addPhones,+ addEmails,+ };+}++/**+ * Scan Contacts cache and fill missing Tribe phones/emails.+ * `dryRun: true` returns planned changes without writing.+ */+export async function enrichTribeFromContacts({ dryRun = false } = {}) {+ const people = await tribe.listPeople();+ const { contacts } = await loadContactIndex();+ const tribeIndex = buildPersonMatchIndex(people);+ // byId for fill math+ const byId = new Map(people.map((p) => [p.id, p]));++ const planned = [];+ const claimed = new Set(); // personId already filled this pass++ for (const contact of contacts) {+ const personId = matchContactToPerson(contact, tribeIndex);+ if (!personId || claimed.has(personId)) continue;+ const person = byId.get(personId);+ if (!person) continue;+ const fill = computePhoneEmailFill(person, contact);+ if (!fill) continue;+ planned.push({+ personId,+ personName: person.name,+ contactId: contact.id,+ contactName: contact.displayName,+ addPhones: fill.addPhones,+ addEmails: fill.addEmails,+ });+ claimed.add(personId);+ if (!dryRun) {+ const updated = await tribe.updatePerson(personId, {+ phones: fill.phones,+ emails: fill.emails,+ });+ if (updated) byId.set(personId, updated);+ }+ }++ return {+ dryRun: Boolean(dryRun),+ matched: planned.length,+ updated: dryRun ? 0 : planned.length,+ changes: planned,+ };+}++/**+ * Suggest contacts that appear in iMessage activity but aren't in Tribe yet.+ * Ranked by event count (handle frequency).+ */+export async function suggestTribeImports({ limit = 50 } = {}) {+ const people = await tribe.listPeople();+ const tribeIndex = buildPersonMatchIndex(people);+ const { contacts, index: contactIndex } = await loadContactIndex();++ // Pull recent-ish imessage events for handle frequency (cap to keep it cheap).+ const events = await humanActivity.listEvents({ source: 'imessage', limit: 2000 });+ const handleCounts = new Map();+ for (const ev of events) {+ const h = ev.metadata?.handle;+ if (!h) continue;+ const key = normalizePhone(h) || normalizeIdentifier(h);+ if (!key) continue;+ // Skip handles already in Tribe.+ const id = identityFromHandle(h);+ if (matchPerson(id, tribeIndex)) continue;+ handleCounts.set(key, (handleCounts.get(key) || 0) + 1);+ }++ // Also surface contacts with phones/emails not in Tribe (even without iMessage).+ const suggestions = [];+ const seenContact = new Set();++ // From iMessage handles → contact or bare handle+ const sortedHandles = [...handleCounts.entries()].sort((a, b) => b[1] - a[1]);+ for (const [key, eventCount] of sortedHandles) {+ let contact = contactIndex.byPhone.get(key) || contactIndex.byEmail.get(key) || null;+ if (contact && seenContact.has(contact.id)) continue;+ if (contact) seenContact.add(contact.id);+ // If no contact, still suggest a bare-handle import shell.+ suggestions.push({+ contactId: contact?.id || null,+ displayName: contact?.displayName || key,+ organization: contact?.organization || null,+ phones: contact?.phones || (key.startsWith('+') ? [key] : []),+ emails: contact?.emails || (key.includes('@') ? [key] : []),+ handle: key,+ eventCount,+ reason: contact ? 'imessage+contacts' : 'imessage-only',+ });+ if (suggestions.length >= limit) break;+ }++ // Top up with unmatched contacts (no iMessage signal yet).+ if (suggestions.length < limit) {+ for (const c of contacts) {+ if (seenContact.has(c.id)) continue;+ if (matchContactToPerson(c, tribeIndex)) continue;+ if ((c.phones || []).length === 0 && (c.emails || []).length === 0) continue;+ seenContact.add(c.id);+ suggestions.push({+ contactId: c.id,+ displayName: c.displayName,+ organization: c.organization || null,+ phones: c.phones || [],+ emails: c.emails || [],+ handle: c.phones?.[0] || c.emails?.[0] || null,+ eventCount: 0,+ reason: 'contacts-only',+ });+ if (suggestions.length >= limit) break;+ }+ }++ return { suggestions, contactsCached: contacts.length, tribeCount: people.length };+}++/**+ * Create a Tribe person from a cached contact (or explicit payload).+ */+export async function importContactToTribe({+ contactId,+ name,+ phones,+ emails,+ organization,+ ring = 'tribe',+ relationship = '',+} = {}) {+ let contact = null;+ if (contactId) {+ const { contacts } = await loadContactIndex();+ contact = contacts.find((c) => c.id === contactId || c.uniqueId === contactId) || null;+ }+ const personName = String(name || contact?.displayName || organization || contact?.organization || '').trim();+ if (!personName) {+ const err = new Error('name is required');+ err.status = 400;+ err.code = 'BAD_REQUEST';+ throw err;+ }+ const personPhones = phones || contact?.phones || [];+ const personEmails = emails || contact?.emails || [];++ // Refuse duplicate: if any phone/email already maps to a person, return that person.+ const people = await tribe.listPeople();+ const tribeIndex = buildPersonMatchIndex(people);+ for (const p of personPhones) {+ const id = matchPerson({ phone: p }, tribeIndex);+ if (id) {+ const existing = people.find((x) => x.id === id);+ return { person: existing, created: false, reason: 'phone-match' };+ }+ }+ for (const e of personEmails) {+ const id = matchPerson({ email: e }, tribeIndex);+ if (id) {+ const existing = people.find((x) => x.id === id);+ return { person: existing, created: false, reason: 'email-match' };+ }+ }++ const notes = organization || contact?.organization+ ? `Imported from Contacts${(organization || contact?.organization) ? ` (${organization || contact.organization})` : ''}`+ : 'Imported from Contacts';++ const person = await tribe.createPerson({+ name: personName,+ ring,+ relationship: relationship || (organization || contact?.organization ? 'contact' : ''),+ phones: personPhones,+ emails: personEmails,+ notes,+ channel: 'iMessage',+ });+ return { person, created: true };+}diff --git a/server/services/tribeContacts.test.js b/server/services/tribeContacts.test.jsnew file mode 100644index 0000000000..e5d7528646--- /dev/null+++ b/server/services/tribeContacts.test.js@@ -0,0 +1,49 @@+import { describe, it, expect } from 'vitest';+import { buildPersonMatchIndex } from '../lib/tribeMatch.js';+import {+ matchContactToPerson,+ computePhoneEmailFill,+} from './tribeContacts.js';++describe('tribeContacts pure helpers', () => {+ const people = [+ { id: 'p1', name: 'Jane Doe', phones: [], emails: ['[email protected]'] },+ { id: 'p2', name: 'Bob', phones: ['+15551112222'], emails: [] },+ ];+ const index = buildPersonMatchIndex(people);++ it('matches contact by email then returns person id', () => {+ const id = matchContactToPerson({+ displayName: 'Jane',+ emails: ['[email protected]'],+ phones: ['+15559998888'],+ }, index);+ expect(id).toBe('p1');+ });++ it('matches contact by exact unique name', () => {+ const id = matchContactToPerson({+ displayName: 'Bob',+ phones: [],+ emails: [],+ }, index);+ expect(id).toBe('p2');+ });++ it('computes only missing phones/emails', () => {+ const fill = computePhoneEmailFill(+ { phones: ['+15551112222'], emails: [] },+ { phones: ['+15551112222', '+15553334444'], emails: ['[email protected]'] },+ );+ expect(fill.addPhones).toEqual(['+15553334444']);+ expect(fill.addEmails).toEqual(['[email protected]']);+ expect(fill.phones).toEqual(['+15551112222', '+15553334444']);+ });++ it('returns null when nothing to add', () => {+ expect(computePhoneEmailFill(+ { phones: ['+15551112222'], emails: ['[email protected]'] },+ { phones: ['+15551112222'], emails: ['[email protected]'] },+ )).toBeNull();+ });+});