Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(contacts): profile fields, vCard import/export, honest prompt index

rubenluetke10-beep0b50c671a9ee
diff --git a/jarvis/contacts/store.py b/jarvis/contacts/store.py
index b9973f4602..95003a2a83 100644
--- a/jarvis/contacts/store.py
+++ b/jarvis/contacts/store.py
@@ -26,6 +26,12 @@ Frontmatter layout::
name: Christoph Meyer
aliases: [Chris]
relationship: friend # optional; one of jarvis.contacts.schema
+ favorite: true # only present when true
+ birthday: 1990-04-12 # optional; ISO date
+ organization: ACME GmbH # optional
+ role: CTO # optional
+ urls: [https://example.com] # optional
+ tags: [tennis, uni] # optional; free-form (no enum, no parity duty)
contact:
phones: ['+4915123456789'] # E.164-normalised (separators stripped)
@@ -40,7 +46,7 @@ import os
import re
import tempfile
from dataclasses import dataclass, field
-from datetime import UTC, datetime
+from datetime import UTC, date, datetime
from pathlib import Path
from typing import Any
@@ -69,6 +75,35 @@ def _validate_email(raw: str) -> str:
return s
+def _validate_birthday(raw: str | None) -> str | None:
+ """Return a canonical ``YYYY-MM-DD`` string, ``None`` for blank input, or
+ raise ``ValueError``. ISO-only keeps the value machine-usable (reminders,
+ sorting) without a date-parsing dependency — the UI's date input already
+ produces this exact shape.
+ """
+ s = (raw or "").strip()
+ if not s:
+ return None
+ try:
+ return date.fromisoformat(s).isoformat()
+ except ValueError as exc:
+ raise ValueError(
+ f"Invalid birthday {raw!r} — expected ISO format YYYY-MM-DD."
+ ) from exc
+
+
+def _clean_str_list(values: list[str] | None) -> list[str]:
+ """Trim + drop empties + dedupe case-insensitively (first spelling wins)."""
+ out: list[str] = []
+ seen: set[str] = set()
+ for v in values or []:
+ s = (v or "").strip()
+ if s and s.lower() not in seen:
+ seen.add(s.lower())
+ out.append(s)
+ return out
+
+
def _normalize_phone(raw: str) -> str:
"""Best-effort E.164 normalisation: keep a leading ``+``, strip separators.
@@ -122,6 +157,30 @@ class Contact:
def relationship(self) -> str | None:
return self._meta.get("relationship") or None
+ @property
+ def favorite(self) -> bool:
+ return bool(self._meta.get("favorite"))
+
+ @property
+ def birthday(self) -> str | None:
+ return self._meta.get("birthday") or None
+
+ @property
+ def organization(self) -> str | None:
+ return self._meta.get("organization") or None
+
+ @property
+ def role(self) -> str | None:
+ return self._meta.get("role") or None
+
+ @property
+ def urls(self) -> list[str]:
+ return list(self._meta.get("urls", []) or [])
+
+ @property
+ def tags(self) -> list[str]:
+ return list(self._meta.get("tags", []) or [])
+
# --- contact info --------------------------------------------------
@property
def _contact(self) -> dict[str, Any]:
@@ -160,6 +219,12 @@ class Contact:
"name": self.name,
"aliases": self.aliases,
"relationship": self.relationship,
+ "favorite": self.favorite,
+ "birthday": self.birthday,
+ "organization": self.organization,
+ "role": self.role,
+ "urls": self.urls,
+ "tags": self.tags,
"emails": self.emails,
"phones": self.phones,
"address": self.address,
@@ -176,6 +241,9 @@ class Contact:
"name": self.name,
"aliases": self.aliases,
"relationship": self.relationship,
+ "favorite": self.favorite,
+ "organization": self.organization,
+ "tags": self.tags,
"primary_email": self.primary_email,
"primary_phone": self.primary_phone,
"email_count": len(self.emails),
@@ -303,6 +371,15 @@ class ContactStore:
name=existing.name,
aliases=existing.aliases,
relationship=rel if rel is not None else existing.relationship,
+ # A voice-upsert only carries the fields in its schema; the
+ # profile fields below MUST ride along or the replace-in-place
+ # put() would silently wipe them (the restore-trap bug class).
+ favorite=existing.favorite,
+ birthday=existing.birthday,
+ organization=existing.organization,
+ role=existing.role,
+ urls=existing.urls,
+ tags=existing.tags,
emails=emails,
phones=phones,
address=addr,
@@ -328,6 +405,12 @@ class ContactStore:
name: str,
aliases: list[str] | None = None,
relationship: str | None = None,
+ favorite: bool = False,
+ birthday: str | None = None,
+ organization: str | None = None,
+ role: str | None = None,
+ urls: list[str] | None = None,
+ tags: list[str] | None = None,
emails: list[str] | None = None,
phones: list[str] | None = None,
address: dict[str, Any] | None = None,
@@ -338,6 +421,11 @@ class ContactStore:
if not clean_name:
raise ValueError("A contact requires a non-empty name.")
rel = normalize_relationship(relationship)
+ clean_birthday = _validate_birthday(birthday)
+ clean_org = (organization or "").strip()
+ clean_role = (role or "").strip()
+ clean_urls = _clean_str_list(urls)
+ clean_tags = _clean_str_list(tags)
clean_emails: list[str] = []
for e in emails or []:
@@ -370,6 +458,20 @@ class ContactStore:
meta: dict[str, Any] = {"identity": {"name": clean_name, "aliases": clean_aliases}}
if rel is not None:
meta["relationship"] = rel
+ # Optional profile fields: written only when set, so untouched records
+ # keep their minimal frontmatter (and diffs stay readable).
+ if favorite:
+ meta["favorite"] = True
+ if clean_birthday:
+ meta["birthday"] = clean_birthday
+ if clean_org:
+ meta["organization"] = clean_org
+ if clean_role:
+ meta["role"] = clean_role
+ if clean_urls:
+ meta["urls"] = clean_urls
+ if clean_tags:
+ meta["tags"] = clean_tags
meta["contact"] = {"emails": clean_emails, "phones": clean_phones, "address": addr}
meta["last_updated"] = datetime.now(UTC).isoformat(timespec="seconds")
@@ -390,6 +492,12 @@ class ContactStore:
"name": current.name,
"aliases": current.aliases,
"relationship": current.relationship,
+ "favorite": current.favorite,
+ "birthday": current.birthday,
+ "organization": current.organization,
+ "role": current.role,
+ "urls": current.urls,
+ "tags": current.tags,
"emails": current.emails,
"phones": current.phones,
"address": current.address,
@@ -420,20 +528,35 @@ class ContactStore:
Detail (emails/phones/address/README) is fetched on demand via the
``contact-lookup`` tool (Chunk B) — never injected into every prompt.
+
+ A book larger than the budget is cut at a LINE boundary with an honest
+ "…and N more" tail, never mid-name: a half-visible name is one the
+ brain can neither resolve nor admit to missing.
"""
contacts = self.list_all()
if not contacts:
return ""
- parts = ["## Contacts"]
+ entries: list[str] = []
for c in contacts:
aliases = c.aliases
tag = f" (aka {', '.join(aliases)})" if aliases else ""
rel = c.relationship
if rel:
- parts.append(f"- **{c.name}**{tag} — {rel}")
+ entries.append(f"- **{c.name}**{tag} — {rel}")
else:
- parts.append(f"- **{c.name}**{tag}")
- out = "\n".join(parts)
- if len(out) > max_chars:
- out = out[: max_chars - 1] + "…"
- return out
+ entries.append(f"- **{c.name}**{tag}")
+ header = "## Contacts"
+ full = "\n".join([header, *entries])
+ if len(full) <= max_chars:
+ return full
+ for keep in range(len(entries) - 1, -1, -1):
+ omitted = len(entries) - keep
+ tail = (
+ f"- …and {omitted} more saved contacts — resolve them on "
+ "demand with the contact-lookup tool."
+ )
+ out = "\n".join([header, *entries[:keep], tail])
+ if len(out) <= max_chars:
+ return out
+ # Degenerate budget (smaller than header + tail): old hard cut.
+ return full[: max_chars - 1] + "…"
diff --git a/jarvis/contacts/vcard.py b/jarvis/contacts/vcard.py
new file mode 100644
index 0000000000..3477e41404
--- /dev/null
+++ b/jarvis/contacts/vcard.py
@@ -0,0 +1,319 @@
+"""Minimal vCard import/export for the contact book — stdlib only.
+
+vCard is a line-folded key/value grammar, not a format that needs a parser
+library (``jarvis.ultrawiki.connectors.export_import`` applies the same
+reasoning): unfold continuation lines, split each property at its first
+colon, done. Export writes vCard 3.0 — the flavor Google/Apple/Outlook all
+accept — with CRLF line endings per the RFC. Base64 blobs (photos, keys) are
+dropped on import; the contact model has no photo field, so none are written.
+
+Import is merge-not-clobber: a card whose name resolves to an existing
+contact (``ContactStore.find_by_alias``) unions the list fields and only
+fills scalar fields that are currently empty — a re-import never overwrites
+curated data. Invalid e-mails/phones/birthdays inside a card are dropped
+value-by-value instead of failing the batch.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from .store import _EMAIL_RE, ContactStore, _normalize_phone, _validate_birthday
+
+log = logging.getLogger(__name__)
+
+#: Properties whose (potentially huge) base64 payload is never useful here.
+_BLOB_PROPERTIES = frozenset({"PHOTO", "LOGO", "SOUND", "KEY"})
+
+_MAX_ERRORS_REPORTED = 10
+
+
+# ----------------------------------------------------------------------
+# TEXT value escaping (RFC 2426 / 6350)
+# ----------------------------------------------------------------------
+
+
+def _escape(value: str) -> str:
+ return value.replace("\\", "\\\\").replace("\n", "\\n").replace(",", "\\,").replace(";", "\\;")
+
+
+def _unescape(value: str) -> str:
+ out: list[str] = []
+ i = 0
+ while i < len(value):
+ ch = value[i]
+ if ch == "\\" and i + 1 < len(value):
+ nxt = value[i + 1]
+ if nxt in ("n", "N"):
+ out.append("\n")
+ else:
+ out.append(nxt)
+ i += 2
+ else:
+ out.append(ch)
+ i += 1
+ return "".join(out)
+
+
+# ----------------------------------------------------------------------
+# Export
+# ----------------------------------------------------------------------
+
+
+def contact_to_vcard(contact: Any) -> str:
+ """Render one ``jarvis.contacts.store.Contact`` as a vCard 3.0 block."""
+ lines: list[str] = ["BEGIN:VCARD", "VERSION:3.0"]
+ name = contact.name
+ lines.append(f"FN:{_escape(name)}")
+ # Best-effort structured name: last word = family name, rest = given.
+ words = name.split()
+ family = words[-1] if len(words) > 1 else ""
+ given = " ".join(words[:-1]) if len(words) > 1 else name
+ lines.append(f"N:{_escape(family)};{_escape(given)};;;")
+ if contact.aliases:
+ lines.append("NICKNAME:" + ",".join(_escape(a) for a in contact.aliases))
+ if contact.organization:
+ lines.append(f"ORG:{_escape(contact.organization)}")
+ if contact.role:
+ lines.append(f"TITLE:{_escape(contact.role)}")
+ if contact.birthday:
+ lines.append(f"BDAY:{contact.birthday}")
+ for email in contact.emails:
+ lines.append(f"EMAIL;TYPE=INTERNET:{_escape(email)}")
+ for phone in contact.phones:
+ lines.append(f"TEL;TYPE=VOICE:{_escape(phone)}")
+ addr = contact.address
+ if addr:
+ # ADR components: PO box; extended; street; locality; region; postal; country.
+ lines.append(
+ "ADR;TYPE=HOME:;;{};{};;{};{}".format(
+ _escape(addr.get("street", "")),
+ _escape(addr.get("city", "")),
+ _escape(addr.get("postal_code", "")),
+ _escape(addr.get("country", "")),
+ )
+ )
+ for url in contact.urls:
+ lines.append(f"URL:{_escape(url)}")
+ if contact.tags:
+ lines.append("CATEGORIES:" + ",".join(_escape(t) for t in contact.tags))
+ note = contact.note_md.strip()
+ if note:
+ lines.append(f"NOTE:{_escape(note)}")
+ last_updated = contact.to_dict().get("last_updated")
+ if last_updated:
+ lines.append(f"REV:{last_updated}")
+ lines.append("END:VCARD")
+ return "\r\n".join(lines)
+
+
+def contacts_to_vcf(contacts: list[Any]) -> str:
+ """The whole book as one ``.vcf`` payload (trailing CRLF included)."""
+ if not contacts:
+ return ""
+ return "\r\n".join(contact_to_vcard(c) for c in contacts) + "\r\n"
+
+
+# ----------------------------------------------------------------------
+# Import — parse
+# ----------------------------------------------------------------------
+
+
+def _unfold_lines(text: str) -> list[str]:
+ """vCard line unfolding: a leading space/tab continues the line before."""
+ out: list[str] = []
+ current = ""
+ for raw in text.splitlines():
+ if raw[:1] in (" ", "\t") and current:
+ current += raw[1:]
+ continue
+ if current:
+ out.append(current)
+ current = raw
+ if current:
+ out.append(current)
+ return out
+
+
+def _parse_bday(value: str) -> str | None:
+ """Normalise a BDAY value to ISO ``YYYY-MM-DD`` or return ``None``.
+
+ Accepts ``1990-04-12`` and the compact ``19900412``; the year-less
+ vCard 4.0 form (``--0412``) has no ISO-date equivalent and is dropped.
+ """
+ v = value.strip()
+ if len(v) == 8 and v.isdigit():
+ v = f"{v[:4]}-{v[4:6]}-{v[6:]}"
+ try:
+ return _validate_birthday(v)
+ except ValueError:
+ return None
+
+
+def parse_vcf(text: str) -> list[dict[str, Any]]:
+ """Parse ``.vcf`` text into ``ContactStore.put``-shaped record dicts.
+
+ Unknown properties are ignored; a card without FN falls back to a
+ reassembled N; a card with neither yields no record.
+ """
+ records: list[dict[str, Any]] = []
+ card: dict[str, Any] | None = None
+ n_fallback = ""
+ for line in _unfold_lines(text):
+ stripped = line.strip()
+ if not stripped:
+ continue
+ upper = stripped.upper()
+ if upper == "BEGIN:VCARD":
+ card = {
+ "name": "",
+ "aliases": [],
+ "emails": [],
+ "phones": [],
+ "urls": [],
+ "tags": [],
+ "address": {},
+ "birthday": None,
+ "organization": None,
+ "role": None,
+ "note": None,
+ }
+ n_fallback = ""
+ continue
+ if upper == "END:VCARD":
+ if card is not None:
+ if not card["name"] and n_fallback:
+ card["name"] = n_fallback
+ if card["name"]:
+ records.append(card)
+ card = None
+ continue
+ if card is None:
+ continue
+ key, sep, value = stripped.partition(":")
+ if not sep or not value.strip():
+ continue
+ # "item1.TEL;TYPE=CELL" → property "TEL" (group prefix + params off).
+ prop = key.split(";", 1)[0].split(".")[-1].strip().upper()
+ value = value.strip()
+ if prop in _BLOB_PROPERTIES:
+ continue
+ if prop == "FN" and not card["name"]:
+ card["name"] = _unescape(value)
+ elif prop == "N" and not n_fallback:
+ parts = [_unescape(p) for p in value.split(";")]
+ family = parts[0] if parts else ""
+ given = parts[1] if len(parts) > 1 else ""
+ n_fallback = " ".join(p for p in (given, family) if p).strip()
+ elif prop == "NICKNAME":
+ card["aliases"].extend(_unescape(a).strip() for a in value.split(",") if a.strip())
+ elif prop == "EMAIL":
+ card["emails"].append(_unescape(value))
+ elif prop == "TEL":
+ card["phones"].append(_unescape(value))
+ elif prop == "URL":
+ card["urls"].append(_unescape(value))
+ elif prop == "CATEGORIES":
+ card["tags"].extend(_unescape(t).strip() for t in value.split(",") if t.strip())
+ elif prop == "ADR" and not card["address"]:
+ parts = [_unescape(p).strip() for p in value.split(";")]
+ parts += [""] * (7 - len(parts))
+ card["address"] = {
+ "street": parts[2],
+ "city": parts[3],
+ "postal_code": parts[5],
+ "country": parts[6],
+ }
+ elif prop == "BDAY" and card["birthday"] is None:
+ card["birthday"] = _parse_bday(value)
+ elif prop == "ORG" and card["organization"] is None:
+ card["organization"] = _unescape(value.split(";", 1)[0]).strip() or None
+ elif prop == "TITLE" and card["role"] is None:
+ card["role"] = _unescape(value).strip() or None
+ elif prop == "NOTE" and card["note"] is None:
+ card["note"] = _unescape(value)
+ return records
+
+
+# ----------------------------------------------------------------------
+# Import — merge into the store
+# ----------------------------------------------------------------------
+
+
+def _union(existing: list[str], incoming: list[str]) -> list[str]:
+ """Case-insensitive list union; the existing spelling/order wins."""
+ out = list(existing)
+ seen = {v.lower() for v in existing}
+ for v in incoming:
+ s = v.strip()
+ if s and s.lower() not in seen:
+ seen.add(s.lower())
+ out.append(s)
+ return out
+
+
+def import_records(store: ContactStore, records: list[dict[str, Any]]) -> dict[str, Any]:
+ """Merge parsed vCard records into the store.
+
+ Returns ``{"created": n, "updated": n, "skipped": n, "errors": [...]}``.
+ A record failing as a whole is counted, never raised — one broken card
+ must not abort a 500-card import.
+ """
+ created = updated = skipped = 0
+ errors: list[str] = []
+ for rec in records:
+ name = (rec.get("name") or "").strip()
+ if not name:
+ skipped += 1
+ continue
+ # Value-level sanitising: drop what the store would reject.
+ emails = [e.strip() for e in rec.get("emails", []) if _EMAIL_RE.match(e.strip())]
+ phones = []
+ for p in rec.get("phones", []):
+ try:
+ phones.append(_normalize_phone(p))
+ except ValueError:
+ pass
+ try:
+ existing = store.find_by_alias(name)
+ if existing is None:
+ store.put(
+ name=name,
+ aliases=rec.get("aliases") or [],
+ birthday=rec.get("birthday"),
+ organization=rec.get("organization"),
+ role=rec.get("role"),
+ urls=rec.get("urls") or [],
+ tags=rec.get("tags") or [],
+ emails=emails,
+ phones=phones,
+ address=rec.get("address") or {},
+ note=rec.get("note"),
+ )
+ created += 1
+ else:
+ addr = dict(existing.address) or (rec.get("address") or {})
+ store.put(
+ slug=existing.slug,
+ name=existing.name,
+ aliases=_union(existing.aliases, rec.get("aliases") or []),
+ relationship=existing.relationship,
+ favorite=existing.favorite,
+ birthday=existing.birthday or rec.get("birthday"),
+ organization=existing.organization or rec.get("organization"),
+ role=existing.role or rec.get("role"),
+ urls=_union(existing.urls, rec.get("urls") or []),
+ tags=_union(existing.tags, rec.get("tags") or []),
+ emails=_union(existing.emails, emails),
+ phones=_union(existing.phones, phones),
+ address=addr,
+ note=existing.note_md if existing.note_md.strip() else rec.get("note"),
+ )
+ updated += 1
+ except ValueError as exc:
+ skipped += 1
+ if len(errors) < _MAX_ERRORS_REPORTED:
+ errors.append(f"{name}: {exc}")
+ log.warning("vcard import: skipped %r: %s", name, exc)
+ return {"created": created, "updated": updated, "skipped": skipped, "errors": errors}
diff --git a/jarvis/ui/web/contacts_routes.py b/jarvis/ui/web/contacts_routes.py
index cb72bc454f..e59dc25376 100644
--- a/jarvis/ui/web/contacts_routes.py
+++ b/jarvis/ui/web/contacts_routes.py
@@ -3,11 +3,17 @@
Endpoints (mounted by the WebServer in ``_build_app()``):
GET /api/contacts → {"contacts": [summary, ...]} sorted by name.
+ GET /api/contacts/export → the whole book as a ``.vcf`` download.
+ POST /api/contacts/import → merge vCard text into the book.
GET /api/contacts/{slug} → full contact dict; 404 if unknown.
POST /api/contacts → create one (server derives the slug); 201.
PATCH /api/contacts/{slug} → partial edit; returns the full contact; 404.
DELETE /api/contacts/{slug} → remove (idempotent → 200, {"removed": bool}).
+NOTE: ``/export`` MUST stay registered before ``GET /{slug}`` — Starlette
+matches routes in registration order, so the dynamic slug route would
+otherwise swallow it (as a 404 for the slug "export").
+
Storage is one ``<slug>.md`` file per contact under
``user_data_dir()/data/contacts/`` (YAML frontmatter + Markdown README), written
atomically by :class:`jarvis.contacts.store.ContactStore`. Like the Socials/avatar
@@ -26,10 +32,12 @@ import threading
from typing import Any
from fastapi import APIRouter, HTTPException
+from fastapi.responses import Response
from pydantic import BaseModel
from jarvis.contacts.schema import Relationship
from jarvis.contacts.store import ContactStore
+from jarvis.contacts.vcard import contacts_to_vcf, import_records, parse_vcf
log = logging.getLogger(__name__)
@@ -43,6 +51,9 @@ _LOCK = threading.Lock()
# (keeps a single file from growing unbounded), not a hard word limit.
_MAX_NOTE_LEN = 16_000
_MAX_NAME_LEN = 200
+# A 2 MB .vcf is ~4000 richly-filled cards — plenty for a personal book,
+# small enough that a mistaken photo-laden export cannot wedge the server.
+_MAX_IMPORT_LEN = 2_000_000
def _store() -> ContactStore:
@@ -67,6 +78,12 @@ class ContactCreate(BaseModel):
name: str
aliases: list[str] = []
relationship: Relationship | None = None
+ favorite: bool = False
+ birthday: str | None = None
+ organization: str | None = None
+ role: str | None = None
+ urls: list[str] = []
+ tags: list[str] = []
emails: list[str] = []
phones: list[str] = []
address: AddressModel | None = None
@@ -77,12 +94,24 @@ class ContactUpdate(BaseModel):
name: str | None = None
aliases: list[str] | None = None
relationship: Relationship | None = None
+ favorite: bool | None = None
+ birthday: str | None = None
+ organization: str | None = None
+ role: str | None = None
+ urls: list[str] | None = None
+ tags: list[str] | None = None
emails: list[str] | None = None
phones: list[str] | None = None
address: AddressModel | None = None
note: str | None = None
+class ImportBody(BaseModel):
+ """Raw ``.vcf`` file content (the UI reads the picked file as text)."""
+
+ vcf: str
+
+
# ----------------------------------------------------------------------
# Validation helpers
# ----------------------------------------------------------------------
@@ -115,6 +144,35 @@ def list_contacts() -> dict[str, Any]:
return {"contacts": [c.to_summary() for c in contacts]}
+# Registered BEFORE GET /{slug} on purpose — see the module docstring NOTE.
+def export_contacts() -> Response:
+ with _LOCK:
+ vcf = contacts_to_vcf(_store().list_all())
+ return Response(
+ content=vcf,
+ media_type="text/vcard; charset=utf-8",
+ headers={"Content-Disposition": 'attachment; filename="contacts.vcf"'},
+ )
+
+
+def import_contacts(body: ImportBody) -> dict[str, Any]:
+ if len(body.vcf) > _MAX_IMPORT_LEN:
+ raise HTTPException(
+ status_code=400,
+ detail=f"vCard payload too large (max {_MAX_IMPORT_LEN} characters).",
+ )
+ records = parse_vcf(body.vcf)
+ if not records:
+ raise HTTPException(
+ status_code=400, detail="No vCard records found in the payload."
+ )
+ with _LOCK:
+ stats = import_records(_store(), records)
+ return {"ok": True, **stats}
+
+
@router.get("/{slug}")
def get_contact(slug: str) -> dict[str, Any]:
with _LOCK:
@@ -135,6 +193,12 @@ def create_contact(body: ContactCreate) -> dict[str, Any]:
name=body.name,
aliases=body.aliases,
relationship=body.relationship,
+ favorite=body.favorite,
+ birthday=body.birthday,
+ organization=body.organization,
+ role=body.role,
+ urls=body.urls,
+ tags=body.tags,
emails=body.emails,
phones=body.phones,
address=address,
diff --git a/tests/unit/contacts/test_store.py b/tests/unit/contacts/test_store.py
index a31c73525c..68816320b9 100644
--- a/tests/unit/contacts/test_store.py
+++ b/tests/unit/contacts/test_store.py
@@ -211,6 +211,94 @@ def test_render_for_prompt_respects_max_chars(store: ContactStore) -> None:
assert len(out) <= 200
+def test_render_for_prompt_cuts_at_line_boundary_with_honest_tail(
+ store: ContactStore,
+) -> None:
+ for i in range(50):
+ store.upsert(name=f"Person {i:02d}", relationship="other")
+ out = store.render_for_prompt(max_chars=300)
+ assert len(out) <= 300
+ # Never a mid-name cut: every kept line is complete, and the omission is
+ # stated instead of hidden.
+ lines = out.splitlines()
+ assert lines[0] == "## Contacts"
+ assert "more saved contacts" in lines[-1]
+ assert "contact-lookup" in lines[-1]
+ for line in lines[1:-1]:
+ assert line.startswith("- **") and line.endswith("— other")
+
+
+# ----------------------------------------------------------------------
+# Profile fields (favorite / birthday / organization / role / urls / tags)
+# ----------------------------------------------------------------------
+
+
+def test_put_roundtrips_profile_fields(store: ContactStore) -> None:
+ c = store.put(
+ name="Frida",
+ favorite=True,
+ birthday="1985-12-01",
+ organization="Studio F",
+ role="Painter",
+ urls=["https://frida.example", "https://frida.example"],
+ tags=["art", "Art", "friends-of-friends"],
+ )
+ assert c.favorite is True
+ assert c.birthday == "1985-12-01"
+ assert c.organization == "Studio F"
+ assert c.role == "Painter"
+ assert c.urls == ["https://frida.example"] # deduped
+ assert c.tags == ["art", "friends-of-friends"] # case-insensitive dedupe
+
+ fresh = ContactStore(base_dir=store.base_dir).get("frida")
+ assert fresh is not None
+ assert fresh.favorite is True
+ assert fresh.birthday == "1985-12-01"
+
+
+def test_put_rejects_non_iso_birthday(store: ContactStore) -> None:
+ with pytest.raises(ValueError):
+ store.put(name="X", birthday="12.04.1990")
+
+
+def test_upsert_preserves_profile_fields_on_merge(store: ContactStore) -> None:
+ store.put(
+ name="Gero",
+ favorite=True,
+ birthday="1970-01-05",
+ organization="Org",
+ role="Boss",
+ urls=["https://gero.example"],
+ tags=["vip"],
+ )
+ # A voice-upsert only carries its own schema fields — the profile fields
+ # must survive the replace-in-place write untouched.
+ store.upsert(name="Gero", email="[email protected]")
+ c = store.get("gero")
+ assert c is not None
+ assert c.emails == ["[email protected]"]
+ assert c.favorite is True
+ assert c.birthday == "1970-01-05"
+ assert c.organization == "Org"
+ assert c.role == "Boss"
+ assert c.urls == ["https://gero.example"]
+ assert c.tags == ["vip"]
+
+
+def test_update_partial_touches_only_given_profile_fields(store: ContactStore) -> None:
+ created = store.put(name="Hana", organization="Old Org", tags=["a"])
+ updated = store.update(created.slug, favorite=True, tags=["a", "b"])
+ assert updated is not None
+ assert updated.favorite is True
+ assert updated.tags == ["a", "b"]
+ assert updated.organization == "Old Org" # untouched
+ # Clearing works via empty string / empty list (never via absence).
+ cleared = store.update(created.slug, organization="", tags=[])
+ assert cleared is not None
+ assert cleared.organization is None
+ assert cleared.tags == []
+
+
# ----------------------------------------------------------------------
# slug + helpers
# ----------------------------------------------------------------------
diff --git a/tests/unit/contacts/test_vcard.py b/tests/unit/contacts/test_vcard.py
new file mode 100644
index 0000000000..a946bba2ac
--- /dev/null
+++ b/tests/unit/contacts/test_vcard.py
@@ -0,0 +1,190 @@
+"""Tests for the vCard import/export module (jarvis/contacts/vcard.py).
+
+Pins the contract the REST import/export endpoints rely on:
+- export → parse round-trips every field the contact model carries,
+- import merges into existing contacts instead of clobbering them,
+- broken values (bad e-mail/phone/birthday) are dropped value-by-value,
+- vCard mechanics: line unfolding, TEXT escaping, base64 blob skipping,
+ compact BDAY normalisation, N-fallback when FN is missing.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from jarvis.contacts.store import ContactStore
+from jarvis.contacts.vcard import (
+ contact_to_vcard,
+ contacts_to_vcf,
+ import_records,
+ parse_vcf,
+)
+
+
+def store(tmp_path: Path) -> ContactStore:
+ return ContactStore(base_dir=tmp_path / "contacts")
+
+
+def _full_contact(store: ContactStore):
+ return store.put(
+ name="Christoph Meyer",
+ aliases=["Chris"],
+ relationship="friend",
+ favorite=True,
+ birthday="1990-04-12",
+ organization="ACME GmbH",
+ role="CTO",
+ urls=["https://example.com"],
+ tags=["tennis", "uni"],
+ emails=["[email protected]"],
+ phones=["+49 151 2345 6789"],
+ address={
+ "street": "Main St 1",
+ "postal_code": "10115",
+ "city": "Berlin",
+ "country": "DE",
+ },
+ note="My oldest friend.\nLikes tennis, obviously.",
+ )
+
+
+# ----------------------------------------------------------------------
+# Export
+# ----------------------------------------------------------------------
+
+
+def test_export_contains_every_field(store: ContactStore) -> None:
+ card = contact_to_vcard(_full_contact(store))
+ assert card.startswith("BEGIN:VCARD")
+ assert card.endswith("END:VCARD")
+ assert "VERSION:3.0" in card
+ assert "FN:Christoph Meyer" in card
+ assert "NICKNAME:Chris" in card
+ assert "ORG:ACME GmbH" in card
+ assert "TITLE:CTO" in card
+ assert "BDAY:1990-04-12" in card
+ assert "EMAIL;TYPE=INTERNET:[email protected]" in card
+ assert "TEL;TYPE=VOICE:+4915123456789" in card
+ assert "URL:https://example.com" in card
+ assert "CATEGORIES:tennis,uni" in card
+ # The note's newline is escaped, commas escaped (TEXT escaping).
+ assert "NOTE:My oldest friend.\\nLikes tennis\\, obviously." in card
+ # Address components land in the right ADR slots.
+ assert "ADR;TYPE=HOME:;;Main St 1;Berlin;;10115;DE" in card
+
+
+def test_export_empty_book_is_empty_string(store: ContactStore) -> None:
+ assert contacts_to_vcf(store.list_all()) == ""
+
+
+# ----------------------------------------------------------------------
+# Round-trip
+# ----------------------------------------------------------------------
+
+
+def test_export_then_import_roundtrips(store: ContactStore, tmp_path: Path) -> None:
+ _full_contact(store)
+ vcf = contacts_to_vcf(store.list_all())
+
+ other = ContactStore(base_dir=tmp_path / "other")
+ stats = import_records(other, parse_vcf(vcf))
+ assert stats == {"created": 1, "updated": 0, "skipped": 0, "errors": []}
+
+ c = other.get("christoph_meyer")
+ assert c is not None
+ assert c.aliases == ["Chris"]
+ assert c.birthday == "1990-04-12"
+ assert c.organization == "ACME GmbH"
+ assert c.role == "CTO"
+ assert c.urls == ["https://example.com"]
+ assert c.tags == ["tennis", "uni"]
+ assert c.emails == ["[email protected]"]
+ assert c.phones == ["+4915123456789"]
+ assert c.address["city"] == "Berlin"
+ assert c.address["postal_code"] == "10115"
+ assert "Likes tennis, obviously." in c.note_md
+
+
+# ----------------------------------------------------------------------
+# Parse mechanics
+# ----------------------------------------------------------------------
+
+
+def test_parse_unfolds_continuation_lines() -> None:
+ vcf = "BEGIN:VCARD\nVERSION:3.0\nFN:Anna Long\n NAME Continued\nEND:VCARD\n"
+ records = parse_vcf(vcf)
+ assert records[0]["name"] == "Anna LongNAME Continued"
+
+
+def test_parse_falls_back_to_n_when_fn_missing() -> None:
+ vcf = "BEGIN:VCARD\nN:Meyer;Christoph;;;\nEND:VCARD\n"
+ assert parse_vcf(vcf)[0]["name"] == "Christoph Meyer"
+
+
+def test_parse_skips_blobs_and_cards_without_name() -> None:
+ vcf = (
+ "BEGIN:VCARD\nPHOTO;ENCODING=b:AAAA\nEND:VCARD\n"
+ "BEGIN:VCARD\nFN:Real Person\nPHOTO;ENCODING=b:AAAA\nEND:VCARD\n"
+ )
+ records = parse_vcf(vcf)
+ assert len(records) == 1
+ assert records[0]["name"] == "Real Person"
+
+
+def test_parse_normalises_compact_bday_and_drops_invalid() -> None:
+ vcf = "BEGIN:VCARD\nFN:A\nBDAY:19900412\nEND:VCARD\n"
+ assert parse_vcf(vcf)[0]["birthday"] == "1990-04-12"
+ vcf_bad = "BEGIN:VCARD\nFN:B\nBDAY:--0412\nEND:VCARD\n"
+ assert parse_vcf(vcf_bad)[0]["birthday"] is None
+
+
+def test_parse_strips_group_prefixes() -> None:
+ vcf = "BEGIN:VCARD\nFN:A\nitem1.TEL;TYPE=CELL:+49151\nEND:VCARD\n"
+ assert parse_vcf(vcf)[0]["phones"] == ["+49151"]
+
+
+# ----------------------------------------------------------------------
+# Import merge semantics
+# ----------------------------------------------------------------------
+
+
+def test_import_merges_into_existing_without_clobbering(store: ContactStore) -> None:
+ store.put(
+ name="Christoph Meyer",
+ relationship="friend",
+ favorite=True,
+ organization="Existing Org",
+ emails=["[email protected]"],
+ note="Curated bio.",
+ )
+ vcf = (
+ "BEGIN:VCARD\nFN:Christoph Meyer\nORG:Imported Org\n"
+ "EMAIL:[email protected]\nNOTE:Imported note\nCATEGORIES:import\nEND:VCARD\n"
+ )
+ stats = import_records(store, parse_vcf(vcf))
+ assert stats["updated"] == 1 and stats["created"] == 0
+
+ c = store.get("christoph_meyer")
+ assert c is not None
+ # Lists union; scalars only fill when empty; curated data survives.
+ assert c.emails == ["[email protected]", "[email protected]"]
+ assert c.organization == "Existing Org"
+ assert c.note_md.strip() == "Curated bio."
+ assert c.tags == ["import"]
+ assert c.favorite is True
+ assert c.relationship == "friend"
+
+
+def test_import_drops_invalid_values_but_keeps_the_record(store: ContactStore) -> None:
+ vcf = (
+ "BEGIN:VCARD\nFN:Messy Card\nEMAIL:not-an-email\nEMAIL:[email protected]\n"
+ "TEL:abc\nTEL:+49 151 1\nEND:VCARD\n"
+ )
+ stats = import_records(store, parse_vcf(vcf))
+ assert stats["created"] == 1
+ c = store.get("messy_card")
+ assert c is not None
+ assert c.emails == ["[email protected]"]
+ assert c.phones == ["+491511"]
diff --git a/tests/unit/ui/web/test_contacts_routes.py b/tests/unit/ui/web/test_contacts_routes.py
index fada1c93e9..ebd2acc040 100644
--- a/tests/unit/ui/web/test_contacts_routes.py
+++ b/tests/unit/ui/web/test_contacts_routes.py
@@ -210,3 +210,83 @@ def test_store_file_is_written_under_data_dir(client: TestClient, tmp_path: Path
created = _make(client, name="On Disk")
md = tmp_path / "Jarvis" / "data" / "contacts" / f"{created['slug']}.md"
assert md.is_file()
+
+
+# ----------------------------------------------------------------------
+# Profile fields over the wire
+# ----------------------------------------------------------------------
+
+
+def test_post_and_patch_profile_fields(client: TestClient) -> None:
+ created = _make(
+ client,
+ name="Profiled Person",
+ favorite=True,
+ birthday="1990-04-12",
+ organization="ACME GmbH",
+ role="CTO",
+ urls=["https://example.com"],
+ tags=["tennis"],
+ )
+ assert created["favorite"] is True
+ assert created["birthday"] == "1990-04-12"
+ assert created["organization"] == "ACME GmbH"
+ assert created["role"] == "CTO"
+ assert created["urls"] == ["https://example.com"]
+ assert created["tags"] == ["tennis"]
+
+ # Summary carries the list-view fields.
+ summary = client.get("/api/contacts").json()["contacts"][0]
+ assert summary["favorite"] is True
+ assert summary["organization"] == "ACME GmbH"
+ assert summary["tags"] == ["tennis"]
+
+ # PATCH toggles favorite without touching anything else.
+ res = client.patch(f"/api/contacts/{created['slug']}", json={"favorite": False})
+ assert res.status_code == 200, res.text
+ assert res.json()["favorite"] is False
+ assert res.json()["organization"] == "ACME GmbH"
+
+
+def test_post_rejects_bad_birthday(client: TestClient) -> None:
+ res = client.post("/api/contacts", json={"name": "X", "birthday": "12.04.1990"})
+ assert res.status_code == 400
+ assert "birthday" in res.json()["detail"].lower()
+
+
+# ----------------------------------------------------------------------
+# vCard export / import
+# ----------------------------------------------------------------------
+
+
+def test_export_returns_vcf_download(client: TestClient) -> None:
+ _make(client, name="Exported Person")
+ res = client.get("/api/contacts/export")
+ assert res.status_code == 200, res.text
+ assert res.headers["content-type"].startswith("text/vcard")
+ assert "attachment" in res.headers["content-disposition"]
+ assert "BEGIN:VCARD" in res.text
+ assert "FN:Exported Person" in res.text
+ # The fixed /export path must not be swallowed by GET /{slug}.
+ assert client.get("/api/contacts/export").status_code == 200
+
+
+def test_import_creates_and_merges(client: TestClient) -> None:
+ _make(client, name="Christoph Meyer", emails=["[email protected]"])
+ vcf = (
+ "BEGIN:VCARD\nFN:Christoph Meyer\nEMAIL:[email protected]\nEND:VCARD\n"
+ "BEGIN:VCARD\nFN:Brand New\nTEL:+49 151 99\nEND:VCARD\n"
+ )
+ res = client.post("/api/contacts/import", json={"vcf": vcf})
+ assert res.status_code == 200, res.text
+ body = res.json()
+ assert body["ok"] is True
+ assert body["created"] == 1
+ assert body["updated"] == 1
+ merged = client.get("/api/contacts/christoph_meyer").json()
+ assert merged["emails"] == ["[email protected]", "[email protected]"]
+
+
+def test_import_rejects_empty_payload(client: TestClient) -> None:
+ res = client.post("/api/contacts/import", json={"vcf": "no cards here"})
+ assert res.status_code == 400