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
feat([issue-2151]): iMessage ingestion from macOS chat.db
Adam Eivyff8bfc6ddaca
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b9d2368f4c..c40ca22294 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -3,6 +3,7 @@## Human Activity Tracking- **[issue-2150] Activity timeline** — a new `/timeline` page shows a unified, day-by-day view of your activity (emails sent/received and calendar events, with more sources coming), backed by a machine-local `human_activity_events` store that your existing message and calendar syncs populate automatically. Pick any day (deep-linkable via `/timeline/:date`), see an hourly activity histogram and per-source tallies, and browse the day's events. Only metadata and a short summary line are stored — full message bodies stay in their per-source caches — and the timeline is machine-local (never federated to peers), like Tribe.+- **[issue-2151] iMessage ingestion (macOS)** — a new Settings → iMessage tab lets you pull your Mac's Messages history into the activity timeline and your Tribe touchpoints. It reads `~/Library/Messages/chat.db` read-only (never writing to Apple's database) using a built-in SQLite reader — no new dependencies — and matches conversations to the people you track by phone number (a new phone field on Tribe people, matched in E.164 form) as well as email. It's off by default and opt-in: enable it, set a sync interval, and use "Check setup" to confirm PortOS has macOS Full Disk Access (with a clear fix if it doesn't) or "Sync now" to run immediately. Only conversation metadata and a short preview line are stored — full message text stays in chat.db — and, like Tribe, nothing federates to your peers. Re-syncs are incremental and idempotent, so running it repeatedly never double-logs.## Privacy Centerdiff --git a/client/src/components/settings/IMessageTab.jsx b/client/src/components/settings/IMessageTab.jsxnew file mode 100644index 0000000000..fbb557b85b--- /dev/null+++ b/client/src/components/settings/IMessageTab.jsx@@ -0,0 +1,195 @@+import { useEffect, useState } from 'react';+import { Save, Loader2, MessageSquare, ShieldCheck, ShieldAlert, RefreshCw } from 'lucide-react';+import toast from '../ui/Toast';+import BrailleSpinner from '../BrailleSpinner';+import {+ getSettings,+ updateSettings,+ getImessageStatus,+ checkImessageSetup,+ syncImessage,+} from '../../services/api';++// Settings → iMessage (#2151). Opt-in, machine-local ingestion of the macOS+// Messages database (chat.db) into the Tribe touchpoint log + activity timeline.+// OFF by default — reading chat.db needs macOS Full Disk Access.+export function IMessageTab() {+ const [loading, setLoading] = useState(true);+ const [enabled, setEnabled] = useState(false);+ const [intervalMinutes, setIntervalMinutes] = useState(30);+ const [savedEnabled, setSavedEnabled] = useState(false);+ const [savedInterval, setSavedInterval] = useState(30);+ const [saving, setSaving] = useState(false);++ const [status, setStatus] = useState(null);+ const [setup, setSetup] = useState(null);+ const [checking, setChecking] = useState(false);+ const [syncing, setSyncing] = useState(false);++ useEffect(() => {+ Promise.all([+ getSettings({ silent: true }).catch(() => ({})),+ getImessageStatus({ silent: true }).catch(() => null),+ ])+ .then(([settings, st]) => {+ const c = settings?.imessage || {};+ const en = typeof c.enabled === 'boolean' ? c.enabled : false;+ const iv = Number.isFinite(c.intervalMinutes) ? c.intervalMinutes : 30;+ setEnabled(en);+ setIntervalMinutes(iv);+ setSavedEnabled(en);+ setSavedInterval(iv);+ setStatus(st);+ })+ .finally(() => setLoading(false));+ }, []);++ const dirty = enabled !== savedEnabled || Number(intervalMinutes) !== Number(savedInterval);++ const handleSave = async () => {+ const iv = Math.max(1, Math.min(1440, Math.floor(Number(intervalMinutes) || 30)));+ setSaving(true);+ const merged = await updateSettings({ imessage: { enabled, intervalMinutes: iv } }).catch(() => null);+ setSaving(false);+ if (!merged) return;+ setIntervalMinutes(iv);+ setSavedEnabled(enabled);+ setSavedInterval(iv);+ toast.success('Saved — scheduler applies on next server restart');+ };++ const handleCheck = async () => {+ setChecking(true);+ const report = await checkImessageSetup({ silent: true }).catch(() => ({ ok: false, error: 'Setup check failed' }));+ setChecking(false);+ setSetup(report);+ if (report?.ok) toast.success(`chat.db reachable — ${report.messageCount ?? 0} message(s)`);+ else toast.error(report?.fullDiskAccessRequired ? 'Full Disk Access required' : 'chat.db not reachable');+ };++ const handleSyncNow = async () => {+ setSyncing(true);+ const result = await syncImessage({ silent: true }).catch(() => ({ ok: false, error: 'Sync failed' }));+ setSyncing(false);+ if (result?.ok) {+ toast.success(`Synced: ${result.recorded} event(s), ${result.touchpointsCreated} touchpoint(s)`);+ setStatus((prev) => ({ ...(prev || {}), state: { ...(prev?.state || {}), lastResult: result, lastRunAt: new Date().toISOString() } }));+ } else {+ toast.error(result?.fullDiskAccessRequired ? 'Full Disk Access required' : (result?.error || 'Sync failed'));+ setSetup(result);+ }+ };++ if (loading) return <BrailleSpinner />;++ const lastResult = 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">+ <MessageSquare size={16} className="text-port-accent" />+ <h3 className="text-lg font-semibold text-white">iMessage ingestion</h3>+ </div>+ <p className="text-sm text-gray-400 mb-4">+ Reads your local macOS Messages database (<code className="text-gray-300">~/Library/Messages/chat.db</code>) read-only+ and feeds both Tribe touchpoints and the activity timeline. Machine-local — nothing federates to peers.+ Requires macOS <strong>Full Disk Access</strong> for the process running PortOS.+ </p>++ <div className="space-y-3">+ <label htmlFor="imessage-enabled" className="flex items-center gap-2 text-sm text-gray-200 cursor-pointer">+ <input+ id="imessage-enabled"+ type="checkbox"+ checked={enabled}+ onChange={(e) => setEnabled(e.target.checked)}+ className="w-4 h-4 accent-port-accent"+ />+ Enable scheduled iMessage sync+ </label>++ <div>+ <label htmlFor="imessage-interval" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">+ Sync interval (minutes)+ </label>+ <input+ id="imessage-interval"+ type="number"+ min={1}+ max={1440}+ value={intervalMinutes}+ onChange={(e) => setIntervalMinutes(e.target.value)}+ className="w-32 px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ </div>++ <div className="flex flex-wrap gap-2 pt-1">+ <button+ type="button"+ onClick={handleSave}+ disabled={!dirty || saving}+ 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 disabled:cursor-not-allowed"+ >+ {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}+ {saving ? 'Saving...' : 'Save'}+ </button>+ <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={handleSyncNow}+ disabled={syncing}+ 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"+ >+ {syncing ? <Loader2 size={14} className="animate-spin" /> : <RefreshCw size={14} />}+ Sync now+ </button>+ </div>+ </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">chat.db reachable at <code className="text-gray-400">{setup.dbPath}</code> — {setup.messageCount ?? 0} message(s).</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>+ )}++ {(lastResult || status?.state?.cursorRowid > 0) && (+ <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">Last sync</h3>+ <dl className="grid grid-cols-2 sm:grid-cols-3 gap-3 text-sm">+ <div><dt className="text-gray-500 text-xs uppercase">Cursor ROWID</dt><dd className="text-gray-200">{status?.state?.cursorRowid ?? 0}</dd></div>+ <div><dt className="text-gray-500 text-xs uppercase">Events recorded</dt><dd className="text-gray-200">{lastResult?.recorded ?? '—'}</dd></div>+ <div><dt className="text-gray-500 text-xs uppercase">Touchpoints</dt><dd className="text-gray-200">{lastResult?.touchpointsCreated ?? '—'}</dd></div>+ <div><dt className="text-gray-500 text-xs uppercase">Scanned</dt><dd className="text-gray-200">{lastResult?.scanned ?? '—'}</dd></div>+ <div><dt className="text-gray-500 text-xs uppercase">Decode skips</dt><dd className="text-gray-200">{lastResult?.decodeFailures ?? '—'}</dd></div>+ <div><dt className="text-gray-500 text-xs uppercase">Last run</dt><dd className="text-gray-200">{status?.state?.lastRunAt ? new Date(status.state.lastRunAt).toLocaleString() : '—'}</dd></div>+ </dl>+ </div>+ )}+ </div>+ );+}++export default IMessageTab;diff --git a/client/src/components/settings/SettingsTabsHeader.jsx b/client/src/components/settings/SettingsTabsHeader.jsxindex 26fb0fcc39..b0bd1ce3c8 100644--- a/client/src/components/settings/SettingsTabsHeader.jsx+++ b/client/src/components/settings/SettingsTabsHeader.jsx@@ -18,6 +18,7 @@ export const TABS = [{ id: 'database', label: 'Database', to: '/settings/database' },{ id: 'embeddings', label: 'Embeddings', to: '/settings/embeddings' },{ id: 'general', label: 'General', to: '/settings/general' },+ { id: 'imessage', label: 'iMessage', to: '/settings/imessage' },{ id: 'local-llm', label: 'Local LLMs', to: '/settings/local-llm' },{ id: 'mortalloom', label: 'MortalLoom', to: '/settings/mortalloom' },{ id: 'prompts', label: 'Prompts', to: '/prompts' },diff --git a/client/src/pages/Settings.jsx b/client/src/pages/Settings.jsxindex c372dcb79d..6768a81f67 100644--- a/client/src/pages/Settings.jsx+++ b/client/src/pages/Settings.jsx@@ -11,6 +11,7 @@ import EmbeddingsTab from '../components/settings/EmbeddingsTab';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 { MortalLoomTab } from '../components/settings/MortalLoomTab';import { SecurityTab } from '../components/settings/SecurityTab';import { SharingTab } from '../components/settings/SharingTab';@@ -35,6 +36,7 @@ export default function Settings() {const renderTabContent = () => {switch (activeTab) {case 'general': return <GeneralTab />;+ case 'imessage': return <IMessageTab />;case 'ai-assignments': return <AiAssignmentsTab />;case 'api-access': return <ApiAccessTab />;case 'autofixer': return <AutofixerTab />;diff --git a/client/src/services/apiMessages.js b/client/src/services/apiMessages.jsindex 87c23caf0e..b24b02a901 100644--- a/client/src/services/apiMessages.js+++ b/client/src/services/apiMessages.js@@ -46,6 +46,11 @@ export const clearMessageCache = (accountId) =>request(`/messages/accounts/${accountId}/cache/clear`, { method: 'POST' });export const enableGmailApi = () => request('/messages/gmail/enable-api', { method: 'POST' });+// iMessage ingestion (#2151) — read-only chat.db sync, tribe + timeline feed.+export const getImessageStatus = (options = {}) => request('/imessage/status', options);+export const checkImessageSetup = (options = {}) => request('/imessage/setup-check', options);+export const syncImessage = (options = {}) => request('/imessage/sync', { method: 'POST', ...options });+// Feeds - RSS/Atom Feed Ingestionexport const getFeeds = () => request('/feeds');export const getFeedStats = (options = {}) => request('/feeds/stats', options);diff --git a/scripts/migrations/163-tribe-people-phones.js b/scripts/migrations/163-tribe-people-phones.jsnew file mode 100644index 0000000000..0f1669d8f3--- /dev/null+++ b/scripts/migrations/163-tribe-people-phones.js@@ -0,0 +1,26 @@+/**+ * Registration stub for the `tribe_people.phones` column + GIN index (issue #2151).+ *+ * The actual DDL — `ALTER TABLE tribe_people ADD COLUMN IF NOT EXISTS phones+ * TEXT[] DEFAULT '{}'` plus `CREATE INDEX IF NOT EXISTS idx_tribe_people_phones+ * ... USING gin (phones)` — is idempotent and lives in `ensureSchema()`+ * (`server/lib/db.js`), which runs at server boot AFTER the DB pool is up. The+ * `scripts/migrations/` runner executes BEFORE the pool is initialized, so a+ * DDL statement cannot live here — the same reason migrations 048–052, 108, and+ * 161 are boot-time + stub-registered.+ *+ * This stub exists so the schema change is *registered the standard way*: it+ * lands in `data/migrations.applied.json` so the migration ledger and `git log`+ * show when `tribe_people.phones` was introduced. The column is additive+ * (mirroring the existing `emails[]`), defaults to `'{}'`, and needs no data+ * backfill — the iMessage sync (#2151) and the Tribe person editor populate it+ * going forward.+ *+ * No-op + idempotent: nothing to do here.+ */++export default {+ async up() {+ console.log('📞 tribe_people.phones: column + GIN index created idempotently by ensureSchema at boot; nothing to do in the file runner');+ },+};diff --git a/server/index.js b/server/index.jsindex b4ca1c164f..0a5d1db426 100644--- a/server/index.js+++ b/server/index.js@@ -48,6 +48,7 @@ import catalogRoutes from './routes/catalog.js';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 notificationsRoutes from './routes/notifications.js';import standardizeRoutes from './routes/standardize.js';import brainRoutes from './routes/brain.js';@@ -168,6 +169,7 @@ import * as agentActionExecutor from './services/agentActionExecutor.js';import * as cos from './services/cos.js';import { startBackupScheduler } from './services/backupScheduler.js';import { startCitySnapshotScheduler } from './services/citySnapshotScheduler.js';+import { startImessageScheduler } from './services/imessageScheduler.js';import * as telegram from './services/telegram.js';import * as telegramBridge from './services/telegramBridge.js';import { getSettings as getInitSettings } from './services/settings.js';@@ -473,6 +475,7 @@ app.use('/api/catalog', catalogRoutes);app.use('/api/memory', memoryRoutes);app.use('/api/tribe', tribeRoutes);app.use('/api/timeline', timelineRoutes);+app.use('/api/imessage', imessageRoutes);app.use('/api/notifications', notificationsRoutes);app.use('/api/standardize', standardizeRoutes);app.use('/api/brain/import', brainImportRoutes);@@ -597,6 +600,9 @@ startBackupScheduler().catch(err => console.error(`❌ Backup scheduler init fai// Initialize CyberCity snapshot scheduler — records periodic city-state frames// for the historical timeline scrubber (issue #877).startCitySnapshotScheduler().catch(err => console.error(`❌ City snapshot scheduler init failed: ${err.message}`));+// Initialize iMessage sync scheduler — OFF by default; only polls chat.db when+// the user opts in via Settings → iMessage (needs macOS Full Disk Access) (#2151).+startImessageScheduler().catch(err => console.error(`❌ iMessage sync scheduler init failed: ${err.message}`));// Periodically GC orphan zero-issue/zero-canon importer shells left by an// abandoned analyze (issue #727).startOrphanShellGc();diff --git a/server/lib/README.md b/server/lib/README.mdindex b11e0a1d70..6b357194bf 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -235,7 +235,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `platform.js` | Platform/OS detection helpers — listening-port probes plus `isAppleSilicon()` (arm64 darwin; gates MLX model features, detect at the route boundary). || `timezone.js` | Timezone utilities for scheduling. || `tribeCadence.js` | Authoritative, pure Tribe care-cadence rules (single source of truth, mirrored to `client/src/lib/tribeCadence.js`): `cadenceStatus(entity)` → `{ state: external/missing/overdue/soon/steady, daysRemaining, daysOverdue }`, `daysSinceDate(dateStr)`, `DEFAULT_CADENCE_DAYS` (45), `SOON_WINDOW_DAYS` (7). Consumed by `personCadenceStatus` / `getCareSummary` in `services/tribe.js` (proactive alert + Care widget) and by the client Tribe page/map. |-| `tribeMatch.js` | Pure, deterministic matcher mapping a calendar attendee / message counterpart (`{ email, name }`) to a tracked Tribe person for auto-logged touchpoints (#2033): `buildPersonMatchIndex(people)` → `{ byIdentifier, byName }`, `matchPerson(identity, index)` (email/handle authoritative, exact unique name fallback — no fuzzy matching), `matchPeople(identities, index)` → de-duplicated Set of personIds, `normalizeIdentifier(value)`. Consumed by `autoLogTouchpoints` in `services/tribe.js` from the calendar and message sync producers. |+| `tribeMatch.js` | Pure, deterministic matcher mapping a calendar attendee / message counterpart (`{ email, phone, name }`) to a tracked Tribe person for auto-logged touchpoints (#2033, #2151): `buildPersonMatchIndex(people)` → `{ byIdentifier, byPhone, byName }`, `matchPerson(identity, index)` (email/handle authoritative, then E.164 phone, then exact unique name fallback — no fuzzy matching), `matchPeople(identities, index)` → de-duplicated Set of personIds, `normalizeIdentifier(value)`, `normalizePhone(value)` (E.164 normalization for iMessage/Signal handles), `identityFromHandle(handle)` (classify a raw `chat.db` handle into email-or-phone). Consumed by `autoLogTouchpoints` in `services/tribe.js` from the calendar, message, and iMessage sync producers. || `viteAllowedHosts.js` | Detect and remediate a managed app's Vite `server.allowedHosts`. `findViteConfig(repoPath)` locates the config; `parseAllowedHosts(src)` / `hostIsAllowed(parsed, host)` decide whether a Tailscale/IP host would be accepted (mirrors Vite's localhost+IP-always-allowed and leading-dot-suffix rules); `rewriteAllowedHosts(src)` deterministically injects `allowedHosts: true` (or bails `ok:false` on ambiguous shapes so the caller can fall back to an LLM fix); `checkViteHost(repoPath, host)` is the one-shot status used by `GET /api/apps/:id/vite-host-check`. || `buildId.js` | Build-ID derived from the built client bundle. |diff --git a/server/lib/db.js b/server/lib/db.jsindex a061edd774..907d479cc7 100644--- a/server/lib/db.js+++ b/server/lib/db.js@@ -375,9 +375,14 @@ async function ensureSchemaImpl() {// calendar attendee / message counterpart back to this tracked person so// touchpoints can be auto-logged (#2033).`ALTER TABLE tribe_people ADD COLUMN IF NOT EXISTS emails TEXT[] DEFAULT '{}'`,+ // Known phone handles for a person — the deterministic key that maps an+ // iMessage/Signal handle (E.164, e.g. +15551234567) back to this tracked+ // person so touchpoints can be auto-logged (#2151). Mirrors emails[].+ `ALTER TABLE tribe_people ADD COLUMN IF NOT EXISTS phones TEXT[] DEFAULT '{}'`,`CREATE INDEX IF NOT EXISTS idx_tribe_people_live ON tribe_people (deleted, ring, updated_at DESC)`,`CREATE INDEX IF NOT EXISTS idx_tribe_people_tags ON tribe_people USING gin (tags)`,`CREATE INDEX IF NOT EXISTS idx_tribe_people_emails ON tribe_people USING gin (emails)`,+ `CREATE INDEX IF NOT EXISTS idx_tribe_people_phones ON tribe_people USING gin (phones)`,`CREATE TABLE IF NOT EXISTS tribe_touchpoints (id UUID PRIMARY KEY DEFAULT gen_random_uuid(),person_id UUID NOT NULL REFERENCES tribe_people(id) ON DELETE CASCADE,diff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.jsindex a46499c310..0becffa949 100644--- a/server/lib/mediaValidation.js+++ b/server/lib/mediaValidation.js@@ -20,6 +20,15 @@ export const citySnapshotConfigSchema = z.object({maxSnapshots: z.number().int().min(10).max(100000).optional()});+// iMessage ingestion config (#2151) — the `settings.imessage` slice. Sync is OFF+// by default and only reads chat.db when enabled (needs macOS Full Disk Access).+// Validated as a settings slice on PUT /api/settings; service-side DEFAULT_CONFIG+// fills any absent field so an install with no `imessage` key still resolves.+export const imessageConfigSchema = z.object({+ enabled: z.boolean().optional(),+ intervalMinutes: z.number().int().min(1).max(1440).optional()+});+// Shared LoRA-training parameter bounds — used by both the settings-slice// defaults and the per-run override on POST /api/lora-training/runs.const loraTrainingParamsSchema = z.object({diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 11c7d14e60..8cc0a80db5 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -174,6 +174,7 @@ export const NAV_COMMANDS = [{ 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'] },+ { id: 'nav.settings.imessage', path: '/settings/imessage', label: 'iMessage', section: 'Settings', aliases: ['settings-imessage', 'imessage', 'imessage-settings'], keywords: ['imessage', 'sync', 'chat.db', 'sms', 'texts', 'tribe', 'timeline', 'full disk access'] },{ id: 'nav.settings.local-llm', path: '/settings/local-llm', label: 'Local LLMs', section: 'Settings', aliases: ['local-llm', 'local-llms', 'ollama', 'lm-studio', 'lmstudio'], keywords: ['ollama', 'lm studio', 'local model', 'local llm', 'gguf', 'pull model', 'install model', 'migrate', 'switch backend'] },{ id: 'nav.settings.local-llm-playground', path: '/local-llm/playground', label: 'Local LLM Playground', section: 'Settings', aliases: ['llm-playground', 'playground', 'model-playground', 'compare-models'], keywords: ['ollama', 'lm studio', 'compare', 'benchmark', 'chat', 'test model', 'ttft', 'tokens per second', 'local llm'] },{ id: 'nav.settings.mortalloom', path: '/settings/mortalloom', label: 'MortalLoom', section: 'Settings', aliases: ['settings-mortalloom', 'mortalloom'] },diff --git a/server/lib/tribeMatch.js b/server/lib/tribeMatch.jsindex ecb2c354c5..ed0841c6ae 100644--- a/server/lib/tribeMatch.js+++ b/server/lib/tribeMatch.js@@ -16,14 +16,56 @@ export function normalizeIdentifier(value) {return String(value).trim().toLowerCase();}+/**+ * Normalize a phone handle to a stable E.164-ish key so a person's stored phone+ * matches an iMessage/Signal handle (`chat.db` stores handles as either an email+ * or an E.164 phone like `+15551234567`). Deterministic, no external library:+ *+ * - strip every character except digits and a leading `+`;+ * - a value that already carries a `+` country code passes through as `+<digits>`;+ * - a bare 11-digit US number starting with `1` gets a `+` (`15551234567` → `+15551234567`);+ * - a bare 10-digit US number is assumed NANP and prefixed `+1` (`5551234567` → `+15551234567`);+ * - anything else (already-international bare digits, short codes) is returned as+ * `+<digits>` so two spellings of the same number still collide.+ *+ * Returns `''` when there is no usable digit sequence. An `@`-bearing value is NOT+ * a phone — callers route those through `normalizeIdentifier` (email path) instead.+ */+export function normalizePhone(value) {+ if (value == null) return '';+ const raw = String(value).trim();+ if (!raw || raw.includes('@')) return '';+ const hasPlus = raw.startsWith('+');+ const digits = raw.replace(/\D/g, '');+ if (!digits) return '';+ if (hasPlus) return `+${digits}`;+ if (digits.length === 11 && digits.startsWith('1')) return `+${digits}`;+ if (digits.length === 10) return `+1${digits}`;+ return `+${digits}`;+}++/**+ * Classify a raw handle (from an iMessage/Signal `chat.db` `handle.id`, or a+ * calendar/message counterpart) into `{ email, phone }` — exactly one is set.+ * A value containing `@` is an email; otherwise it's treated as a phone.+ */+export function identityFromHandle(handle) {+ const raw = handle == null ? '' : String(handle).trim();+ if (!raw) return {};+ if (raw.includes('@')) return { email: normalizeIdentifier(raw) };+ const phone = normalizePhone(raw);+ return phone ? { phone } : {};+}+/*** Build lookup indexes from a list of tribe people. Returns- * `{ byIdentifier: Map<email, personId>, byName: Map<name, personId[]> }`.- * The first person to claim an identifier wins (identifiers are meant to be- * unique to one person); names collect every owner so ambiguity is detectable.+ * `{ byIdentifier: Map<email, personId>, byPhone: Map<e164, personId>, byName: Map<name, personId[]> }`.+ * The first person to claim an identifier/phone wins (they're meant to be unique+ * to one person); names collect every owner so ambiguity is detectable.*/export function buildPersonMatchIndex(people = []) {const byIdentifier = new Map();+ const byPhone = new Map();const byName = new Map();for (const person of people) {if (!person?.id) continue;@@ -31,6 +73,10 @@ export function buildPersonMatchIndex(people = []) {const key = normalizeIdentifier(identifier);if (key && !byIdentifier.has(key)) byIdentifier.set(key, person.id);}+ for (const rawPhone of person.phones || []) {+ const key = normalizePhone(rawPhone);+ if (key && !byPhone.has(key)) byPhone.set(key, person.id);+ }const nameKey = normalizeIdentifier(person.name);if (nameKey) {const owners = byName.get(nameKey) || [];@@ -38,17 +84,19 @@ export function buildPersonMatchIndex(people = []) {byName.set(nameKey, owners);}}- return { byIdentifier, byName };+ return { byIdentifier, byPhone, byName };}/**- * Resolve a single `{ email, name }` identity to a personId, or `null`.- * Email/handle wins; exact unique name is the fallback.+ * Resolve a single `{ email, phone, name }` identity to a personId, or `null`.+ * Email/handle wins, then phone (E.164-normalized), then exact unique name.*/export function matchPerson(identity, index) {if (!identity || !index) return null;const email = normalizeIdentifier(identity.email);if (email && index.byIdentifier.has(email)) return index.byIdentifier.get(email);+ const phone = normalizePhone(identity.phone);+ if (phone && index.byPhone?.has(phone)) return index.byPhone.get(phone);const name = normalizeIdentifier(identity.name);if (name) {const owners = index.byName.get(name);@@ -58,16 +106,18 @@ export function matchPerson(identity, index) {}/**- * Resolve many identities (mixed `{ email, name }` objects or bare email/handle- * strings) to a de-duplicated Set of personIds. A single event/message that- * involves the same tracked person twice (organizer + attendee) yields one id.+ * Resolve many identities (mixed `{ email, phone, name }` objects or bare+ * email/handle strings) to a de-duplicated Set of personIds. A single+ * event/message that involves the same tracked person twice (organizer ++ * attendee) yields one id. A bare string is classified as email-or-phone via+ * `identityFromHandle`, so a raw `+15551234567` handle resolves by phone.*/export function matchPeople(identities = [], index) {const ids = new Set();if (!index) return ids;for (const raw of identities) {if (!raw) continue;- const identity = typeof raw === 'string' ? { email: raw } : raw;+ const identity = typeof raw === 'string' ? identityFromHandle(raw) : raw;const id = matchPerson(identity, index);if (id) ids.add(id);}diff --git a/server/lib/tribeMatch.test.js b/server/lib/tribeMatch.test.jsindex 82349097cb..8714542fc7 100644--- a/server/lib/tribeMatch.test.js+++ b/server/lib/tribeMatch.test.js@@ -1,6 +1,8 @@import { describe, it, expect } from 'vitest';import {normalizeIdentifier,+ normalizePhone,+ identityFromHandle,buildPersonMatchIndex,matchPerson,matchPeople,@@ -8,11 +10,11 @@ import {const PEOPLE = [{ id: 'ada', name: 'Ada Lovelace', emails: ['[email protected]', '[email protected]'] },- { id: 'grace', name: 'Grace Hopper', emails: ['[email protected]'] },+ { id: 'grace', name: 'Grace Hopper', emails: ['[email protected]'], phones: ['+1 (555) 123-4567'] },// Two people share the first name "Sam" — an ambiguous name must not resolve.{ id: 'sam1', name: 'Sam', emails: [] },{ id: 'sam2', name: 'Sam', emails: [] },- { id: 'lin', name: 'Lin', emails: [] },+ { id: 'lin', name: 'Lin', emails: [], phones: ['5559876543'] },];describe('tribeMatch', () => {@@ -26,6 +28,41 @@ describe('tribeMatch', () => {});});+ describe('normalizePhone', () => {+ it('passes through an explicit + country code, stripping punctuation', () => {+ expect(normalizePhone('+1 (555) 123-4567')).toBe('+15551234567');+ expect(normalizePhone('+44 20 7946 0958')).toBe('+442079460958');+ });+ it('prefixes + on an 11-digit US number starting with 1', () => {+ expect(normalizePhone('15551234567')).toBe('+15551234567');+ });+ it('assumes +1 for a bare 10-digit NANP number', () => {+ expect(normalizePhone('555-123-4567')).toBe('+15551234567');+ expect(normalizePhone('5551234567')).toBe('+15551234567');+ });+ it('collides two spellings of the same number', () => {+ expect(normalizePhone('(555) 123 4567')).toBe(normalizePhone('+1 555 123 4567'));+ });+ it('is empty for an email or an empty/nullish value', () => {+ expect(normalizePhone('[email protected]')).toBe('');+ expect(normalizePhone('')).toBe('');+ expect(normalizePhone(null)).toBe('');+ });+ });++ describe('identityFromHandle', () => {+ it('classifies an @-bearing handle as an email', () => {+ expect(identityFromHandle('[email protected]')).toEqual({ email: '[email protected]' });+ });+ it('classifies a phone handle as an E.164 phone', () => {+ expect(identityFromHandle('+1 (555) 123-4567')).toEqual({ phone: '+15551234567' });+ });+ it('returns an empty object for a blank handle', () => {+ expect(identityFromHandle('')).toEqual({});+ expect(identityFromHandle(null)).toEqual({});+ });+ });+describe('buildPersonMatchIndex', () => {it('indexes every email case-insensitively, first claimant wins', () => {const { byIdentifier } = buildPersonMatchIndex(PEOPLE);@@ -38,6 +75,11 @@ describe('tribeMatch', () => {expect(byName.get('sam')).toEqual(['sam1', 'sam2']);expect(byName.get('lin')).toEqual(['lin']);});+ it('indexes phones E.164-normalized, first claimant wins', () => {+ const { byPhone } = buildPersonMatchIndex(PEOPLE);+ expect(byPhone.get('+15551234567')).toBe('grace');+ expect(byPhone.get('+15559876543')).toBe('lin');+ });it('skips people without an id', () => {const { byIdentifier } = buildPersonMatchIndex([{ name: 'X', emails: ['[email protected]'] }]);expect(byIdentifier.size).toBe(0);@@ -52,6 +94,14 @@ describe('tribeMatch', () => {it('falls back to an exact unique name when no email match', () => {expect(matchPerson({ name: 'lin' }, index)).toBe('lin');});+ it('matches by phone (E.164-normalized) when no email', () => {+ expect(matchPerson({ phone: '555-123-4567' }, index)).toBe('grace');+ expect(matchPerson({ phone: '+15559876543' }, index)).toBe('lin');+ });+ it('prefers email over phone', () => {+ // email → grace, phone → lin. Email wins.+ expect(matchPerson({ email: '[email protected]', phone: '5559876543' }, index)).toBe('grace');+ });it('refuses an ambiguous name (multiple owners)', () => {expect(matchPerson({ name: 'Sam' }, index)).toBeNull();});@@ -81,6 +131,13 @@ describe('tribeMatch', () => {expect(ids.has('lin')).toBe(true);expect(ids.size).toBe(2);});+ it('classifies a bare phone-handle string and matches by phone', () => {+ // A raw chat.db handle like "+15551234567" resolves to the person by phone.+ const ids = matchPeople(['+1 (555) 123-4567', '5559876543'], index);+ expect(ids.has('grace')).toBe(true);+ expect(ids.has('lin')).toBe(true);+ expect(ids.size).toBe(2);+ });it('drops unmatched and empty identities', () => {const ids = matchPeople([null, '', { email: '[email protected]' }, { name: 'Sam' }], index);expect(ids.size).toBe(0);diff --git a/server/routes/imessage.js b/server/routes/imessage.jsnew file mode 100644index 0000000000..b1de47b728--- /dev/null+++ b/server/routes/imessage.js@@ -0,0 +1,30 @@+import { Router } from 'express';++import { asyncHandler } from '../lib/errorHandler.js';+import * as imessageSync from '../services/imessageSync.js';++const router = Router();++// Setup check — attempt a read-only open of chat.db and report an actionable+// Full Disk Access error when blocked. Never throws (checkSetup returns a report),+// so a denied macOS TCC prompt surfaces as a clean JSON error the UI can render.+router.get('/setup-check', asyncHandler(async (req, res) => {+ const report = await imessageSync.checkSetup();+ res.json(report);+}));++// Status — current config (enabled/interval) + machine-local cursor state. No+// chat.db open, so this is cheap and safe to poll from the settings tab.+router.get('/status', asyncHandler(async (req, res) => {+ const status = await imessageSync.getStatus();+ res.json(status);+}));++// Run one incremental sync pass now (explicit user action). Returns the pass+// summary, or a Full-Disk-Access error report when chat.db can't be opened.+router.post('/sync', asyncHandler(async (req, res) => {+ const result = await imessageSync.runSync();+ res.json(result);+}));++export default router;diff --git a/server/routes/settings.js b/server/routes/settings.jsindex 9737dda247..95ad3524cc 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -10,7 +10,7 @@ import {} from '../services/mediaJobQueue/index.js';import { asyncHandler } from '../lib/errorHandler.js';import { isPlainObject } from '../lib/objects.js';-import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, validateRequest } from '../lib/validation.js';+import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, validateRequest } from '../lib/validation.js';const router = Router();@@ -148,6 +148,11 @@ router.put('/', asyncHandler(async (req, res) => {if (req.body?.citySnapshots !== undefined) {validateRequest(citySnapshotConfigSchema.partial(), req.body.citySnapshots);}+ // iMessage ingestion config (#2151) — validate the slice when present so a+ // malformed enabled/interval can't reach disk and break the sync scheduler.+ if (req.body?.imessage !== undefined) {+ validateRequest(imessageConfigSchema.partial(), req.body.imessage);+ }// LoRA training config (caption provider + training defaults) — validate// the slice when present so a malformed save can't write bad bounds the// trainer would then pass to the python child.diff --git a/server/routes/tribe.js b/server/routes/tribe.jsindex 88015ef80a..0370bb2456 100644--- a/server/routes/tribe.js+++ b/server/routes/tribe.js@@ -25,6 +25,10 @@ const personSchema = z.object({// counterparts to this person (#2033). Service-side `normalizeEmails` lowercases// and de-duplicates; the UI splits its single-line input to an array like tags.emails: z.array(z.string().max(320)).max(100).optional().default([]),+ // Known phone handles used to auto-match iMessage/Signal counterparts to this+ // person (#2151). Service-side `normalizePhones` E.164-normalizes and+ // de-duplicates; the UI splits its single-line input to an array like tags.+ phones: z.array(z.string().max(40)).max(100).optional().default([]),nextMove: z.string().max(2000).optional().default(''),notes: z.string().max(10000).optional().default(''),});diff --git a/server/services/imessageScheduler.js b/server/services/imessageScheduler.jsnew file mode 100644index 0000000000..fde7e5a82d--- /dev/null+++ b/server/services/imessageScheduler.js@@ -0,0 +1,54 @@+/**+ * iMessage Sync Scheduler (#2151)+ *+ * Registers an interval job that periodically runs the incremental iMessage+ * ingestion (see imessageSync.js). Mirrors the citySnapshotScheduler pattern.+ *+ * OFF by default: the scheduler is only registered when the user has opted in via+ * Settings → iMessage (`settings.imessage.enabled`). Reading chat.db needs macOS+ * Full Disk Access, so we never poll it silently. The interval value is locked in+ * at registration (changing it needs a restart), but the `enabled` toggle is+ * re-read on every tick so disabling from settings stops runs without a restart.+ *+ * No LLM calls happen on this path — ingestion is deterministic — so the+ * no-cold-bootstrap AI policy does not gate it; the opt-in is purely about Full+ * Disk Access + user intent.+ */++import { schedule } from './eventScheduler.js';+import { getImessageConfig, runSync } from './imessageSync.js';++const EVENT_ID = 'imessage-sync';++/**+ * Start the iMessage sync scheduler. No-ops when disabled in settings.+ */+export async function startImessageScheduler() {+ const { enabled, intervalMinutes } = await getImessageConfig();++ if (!enabled) {+ console.log('💬 iMessage sync scheduler: disabled in settings — skipping');+ return;+ }++ const intervalMs = intervalMinutes * 60 * 1000;++ schedule({+ id: EVENT_ID,+ type: 'interval',+ intervalMs,+ handler: async () => {+ // Re-read settings each run so an `enabled: false` toggle takes effect+ // without a restart (the interval value itself is locked at registration).+ const current = await getImessageConfig();+ if (!current.enabled) {+ console.log('💬 iMessage sync scheduler: disabled since registration — skipping run');+ return;+ }+ await runSync();+ },+ metadata: { source: 'imessageScheduler' },+ });++ console.log(`💬 iMessage sync scheduler: registered every ${intervalMinutes}min`);+}diff --git a/server/services/imessageSync.js b/server/services/imessageSync.jsnew file mode 100644index 0000000000..9ae217b865--- /dev/null+++ b/server/services/imessageSync.js@@ -0,0 +1,429 @@+/**+ * iMessage ingestion (#2151) — read the local macOS Messages database+ * (`~/Library/Messages/chat.db`) and feed both the Tribe touchpoint log and the+ * machine-local human-activity timeline (#2150).+ *+ * Design constraints (see docs/plans/2026-07-04-human-activity-tracking.md):+ *+ * - **Zero new dependencies.** SQLite reads use Node's built-in `node:sqlite`+ * (Node ≥22). The DB is opened `readOnly: true` — we NEVER write to Apple's DB.+ * - **Machine-local.** The incremental cursor lives in a `data/` JSON file, not a+ * federated store — chat.db is per-machine. Derived events land in the+ * already-machine-local `human_activity_events` table.+ * - **LLM-free + idempotent.** Deterministic identity matching via `tribeMatch`;+ * every event/touchpoint carries a stable dedupe key so re-syncs are no-ops.+ * - **Best-effort text.** When `message.text` is NULL, the body is extracted from+ * the archived `attributedBody` typedstream; a parse failure is counted and+ * skipped, never fatal.+ * - **Full Disk Access.** Opening chat.db requires the node/PM2 process to have+ * macOS Full Disk Access; `checkSetup()` reports an actionable error when blocked.+ *+ * The pure mappers (epoch conversion, typedstream decode, candidate mapping) are+ * exported and unit-tested with fixtures — no real chat.db required.+ */+import { DatabaseSync } from 'node:sqlite';++import { expandHome, dataPath, atomicWrite, tryReadFile, safeJSONParse } from '../lib/fileUtils.js';+import { getUserTimezone } from '../lib/timezone.js';+import { identityFromHandle } from '../lib/tribeMatch.js';+import { shortSummary, localDayKey } from './humanActivity.js';+import { getSettings } from './settings.js';++// ---------------------------------------------------------------------------+// Constants+// ---------------------------------------------------------------------------++// Milliseconds between the Unix epoch (1970-01-01) and the Apple/Cocoa epoch+// (2001-01-01 UTC). `message.date` is measured from the Apple epoch.+const APPLE_EPOCH_OFFSET_MS = 978307200000;++// The default location of the macOS Messages database. Overridable via env for+// tests / non-default home layouts. `expandHome` resolves the leading `~/`.+const DEFAULT_CHAT_DB = '~/Library/Messages/chat.db';++const STATE_FILE = 'imessage-sync-state.json';++// Config defaults — surfaced via getImessageConfig(). Sync is OFF by default;+// the user opts in from Settings → iMessage. Reading chat.db needs Full Disk+// Access, so we never enable it silently.+const DEFAULT_CONFIG = {+ enabled: false,+ intervalMinutes: 30,+};++// How many messages to pull per sync pass. Bounds memory + keeps a first sync on+// a huge history from blocking; the ROWID cursor means the next pass resumes.+const SCAN_LIMIT = 5000;++// ---------------------------------------------------------------------------+// Pure helpers (exported for unit tests — no DB, no filesystem, no side effects)+// ---------------------------------------------------------------------------++/**+ * Convert an Apple `message.date` value to a JS Date, or `null` when unusable.+ *+ * Modern macOS (10.13+) stores nanoseconds since the Apple epoch; legacy stores+ * whole seconds. A post-2001 nanosecond value is ~1e17+, a seconds value is+ * ~1e8–1e9, so a `1e12` threshold cleanly separates the two. (Sub-millisecond+ * precision is irrelevant here and Number is plenty accurate at second scale.)+ */+export function appleDateToDate(value) {+ if (value == null) return null;+ const n = typeof value === 'bigint' ? Number(value) : Number(value);+ if (!Number.isFinite(n) || n === 0) return null;+ const seconds = Math.abs(n) >= 1e12 ? n / 1e9 : n;+ const ms = APPLE_EPOCH_OFFSET_MS + seconds * 1000;+ const d = new Date(ms);+ return Number.isNaN(d.getTime()) ? null : d;+}++/**+ * Best-effort plain-text extraction from an archived `attributedBody` typedstream+ * (the `streamtyped` NSAttributedString blob Messages stores when `text` is NULL).+ * Returns the message string, or `null` when the blob can't be parsed — the caller+ * counts a decode failure and skips the row rather than erroring the whole sync.+ *+ * Heuristic (matches the well-known imessage-exporter approach): locate the+ * `NSString` class marker, then the length-prefixed UTF-8 payload after the `+`+ * (0x2b) start-of-value marker. Lengths use typedstream's varint-ish prefix:+ * a byte < 0x80 is the length; 0x81 = uint16-LE follows; 0x82 = uint32-LE follows.+ */+export function decodeAttributedBody(buffer) {+ if (!buffer || !buffer.length) return null;+ const buf = Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer);+ const marker = buf.indexOf('NSString', 0, 'latin1');+ if (marker === -1) return null;+ let i = buf.indexOf(0x2b, marker); // '+' — start-of-value marker+ if (i === -1) return null;+ i += 1;+ if (i >= buf.length) return null;+ let len = buf[i];+ i += 1;+ if (len === 0x81) {+ if (i + 1 >= buf.length) return null;+ len = buf[i] | (buf[i + 1] << 8);+ i += 2;+ } else if (len === 0x82) {+ if (i + 3 >= buf.length) return null;+ len = buf[i] | (buf[i + 1] << 8) | (buf[i + 2] << 16) | (buf[i + 3] * 0x1000000);+ i += 4;+ } else if (len > 0x80) {+ return null; // an encoding we don't handle — best-effort skip+ }+ if (len <= 0 || i + len > buf.length) return null;+ const text = buf.toString('utf8', i, i + len).trim();+ return text || null;+}++/**+ * Resolve a normalized message record's body text: the plain `text` column when+ * present, else a best-effort decode of `attributedBody`. Returns+ * `{ text, decodeFailed }` — `decodeFailed` is true only when `text` was NULL AND+ * the attributedBody blob existed but could not be parsed (so the caller can tally+ * skips without treating an empty-body message as a failure).+ */+export function resolveMessageText(row) {+ if (row?.text != null && String(row.text).length > 0) {+ return { text: String(row.text), decodeFailed: false };+ }+ if (row?.attributedBody && row.attributedBody.length) {+ const decoded = decodeAttributedBody(row.attributedBody);+ if (decoded != null) return { text: decoded, decodeFailed: false };+ return { text: '', decodeFailed: true };+ }+ return { text: '', decodeFailed: false };+}++/**+ * Map one normalized message record to a human-activity candidate, or `null`.+ * `msg`: { guid, rowid, at: Date, text, isFromMe, handle, chatGuid, chatName,+ * service, participants: string[] }+ * Dedupe key is `imsg:<message.guid>` (one activity event per message).+ */+export function imessageActivityCandidate(msg) {+ if (!msg?.guid || !(msg.at instanceof Date) || Number.isNaN(msg.at.getTime())) return null;+ const kind = msg.isFromMe ? 'message.sent' : 'message.received';+ const counterpart = msg.isFromMe ? '' : (msg.handle || '');+ const participants = (msg.participants || [])+ .map(identityFromHandle)+ .filter((p) => p && (p.email || p.phone));+ return {+ source: 'imessage',+ accountId: null,+ kind,+ happenedAt: msg.at.toISOString(),+ title: msg.chatName || counterpart || 'iMessage',+ summary: shortSummary(msg.text || ''),+ participants,+ dedupeKey: `imsg:${msg.guid}`,+ metadata: {+ chatGuid: msg.chatGuid || null,+ service: msg.service || null,+ handle: counterpart || null,+ rowid: msg.rowid ?? null,+ },+ };+}++export function imessageActivityCandidates(messages = []) {+ return (messages || []).map(imessageActivityCandidate).filter(Boolean);+}++/**+ * Group message records into Tribe touchpoint candidates — one per (chat, local+ * day) so a busy thread logs a single daily touchpoint per matched person. Each+ * candidate's `identities` are the chat's participant handles (classified as+ * email-or-phone), matched deterministically to tracked people downstream.+ * Dedupe key is `imsg:<chatGuid>:<localDay>` (mirrors the `msg:` convention).+ */+export function imessageTouchpointCandidates(messages = [], timezone) {+ const byKey = new Map();+ for (const msg of messages || []) {+ if (!(msg?.at instanceof Date) || Number.isNaN(msg.at.getTime())) continue;+ if (!msg.chatGuid) continue;+ const day = localDayKey(msg.at, timezone);+ if (!day) continue;+ const key = `${msg.chatGuid} ${day}`;+ let entry = byKey.get(key);+ if (!entry) {+ entry = { chatGuid: msg.chatGuid, day, at: msg.at, name: msg.chatName || '', handles: new Set() };+ byKey.set(key, entry);+ }+ for (const h of msg.participants || []) if (h) entry.handles.add(h);+ if (msg.at > entry.at) entry.at = msg.at; // latest instant in the day+ }+ const out = [];+ for (const entry of byKey.values()) {+ const identities = [...entry.handles]+ .map(identityFromHandle)+ .filter((p) => p && (p.email || p.phone));+ if (identities.length === 0) continue;+ out.push({+ identities,+ source: 'imessage',+ happenedAt: entry.at.toISOString(),+ channel: 'iMessage',+ summary: entry.name || 'iMessage conversation',+ dedupeKey: `imsg:${entry.chatGuid}:${entry.day}`,+ metadata: { chatGuid: entry.chatGuid, day: entry.day },+ });+ }+ return out;+}++// ---------------------------------------------------------------------------+// Config + machine-local cursor state+// ---------------------------------------------------------------------------++export async function getImessageConfig() {+ const settings = await getSettings().catch(() => ({}));+ const c = settings?.imessage || {};+ return {+ enabled: typeof c.enabled === 'boolean' ? c.enabled : DEFAULT_CONFIG.enabled,+ intervalMinutes: Number.isFinite(c.intervalMinutes) && c.intervalMinutes >= 1+ ? Math.floor(c.intervalMinutes)+ : DEFAULT_CONFIG.intervalMinutes,+ };+}++function stateFilePath() {+ return dataPath(STATE_FILE);+}++// Machine-local incremental cursor. NOT federated — chat.db and its ROWIDs are+// per-machine, so this state must never sync to a peer.+export async function readSyncState() {+ const raw = await tryReadFile(stateFilePath());+ const parsed = raw ? safeJSONParse(raw, null, { allowArray: false }) : null;+ return {+ cursorRowid: Number.isFinite(parsed?.cursorRowid) ? parsed.cursorRowid : 0,+ lastRunAt: parsed?.lastRunAt || null,+ lastResult: parsed?.lastResult || null,+ };+}++async function writeSyncState(state) {+ await atomicWrite(stateFilePath(), JSON.stringify(state, null, 2));+}++// ---------------------------------------------------------------------------+// chat.db access (side-effecting — try/catch is sanctioned here: this runs+// outside the Express request lifecycle and a native open error must not crash+// the process). We open readOnly and never mutate Apple's database.+// ---------------------------------------------------------------------------++export function chatDbPath() {+ return expandHome(process.env.IMESSAGE_CHAT_DB || DEFAULT_CHAT_DB);+}++// Classify a chat.db open failure so the UI can surface an actionable message.+// A macOS sandbox / TCC denial surfaces as EPERM/EACCES or SQLite "unable to+// open database file" (SQLITE_CANTOPEN) — all of which mean Full Disk Access is+// missing for the running process.+function isFullDiskAccessError(err) {+ const msg = String(err?.message || '').toLowerCase();+ return err?.code === 'EACCES'+ || err?.code === 'EPERM'+ || msg.includes('unable to open')+ || msg.includes('not authorized')+ || msg.includes('operation not permitted');+}++const FDA_REMEDIATION = 'Grant Full Disk Access to the process running PortOS (node or the PM2 daemon): System Settings → Privacy & Security → Full Disk Access → enable your terminal / node / pm2, then restart PortOS.';++/**+ * Attempt to open chat.db read-only and run a trivial probe query. Returns a+ * structured report — never throws — so the setup-check route can render an+ * actionable Full Disk Access error when blocked.+ */+export async function checkSetup() {+ const path = chatDbPath();+ let db;+ try {+ db = new DatabaseSync(path, { readOnly: true });+ const row = db.prepare('SELECT COUNT(*) AS n FROM message').get();+ return { ok: true, dbPath: path, messageCount: Number(row?.n || 0) };+ } catch (err) {+ const fullDiskAccessRequired = isFullDiskAccessError(err);+ return {+ ok: false,+ dbPath: path,+ error: err?.message || 'Failed to open chat.db',+ fullDiskAccessRequired,+ remediation: fullDiskAccessRequired ? FDA_REMEDIATION : `Could not read ${path}: ${err?.message || 'unknown error'}`,+ };+ } finally {+ try { db?.close(); } catch { /* already closed / never opened */ }+ }+}++// Read a batch of messages after `cursorRowid` plus the chat→participants map.+// Returns normalized message records (the shape the pure mappers consume) and the+// max ROWID seen. Kept separate from runSync so the SQL boundary is small and the+// mapping stays pure/testable.+function readMessages(db, cursorRowid, limit) {+ const partRows = db.prepare(+ `SELECT c.guid AS chat_guid, h.id AS handle+ FROM chat c+ JOIN chat_handle_join chj ON chj.chat_id = c.ROWID+ JOIN handle h ON h.ROWID = chj.handle_id`,+ ).all();+ const participantsByChat = new Map();+ for (const r of partRows) {+ if (!r.chat_guid || !r.handle) continue;+ const list = participantsByChat.get(r.chat_guid) || [];+ list.push(r.handle);+ participantsByChat.set(r.chat_guid, list);+ }++ // `m.date` is nanoseconds since 2001 on modern macOS — a value that exceeds+ // Number.MAX_SAFE_INTEGER, which node:sqlite REFUSES to return as a JS number+ // (throws ERR_OUT_OF_RANGE). CAST it to TEXT so it comes back as a decimal+ // string; appleDateToDate parses it (second-scale precision is all we need).+ const rows = db.prepare(+ `SELECT m.ROWID AS rowid, m.guid, CAST(m.date AS TEXT) AS date, m.text, m.attributedBody,+ m.is_from_me AS is_from_me, m.service,+ h.id AS handle,+ c.guid AS chat_guid, c.display_name AS chat_name, c.chat_identifier+ FROM message m+ JOIN chat_message_join cmj ON cmj.message_id = m.ROWID+ JOIN chat c ON c.ROWID = cmj.chat_id+ LEFT JOIN handle h ON h.ROWID = m.handle_id+ WHERE m.ROWID > ?+ ORDER BY m.ROWID ASC+ LIMIT ?`,+ ).all(cursorRowid, limit);++ let maxRowid = cursorRowid;+ let decodeFailures = 0;+ const messages = [];+ for (const row of rows) {+ const rowid = Number(row.rowid);+ if (rowid > maxRowid) maxRowid = rowid;+ const at = appleDateToDate(row.date);+ if (!at) continue;+ const { text, decodeFailed } = resolveMessageText(row);+ if (decodeFailed) decodeFailures += 1;+ const chatGuid = row.chat_guid || null;+ const participants = chatGuid ? (participantsByChat.get(chatGuid) || []) : [];+ // Fall back to the message sender's handle when the chat has no join rows.+ if (participants.length === 0 && row.handle) participants.push(row.handle);+ messages.push({+ guid: row.guid,+ rowid,+ at,+ text,+ isFromMe: Number(row.is_from_me) === 1,+ handle: row.handle || '',+ chatGuid,+ chatName: row.chat_name || row.chat_identifier || '',+ service: row.service || null,+ participants,+ });+ }+ return { messages, maxRowid, scanned: rows.length, decodeFailures };+}++/**+ * Run one incremental sync pass: read new messages after the stored ROWID cursor,+ * record activity events + Tribe touchpoints, and advance the cursor. Returns a+ * summary. Safe to call repeatedly — dedupe keys make re-ingestion a no-op. This+ * runs outside the request lifecycle (scheduler / explicit endpoint), so the+ * chat.db open is try/catch-guarded and returns an error report instead of throwing.+ */+export async function runSync() {+ const state = await readSyncState();+ const path = chatDbPath();+ let db;+ let batch;+ try {+ db = new DatabaseSync(path, { readOnly: true });+ batch = readMessages(db, state.cursorRowid, SCAN_LIMIT);+ } catch (err) {+ const fullDiskAccessRequired = isFullDiskAccessError(err);+ console.error(`❌ iMessage sync failed to open chat.db: ${err?.message || err}`);+ return {+ ok: false,+ error: err?.message || 'Failed to open chat.db',+ fullDiskAccessRequired,+ remediation: fullDiskAccessRequired ? FDA_REMEDIATION : undefined,+ };+ } finally {+ try { db?.close(); } catch { /* noop */ }+ }++ const timezone = await getUserTimezone();+ const { recordEvents } = await import('./humanActivity.js');+ const tribe = await import('./tribe.js');++ const activityCandidates = imessageActivityCandidates(batch.messages);+ const touchpointCandidates = imessageTouchpointCandidates(batch.messages, timezone);++ const activityResult = await recordEvents(activityCandidates).catch((err) => {+ console.error(`❌ iMessage activity record failed: ${err?.message || err}`);+ return { recorded: 0, skipped: activityCandidates.length };+ });+ const touchpointResult = await tribe.autoLogTouchpoints(touchpointCandidates).catch((err) => {+ console.error(`❌ iMessage touchpoint log failed: ${err?.message || err}`);+ return { created: 0, matched: 0 };+ });++ const result = {+ ok: true,+ scanned: batch.scanned,+ recorded: activityResult.recorded,+ touchpointsCreated: touchpointResult.created,+ touchpointsMatched: touchpointResult.matched,+ decodeFailures: batch.decodeFailures,+ cursorRowid: batch.maxRowid,+ };+ await writeSyncState({ cursorRowid: batch.maxRowid, lastRunAt: new Date().toISOString(), lastResult: result });+ console.log(`💬 iMessage sync: scanned ${result.scanned}, recorded ${result.recorded} event(s), ${result.touchpointsCreated} touchpoint(s), ${result.decodeFailures} decode-skip(s), cursor→${result.cursorRowid}`);+ return result;+}++// Status for the settings UI: config + cursor state (no chat.db open).+export async function getStatus() {+ const [config, state] = await Promise.all([getImessageConfig(), readSyncState()]);+ return { config, state };+}diff --git a/server/services/imessageSync.test.js b/server/services/imessageSync.test.jsnew file mode 100644index 0000000000..e11c9105f2--- /dev/null+++ b/server/services/imessageSync.test.js@@ -0,0 +1,192 @@+import { describe, it, expect } from 'vitest';+import {+ appleDateToDate,+ decodeAttributedBody,+ resolveMessageText,+ imessageActivityCandidate,+ imessageActivityCandidates,+ imessageTouchpointCandidates,+} from './imessageSync.js';++// Milliseconds between the Unix epoch and the Apple/Cocoa epoch (2001-01-01 UTC).+const APPLE_EPOCH_OFFSET_MS = 978307200000;++// Build a minimal typedstream-ish attributedBody blob the decoder understands:+// some preamble, the "NSString" class marker, a '+' start-of-value marker, then a+// length prefix + UTF-8 payload. `len < 0x80` uses the single-byte form; larger+// strings use the 0x81 uint16-LE form.+function makeAttributedBody(text) {+ const payload = Buffer.from(text, 'utf8');+ const preamble = Buffer.from('streamtyped\x81\xe8\x03\x84\x01\x40\x84\x84\x84NSString\x01\x94\x84\x01\x2b', 'latin1');+ let lenBytes;+ if (payload.length < 0x80) {+ lenBytes = Buffer.from([payload.length]);+ } else {+ lenBytes = Buffer.from([0x81, payload.length & 0xff, (payload.length >> 8) & 0xff]);+ }+ return Buffer.concat([preamble, lenBytes, payload, Buffer.from('\x86', 'latin1')]);+}++describe('imessageSync pure helpers', () => {+ describe('appleDateToDate', () => {+ const known = Date.UTC(2021, 0, 1, 0, 0, 0); // 2021-01-01T00:00:00Z+ const appleSeconds = (known - APPLE_EPOCH_OFFSET_MS) / 1000;++ it('converts modern nanosecond values (ns since 2001)', () => {+ const ns = appleSeconds * 1e9;+ const d = appleDateToDate(ns);+ expect(d).toBeInstanceOf(Date);+ expect(d.getTime()).toBe(known);+ });+ it('converts legacy second values (s since 2001)', () => {+ const d = appleDateToDate(appleSeconds);+ expect(d.getTime()).toBe(known);+ });+ it('handles a decimal STRING value (the runtime shape — date is CAST to TEXT in SQL)', () => {+ // node:sqlite refuses to return the >2^53 ns integer as a number, so the+ // query CASTs it to TEXT; appleDateToDate must parse that decimal string.+ const d = appleDateToDate(String(appleSeconds * 1e9));+ expect(d.getTime()).toBe(known);+ expect(appleDateToDate(String(appleSeconds))).toEqual(new Date(known)); // legacy seconds as string+ });+ it('handles a bigint nanosecond value (node:sqlite may return BigInt)', () => {+ const d = appleDateToDate(BigInt(Math.round(appleSeconds)) * 1000000000n);+ // second-level accuracy is all we need+ expect(Math.round(d.getTime() / 1000)).toBe(Math.round(known / 1000));+ });+ it('returns null for 0 / null / non-finite', () => {+ expect(appleDateToDate(0)).toBeNull();+ expect(appleDateToDate(null)).toBeNull();+ expect(appleDateToDate(undefined)).toBeNull();+ expect(appleDateToDate(NaN)).toBeNull();+ expect(appleDateToDate('not a number')).toBeNull();+ });+ });++ describe('decodeAttributedBody', () => {+ it('extracts a short single-byte-length string', () => {+ expect(decodeAttributedBody(makeAttributedBody('hello world'))).toBe('hello world');+ });+ it('extracts a long string via the 0x81 uint16-LE length prefix', () => {+ const long = 'x'.repeat(300);+ expect(decodeAttributedBody(makeAttributedBody(long))).toBe(long);+ });+ it('extracts UTF-8 multibyte content', () => {+ expect(decodeAttributedBody(makeAttributedBody('café ☕️ 日本語'))).toBe('café ☕️ 日本語');+ });+ it('returns null when the blob has no NSString marker (parse failure)', () => {+ expect(decodeAttributedBody(Buffer.from('garbage-without-marker'))).toBeNull();+ });+ it('returns null for empty / nullish input', () => {+ expect(decodeAttributedBody(Buffer.alloc(0))).toBeNull();+ expect(decodeAttributedBody(null)).toBeNull();+ expect(decodeAttributedBody(undefined)).toBeNull();+ });+ });++ describe('resolveMessageText', () => {+ it('prefers the plain text column when present', () => {+ expect(resolveMessageText({ text: 'plain body', attributedBody: makeAttributedBody('archived') }))+ .toEqual({ text: 'plain body', decodeFailed: false });+ });+ it('falls back to a decoded attributedBody when text is NULL', () => {+ expect(resolveMessageText({ text: null, attributedBody: makeAttributedBody('archived') }))+ .toEqual({ text: 'archived', decodeFailed: false });+ });+ it('flags decodeFailed when text is NULL and the blob is unparseable', () => {+ const r = resolveMessageText({ text: null, attributedBody: Buffer.from('no-marker-here') });+ expect(r.text).toBe('');+ expect(r.decodeFailed).toBe(true);+ });+ it('is not a failure when there is neither text nor attributedBody', () => {+ expect(resolveMessageText({ text: null, attributedBody: null }))+ .toEqual({ text: '', decodeFailed: false });+ });+ });++ describe('imessageActivityCandidate', () => {+ const at = new Date('2024-03-10T15:30:00.000Z');+ const base = {+ guid: 'ABC-123',+ rowid: 42,+ at,+ text: 'hey there',+ chatGuid: 'iMessage;-;+15551234567',+ chatName: 'Grace',+ service: 'iMessage',+ handle: '+15551234567',+ participants: ['+15551234567'],+ };++ it('maps a received message with the imsg:<guid> dedupe key', () => {+ const c = imessageActivityCandidate({ ...base, isFromMe: false });+ expect(c.source).toBe('imessage');+ expect(c.kind).toBe('message.received');+ expect(c.dedupeKey).toBe('imsg:ABC-123');+ expect(c.happenedAt).toBe(at.toISOString());+ expect(c.participants).toEqual([{ phone: '+15551234567' }]);+ expect(c.metadata.chatGuid).toBe('iMessage;-;+15551234567');+ });+ it('maps a sent message to message.sent', () => {+ const c = imessageActivityCandidate({ ...base, isFromMe: true, handle: '' });+ expect(c.kind).toBe('message.sent');+ });+ it('returns null when guid or timestamp is missing/invalid', () => {+ expect(imessageActivityCandidate({ ...base, guid: '' })).toBeNull();+ expect(imessageActivityCandidate({ ...base, at: new Date('nope') })).toBeNull();+ expect(imessageActivityCandidate(null)).toBeNull();+ });+ it('imessageActivityCandidates filters out invalid rows', () => {+ const list = imessageActivityCandidates([+ { ...base, isFromMe: false },+ { ...base, guid: '' },+ ]);+ expect(list).toHaveLength(1);+ });+ });++ describe('imessageTouchpointCandidates', () => {+ const tz = 'America/New_York';+ // Both instants fall on 2024-03-10 in America/New_York.+ const m1 = {+ guid: 'g1', at: new Date('2024-03-10T14:00:00.000Z'), chatGuid: 'chat-A',+ chatName: 'Grace', isFromMe: false, handle: '+15551234567', participants: ['+15551234567'],+ };+ const m2 = {+ guid: 'g2', at: new Date('2024-03-10T18:00:00.000Z'), chatGuid: 'chat-A',+ chatName: 'Grace', isFromMe: true, handle: '', participants: ['+15551234567'],+ };+ // Next local day, same chat.+ const m3 = {+ guid: 'g3', at: new Date('2024-03-12T02:00:00.000Z'), chatGuid: 'chat-A',+ chatName: 'Grace', isFromMe: false, handle: '+15551234567', participants: ['+15551234567'],+ };++ it('collapses a chat/day to ONE touchpoint with imsg:<chatGuid>:<localDay>', () => {+ const out = imessageTouchpointCandidates([m1, m2], tz);+ expect(out).toHaveLength(1);+ expect(out[0].dedupeKey).toBe('imsg:chat-A:2024-03-10');+ expect(out[0].source).toBe('imessage');+ expect(out[0].channel).toBe('iMessage');+ expect(out[0].identities).toEqual([{ phone: '+15551234567' }]);+ // happenedAt is the latest instant within the day.+ expect(out[0].happenedAt).toBe(m2.at.toISOString());+ });+ it('emits a separate touchpoint per local day', () => {+ const out = imessageTouchpointCandidates([m1, m3], tz);+ const keys = out.map((c) => c.dedupeKey).sort();+ expect(keys).toEqual(['imsg:chat-A:2024-03-10', 'imsg:chat-A:2024-03-11']);+ });+ it('drops entries with no resolvable participant handles', () => {+ const out = imessageTouchpointCandidates([{ ...m1, participants: [] }], tz);+ expect(out).toHaveLength(0);+ });+ it('skips rows without a chatGuid or a valid timestamp', () => {+ const out = imessageTouchpointCandidates([+ { ...m1, chatGuid: null },+ { ...m1, at: new Date('bad') },+ ], tz);+ expect(out).toHaveLength(0);+ });+ });+});diff --git a/server/services/tribe.js b/server/services/tribe.jsindex b19859edb3..51408f7659 100644--- a/server/services/tribe.js+++ b/server/services/tribe.js@@ -16,7 +16,7 @@ import { v4 as uuidv4 } from '../lib/uuid.js';import { ensureSchema, query, withTransaction } from '../lib/db.js';import { ServerError } from '../lib/errorHandler.js';import { cadenceStatus } from '../lib/tribeCadence.js';-import { buildPersonMatchIndex, matchPeople, normalizeIdentifier } from '../lib/tribeMatch.js';+import { buildPersonMatchIndex, matchPeople, normalizeIdentifier, normalizePhone } from '../lib/tribeMatch.js';import * as calendarSync from './calendarSync.js';// Default check-in cadence (days) per ring. Mirrored on the client in@@ -68,6 +68,20 @@ export function normalizeEmails(emails) {return [...seen];}+// Phone handles used to match a person to iMessage/Signal counterparts (#2151).+// E.164-normalized + de-duplicated so matching (which also normalizes) is stable.+export function normalizePhones(phones) {+ const list = Array.isArray(phones)+ ? phones+ : (phones == null ? [] : String(phones).split(','));+ const seen = new Set();+ for (const raw of list) {+ const key = normalizePhone(raw);+ if (key) seen.add(key);+ }+ return [...seen];+}+export function rowToPerson(row) {return {id: row.id,@@ -81,6 +95,7 @@ export function rowToPerson(row) {energy: row.energy || 'steady',tags: row.tags || [],emails: row.emails || [],+ phones: row.phones || [],nextMove: row.next_move || '',notes: row.notes || '',touchpointCount: Number(row.touchpoint_count || 0),@@ -227,8 +242,8 @@ export async function createPerson(data) {const result = await query(`INSERT INTO tribe_people (id, name, relationship, ring, cadence_days, last_contact_on, channel,- energy, tags, emails, next_move, notes, updated_at- ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,NOW())+ energy, tags, emails, phones, next_move, notes, updated_at+ ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,NOW())RETURNING *, 0 AS touchpoint_count, 0 AS linked_memory_count`,[id,@@ -241,6 +256,7 @@ export async function createPerson(data) {data.energy || 'steady',normalizeTags(data.tags),normalizeEmails(data.emails),+ normalizePhones(data.phones),data.nextMove || '',data.notes || '',],@@ -264,8 +280,9 @@ export async function updatePerson(id, updates) {energy = $8,tags = $9,emails = $10,- next_move = $11,- notes = $12,+ phones = $11,+ next_move = $12,+ notes = $13,updated_at = NOW()WHERE id = $1 AND deleted = FALSERETURNING *,@@ -282,6 +299,7 @@ export async function updatePerson(id, updates) {next.energy || 'steady',normalizeTags(next.tags),normalizeEmails(next.emails),+ normalizePhones(next.phones),next.nextMove || '',next.notes || '',],