Skip to content

Personal AI, On Personal Devices

Python

feat: add Apple Contacts connector (macOS AddressBook) (#248)

Andrew Park54d79ef23520
diff --git a/frontend/src/pages/DataSourcesPage.tsx b/frontend/src/pages/DataSourcesPage.tsx
index be729b74..37043b6f 100644
--- a/frontend/src/pages/DataSourcesPage.tsx
+++ b/frontend/src/pages/DataSourcesPage.tsx
@@ -281,7 +281,7 @@ const iconMap: Record<string, string> = {
gmail: '\u2709\uFE0F', gmail_imap: '\u2709\uFE0F', gmail_api: '\u2709\uFE0F', slack: '#',
imessage: '\uD83D\uDCAC', gdrive: '\uD83D\uDCC1', notion: '\uD83D\uDCC4',
obsidian: '\uD83D\uDCC1', granola: '\uD83C\uDF99\uFE0F', gcalendar: '\uD83D\uDCC5',
- gcontacts: '\uD83D\uDCC7', outlook: '\u2709\uFE0F', apple_notes: '\uD83C\uDF4E',
+ gcontacts: '\uD83D\uDCC7', apple_contacts: 'πŸ“‡', outlook: '\u2709\uFE0F', apple_notes: '\uD83C\uDF4E',
dropbox: '\uD83D\uDCE6', whatsapp: '\uD83D\uDCF1', upload: '\uD83D\uDCC2',
};
diff --git a/frontend/src/types/connectors.ts b/frontend/src/types/connectors.ts
index 48af7daa..cb212be6 100644
--- a/frontend/src/types/connectors.ts
+++ b/frontend/src/types/connectors.ts
@@ -359,6 +359,27 @@ export const SOURCE_CATALOG: ConnectorMeta[] = [
},
],
},
+ {
+ connector_id: 'apple_contacts',
+ display_name: 'Apple Contacts',
+ auth_type: 'local',
+ category: 'pim',
+ icon: 'Users',
+ color: 'text-orange-400',
+ description: 'macOS Contacts app',
+ unitLabel: 'contacts',
+ steps: [
+ {
+ label: 'Open the Apple menu () β†’ System Settings β†’ Privacy & Security (in the left sidebar) β†’ scroll down and click "Full Disk Access"',
+ },
+ {
+ label: 'Click the "+" button at the bottom of the list. Navigate to Applications β†’ Utilities β†’ select "Terminal.app" (or iTerm2/Warp if you use those). If you\'re using the desktop app, also add "OpenJarvis.app" from Applications',
+ },
+ {
+ label: 'Toggle the switch ON next to each app you added. Close and reopen your terminal (or restart OpenJarvis). Apple Contacts will be detected automatically β€” no credentials needed',
+ },
+ ],
+ },
{
connector_id: 'outlook',
display_name: 'Outlook',
diff --git a/src/openjarvis/connectors/__init__.py b/src/openjarvis/connectors/__init__.py
index 2c59dee8..6aa3ad2c 100644
--- a/src/openjarvis/connectors/__init__.py
+++ b/src/openjarvis/connectors/__init__.py
@@ -58,6 +58,11 @@ try:
except ImportError:
pass
+try:
+ import openjarvis.connectors.apple_contacts # noqa: F401
+except ImportError:
+ pass
+
try:
import openjarvis.connectors.slack_connector # noqa: F401
except ImportError:
diff --git a/src/openjarvis/connectors/apple_contacts.py b/src/openjarvis/connectors/apple_contacts.py
new file mode 100644
index 00000000..4213bdfd
--- /dev/null
+++ b/src/openjarvis/connectors/apple_contacts.py
@@ -0,0 +1,482 @@
+"""Apple Contacts connector β€” reads directly from the macOS Contacts SQLite database.
+
+No API calls, no OAuth. The connector opens
+``~/Library/Application Support/AddressBook/AddressBook-v22.abcddb``
+in read-only mode and yields one :class:`Document` per contact.
+
+Requires **Full Disk Access** granted to the terminal / app in
+System Settings β†’ Privacy & Security β†’ Full Disk Access.
+
+Timestamp notes
+---------------
+The Contacts database stores timestamps as seconds since the Apple epoch
+of 2001-01-01 00:00:00 UTC.
+"""
+
+from __future__ import annotations
+
+import sqlite3
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+from typing import Any, Dict, Iterator, List, Optional
+
+from openjarvis.connectors._stubs import BaseConnector, Document, SyncStatus
+from openjarvis.core.registry import ConnectorRegistry
+from openjarvis.tools._stubs import ToolSpec
+
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+_ADDRESSBOOK_DIR = Path.home() / "Library" / "Application Support" / "AddressBook"
+
+_DEFAULT_DB_PATH = _ADDRESSBOOK_DIR / "AddressBook-v22.abcddb"
+
+_DB_FILENAME = "AddressBook-v22.abcddb"
+
+# Apple epoch: 2001-01-01 00:00:00 UTC
+_APPLE_EPOCH = datetime(2001, 1, 1, tzinfo=timezone.utc)
+
+# Apple Contacts stores labels in the format _$!<Label>!$_
+_LABEL_PREFIX = "_$!<"
+_LABEL_SUFFIX = ">!$_"
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _apple_ts_to_datetime(apple_seconds: float) -> datetime:
+ """Convert an Apple seconds timestamp to a UTC datetime."""
+ return _APPLE_EPOCH + timedelta(seconds=apple_seconds)
+
+
+def _clean_label(raw: str | None) -> str:
+ """Strip Apple's internal label markup (``_$!<Work>!$_`` β†’ ``Work``)."""
+ if not raw:
+ return ""
+ if raw.startswith(_LABEL_PREFIX) and raw.endswith(_LABEL_SUFFIX):
+ return raw[len(_LABEL_PREFIX) : -len(_LABEL_SUFFIX)]
+ return raw
+
+
+def _build_name(first: str, middle: str, last: str, org: str) -> str:
+ """Build a display name from name components."""
+ parts = [p for p in (first, middle, last) if p]
+ name = " ".join(parts)
+ if not name and org:
+ return org
+ return name
+
+
+def _format_address(
+ street: str, city: str, state: str, zipcode: str, country: str
+) -> str:
+ """Format a postal address into a single string."""
+ line1 = street or ""
+ parts2 = [p for p in (city, state) if p]
+ line2 = ", ".join(parts2)
+ if zipcode:
+ line2 = f"{line2} {zipcode}".strip()
+ if country:
+ line2 = f"{line2}, {country}".strip(", ")
+ lines = [part for part in (line1, line2) if part]
+ return "\n".join(lines)
+
+
+# ---------------------------------------------------------------------------
+# SQL queries
+# ---------------------------------------------------------------------------
+
+_CONTACTS_QUERY = """\
+SELECT r.Z_PK,
+ r.ZFIRSTNAME,
+ r.ZMIDDLENAME,
+ r.ZLASTNAME,
+ r.ZORGANIZATION,
+ r.ZJOBTITLE,
+ r.ZDEPARTMENT,
+ r.ZNICKNAME,
+ r.ZBIRTHDAY,
+ r.ZCREATIONDATE,
+ r.ZMODIFICATIONDATE,
+ r.ZUNIQUEID
+FROM ZABCDRECORD r
+WHERE r.ZFIRSTNAME IS NOT NULL
+ OR r.ZLASTNAME IS NOT NULL
+ OR r.ZORGANIZATION IS NOT NULL
+ORDER BY r.ZMODIFICATIONDATE ASC
+"""
+
+_PHONES_QUERY = """\
+SELECT ZFULLNUMBER, ZLABEL FROM ZABCDPHONENUMBER WHERE ZOWNER = ?
+ORDER BY ZORDERINGINDEX
+"""
+
+_EMAILS_QUERY = """\
+SELECT ZADDRESS, ZLABEL FROM ZABCDEMAILADDRESS WHERE ZOWNER = ?
+ORDER BY ZORDERINGINDEX
+"""
+
+_ADDRESSES_QUERY = """\
+SELECT ZSTREET, ZCITY, ZSTATE, ZZIPCODE, ZCOUNTRYNAME, ZLABEL
+FROM ZABCDPOSTALADDRESS WHERE ZOWNER = ?
+ORDER BY ZORDERINGINDEX
+"""
+
+_URLS_QUERY = """\
+SELECT ZURL, ZLABEL FROM ZABCDURLADDRESS WHERE ZOWNER = ?
+ORDER BY ZORDERINGINDEX
+"""
+
+_SOCIAL_QUERY = """\
+SELECT ZUSERNAME, ZSERVICENAME, ZLABEL FROM ZABCDSOCIALPROFILE WHERE ZOWNER = ?
+ORDER BY ZORDERINGINDEX
+"""
+
+_NOTES_QUERY = """\
+SELECT ZTEXT FROM ZABCDNOTE WHERE ZCONTACT = ?
+"""
+
+_SEARCH_QUERY = """\
+SELECT r.Z_PK,
+ r.ZFIRSTNAME,
+ r.ZMIDDLENAME,
+ r.ZLASTNAME,
+ r.ZORGANIZATION,
+ r.ZJOBTITLE,
+ r.ZDEPARTMENT,
+ r.ZNICKNAME,
+ r.ZMODIFICATIONDATE,
+ r.ZUNIQUEID
+FROM ZABCDRECORD r
+WHERE (r.ZFIRSTNAME LIKE ? OR r.ZLASTNAME LIKE ?
+ OR r.ZORGANIZATION LIKE ? OR r.ZNICKNAME LIKE ?
+ OR r.ZJOBTITLE LIKE ?)
+LIMIT ?
+"""
+
+# ---------------------------------------------------------------------------
+# AppleContactsConnector
+# ---------------------------------------------------------------------------
+
+
[email protected]("apple_contacts")
+class AppleContactsConnector(BaseConnector):
+ """Connector that reads contacts from the macOS Contacts SQLite database.
+
+ Parameters
+ ----------
+ db_path:
+ Path to ``AddressBook-v22.abcddb``. Defaults to
+ ``~/Library/Application Support/AddressBook/AddressBook-v22.abcddb``.
+ """
+
+ connector_id = "apple_contacts"
+ display_name = "Apple Contacts"
+ auth_type = "local"
+
+ def __init__(self, db_path: str = "") -> None:
+ self._db_path: Path = Path(db_path) if db_path else _DEFAULT_DB_PATH
+ self._connected: bool = False
+ self._items_synced: int = 0
+ self._items_total: int = 0
+ self._last_sync: Optional[datetime] = None
+
+ # ------------------------------------------------------------------
+ # Internal helpers
+ # ------------------------------------------------------------------
+
+ def _all_db_paths(self) -> List[Path]:
+ """Return paths to all AddressBook databases (main + iCloud sources).
+
+ macOS stores the local address book at the top level and synced
+ accounts (iCloud, Exchange, etc.) under ``Sources/<UUID>/``.
+ """
+ paths: List[Path] = []
+ # Main database
+ if self._db_path.exists():
+ paths.append(self._db_path)
+ # Source databases (iCloud, Exchange, etc.)
+ sources_dir = self._db_path.parent / "Sources"
+ if sources_dir.is_dir():
+ for child in sorted(sources_dir.iterdir()):
+ candidate = child / _DB_FILENAME
+ if candidate.exists():
+ paths.append(candidate)
+ return paths
+
+ @staticmethod
+ def _open_db(path: Path) -> sqlite3.Connection | None:
+ """Open a Contacts database read-only. Returns None on failure."""
+ try:
+ return sqlite3.connect(f"file:{path}?mode=ro", uri=True)
+ except sqlite3.OperationalError:
+ return None
+
+ def _build_content(
+ self, conn: sqlite3.Connection, pk: int, meta: Dict[str, Any]
+ ) -> str:
+ """Build a human-readable text block for one contact."""
+ lines: List[str] = []
+
+ name = meta.get("name", "")
+ if name:
+ lines.append(name)
+
+ org = meta.get("organization", "")
+ title = meta.get("job_title", "")
+ dept = meta.get("department", "")
+ if org or title:
+ org_parts = [p for p in (title, dept, org) if p]
+ lines.append(" β€” ".join(org_parts))
+
+ nickname = meta.get("nickname", "")
+ if nickname:
+ lines.append(f"Nickname: {nickname}")
+
+ birthday = meta.get("birthday", "")
+ if birthday:
+ lines.append(f"Birthday: {birthday}")
+
+ # Phone numbers
+ phones = conn.execute(_PHONES_QUERY, (pk,)).fetchall()
+ for number, label in phones:
+ if number:
+ lbl = _clean_label(label)
+ prefix = f"{lbl}: " if lbl else ""
+ lines.append(f"Phone {prefix}{number}")
+
+ # Email addresses
+ emails = conn.execute(_EMAILS_QUERY, (pk,)).fetchall()
+ for addr, label in emails:
+ if addr:
+ lbl = _clean_label(label)
+ prefix = f"{lbl}: " if lbl else ""
+ lines.append(f"Email {prefix}{addr}")
+
+ # Postal addresses
+ addresses = conn.execute(_ADDRESSES_QUERY, (pk,)).fetchall()
+ for street, city, state, zipcode, country, label in addresses:
+ formatted = _format_address(
+ street or "",
+ city or "",
+ state or "",
+ zipcode or "",
+ country or "",
+ )
+ if formatted:
+ lbl = _clean_label(label)
+ prefix = f"{lbl}: " if lbl else ""
+ lines.append(f"Address {prefix}{formatted}")
+
+ # URLs
+ urls = conn.execute(_URLS_QUERY, (pk,)).fetchall()
+ for url, label in urls:
+ if url:
+ lbl = _clean_label(label)
+ prefix = f"{lbl}: " if lbl else ""
+ lines.append(f"URL {prefix}{url}")
+
+ # Social profiles
+ socials = conn.execute(_SOCIAL_QUERY, (pk,)).fetchall()
+ for username, service, label in socials:
+ if username:
+ svc = service or _clean_label(label) or ""
+ lines.append(f"Social {svc}: {username}")
+
+ # Notes
+ notes = conn.execute(_NOTES_QUERY, (pk,)).fetchall()
+ for (text,) in notes:
+ if text:
+ lines.append(f"Notes: {text}")
+
+ return "\n".join(lines)
+
+ # ------------------------------------------------------------------
+ # BaseConnector interface
+ # ------------------------------------------------------------------
+
+ def is_connected(self) -> bool:
+ """Return ``True`` if any AddressBook database exists."""
+ return len(self._all_db_paths()) > 0
+
+ def disconnect(self) -> None:
+ """Mark the connector as disconnected."""
+ self._connected = False
+
+ def sync(
+ self,
+ *,
+ since: Optional[datetime] = None,
+ cursor: Optional[str] = None, # noqa: ARG002
+ ) -> Iterator[Document]:
+ """Read contacts from AddressBook and yield one :class:`Document` each.
+
+ Parameters
+ ----------
+ since:
+ If provided, skip contacts whose modification time is before
+ this datetime.
+ cursor:
+ Not used for this local connector (included for API
+ compatibility).
+
+ Yields
+ ------
+ Document
+ One document per contact with all fields as structured text.
+ """
+ db_paths = self._all_db_paths()
+ if not db_paths:
+ return
+
+ seen_ids: set[str] = set()
+ synced = 0
+ total = 0
+
+ for db_path in db_paths:
+ conn = self._open_db(db_path)
+ if conn is None:
+ continue
+
+ try:
+ rows = conn.execute(_CONTACTS_QUERY).fetchall()
+ total += len(rows)
+ self._items_total = total
+
+ for row in rows:
+ pk: int = row[0]
+ first: str = row[1] or ""
+ middle: str = row[2] or ""
+ last: str = row[3] or ""
+ org: str = row[4] or ""
+ job_title: str = row[5] or ""
+ department: str = row[6] or ""
+ nickname: str = row[7] or ""
+ birthday_ts: float | None = row[8]
+ creation_ts: float = row[9] or 0.0
+ mod_ts: float = row[10] or 0.0
+ unique_id: str = row[11] or str(pk)
+
+ # Deduplicate across sources
+ if unique_id in seen_ids:
+ continue
+ seen_ids.add(unique_id)
+
+ timestamp = (
+ _apple_ts_to_datetime(mod_ts)
+ if mod_ts
+ else _apple_ts_to_datetime(creation_ts)
+ )
+
+ # Apply since filter
+ if since is not None:
+ since_utc = since
+ if since_utc.tzinfo is None:
+ since_utc = since_utc.replace(tzinfo=timezone.utc)
+ if timestamp < since_utc:
+ continue
+
+ name = _build_name(first, middle, last, org)
+ birthday = ""
+ if birthday_ts:
+ try:
+ birthday = _apple_ts_to_datetime(birthday_ts).strftime(
+ "%Y-%m-%d"
+ )
+ except (ValueError, OverflowError):
+ pass
+
+ meta: Dict[str, Any] = {
+ "name": name,
+ "first_name": first,
+ "last_name": last,
+ "organization": org,
+ "job_title": job_title,
+ "department": department,
+ "nickname": nickname,
+ "birthday": birthday,
+ }
+
+ content = self._build_content(conn, pk, meta)
+
+ doc = Document(
+ doc_id=f"apple_contacts:{unique_id}",
+ source="apple_contacts",
+ doc_type="contact",
+ content=content,
+ title=name,
+ author=name,
+ timestamp=timestamp,
+ metadata=meta,
+ )
+ synced += 1
+ yield doc
+
+ finally:
+ conn.close()
+
+ self._items_synced = synced
+ self._last_sync = datetime.now(tz=timezone.utc)
+
+ def sync_status(self) -> SyncStatus:
+ """Return sync progress from the most recent :meth:`sync` call."""
+ return SyncStatus(
+ state="idle",
+ items_synced=self._items_synced,
+ items_total=self._items_total,
+ last_sync=self._last_sync,
+ )
+
+ # ------------------------------------------------------------------
+ # MCP tools
+ # ------------------------------------------------------------------
+
+ def mcp_tools(self) -> List[ToolSpec]:
+ """Expose MCP tool specs for real-time Apple Contacts queries."""
+ return [
+ ToolSpec(
+ name="contacts_search",
+ description=(
+ "Search Apple Contacts by name, organization, or job title. "
+ "Returns matching contacts with full details."
+ ),
+ parameters={
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": "Search query string",
+ },
+ "max_results": {
+ "type": "integer",
+ "description": "Maximum number of contacts to return",
+ "default": 20,
+ },
+ },
+ "required": ["query"],
+ },
+ category="knowledge",
+ ),
+ ToolSpec(
+ name="contacts_get_contact",
+ description=(
+ "Retrieve full details of an Apple Contact by its "
+ "unique identifier."
+ ),
+ parameters={
+ "type": "object",
+ "properties": {
+ "contact_id": {
+ "type": "string",
+ "description": (
+ "Apple Contacts unique identifier (ZUNIQUEID)"
+ ),
+ },
+ },
+ "required": ["contact_id"],
+ },
+ category="knowledge",
+ ),
+ ]
diff --git a/tests/connectors/test_apple_contacts.py b/tests/connectors/test_apple_contacts.py
new file mode 100644
index 00000000..d1390d98
--- /dev/null
+++ b/tests/connectors/test_apple_contacts.py
@@ -0,0 +1,626 @@
+"""Tests for AppleContactsConnector β€” local macOS Contacts database connector.
+
+All tests use a temporary SQLite database that mimics the real AddressBook
+schema. No actual macOS Contacts database is required.
+"""
+
+from __future__ import annotations
+
+import sqlite3
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import List
+
+import pytest
+
+from openjarvis.connectors._stubs import Document
+from openjarvis.core.registry import ConnectorRegistry
+
+# ---------------------------------------------------------------------------
+# Helper: create a fake AddressBook database
+# ---------------------------------------------------------------------------
+
+
+def _create_fake_contacts_db(db_path: Path) -> None:
+ """Populate a SQLite file with the Apple Contacts schema and sample rows."""
+ conn = sqlite3.connect(str(db_path))
+ conn.executescript("""
+ CREATE TABLE ZABCDRECORD (
+ Z_PK INTEGER PRIMARY KEY,
+ Z_ENT INTEGER,
+ Z_OPT INTEGER,
+ ZISALL INTEGER,
+ ZTYPE INTEGER,
+ ZFIRSTNAME VARCHAR,
+ ZMIDDLENAME VARCHAR,
+ ZLASTNAME VARCHAR,
+ ZORGANIZATION VARCHAR,
+ ZJOBTITLE VARCHAR,
+ ZDEPARTMENT VARCHAR,
+ ZNICKNAME VARCHAR,
+ ZBIRTHDAY TIMESTAMP,
+ ZCREATIONDATE TIMESTAMP,
+ ZMODIFICATIONDATE TIMESTAMP,
+ ZUNIQUEID VARCHAR
+ );
+
+ CREATE TABLE ZABCDPHONENUMBER (
+ Z_PK INTEGER PRIMARY KEY,
+ Z_ENT INTEGER,
+ Z_OPT INTEGER,
+ ZISPRIMARY INTEGER,
+ ZISPRIVATE INTEGER,
+ ZORDERINGINDEX INTEGER,
+ ZOWNER INTEGER,
+ Z22_OWNER INTEGER,
+ ZFULLNUMBER VARCHAR,
+ ZLABEL VARCHAR,
+ ZUNIQUEID VARCHAR,
+ ZIOSLEGACYIDENTIFIER INTEGER
+ );
+
+ CREATE TABLE ZABCDEMAILADDRESS (
+ Z_PK INTEGER PRIMARY KEY,
+ Z_ENT INTEGER,
+ Z_OPT INTEGER,
+ ZISPRIMARY INTEGER,
+ ZISPRIVATE INTEGER,
+ ZORDERINGINDEX INTEGER,
+ ZOWNER INTEGER,
+ Z22_OWNER INTEGER,
+ ZADDRESS VARCHAR,
+ ZADDRESSNORMALIZED VARCHAR,
+ ZLABEL VARCHAR,
+ ZUNIQUEID VARCHAR,
+ ZIOSLEGACYIDENTIFIER INTEGER
+ );
+
+ CREATE TABLE ZABCDPOSTALADDRESS (
+ Z_PK INTEGER PRIMARY KEY,
+ Z_ENT INTEGER,
+ Z_OPT INTEGER,
+ ZISPRIMARY INTEGER,
+ ZISPRIVATE INTEGER,
+ ZORDERINGINDEX INTEGER,
+ ZOWNER INTEGER,
+ Z22_OWNER INTEGER,
+ ZSTREET VARCHAR,
+ ZCITY VARCHAR,
+ ZSTATE VARCHAR,
+ ZZIPCODE VARCHAR,
+ ZCOUNTRYNAME VARCHAR,
+ ZLABEL VARCHAR,
+ ZUNIQUEID VARCHAR,
+ ZIOSLEGACYIDENTIFIER INTEGER
+ );
+
+ CREATE TABLE ZABCDURLADDRESS (
+ Z_PK INTEGER PRIMARY KEY,
+ Z_ENT INTEGER,
+ Z_OPT INTEGER,
+ ZISPRIMARY INTEGER,
+ ZISPRIVATE INTEGER,
+ ZORDERINGINDEX INTEGER,
+ ZOWNER INTEGER,
+ Z22_OWNER INTEGER,
+ ZLABEL VARCHAR,
+ ZUNIQUEID VARCHAR,
+ ZURL VARCHAR,
+ ZIOSLEGACYIDENTIFIER INTEGER
+ );
+
+ CREATE TABLE ZABCDSOCIALPROFILE (
+ Z_PK INTEGER PRIMARY KEY,
+ Z_ENT INTEGER,
+ Z_OPT INTEGER,
+ ZISPRIMARY INTEGER,
+ ZISPRIVATE INTEGER,
+ ZORDERINGINDEX INTEGER,
+ ZOWNER INTEGER,
+ Z22_OWNER INTEGER,
+ ZUSERNAME VARCHAR,
+ ZSERVICENAME VARCHAR,
+ ZLABEL VARCHAR,
+ ZUNIQUEID VARCHAR,
+ ZIOSLEGACYIDENTIFIER INTEGER
+ );
+
+ CREATE TABLE ZABCDNOTE (
+ Z_PK INTEGER PRIMARY KEY,
+ Z_ENT INTEGER,
+ Z_OPT INTEGER,
+ ZCONTACT INTEGER,
+ Z22_CONTACT INTEGER,
+ ZTEXT VARCHAR
+ );
+ """)
+
+ # ── System row (ZISALL=1, no name β€” should be skipped) ───────────
+ conn.execute(
+ "INSERT INTO ZABCDRECORD "
+ "(Z_PK, ZISALL, ZFIRSTNAME, ZLASTNAME, ZORGANIZATION, "
+ " ZCREATIONDATE, ZMODIFICATIONDATE, ZUNIQUEID) "
+ "VALUES (1, 1, NULL, NULL, NULL, 700000000.0, 700000000.0, 'sys-all')"
+ )
+
+ # ── Contact 1: Alice Smith ───────────────────────────────────────
+ conn.execute(
+ "INSERT INTO ZABCDRECORD "
+ "(Z_PK, ZFIRSTNAME, ZMIDDLENAME, ZLASTNAME, ZORGANIZATION, "
+ " ZJOBTITLE, ZDEPARTMENT, ZNICKNAME, ZBIRTHDAY, "
+ " ZCREATIONDATE, ZMODIFICATIONDATE, ZUNIQUEID) "
+ "VALUES (2, 'Alice', 'M', 'Smith', 'Acme Corp', "
+ " 'Engineer', 'R&D', 'Ali', 694310400.0, "
+ " 694310400.0, 694396800.0, 'uid-alice')"
+ )
+ # Phone
+ conn.execute(
+ "INSERT INTO ZABCDPHONENUMBER "
+ "(Z_PK, ZORDERINGINDEX, ZOWNER, ZFULLNUMBER, ZLABEL) "
+ "VALUES (1, 0, 2, '+1-555-0100', '_$!<Mobile>!$_')"
+ )
+ # Email
+ conn.execute(
+ "INSERT INTO ZABCDEMAILADDRESS "
+ "(Z_PK, ZORDERINGINDEX, ZOWNER, ZADDRESS, ZLABEL) "
+ "VALUES (1, 0, 2, '[email protected]', '_$!<Work>!$_')"
+ )
+ # Address
+ conn.execute(
+ "INSERT INTO ZABCDPOSTALADDRESS "
+ "(Z_PK, ZORDERINGINDEX, ZOWNER, ZSTREET, ZCITY, ZSTATE, "
+ " ZZIPCODE, ZCOUNTRYNAME, ZLABEL) "
+ "VALUES (1, 0, 2, '123 Main St', 'Springfield', 'IL', "
+ " '62704', 'United States', '_$!<Work>!$_')"
+ )
+ # URL
+ conn.execute(
+ "INSERT INTO ZABCDURLADDRESS "
+ "(Z_PK, ZORDERINGINDEX, ZOWNER, ZURL, ZLABEL) "
+ "VALUES (1, 0, 2, 'https://alice.dev', '_$!<HomePage>!$_')"
+ )
+ # Social profile
+ conn.execute(
+ "INSERT INTO ZABCDSOCIALPROFILE "
+ "(Z_PK, ZORDERINGINDEX, ZOWNER, ZUSERNAME, ZSERVICENAME, ZLABEL) "
+ "VALUES (1, 0, 2, '@alicesmith', 'Twitter', NULL)"
+ )
+ # Note
+ conn.execute(
+ "INSERT INTO ZABCDNOTE (Z_PK, ZCONTACT, ZTEXT) "
+ "VALUES (1, 2, 'Met at WWDC 2024')"
+ )
+
+ # ── Contact 2: Acme Corp (org-only, no person name) ─────────────
+ conn.execute(
+ "INSERT INTO ZABCDRECORD "
+ "(Z_PK, ZFIRSTNAME, ZLASTNAME, ZORGANIZATION, "
+ " ZCREATIONDATE, ZMODIFICATIONDATE, ZUNIQUEID) "
+ "VALUES (3, NULL, NULL, 'Acme Corp', "
+ " 694310400.0, 694310400.0, 'uid-acme')"
+ )
+ # Phone
+ conn.execute(
+ "INSERT INTO ZABCDPHONENUMBER "
+ "(Z_PK, ZORDERINGINDEX, ZOWNER, ZFULLNUMBER, ZLABEL) "
+ "VALUES (2, 0, 3, '1-800-ACME', '_$!<Main>!$_')"
+ )
+
+ # ── Contact 3: Bob Jones (minimal β€” name only) ──────────────────
+ conn.execute(
+ "INSERT INTO ZABCDRECORD "
+ "(Z_PK, ZFIRSTNAME, ZLASTNAME, "
+ " ZCREATIONDATE, ZMODIFICATIONDATE, ZUNIQUEID) "
+ "VALUES (4, 'Bob', 'Jones', "
+ " 694400000.0, 694500000.0, 'uid-bob')"
+ )
+
+ conn.commit()
+ conn.close()
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+def fake_db(tmp_path: Path) -> Path:
+ """Return path to a populated fake AddressBook database."""
+ db_path = tmp_path / "AddressBook-v22.abcddb"
+ _create_fake_contacts_db(db_path)
+ return db_path
+
+
+def connector(fake_db: Path):
+ """AppleContactsConnector pointing at the fake DB."""
+ from openjarvis.connectors.apple_contacts import AppleContactsConnector
+
+ return AppleContactsConnector(db_path=str(fake_db))
+
+
+# ---------------------------------------------------------------------------
+# Test 1 β€” is_connected returns True when db_path exists
+# ---------------------------------------------------------------------------
+
+
+def test_is_connected(connector) -> None:
+ """is_connected() returns True when AddressBook database exists."""
+ assert connector.is_connected() is True
+
+
+# ---------------------------------------------------------------------------
+# Test 2 β€” is_connected returns False for a missing file
+# ---------------------------------------------------------------------------
+
+
+def test_not_connected_missing_db() -> None:
+ """is_connected() returns False when the database file does not exist."""
+ from openjarvis.connectors.apple_contacts import AppleContactsConnector
+
+ conn = AppleContactsConnector(db_path="/nonexistent/path/AddressBook.db")
+ assert conn.is_connected() is False
+
+
+# ---------------------------------------------------------------------------
+# Test 3 β€” sync yields 3 contacts (skips system row), correct source/type
+# ---------------------------------------------------------------------------
+
+
+def test_sync_yields_contacts(connector) -> None:
+ """sync() yields one Document per real contact (3 total, skips system row)."""
+ docs: List[Document] = list(connector.sync())
+ assert len(docs) == 3
+ for doc in docs:
+ assert doc.source == "apple_contacts"
+ assert doc.doc_type == "contact"
+
+
+# ---------------------------------------------------------------------------
+# Test 4 β€” sync extracts phone numbers, emails, addresses, URLs, socials
+# ---------------------------------------------------------------------------
+
+
+def test_sync_extracts_all_fields(connector) -> None:
+ """sync() includes phone, email, address, URL, social, and notes in content."""
+ docs: List[Document] = list(connector.sync())
+ alice = next(d for d in docs if d.doc_id == "apple_contacts:uid-alice")
+
+ assert "Alice M Smith" in alice.content
+ assert "+1-555-0100" in alice.content
+ assert "[email protected]" in alice.content
+ assert "123 Main St" in alice.content
+ assert "Springfield" in alice.content
+ assert "https://alice.dev" in alice.content
+ assert "@alicesmith" in alice.content
+ assert "Met at WWDC 2024" in alice.content
+
+
+# ---------------------------------------------------------------------------
+# Test 5 β€” sync cleans Apple label markup
+# ---------------------------------------------------------------------------
+
+
+def test_sync_cleans_labels(connector) -> None:
+ """sync() strips _$!<Label>!$_ markup from content."""
+ docs: List[Document] = list(connector.sync())
+ alice = next(d for d in docs if d.doc_id == "apple_contacts:uid-alice")
+
+ assert "_$!<" not in alice.content
+ assert ">!$_" not in alice.content
+ assert "Mobile" in alice.content
+ assert "Work" in alice.content
+
+
+# ---------------------------------------------------------------------------
+# Test 6 β€” org-only contact uses organization as title
+# ---------------------------------------------------------------------------
+
+
+def test_org_only_contact(connector) -> None:
+ """A contact with only an organization name uses it as the title."""
+ docs: List[Document] = list(connector.sync())
+ acme = next(d for d in docs if d.doc_id == "apple_contacts:uid-acme")
+
+ assert acme.title == "Acme Corp"
+ assert "1-800-ACME" in acme.content
+
+
+# ---------------------------------------------------------------------------
+# Test 7 β€” minimal contact (name only, no other fields)
+# ---------------------------------------------------------------------------
+
+
+def test_minimal_contact(connector) -> None:
+ """A contact with only a name still syncs correctly."""
+ docs: List[Document] = list(connector.sync())
+ bob = next(d for d in docs if d.doc_id == "apple_contacts:uid-bob")
+
+ assert bob.title == "Bob Jones"
+ assert bob.content.strip() == "Bob Jones"
+
+
+# ---------------------------------------------------------------------------
+# Test 8 β€” sync respects the since filter
+# ---------------------------------------------------------------------------
+
+
+def test_sync_since_filter(connector) -> None:
+ """sync(since=...) skips contacts modified before the given datetime."""
+ # Alice was modified at 694396800 (2023-01-03), Bob at 694500000 (2023-01-04)
+ # Acme was modified at 694310400 (2023-01-02)
+ # Pick a cutoff that excludes Alice and Acme but includes Bob
+ cutoff = datetime(2023, 1, 3, 12, 0, 0, tzinfo=timezone.utc)
+ docs: List[Document] = list(connector.sync(since=cutoff))
+
+ ids = {d.doc_id for d in docs}
+ assert "apple_contacts:uid-bob" in ids
+ # Alice's mod date (694396800) is 2023-01-03 00:00:00 UTC, before cutoff
+ assert "apple_contacts:uid-alice" not in ids
+
+
+# ---------------------------------------------------------------------------
+# Test 9 β€” sync_status tracks progress
+# ---------------------------------------------------------------------------
+
+
+def test_sync_status(connector) -> None:
+ """sync_status() reports items_synced and items_total after sync."""
+ list(connector.sync()) # exhaust the generator
+ status = connector.sync_status()
+
+ assert status.items_synced == 3
+ assert status.items_total == 3
+ assert status.last_sync is not None
+
+
+# ---------------------------------------------------------------------------
+# Test 10 β€” metadata contains structured fields
+# ---------------------------------------------------------------------------
+
+
+def test_metadata_fields(connector) -> None:
+ """Documents include structured metadata with name components."""
+ docs: List[Document] = list(connector.sync())
+ alice = next(d for d in docs if d.doc_id == "apple_contacts:uid-alice")
+
+ assert alice.metadata["first_name"] == "Alice"
+ assert alice.metadata["last_name"] == "Smith"
+ assert alice.metadata["organization"] == "Acme Corp"
+ assert alice.metadata["job_title"] == "Engineer"
+ assert alice.metadata["nickname"] == "Ali"
+
+
+# ---------------------------------------------------------------------------
+# Test 11 β€” disconnect sets connected flag to False
+# ---------------------------------------------------------------------------
+
+
+def test_disconnect(connector) -> None:
+ """disconnect() marks the connector as disconnected."""
+ assert connector.is_connected() is True
+ connector.disconnect()
+ assert connector._connected is False
+
+
+# ---------------------------------------------------------------------------
+# Test 12 β€” mcp_tools returns exactly 2 tool specs
+# ---------------------------------------------------------------------------
+
+
+def test_mcp_tools(connector) -> None:
+ """mcp_tools() returns exactly 2 tools with the expected names."""
+ tools = connector.mcp_tools()
+ names = {t.name for t in tools}
+ assert len(tools) == 2
+ assert "contacts_search" in names
+ assert "contacts_get_contact" in names
+
+
+# ---------------------------------------------------------------------------
+# Test 13 β€” ConnectorRegistry contains "apple_contacts" after import
+# ---------------------------------------------------------------------------
+
+
+def test_registry() -> None:
+ """AppleContactsConnector is registered and retrievable."""
+ from openjarvis.connectors.apple_contacts import AppleContactsConnector
+
+ ConnectorRegistry.register_value("apple_contacts", AppleContactsConnector)
+ assert ConnectorRegistry.contains("apple_contacts")
+ cls = ConnectorRegistry.get("apple_contacts")
+ assert cls.connector_id == "apple_contacts"
+
+
+# ---------------------------------------------------------------------------
+# Test 14 β€” sync handles empty database gracefully
+# ---------------------------------------------------------------------------
+
+
+def test_sync_empty_db(tmp_path: Path) -> None:
+ """sync() yields nothing when the database has no contacts."""
+ from openjarvis.connectors.apple_contacts import AppleContactsConnector
+
+ db_path = tmp_path / "Empty.abcddb"
+ conn = sqlite3.connect(str(db_path))
+ conn.executescript("""
+ CREATE TABLE ZABCDRECORD (
+ Z_PK INTEGER PRIMARY KEY, ZFIRSTNAME VARCHAR,
+ ZMIDDLENAME VARCHAR, ZLASTNAME VARCHAR,
+ ZORGANIZATION VARCHAR, ZJOBTITLE VARCHAR,
+ ZDEPARTMENT VARCHAR, ZNICKNAME VARCHAR,
+ ZBIRTHDAY TIMESTAMP, ZCREATIONDATE TIMESTAMP,
+ ZMODIFICATIONDATE TIMESTAMP, ZUNIQUEID VARCHAR
+ );
+ CREATE TABLE ZABCDPHONENUMBER (
+ Z_PK INTEGER PRIMARY KEY, ZOWNER INTEGER,
+ ZORDERINGINDEX INTEGER, ZFULLNUMBER VARCHAR, ZLABEL VARCHAR
+ );
+ CREATE TABLE ZABCDEMAILADDRESS (
+ Z_PK INTEGER PRIMARY KEY, ZOWNER INTEGER,
+ ZORDERINGINDEX INTEGER, ZADDRESS VARCHAR, ZLABEL VARCHAR
+ );
+ CREATE TABLE ZABCDPOSTALADDRESS (
+ Z_PK INTEGER PRIMARY KEY, ZOWNER INTEGER,
+ ZORDERINGINDEX INTEGER, ZSTREET VARCHAR, ZCITY VARCHAR,
+ ZSTATE VARCHAR, ZZIPCODE VARCHAR, ZCOUNTRYNAME VARCHAR,
+ ZLABEL VARCHAR
+ );
+ CREATE TABLE ZABCDURLADDRESS (
+ Z_PK INTEGER PRIMARY KEY, ZOWNER INTEGER,
+ ZORDERINGINDEX INTEGER, ZURL VARCHAR, ZLABEL VARCHAR
+ );
+ CREATE TABLE ZABCDSOCIALPROFILE (
+ Z_PK INTEGER PRIMARY KEY, ZOWNER INTEGER,
+ ZORDERINGINDEX INTEGER, ZUSERNAME VARCHAR,
+ ZSERVICENAME VARCHAR, ZLABEL VARCHAR
+ );
+ CREATE TABLE ZABCDNOTE (
+ Z_PK INTEGER PRIMARY KEY, ZCONTACT INTEGER, ZTEXT VARCHAR
+ );
+ """)
+ conn.close()
+
+ c = AppleContactsConnector(db_path=str(db_path))
+ docs = list(c.sync())
+ assert docs == []
+
+
+# ---------------------------------------------------------------------------
+# Test 15 β€” sync handles missing database gracefully
+# ---------------------------------------------------------------------------
+
+
+def test_sync_missing_db() -> None:
+ """sync() yields nothing when the database file doesn't exist."""
+ from openjarvis.connectors.apple_contacts import AppleContactsConnector
+
+ c = AppleContactsConnector(db_path="/nonexistent/AddressBook.db")
+ docs = list(c.sync())
+ assert docs == []
+
+
+# ---------------------------------------------------------------------------
+# Helper: create a minimal contacts DB with just the required tables
+# ---------------------------------------------------------------------------
+
+_MINIMAL_SCHEMA = """
+ CREATE TABLE ZABCDRECORD (
+ Z_PK INTEGER PRIMARY KEY, ZFIRSTNAME VARCHAR,
+ ZMIDDLENAME VARCHAR, ZLASTNAME VARCHAR,
+ ZORGANIZATION VARCHAR, ZJOBTITLE VARCHAR,
+ ZDEPARTMENT VARCHAR, ZNICKNAME VARCHAR,
+ ZBIRTHDAY TIMESTAMP, ZCREATIONDATE TIMESTAMP,
+ ZMODIFICATIONDATE TIMESTAMP, ZUNIQUEID VARCHAR
+ );
+ CREATE TABLE ZABCDPHONENUMBER (
+ Z_PK INTEGER PRIMARY KEY, ZOWNER INTEGER,
+ ZORDERINGINDEX INTEGER, ZFULLNUMBER VARCHAR, ZLABEL VARCHAR
+ );
+ CREATE TABLE ZABCDEMAILADDRESS (
+ Z_PK INTEGER PRIMARY KEY, ZOWNER INTEGER,
+ ZORDERINGINDEX INTEGER, ZADDRESS VARCHAR, ZLABEL VARCHAR
+ );
+ CREATE TABLE ZABCDPOSTALADDRESS (
+ Z_PK INTEGER PRIMARY KEY, ZOWNER INTEGER,
+ ZORDERINGINDEX INTEGER, ZSTREET VARCHAR, ZCITY VARCHAR,
+ ZSTATE VARCHAR, ZZIPCODE VARCHAR, ZCOUNTRYNAME VARCHAR,
+ ZLABEL VARCHAR
+ );
+ CREATE TABLE ZABCDURLADDRESS (
+ Z_PK INTEGER PRIMARY KEY, ZOWNER INTEGER,
+ ZORDERINGINDEX INTEGER, ZURL VARCHAR, ZLABEL VARCHAR
+ );
+ CREATE TABLE ZABCDSOCIALPROFILE (
+ Z_PK INTEGER PRIMARY KEY, ZOWNER INTEGER,
+ ZORDERINGINDEX INTEGER, ZUSERNAME VARCHAR,
+ ZSERVICENAME VARCHAR, ZLABEL VARCHAR
+ );
+ CREATE TABLE ZABCDNOTE (
+ Z_PK INTEGER PRIMARY KEY, ZCONTACT INTEGER, ZTEXT VARCHAR
+ );
+"""
+
+
+def _create_minimal_db(db_path: Path, contacts: list[tuple]) -> None:
+ """Create a DB with given contacts: [(pk, first, last, org, uid), ...]."""
+ conn = sqlite3.connect(str(db_path))
+ conn.executescript(_MINIMAL_SCHEMA)
+ for pk, first, last, org, uid in contacts:
+ conn.execute(
+ "INSERT INTO ZABCDRECORD "
+ "(Z_PK, ZFIRSTNAME, ZLASTNAME, ZORGANIZATION, "
+ " ZCREATIONDATE, ZMODIFICATIONDATE, ZUNIQUEID) "
+ f"VALUES ({pk}, ?, ?, ?, 694310400.0, 694310400.0, ?)",
+ (first, last, org, uid),
+ )
+ conn.commit()
+ conn.close()
+
+
+# ---------------------------------------------------------------------------
+# Test 16 β€” sync reads contacts from iCloud source databases
+# ---------------------------------------------------------------------------
+
+
+def test_sync_reads_source_databases(tmp_path: Path) -> None:
+ """sync() reads contacts from Sources/<UUID>/ databases."""
+ from openjarvis.connectors.apple_contacts import AppleContactsConnector
+
+ # Main DB with 1 contact
+ main_db = tmp_path / "AddressBook-v22.abcddb"
+ _create_minimal_db(main_db, [(1, "Local", "Contact", None, "uid-local")])
+
+ # Source DB with 2 contacts
+ source_dir = tmp_path / "Sources" / "FAKE-UUID-1"
+ source_dir.mkdir(parents=True)
+ _create_minimal_db(
+ source_dir / "AddressBook-v22.abcddb",
+ [
+ (1, "Cloud", "One", None, "uid-cloud1"),
+ (2, "Cloud", "Two", None, "uid-cloud2"),
+ ],
+ )
+
+ c = AppleContactsConnector(db_path=str(main_db))
+ docs = list(c.sync())
+
+ assert len(docs) == 3
+ ids = {d.doc_id for d in docs}
+ assert "apple_contacts:uid-local" in ids
+ assert "apple_contacts:uid-cloud1" in ids
+ assert "apple_contacts:uid-cloud2" in ids
+
+
+# ---------------------------------------------------------------------------
+# Test 17 β€” sync deduplicates contacts across sources
+# ---------------------------------------------------------------------------
+
+
+def test_sync_deduplicates_across_sources(tmp_path: Path) -> None:
+ """sync() deduplicates contacts that appear in multiple databases."""
+ from openjarvis.connectors.apple_contacts import AppleContactsConnector
+
+ # Main DB with Alice
+ main_db = tmp_path / "AddressBook-v22.abcddb"
+ _create_minimal_db(main_db, [(1, "Alice", "Smith", None, "uid-alice")])
+
+ # Source DB also has Alice (same ZUNIQUEID) + Bob
+ source_dir = tmp_path / "Sources" / "FAKE-UUID-1"
+ source_dir.mkdir(parents=True)
+ _create_minimal_db(
+ source_dir / "AddressBook-v22.abcddb",
+ [
+ (1, "Alice", "Smith", None, "uid-alice"), # duplicate
+ (2, "Bob", "Jones", None, "uid-bob"),
+ ],
+ )
+
+ c = AppleContactsConnector(db_path=str(main_db))
+ docs = list(c.sync())
+
+ assert len(docs) == 2
+ ids = {d.doc_id for d in docs}
+ assert "apple_contacts:uid-alice" in ids
+ assert "apple_contacts:uid-bob" in ids