Skip to content

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

add tribe relationship manager

[._.]/ Adam Eivy3543795471c2
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 66c9fe0fb0..be9a6a6bd3 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -26,6 +26,7 @@ const FeatureAgents = lazyWithReload(() => import('./pages/FeatureAgents'));
const FeatureAgentDetail = lazyWithReload(() => import('./pages/FeatureAgentDetail'));
const CalendarPage = lazyWithReload(() => import('./pages/Calendar'));
const Messages = lazyWithReload(() => import('./pages/Messages'));
+const Tribe = lazyWithReload(() => import('./pages/Tribe'));
const Goals = lazyWithReload(() => import('./pages/Goals'));
const OpenClawPage = lazyWithReload(() => import('./pages/OpenClaw'));
const Submodules = lazyWithReload(() => import('./pages/Submodules'));
@@ -242,6 +243,7 @@ export default function App() {
<Route path="review" element={<Review />} />
<Route path="messages" element={<Navigate to="/messages/inbox" replace />} />
<Route path="messages/:tab" element={<Messages />} />
+ <Route path="tribe" element={<Tribe />} />
<Route path="openclaw" element={<OpenClawPage />} />
<Route path="datadog" element={<Navigate to="/devtools/datadog" replace />} />
<Route path="jira" element={<Navigate to="/devtools/jira" replace />} />
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 8bc3309913..5ca1a49e21 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -154,6 +154,7 @@ const navItems = [
{ to: '/openclaw', label: 'OpenClaw', icon: MessagesSquare },
{ to: '/rapid-reader', label: 'Rapid Reader', icon: Zap },
{ to: '/agents', label: 'Social Agents', icon: Users },
+ { to: '/tribe', label: 'Tribe', icon: Users },
{ to: '/brain/trust', label: 'Trust', icon: Shield },
{ to: '/wiki/overview', label: 'Wiki', icon: BookOpen },
],
diff --git a/client/src/pages/Tribe.jsx b/client/src/pages/Tribe.jsx
new file mode 100644
index 0000000000..8390adef45
--- /dev/null
+++ b/client/src/pages/Tribe.jsx
@@ -0,0 +1,911 @@
+import { useEffect, useMemo, useState } from 'react';
+import {
+ Calendar,
+ Clock,
+ Edit3,
+ Filter,
+ Heart,
+ MessageCircle,
+ Network,
+ Plus,
+ Save,
+ Search,
+ Trash2,
+ UserRound,
+ Users,
+ X,
+} from 'lucide-react';
+
+import * as api from '../services/api';
+import BrailleSpinner from '../components/BrailleSpinner';
+import PageHeader from '../components/PageHeader';
+import toast from '../components/ui/Toast';
+import TabPills from '../components/ui/TabPills';
+
+const STORAGE_KEY = 'portos-tribe-v1';
+
+const RINGS = [
+ { id: 'support', label: 'Support', cap: 5, cadenceDays: 7, tone: 'text-rose-300', bg: 'bg-rose-500/10', border: 'border-rose-500/30' },
+ { id: 'core', label: 'Core', cap: 15, cadenceDays: 21, tone: 'text-amber-300', bg: 'bg-amber-500/10', border: 'border-amber-500/30' },
+ { id: 'tribe', label: 'Tribe', cap: 50, cadenceDays: 45, tone: 'text-teal-300', bg: 'bg-teal-500/10', border: 'border-teal-500/30' },
+ { id: 'village', label: 'Village', cap: 150, cadenceDays: 90, tone: 'text-sky-300', bg: 'bg-sky-500/10', border: 'border-sky-500/30' },
+];
+
+const ENERGY = [
+ { id: 'nourishing', label: 'Nourishing', className: 'text-emerald-300 bg-emerald-500/10 border-emerald-500/30' },
+ { id: 'steady', label: 'Steady', className: 'text-sky-300 bg-sky-500/10 border-sky-500/30' },
+ { id: 'complex', label: 'Complex', className: 'text-amber-300 bg-amber-500/10 border-amber-500/30' },
+ { id: 'draining', label: 'Draining', className: 'text-rose-300 bg-rose-500/10 border-rose-500/30' },
+];
+
+const TABS = [
+ { id: 'circle', label: 'Circle', icon: Network },
+ { id: 'care', label: 'Care Queue', icon: Clock },
+ { id: 'focus', label: 'Focus', icon: Heart },
+];
+
+const emptyDraft = () => ({
+ id: null,
+ name: '',
+ relationship: '',
+ ring: 'tribe',
+ cadenceDays: 45,
+ lastContact: '',
+ channel: '',
+ energy: 'steady',
+ tags: '',
+ nextMove: '',
+ notes: '',
+});
+
+function todayISO() {
+ return new Date().toISOString().slice(0, 10);
+}
+
+function daysBetween(date) {
+ if (!date) return null;
+ const start = new Date(`${date}T00:00:00`);
+ if (Number.isNaN(start.getTime())) return null;
+ const now = new Date();
+ const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
+ return Math.floor((today - start) / 86400000);
+}
+
+function contactStatus(contact) {
+ const elapsed = daysBetween(contact.lastContact);
+ if (elapsed == null) return { label: 'No touchpoint', tone: 'text-gray-300', state: 'missing', daysRemaining: null };
+ const daysRemaining = Number(contact.cadenceDays || 45) - elapsed;
+ if (daysRemaining < 0) return { label: `${Math.abs(daysRemaining)}d overdue`, tone: 'text-rose-300', state: 'overdue', daysRemaining };
+ if (daysRemaining <= 7) return { label: `${daysRemaining}d left`, tone: 'text-amber-300', state: 'soon', daysRemaining };
+ return { label: `${daysRemaining}d left`, tone: 'text-emerald-300', state: 'steady', daysRemaining };
+}
+
+function ringFor(id) {
+ return RINGS.find((ring) => ring.id === id) || RINGS[2];
+}
+
+function energyFor(id) {
+ return ENERGY.find((energy) => energy.id === id) || ENERGY[1];
+}
+
+function tagsToArray(tags) {
+ if (Array.isArray(tags)) return tags.map((tag) => String(tag).trim()).filter(Boolean);
+ return String(tags || '').split(',').map((tag) => tag.trim()).filter(Boolean);
+}
+
+function tagsToInput(tags) {
+ return tagsToArray(tags).join(', ');
+}
+
+function parseStoredContacts(value) {
+ if (!value) return [];
+ try {
+ const parsed = JSON.parse(value);
+ return Array.isArray(parsed) ? parsed : [];
+ } catch {
+ return [];
+ }
+}
+
+function StatTile({ icon: Icon, label, value, detail, className = '' }) {
+ return (
+ <div className={`border border-port-border bg-port-card rounded p-4 min-w-0 ${className}`}>
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0">
+ <p className="text-xs uppercase tracking-wide text-gray-500">{label}</p>
+ <p className="mt-1 text-2xl font-semibold text-white">{value}</p>
+ {detail && <p className="mt-1 text-xs text-gray-500 truncate">{detail}</p>}
+ </div>
+ <Icon size={20} className="shrink-0 text-port-accent" aria-hidden="true" />
+ </div>
+ </div>
+ );
+}
+
+function RingMeter({ ring, contacts, active, onClick }) {
+ const count = contacts.filter((contact) => contact.ring === ring.id).length;
+ const fill = Math.min(100, Math.round((count / ring.cap) * 100));
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className={`w-full text-left border rounded p-4 transition-colors ${ring.bg} ${active ? `${ring.border} ring-1 ring-port-accent/30` : 'border-port-border hover:border-port-accent/50'}`}
+ >
+ <div className="flex items-center justify-between gap-3">
+ <div>
+ <p className={`text-sm font-semibold ${ring.tone}`}>{ring.label}</p>
+ <p className="text-xs text-gray-500">{count} / {ring.cap}</p>
+ </div>
+ <span className="text-xs text-gray-400">{ring.cadenceDays}d</span>
+ </div>
+ <div className="mt-3 h-2 rounded-full bg-black/30 overflow-hidden">
+ <div className="h-full rounded-full bg-current text-port-accent" style={{ width: `${fill}%` }} />
+ </div>
+ </button>
+ );
+}
+
+function ContactCard({ contact, active, onSelect, onLogTouch }) {
+ const ring = ringFor(contact.ring);
+ const energy = energyFor(contact.energy);
+ const status = contactStatus(contact);
+ const tags = tagsToArray(contact.tags).slice(0, 3);
+
+ return (
+ <button
+ type="button"
+ onClick={onSelect}
+ className={`w-full text-left border rounded p-4 transition-colors bg-port-card ${
+ active ? 'border-port-accent/70 ring-1 ring-port-accent/30' : 'border-port-border hover:border-port-accent/40'
+ }`}
+ >
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0">
+ <div className="flex items-center gap-2 min-w-0">
+ <UserRound size={16} className="shrink-0 text-gray-500" aria-hidden="true" />
+ <h3 className="font-semibold text-white truncate">{contact.name || 'Unnamed person'}</h3>
+ </div>
+ <p className="mt-1 text-sm text-gray-400 truncate">{contact.relationship || 'Relationship'}</p>
+ </div>
+ <span className={`shrink-0 rounded border px-2 py-1 text-xs ${ring.bg} ${ring.border} ${ring.tone}`}>
+ {ring.label}
+ </span>
+ </div>
+
+ <div className="mt-4 flex flex-wrap items-center gap-2">
+ <span className={`rounded border px-2 py-1 text-xs ${energy.className}`}>{energy.label}</span>
+ <span className={`text-xs ${status.tone}`}>{status.label}</span>
+ {contact.channel && <span className="text-xs text-gray-500">{contact.channel}</span>}
+ </div>
+
+ {tags.length > 0 && (
+ <div className="mt-3 flex flex-wrap gap-1.5">
+ {tags.map((tag) => (
+ <span key={tag} className="rounded bg-port-bg px-2 py-1 text-[11px] text-gray-400">{tag}</span>
+ ))}
+ </div>
+ )}
+
+ {contact.nextMove && (
+ <p className="mt-3 text-sm text-gray-300 line-clamp-2">{contact.nextMove}</p>
+ )}
+
+ <div className="mt-4 flex items-center justify-between gap-3 text-xs text-gray-500">
+ <span>{contact.lastContact ? `Last ${contact.lastContact}` : 'No date logged'}</span>
+ <span
+ role="button"
+ tabIndex={0}
+ onClick={(event) => {
+ event.stopPropagation();
+ onLogTouch();
+ }}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ event.stopPropagation();
+ onLogTouch();
+ }
+ }}
+ className="inline-flex items-center gap-1 rounded px-2 py-1 text-port-accent hover:bg-port-accent/10"
+ >
+ <MessageCircle size={13} aria-hidden="true" />
+ Touch
+ </span>
+ </div>
+ </button>
+ );
+}
+
+function ContactForm({ draft, onChange, onSave, onDelete, onNew, isExisting, saving }) {
+ const update = (field, value) => onChange({ ...draft, [field]: value });
+
+ return (
+ <form
+ className="border border-port-border bg-port-card rounded p-4"
+ onSubmit={(event) => {
+ event.preventDefault();
+ onSave();
+ }}
+ >
+ <div className="flex items-center justify-between gap-3">
+ <div className="flex items-center gap-2 min-w-0">
+ <Edit3 size={18} className="text-port-accent shrink-0" aria-hidden="true" />
+ <h2 className="text-sm font-semibold text-white truncate">{isExisting ? 'Relationship' : 'New Relationship'}</h2>
+ </div>
+ <button
+ type="button"
+ onClick={onNew}
+ title="New relationship"
+ aria-label="New relationship"
+ className="inline-flex h-9 w-9 items-center justify-center rounded border border-port-border text-gray-300 hover:text-white hover:bg-port-border/40"
+ >
+ <Plus size={16} aria-hidden="true" />
+ </button>
+ </div>
+
+ <div className="mt-4 grid gap-3 sm:grid-cols-2">
+ <label className="block">
+ <span className="text-xs text-gray-500">Name</span>
+ <input
+ value={draft.name}
+ onChange={(event) => update('name', event.target.value)}
+ className="mt-1 w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white outline-none focus:border-port-accent"
+ placeholder="Person"
+ />
+ </label>
+ <label className="block">
+ <span className="text-xs text-gray-500">Relationship</span>
+ <input
+ value={draft.relationship}
+ onChange={(event) => update('relationship', event.target.value)}
+ className="mt-1 w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white outline-none focus:border-port-accent"
+ placeholder="Friend, mentor, family"
+ />
+ </label>
+ <label className="block">
+ <span className="text-xs text-gray-500">Ring</span>
+ <select
+ value={draft.ring}
+ onChange={(event) => {
+ const ring = ringFor(event.target.value);
+ onChange({ ...draft, ring: ring.id, cadenceDays: ring.cadenceDays });
+ }}
+ className="mt-1 w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white outline-none focus:border-port-accent"
+ >
+ {RINGS.map((ring) => <option key={ring.id} value={ring.id}>{ring.label}</option>)}
+ </select>
+ </label>
+ <label className="block">
+ <span className="text-xs text-gray-500">Cadence</span>
+ <input
+ type="number"
+ min="1"
+ value={draft.cadenceDays}
+ onChange={(event) => update('cadenceDays', event.target.value)}
+ className="mt-1 w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white outline-none focus:border-port-accent"
+ />
+ </label>
+ <label className="block">
+ <span className="text-xs text-gray-500">Last Contact</span>
+ <input
+ type="date"
+ value={draft.lastContact}
+ onChange={(event) => update('lastContact', event.target.value)}
+ className="mt-1 w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white outline-none focus:border-port-accent"
+ />
+ </label>
+ <label className="block">
+ <span className="text-xs text-gray-500">Energy</span>
+ <select
+ value={draft.energy}
+ onChange={(event) => update('energy', event.target.value)}
+ className="mt-1 w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white outline-none focus:border-port-accent"
+ >
+ {ENERGY.map((energy) => <option key={energy.id} value={energy.id}>{energy.label}</option>)}
+ </select>
+ </label>
+ <label className="block sm:col-span-2">
+ <span className="text-xs text-gray-500">Channel</span>
+ <input
+ value={draft.channel}
+ onChange={(event) => update('channel', event.target.value)}
+ className="mt-1 w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white outline-none focus:border-port-accent"
+ placeholder="Text, call, dinner, walk"
+ />
+ </label>
+ <label className="block sm:col-span-2">
+ <span className="text-xs text-gray-500">Tags</span>
+ <input
+ value={draft.tags}
+ onChange={(event) => update('tags', event.target.value)}
+ className="mt-1 w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white outline-none focus:border-port-accent"
+ placeholder="comma, separated"
+ />
+ </label>
+ <label className="block sm:col-span-2">
+ <span className="text-xs text-gray-500">Next Move</span>
+ <textarea
+ value={draft.nextMove}
+ onChange={(event) => update('nextMove', event.target.value)}
+ rows={2}
+ className="mt-1 w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white outline-none focus:border-port-accent"
+ placeholder="A concrete next touchpoint"
+ />
+ </label>
+ <label className="block sm:col-span-2">
+ <span className="text-xs text-gray-500">Notes</span>
+ <textarea
+ value={draft.notes}
+ onChange={(event) => update('notes', event.target.value)}
+ rows={4}
+ className="mt-1 w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white outline-none focus:border-port-accent"
+ placeholder="Context worth remembering"
+ />
+ </label>
+ </div>
+
+ <div className="mt-4 flex flex-wrap items-center justify-between gap-2">
+ <button
+ type="submit"
+ disabled={saving}
+ className="inline-flex items-center gap-2 rounded bg-port-accent px-3 py-2 text-sm font-medium text-black hover:bg-port-accent/90"
+ >
+ <Save size={15} aria-hidden="true" />
+ {saving ? 'Saving' : 'Save'}
+ </button>
+ {isExisting && (
+ <button
+ type="button"
+ onClick={onDelete}
+ className="inline-flex items-center gap-2 rounded border border-rose-500/40 px-3 py-2 text-sm text-rose-300 hover:bg-rose-500/10"
+ >
+ <Trash2 size={15} aria-hidden="true" />
+ Delete
+ </button>
+ )}
+ </div>
+ </form>
+ );
+}
+
+function MemoryLinksPanel({ personId }) {
+ const [links, setLinks] = useState([]);
+ const [memories, setMemories] = useState([]);
+ const [memoryId, setMemoryId] = useState('');
+ const [note, setNote] = useState('');
+ const [loading, setLoading] = useState(false);
+
+ useEffect(() => {
+ if (!personId) return;
+ let cancelled = false;
+ setLoading(true);
+ Promise.all([
+ api.getTribeMemoryLinks(personId).catch(() => ({ links: [] })),
+ api.getMemories({ limit: 25, sortBy: 'updatedAt', sortOrder: 'desc' }).catch(() => ({ memories: [] })),
+ ]).then(([linkResult, memoryResult]) => {
+ if (cancelled) return;
+ setLinks(linkResult?.links || []);
+ setMemories(memoryResult?.memories || []);
+ }).finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ return () => { cancelled = true; };
+ }, [personId]);
+
+ const linkMemory = async () => {
+ if (!memoryId) return;
+ const result = await api.linkTribeMemory(personId, { memoryId, note }).catch((err) => {
+ toast.error(err.message || 'Failed to link memory');
+ return null;
+ });
+ if (!result) return;
+ setLinks(result.links || []);
+ setMemoryId('');
+ setNote('');
+ };
+
+ const unlinkMemory = async (id) => {
+ await api.unlinkTribeMemory(personId, id).catch((err) => toast.error(err.message || 'Failed to unlink memory'));
+ setLinks((current) => current.filter((link) => link.memoryId !== id));
+ };
+
+ return (
+ <section className="mt-4 border border-port-border bg-port-card rounded p-4">
+ <div className="flex items-center justify-between gap-3">
+ <h2 className="text-sm font-semibold text-white">Brain Memories</h2>
+ {loading && <span className="text-xs text-gray-500">Loading</span>}
+ </div>
+ <div className="mt-3 grid gap-2">
+ <select
+ value={memoryId}
+ onChange={(event) => setMemoryId(event.target.value)}
+ className="w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white outline-none focus:border-port-accent"
+ >
+ <option value="">Select recent memory</option>
+ {memories.map((memory) => (
+ <option key={memory.id} value={memory.id}>{memory.summary || memory.id}</option>
+ ))}
+ </select>
+ <input
+ value={note}
+ onChange={(event) => setNote(event.target.value)}
+ className="w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white outline-none focus:border-port-accent"
+ placeholder="Why this memory matters"
+ />
+ <button
+ type="button"
+ onClick={linkMemory}
+ disabled={!memoryId}
+ className="inline-flex items-center justify-center gap-2 rounded border border-port-border px-3 py-2 text-sm text-gray-300 hover:bg-port-border/40 hover:text-white disabled:opacity-50"
+ >
+ <Plus size={15} aria-hidden="true" />
+ Link Memory
+ </button>
+ </div>
+
+ <div className="mt-4 grid gap-2">
+ {links.length ? links.map((link) => (
+ <div key={link.memoryId} className="rounded border border-port-border bg-port-bg p-3">
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0">
+ <p className="text-sm font-medium text-white line-clamp-2">{link.memory?.summary || link.memoryId}</p>
+ {link.note && <p className="mt-1 text-xs text-gray-500">{link.note}</p>}
+ </div>
+ <button
+ type="button"
+ onClick={() => unlinkMemory(link.memoryId)}
+ title="Unlink memory"
+ aria-label="Unlink memory"
+ className="shrink-0 rounded p-1 text-gray-500 hover:text-rose-300"
+ >
+ <X size={14} aria-hidden="true" />
+ </button>
+ </div>
+ </div>
+ )) : (
+ <p className="text-sm text-gray-500">No memories linked yet.</p>
+ )}
+ </div>
+ </section>
+ );
+}
+
+function TouchpointsPanel({ personId }) {
+ const [touchpoints, setTouchpoints] = useState([]);
+
+ useEffect(() => {
+ if (!personId) return;
+ let cancelled = false;
+ api.getTribeTouchpoints(personId, 8)
+ .then((result) => { if (!cancelled) setTouchpoints(result?.touchpoints || []); })
+ .catch(() => { if (!cancelled) setTouchpoints([]); });
+ return () => { cancelled = true; };
+ }, [personId]);
+
+ if (!personId) return null;
+
+ return (
+ <section className="mt-4 border border-port-border bg-port-card rounded p-4">
+ <h2 className="text-sm font-semibold text-white">Touchpoints</h2>
+ <div className="mt-3 grid gap-2">
+ {touchpoints.length ? touchpoints.map((touchpoint) => (
+ <div key={touchpoint.id} className="rounded border border-port-border bg-port-bg p-3">
+ <div className="flex items-center justify-between gap-3 text-xs text-gray-500">
+ <span>{touchpoint.happenedAt?.slice(0, 10)}</span>
+ <span>{touchpoint.source}</span>
+ </div>
+ <p className="mt-1 text-sm text-gray-300">{touchpoint.summary || touchpoint.channel || 'Touchpoint'}</p>
+ </div>
+ )) : (
+ <p className="text-sm text-gray-500">No touchpoints logged yet.</p>
+ )}
+ </div>
+ </section>
+ );
+}
+
+function EmptyState({ onNew }) {
+ return (
+ <div className="flex min-h-[280px] flex-col items-center justify-center rounded border border-dashed border-port-border bg-port-card/60 p-8 text-center">
+ <Users size={42} className="text-gray-600" aria-hidden="true" />
+ <h2 className="mt-4 text-lg font-semibold text-white">No relationships yet</h2>
+ <p className="mt-2 max-w-md text-sm text-gray-500">
+ Add the first person in your circle, then PortOS can keep cadence, ring size, and care queue visible.
+ </p>
+ <button
+ type="button"
+ onClick={onNew}
+ className="mt-5 inline-flex items-center gap-2 rounded bg-port-accent px-3 py-2 text-sm font-medium text-black hover:bg-port-accent/90"
+ >
+ <Plus size={15} aria-hidden="true" />
+ Add Relationship
+ </button>
+ </div>
+ );
+}
+
+function CareQueue({ contacts, onSelect, onLogTouch, onNew }) {
+ const queue = [...contacts].sort((a, b) => {
+ const aStatus = contactStatus(a);
+ const bStatus = contactStatus(b);
+ const aScore = aStatus.daysRemaining == null ? -999 : aStatus.daysRemaining;
+ const bScore = bStatus.daysRemaining == null ? -999 : bStatus.daysRemaining;
+ return aScore - bScore;
+ });
+
+ if (!queue.length) return <EmptyState onNew={onNew} />;
+
+ return (
+ <div className="grid gap-3">
+ {queue.map((contact) => (
+ <ContactCard
+ key={contact.id}
+ contact={contact}
+ active={false}
+ onSelect={() => onSelect(contact)}
+ onLogTouch={() => onLogTouch(contact.id)}
+ />
+ ))}
+ </div>
+ );
+}
+
+function FocusPanel({ contacts }) {
+ const byEnergy = ENERGY.map((energy) => ({
+ ...energy,
+ count: contacts.filter((contact) => contact.energy === energy.id).length,
+ }));
+ const support = contacts.filter((contact) => contact.ring === 'support');
+ const nextMoves = contacts.filter((contact) => contact.nextMove).slice(0, 8);
+
+ return (
+ <div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(280px,360px)]">
+ <section className="border border-port-border bg-port-card rounded p-4">
+ <div className="flex items-center gap-2">
+ <Heart size={18} className="text-port-accent" aria-hidden="true" />
+ <h2 className="text-sm font-semibold text-white">Inner Circle</h2>
+ </div>
+ <div className="mt-4 grid gap-3 sm:grid-cols-2">
+ {support.length ? support.map((contact) => (
+ <div key={contact.id} className="rounded border border-port-border bg-port-bg p-3">
+ <p className="font-medium text-white">{contact.name}</p>
+ <p className="mt-1 text-sm text-gray-500">{contact.relationship || 'Support'}</p>
+ {contact.nextMove && <p className="mt-3 text-sm text-gray-300">{contact.nextMove}</p>}
+ </div>
+ )) : (
+ <p className="text-sm text-gray-500 sm:col-span-2">No support-ring relationships yet.</p>
+ )}
+ </div>
+ </section>
+
+ <aside className="grid gap-4">
+ <div className="border border-port-border bg-port-card rounded p-4">
+ <h2 className="text-sm font-semibold text-white">Energy Mix</h2>
+ <div className="mt-4 grid gap-2">
+ {byEnergy.map((energy) => (
+ <div key={energy.id} className="flex items-center justify-between gap-3">
+ <span className={`rounded border px-2 py-1 text-xs ${energy.className}`}>{energy.label}</span>
+ <span className="text-sm text-gray-300">{energy.count}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <div className="border border-port-border bg-port-card rounded p-4">
+ <h2 className="text-sm font-semibold text-white">Next Moves</h2>
+ <div className="mt-4 grid gap-3">
+ {nextMoves.length ? nextMoves.map((contact) => (
+ <div key={contact.id} className="border-l border-port-accent/40 pl-3">
+ <p className="text-sm font-medium text-white">{contact.name}</p>
+ <p className="text-sm text-gray-400">{contact.nextMove}</p>
+ </div>
+ )) : (
+ <p className="text-sm text-gray-500">No next moves captured.</p>
+ )}
+ </div>
+ </div>
+ </aside>
+ </div>
+ );
+}
+
+export default function Tribe() {
+ const [contacts, setContacts] = useState([]);
+ const [draft, setDraft] = useState(emptyDraft);
+ const [query, setQuery] = useState('');
+ const [ringFilter, setRingFilter] = useState('all');
+ const [activeTab, setActiveTab] = useState('circle');
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+
+ const selectedId = draft.id;
+
+ const loadContacts = async () => {
+ setLoading(true);
+ const result = await api.getTribePeople({ silent: true }).catch((err) => {
+ toast.error(err.message || 'Failed to load Tribe');
+ return { people: [] };
+ });
+ let people = result?.people || [];
+
+ const legacy = typeof localStorage === 'undefined'
+ ? []
+ : parseStoredContacts(localStorage.getItem(STORAGE_KEY));
+ if (people.length === 0 && legacy.length > 0) {
+ const imported = [];
+ for (const contact of legacy) {
+ const created = await api.createTribePerson({
+ name: contact.name || 'Unnamed person',
+ relationship: contact.relationship || '',
+ ring: contact.ring || 'tribe',
+ cadenceDays: Math.max(1, Number(contact.cadenceDays) || ringFor(contact.ring).cadenceDays),
+ lastContact: contact.lastContact || null,
+ channel: contact.channel || '',
+ energy: contact.energy || 'steady',
+ tags: tagsToArray(contact.tags),
+ nextMove: contact.nextMove || '',
+ notes: contact.notes || '',
+ }).catch(() => null);
+ if (created) imported.push(created);
+ }
+ if (imported.length > 0) {
+ people = imported;
+ localStorage.removeItem(STORAGE_KEY);
+ toast.success(`Imported ${imported.length} Tribe relationship${imported.length === 1 ? '' : 's'} into Postgres`);
+ }
+ }
+
+ setContacts(people);
+ setLoading(false);
+ };
+
+ useEffect(() => {
+ loadContacts();
+ }, []);
+
+ const filteredContacts = useMemo(() => {
+ const normalized = query.trim().toLowerCase();
+ return contacts.filter((contact) => {
+ if (ringFilter !== 'all' && contact.ring !== ringFilter) return false;
+ if (!normalized) return true;
+ const haystack = [
+ contact.name,
+ contact.relationship,
+ contact.channel,
+ tagsToArray(contact.tags).join(' '),
+ contact.nextMove,
+ contact.notes,
+ ].join(' ').toLowerCase();
+ return haystack.includes(normalized);
+ });
+ }, [contacts, query, ringFilter]);
+
+ const overdueCount = contacts.filter((contact) => ['missing', 'overdue'].includes(contactStatus(contact).state)).length;
+ const soonCount = contacts.filter((contact) => contactStatus(contact).state === 'soon').length;
+ const supportCount = contacts.filter((contact) => contact.ring === 'support').length;
+
+ const selectContact = (contact) => setDraft({
+ ...emptyDraft(),
+ ...contact,
+ tags: tagsToInput(contact.tags),
+ cadenceDays: contact.cadenceDays || ringFor(contact.ring).cadenceDays,
+ });
+
+ const saveDraft = async () => {
+ const normalized = {
+ ...draft,
+ name: draft.name.trim() || 'Unnamed person',
+ relationship: draft.relationship.trim(),
+ channel: draft.channel.trim(),
+ tags: tagsToArray(draft.tags),
+ nextMove: draft.nextMove.trim(),
+ notes: draft.notes.trim(),
+ cadenceDays: Math.max(1, Number(draft.cadenceDays) || ringFor(draft.ring).cadenceDays),
+ };
+
+ setSaving(true);
+ const saved = draft.id
+ ? await api.updateTribePerson(draft.id, normalized).catch((err) => {
+ toast.error(err.message || 'Failed to save relationship');
+ return null;
+ })
+ : await api.createTribePerson(normalized).catch((err) => {
+ toast.error(err.message || 'Failed to save relationship');
+ return null;
+ });
+ setSaving(false);
+ if (!saved) return;
+
+ setContacts((current) => (
+ current.some((contact) => contact.id === saved.id)
+ ? current.map((contact) => (contact.id === saved.id ? saved : contact))
+ : [saved, ...current]
+ ));
+ selectContact(saved);
+ };
+
+ const deleteDraft = async () => {
+ if (!draft.id) return;
+ await api.deleteTribePerson(draft.id).catch((err) => {
+ toast.error(err.message || 'Failed to delete relationship');
+ return null;
+ });
+ setContacts((current) => current.filter((contact) => contact.id !== draft.id));
+ setDraft(emptyDraft());
+ };
+
+ const logTouch = async (id) => {
+ const date = todayISO();
+ await api.createTribeTouchpoint(id, {
+ happenedAt: new Date().toISOString(),
+ channel: contacts.find((contact) => contact.id === id)?.channel || '',
+ summary: 'Manual touchpoint',
+ source: 'user',
+ }).catch((err) => {
+ toast.error(err.message || 'Failed to log touchpoint');
+ return null;
+ });
+ setContacts((current) => current.map((contact) => (
+ contact.id === id ? { ...contact, lastContact: date } : contact
+ )));
+ if (draft.id === id) setDraft((current) => ({ ...current, lastContact: date }));
+ };
+
+ const clearFilters = () => {
+ setQuery('');
+ setRingFilter('all');
+ };
+
+ const actions = (
+ <button
+ type="button"
+ onClick={() => setDraft(emptyDraft())}
+ className="inline-flex items-center gap-2 rounded border border-port-border px-3 py-2 text-sm text-gray-300 hover:bg-port-border/40 hover:text-white"
+ >
+ <Plus size={15} aria-hidden="true" />
+ Add
+ </button>
+ );
+
+ return (
+ <div className="flex h-full flex-col">
+ <PageHeader
+ icon={Users}
+ title="Tribe"
+ subtitle="Relationships, rings, cadence, and care."
+ actions={actions}
+ />
+
+ <TabPills tabs={TABS} activeTab={activeTab} onChange={setActiveTab} ariaLabel="Tribe sections" />
+
+ <main className="flex-1 overflow-auto p-4">
+ <div className="mx-auto grid max-w-7xl gap-4">
+ {loading && (
+ <div className="flex min-h-[220px] items-center justify-center">
+ <BrailleSpinner text="Loading Tribe" />
+ </div>
+ )}
+ {!loading && (
+ <>
+ <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
+ <StatTile icon={Users} label="Relationships" value={contacts.length} detail={`${supportCount} support ring`} />
+ <StatTile icon={Clock} label="Needs Care" value={overdueCount} detail="missing or overdue" />
+ <StatTile icon={Calendar} label="Coming Up" value={soonCount} detail="due within 7 days" />
+ <StatTile icon={Heart} label="Capacity" value={`${contacts.length}/150`} detail="village horizon" />
+ </div>
+
+ {activeTab === 'circle' && (
+ <div className="grid gap-4 xl:grid-cols-[310px_minmax(0,1fr)_minmax(330px,420px)]">
+ <aside className="grid content-start gap-3">
+ {RINGS.map((ring) => (
+ <RingMeter
+ key={ring.id}
+ ring={ring}
+ contacts={contacts}
+ active={ringFilter === ring.id}
+ onClick={() => setRingFilter(ringFilter === ring.id ? 'all' : ring.id)}
+ />
+ ))}
+ </aside>
+
+ <section className="min-w-0">
+ <div className="mb-3 flex flex-col gap-2 sm:flex-row">
+ <label className="relative min-w-0 flex-1">
+ <Search size={16} className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-gray-500" aria-hidden="true" />
+ <input
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ className="w-full rounded border border-port-border bg-port-card py-2 pl-9 pr-3 text-sm text-white outline-none focus:border-port-accent"
+ placeholder="Search relationships"
+ />
+ </label>
+ <label className="relative sm:w-44">
+ <Filter size={15} className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-gray-500" aria-hidden="true" />
+ <select
+ value={ringFilter}
+ onChange={(event) => setRingFilter(event.target.value)}
+ className="w-full rounded border border-port-border bg-port-card py-2 pl-9 pr-3 text-sm text-white outline-none focus:border-port-accent"
+ >
+ <option value="all">All rings</option>
+ {RINGS.map((ring) => <option key={ring.id} value={ring.id}>{ring.label}</option>)}
+ </select>
+ </label>
+ {(query || ringFilter !== 'all') && (
+ <button
+ type="button"
+ onClick={clearFilters}
+ title="Clear filters"
+ aria-label="Clear filters"
+ className="inline-flex h-10 w-10 items-center justify-center rounded border border-port-border text-gray-400 hover:bg-port-border/40 hover:text-white"
+ >
+ <X size={16} aria-hidden="true" />
+ </button>
+ )}
+ </div>
+
+ {contacts.length === 0 ? (
+ <EmptyState onNew={() => setDraft(emptyDraft())} />
+ ) : (
+ <div className="grid gap-3 md:grid-cols-2">
+ {filteredContacts.map((contact) => (
+ <ContactCard
+ key={contact.id}
+ contact={contact}
+ active={selectedId === contact.id}
+ onSelect={() => selectContact(contact)}
+ onLogTouch={() => logTouch(contact.id)}
+ />
+ ))}
+ {filteredContacts.length === 0 && (
+ <div className="rounded border border-port-border bg-port-card p-8 text-center text-sm text-gray-500 md:col-span-2">
+ No relationships match the current filters.
+ </div>
+ )}
+ </div>
+ )}
+ </section>
+
+ <aside className="min-w-0">
+ <ContactForm
+ draft={draft}
+ onChange={setDraft}
+ onSave={saveDraft}
+ onDelete={deleteDraft}
+ onNew={() => setDraft(emptyDraft())}
+ isExisting={Boolean(draft.id)}
+ saving={saving}
+ />
+ {draft.id && <MemoryLinksPanel personId={draft.id} />}
+ {draft.id && <TouchpointsPanel personId={draft.id} />}
+ </aside>
+ </div>
+ )}
+
+ {activeTab === 'care' && (
+ <div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(330px,420px)]">
+ <CareQueue
+ contacts={contacts}
+ onSelect={(contact) => { selectContact(contact); setActiveTab('circle'); }}
+ onLogTouch={logTouch}
+ onNew={() => setDraft(emptyDraft())}
+ />
+ <ContactForm
+ draft={draft}
+ onChange={setDraft}
+ onSave={saveDraft}
+ onDelete={deleteDraft}
+ onNew={() => setDraft(emptyDraft())}
+ isExisting={Boolean(draft.id)}
+ saving={saving}
+ />
+ </div>
+ )}
+
+ {activeTab === 'focus' && <FocusPanel contacts={contacts} />}
+ </>
+ )}
+ </div>
+ </main>
+ </div>
+ );
+}
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 514597637f..d35292cee5 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -32,6 +32,7 @@ export * from './apiGSD.js';
export * from './apiGithub.js';
export * from './apiLoops.js';
export * from './apiMemory.js';
+export * from './apiTribe.js';
export * from './apiBrain.js';
export * from './apiNotes.js';
export * from './apiDigitalTwin.js';
diff --git a/client/src/services/apiTribe.js b/client/src/services/apiTribe.js
new file mode 100644
index 0000000000..35062ecac5
--- /dev/null
+++ b/client/src/services/apiTribe.js
@@ -0,0 +1,45 @@
+import { request } from './apiCore.js';
+
+export const getTribePeople = (options = {}) => {
+ const params = new URLSearchParams();
+ if (options.search) params.set('search', options.search);
+ if (options.ring && options.ring !== 'all') params.set('ring', options.ring);
+ const qs = params.toString();
+ return request(`/tribe/people${qs ? `?${qs}` : ''}`, { silent: options.silent });
+};
+
+export const createTribePerson = (data) => request('/tribe/people', {
+ method: 'POST',
+ body: JSON.stringify(data),
+});
+
+export const updateTribePerson = (id, data) => request(`/tribe/people/${id}`, {
+ method: 'PUT',
+ body: JSON.stringify(data),
+});
+
+export const deleteTribePerson = (id) => request(`/tribe/people/${id}`, { method: 'DELETE' });
+
+export const getTribeTouchpoints = (personId, limit = 50) =>
+ request(`/tribe/people/${personId}/touchpoints?limit=${limit}`);
+
+export const createTribeTouchpoint = (personId, data = {}) => request(`/tribe/people/${personId}/touchpoints`, {
+ method: 'POST',
+ body: JSON.stringify(data),
+});
+
+export const createTribeCalendarTouchpoint = (personId, data) =>
+ request(`/tribe/people/${personId}/touchpoints/calendar`, {
+ method: 'POST',
+ body: JSON.stringify(data),
+ });
+
+export const getTribeMemoryLinks = (personId) => request(`/tribe/people/${personId}/memories`);
+
+export const linkTribeMemory = (personId, data) => request(`/tribe/people/${personId}/memories`, {
+ method: 'POST',
+ body: JSON.stringify(data),
+});
+
+export const unlinkTribeMemory = (personId, memoryId) =>
+ request(`/tribe/people/${personId}/memories/${memoryId}`, { method: 'DELETE' });
diff --git a/server/index.js b/server/index.js
index 08142e8199..d998f090d8 100644
--- a/server/index.js
+++ b/server/index.js
@@ -45,6 +45,7 @@ import feedsRoutes from './routes/feeds.js';
import gsdRoutes from './routes/gsd.js';
import catalogRoutes from './routes/catalog.js';
import memoryRoutes from './routes/memory.js';
+import tribeRoutes from './routes/tribe.js';
import notificationsRoutes from './routes/notifications.js';
import standardizeRoutes from './routes/standardize.js';
import brainRoutes from './routes/brain.js';
@@ -477,6 +478,7 @@ app.use('/api/feature-agents', featureAgentsRoutes);
app.use('/api/feeds', feedsRoutes);
app.use('/api/catalog', catalogRoutes);
app.use('/api/memory', memoryRoutes);
+app.use('/api/tribe', tribeRoutes);
app.use('/api/notifications', notificationsRoutes);
app.use('/api/standardize', standardizeRoutes);
app.use('/api/brain/import', brainImportRoutes);
diff --git a/server/lib/db.js b/server/lib/db.js
index 62ab1b01d0..21460524ac 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -354,6 +354,47 @@ async function ensureSchemaImpl() {
id TEXT PRIMARY KEY,
applied_at TIMESTAMPTZ DEFAULT NOW()
)`,
+ `CREATE TABLE IF NOT EXISTS tribe_people (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ name TEXT NOT NULL,
+ relationship TEXT DEFAULT '',
+ ring VARCHAR(32) NOT NULL DEFAULT 'tribe',
+ cadence_days INTEGER NOT NULL DEFAULT 45,
+ last_contact_on DATE,
+ channel TEXT DEFAULT '',
+ energy VARCHAR(32) NOT NULL DEFAULT 'steady',
+ tags TEXT[] DEFAULT '{}',
+ next_move TEXT DEFAULT '',
+ notes TEXT DEFAULT '',
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ `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 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,
+ happened_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ channel TEXT DEFAULT '',
+ summary TEXT DEFAULT '',
+ source VARCHAR(32) NOT NULL DEFAULT 'user',
+ calendar_account_id TEXT,
+ calendar_event_id TEXT,
+ metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_tribe_touchpoints_person ON tribe_touchpoints (person_id, happened_at DESC)`,
+ `CREATE INDEX IF NOT EXISTS idx_tribe_touchpoints_calendar ON tribe_touchpoints (calendar_account_id, calendar_event_id)`,
+ `CREATE TABLE IF NOT EXISTS tribe_memory_links (
+ person_id UUID NOT NULL REFERENCES tribe_people(id) ON DELETE CASCADE,
+ memory_id UUID NOT NULL REFERENCES memories(id) ON DELETE CASCADE,
+ note TEXT DEFAULT '',
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ PRIMARY KEY (person_id, memory_id)
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_tribe_memory_links_memory ON tribe_memory_links (memory_id)`,
];
for (const sql of upgrades) {
await pool.query(sql);
@@ -1159,7 +1200,7 @@ async function ensureSchemaImpl() {
'story_builder_sessions', 'writers_room_works', 'writers_room_folders',
'writers_room_draft_versions', 'catalog_ingredients', 'catalog_scraps',
'catalog_user_types', 'creative_director_projects', 'lora_training_runs',
- 'authors',
+ 'authors', 'tribe_people', 'tribe_touchpoints',
];
for (const t of auditedTables) {
catalogDDL.push(`DROP TRIGGER IF EXISTS trg_${t}_audit ON ${t}`);
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 3a2ae3b89b..cda3c1e9ab 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -88,6 +88,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.messages.sync', path: '/messages/sync', label: 'Sync', section: 'Brain', aliases: ['messages-sync'] },
{ id: 'nav.openclaw', path: '/openclaw', label: 'OpenClaw', section: 'Brain', aliases: ['openclaw'] },
{ id: 'nav.social-agents', path: '/agents', label: 'Social Agents', section: 'Brain', aliases: ['social-agents'] },
+ { id: 'nav.tribe', path: '/tribe', label: 'Tribe', section: 'Brain', aliases: ['tribe', 'relationships', 'relationship-manager', 'people'], keywords: ['dunbar', 'friends', 'family', 'network', 'social graph', 'care cadence'] },
{ id: 'nav.devtools.runs', path: '/devtools/runs', label: 'AI Runs', section: 'Dev Tools', aliases: ['ai-runs', 'devtools'] },
{ id: 'nav.devtools.agents', path: '/devtools/agents', label: 'AI Agents', section: 'Dev Tools', aliases: ['ai-agents'] },
diff --git a/server/routes/tribe.js b/server/routes/tribe.js
new file mode 100644
index 0000000000..6b16f705cc
--- /dev/null
+++ b/server/routes/tribe.js
@@ -0,0 +1,128 @@
+import { Router } from 'express';
+import { z } from 'zod';
+
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
+import { partialWithoutDefaults } from '../lib/zodCompat.js';
+import * as tribe from '../services/tribe.js';
+
+const router = Router();
+
+const ringSchema = z.enum(['support', 'core', 'tribe', 'village']);
+const energySchema = z.enum(['nourishing', 'steady', 'complex', 'draining']);
+
+const personSchema = z.object({
+ id: z.string().guid().optional(),
+ name: z.string().min(1).max(200),
+ relationship: z.string().max(200).optional().default(''),
+ ring: ringSchema.optional().default('tribe'),
+ cadenceDays: z.number().int().min(1).max(3650).optional(),
+ lastContact: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).nullable().optional(),
+ channel: z.string().max(200).optional().default(''),
+ energy: energySchema.optional().default('steady'),
+ tags: z.array(z.string().max(80)).max(50).optional().default([]),
+ nextMove: z.string().max(2000).optional().default(''),
+ notes: z.string().max(10000).optional().default(''),
+});
+
+const personUpdateSchema = partialWithoutDefaults(personSchema).extend({
+ id: z.never().optional(),
+});
+
+const touchpointSchema = z.object({
+ happenedAt: z.string().datetime().optional(),
+ channel: z.string().max(200).optional().default(''),
+ summary: z.string().max(2000).optional().default(''),
+ source: z.enum(['user', 'calendar', 'message', 'import']).optional().default('user'),
+ calendarAccountId: z.string().max(200).nullable().optional(),
+ calendarEventId: z.string().max(500).nullable().optional(),
+ metadata: z.record(z.unknown()).optional().default({}),
+});
+
+const calendarTouchpointSchema = z.object({
+ accountId: z.string().guid(),
+ eventId: z.string().min(1).max(500),
+ summary: z.string().max(2000).optional(),
+});
+
+const memoryLinkSchema = z.object({
+ memoryId: z.string().guid(),
+ note: z.string().max(1000).optional().default(''),
+});
+
+router.get('/people', asyncHandler(async (req, res) => {
+ const people = await tribe.listPeople({
+ search: req.query.search || undefined,
+ ring: req.query.ring || undefined,
+ });
+ res.json({ people });
+}));
+
+router.post('/people', asyncHandler(async (req, res) => {
+ const data = validateRequest(personSchema, req.body);
+ const person = await tribe.createPerson(data);
+ req.app.get('io')?.emit('tribe:changed', { personId: person.id });
+ res.status(201).json(person);
+}));
+
+router.get('/people/:id', asyncHandler(async (req, res) => {
+ const person = await tribe.getPerson(req.params.id);
+ if (!person) throw new ServerError('Person not found', { status: 404 });
+ res.json(person);
+}));
+
+router.put('/people/:id', asyncHandler(async (req, res) => {
+ const data = validateRequest(personUpdateSchema, req.body);
+ const person = await tribe.updatePerson(req.params.id, data);
+ if (!person) throw new ServerError('Person not found', { status: 404 });
+ req.app.get('io')?.emit('tribe:changed', { personId: person.id });
+ res.json(person);
+}));
+
+router.delete('/people/:id', asyncHandler(async (req, res) => {
+ const deleted = await tribe.deletePerson(req.params.id);
+ if (!deleted) throw new ServerError('Person not found', { status: 404 });
+ req.app.get('io')?.emit('tribe:changed', { personId: req.params.id });
+ res.json({ success: true });
+}));
+
+router.get('/people/:id/touchpoints', asyncHandler(async (req, res) => {
+ const limit = Math.min(Math.max(parseInt(req.query.limit, 10) || 50, 1), 200);
+ const touchpoints = await tribe.listTouchpoints(req.params.id, limit);
+ res.json({ touchpoints });
+}));
+
+router.post('/people/:id/touchpoints', asyncHandler(async (req, res) => {
+ const data = validateRequest(touchpointSchema, req.body);
+ const touchpoint = await tribe.createTouchpoint(req.params.id, data);
+ req.app.get('io')?.emit('tribe:changed', { personId: req.params.id });
+ res.status(201).json(touchpoint);
+}));
+
+router.post('/people/:id/touchpoints/calendar', asyncHandler(async (req, res) => {
+ const data = validateRequest(calendarTouchpointSchema, req.body);
+ const touchpoint = await tribe.createCalendarTouchpoint(req.params.id, data);
+ req.app.get('io')?.emit('tribe:changed', { personId: req.params.id });
+ res.status(201).json(touchpoint);
+}));
+
+router.get('/people/:id/memories', asyncHandler(async (req, res) => {
+ const links = await tribe.listMemoryLinks(req.params.id);
+ res.json({ links });
+}));
+
+router.post('/people/:id/memories', asyncHandler(async (req, res) => {
+ const { memoryId, note } = validateRequest(memoryLinkSchema, req.body);
+ await tribe.linkMemory(req.params.id, memoryId, note);
+ const links = await tribe.listMemoryLinks(req.params.id);
+ req.app.get('io')?.emit('tribe:changed', { personId: req.params.id });
+ res.status(201).json({ links });
+}));
+
+router.delete('/people/:id/memories/:memoryId', asyncHandler(async (req, res) => {
+ await tribe.unlinkMemory(req.params.id, req.params.memoryId);
+ req.app.get('io')?.emit('tribe:changed', { personId: req.params.id });
+ res.json({ success: true });
+}));
+
+export default router;
diff --git a/server/routes/tribe.test.js b/server/routes/tribe.test.js
new file mode 100644
index 0000000000..126e1343dd
--- /dev/null
+++ b/server/routes/tribe.test.js
@@ -0,0 +1,160 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import tribeRoutes from './tribe.js';
+
+vi.mock('../services/tribe.js', () => ({
+ listPeople: vi.fn(),
+ getPerson: vi.fn(),
+ createPerson: vi.fn(),
+ updatePerson: vi.fn(),
+ deletePerson: vi.fn(),
+ listTouchpoints: vi.fn(),
+ createTouchpoint: vi.fn(),
+ createCalendarTouchpoint: vi.fn(),
+ listMemoryLinks: vi.fn(),
+ linkMemory: vi.fn(),
+ unlinkMemory: vi.fn(),
+}));
+
+import * as tribe from '../services/tribe.js';
+
+const PERSON_ID = '11111111-1111-4111-8111-111111111111';
+const MEMORY_ID = '22222222-2222-4222-8222-222222222222';
+const ACCOUNT_ID = '33333333-3333-4333-8333-333333333333';
+
+describe('Tribe Routes', () => {
+ let app;
+ let emit;
+
+ beforeEach(() => {
+ emit = vi.fn();
+ app = express();
+ app.use(express.json());
+ app.set('io', { emit });
+ app.use('/api/tribe', tribeRoutes);
+ vi.clearAllMocks();
+ });
+
+ it('lists people with search and ring filters', async () => {
+ tribe.listPeople.mockResolvedValue([{ id: PERSON_ID, name: 'Ada' }]);
+
+ const response = await request(app).get('/api/tribe/people?search=ada&ring=core');
+
+ expect(response.status).toBe(200);
+ expect(response.body.people).toEqual([{ id: PERSON_ID, name: 'Ada' }]);
+ expect(tribe.listPeople).toHaveBeenCalledWith({ search: 'ada', ring: 'core' });
+ });
+
+ it('creates a person and emits tribe changes', async () => {
+ tribe.createPerson.mockResolvedValue({ id: PERSON_ID, name: 'Ada', ring: 'core' });
+
+ const response = await request(app)
+ .post('/api/tribe/people')
+ .send({ name: 'Ada', ring: 'core', tags: ['mentor'] });
+
+ expect(response.status).toBe(201);
+ expect(response.body.id).toBe(PERSON_ID);
+ expect(tribe.createPerson).toHaveBeenCalledWith(expect.objectContaining({
+ name: 'Ada',
+ ring: 'core',
+ tags: ['mentor'],
+ }));
+ expect(emit).toHaveBeenCalledWith('tribe:changed', { personId: PERSON_ID });
+ });
+
+ it('updates a person with partial fields', async () => {
+ tribe.updatePerson.mockResolvedValue({ id: PERSON_ID, name: 'Ada', nextMove: 'Coffee' });
+
+ const response = await request(app)
+ .put(`/api/tribe/people/${PERSON_ID}`)
+ .send({ nextMove: 'Coffee' });
+
+ expect(response.status).toBe(200);
+ expect(tribe.updatePerson).toHaveBeenCalledWith(PERSON_ID, { nextMove: 'Coffee' });
+ expect(emit).toHaveBeenCalledWith('tribe:changed', { personId: PERSON_ID });
+ });
+
+ it('logs touchpoints with calendar-ready metadata', async () => {
+ const touchpoint = {
+ id: 'touch-1',
+ personId: PERSON_ID,
+ source: 'calendar',
+ calendarAccountId: ACCOUNT_ID,
+ calendarEventId: 'event-1',
+ };
+ tribe.createTouchpoint.mockResolvedValue(touchpoint);
+
+ const response = await request(app)
+ .post(`/api/tribe/people/${PERSON_ID}/touchpoints`)
+ .send({
+ happenedAt: '2026-06-18T15:00:00.000Z',
+ source: 'calendar',
+ calendarAccountId: ACCOUNT_ID,
+ calendarEventId: 'event-1',
+ metadata: { title: 'Walk' },
+ });
+
+ expect(response.status).toBe(201);
+ expect(response.body.calendarEventId).toBe('event-1');
+ expect(tribe.createTouchpoint).toHaveBeenCalledWith(PERSON_ID, expect.objectContaining({
+ source: 'calendar',
+ calendarAccountId: ACCOUNT_ID,
+ calendarEventId: 'event-1',
+ metadata: { title: 'Walk' },
+ }));
+ });
+
+ it('creates touchpoints from calendar events', async () => {
+ tribe.createCalendarTouchpoint.mockResolvedValue({
+ id: 'touch-2',
+ personId: PERSON_ID,
+ source: 'calendar',
+ });
+
+ const response = await request(app)
+ .post(`/api/tribe/people/${PERSON_ID}/touchpoints/calendar`)
+ .send({ accountId: ACCOUNT_ID, eventId: 'cal-event-1', summary: 'Synced over lunch' });
+
+ expect(response.status).toBe(201);
+ expect(tribe.createCalendarTouchpoint).toHaveBeenCalledWith(PERSON_ID, {
+ accountId: ACCOUNT_ID,
+ eventId: 'cal-event-1',
+ summary: 'Synced over lunch',
+ });
+ });
+
+ it('links and unlinks brain memories for a person', async () => {
+ tribe.linkMemory.mockResolvedValue({ personId: PERSON_ID, memoryId: MEMORY_ID });
+ tribe.listMemoryLinks.mockResolvedValue([{ personId: PERSON_ID, memoryId: MEMORY_ID }]);
+
+ const createResponse = await request(app)
+ .post(`/api/tribe/people/${PERSON_ID}/memories`)
+ .send({ memoryId: MEMORY_ID, note: 'Birthday context' });
+
+ expect(createResponse.status).toBe(201);
+ expect(createResponse.body.links).toEqual([{ personId: PERSON_ID, memoryId: MEMORY_ID }]);
+ expect(tribe.linkMemory).toHaveBeenCalledWith(PERSON_ID, MEMORY_ID, 'Birthday context');
+
+ tribe.unlinkMemory.mockResolvedValue(true);
+ const deleteResponse = await request(app)
+ .delete(`/api/tribe/people/${PERSON_ID}/memories/${MEMORY_ID}`);
+
+ expect(deleteResponse.status).toBe(200);
+ expect(deleteResponse.body.success).toBe(true);
+ expect(tribe.unlinkMemory).toHaveBeenCalledWith(PERSON_ID, MEMORY_ID);
+ });
+
+ it('rejects invalid person payloads before service calls', async () => {
+ const validationApp = express();
+ validationApp.use(express.json());
+ validationApp.use('/api/tribe', tribeRoutes);
+
+ const response = await request(validationApp)
+ .post('/api/tribe/people')
+ .send({ name: '', ring: 'outer-space' });
+
+ expect(response.status).toBe(400);
+ expect(tribe.createPerson).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index e87499c395..ad17929b3c 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -76,6 +76,52 @@ CREATE TABLE IF NOT EXISTS memory_links (
PRIMARY KEY (source_id, target_id)
);
+-- Relationship / Tribe graph. People live in Postgres so they can be joined to
+-- Brain memories, touchpoint history, and calendar event references.
+CREATE TABLE IF NOT EXISTS tribe_people (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ name TEXT NOT NULL,
+ relationship TEXT DEFAULT '',
+ ring VARCHAR(32) NOT NULL DEFAULT 'tribe',
+ cadence_days INTEGER NOT NULL DEFAULT 45,
+ last_contact_on DATE,
+ channel TEXT DEFAULT '',
+ energy VARCHAR(32) NOT NULL DEFAULT 'steady',
+ tags TEXT[] DEFAULT '{}',
+ next_move TEXT DEFAULT '',
+ notes TEXT DEFAULT '',
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+);
+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 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,
+ happened_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ channel TEXT DEFAULT '',
+ summary TEXT DEFAULT '',
+ source VARCHAR(32) NOT NULL DEFAULT 'user',
+ calendar_account_id TEXT,
+ calendar_event_id TEXT,
+ metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW()
+);
+CREATE INDEX IF NOT EXISTS idx_tribe_touchpoints_person ON tribe_touchpoints (person_id, happened_at DESC);
+CREATE INDEX IF NOT EXISTS idx_tribe_touchpoints_calendar ON tribe_touchpoints (calendar_account_id, calendar_event_id);
+
+CREATE TABLE IF NOT EXISTS tribe_memory_links (
+ person_id UUID NOT NULL REFERENCES tribe_people(id) ON DELETE CASCADE,
+ memory_id UUID NOT NULL REFERENCES memories(id) ON DELETE CASCADE,
+ note TEXT DEFAULT '',
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ PRIMARY KEY (person_id, memory_id)
+);
+CREATE INDEX IF NOT EXISTS idx_tribe_memory_links_memory ON tribe_memory_links (memory_id);
+
-- Auto-update updated_at and sync_sequence on content/metadata changes.
-- Skips bump for access-stat-only updates (access_count, last_accessed)
-- to avoid sync noise from read operations.
@@ -969,3 +1015,7 @@ DROP TRIGGER IF EXISTS trg_lora_training_runs_audit ON lora_training_runs;
CREATE TRIGGER trg_lora_training_runs_audit AFTER UPDATE OR DELETE ON lora_training_runs FOR EACH ROW EXECUTE FUNCTION record_audit_log();
DROP TRIGGER IF EXISTS trg_authors_audit ON authors;
CREATE TRIGGER trg_authors_audit AFTER UPDATE OR DELETE ON authors FOR EACH ROW EXECUTE FUNCTION record_audit_log();
+DROP TRIGGER IF EXISTS trg_tribe_people_audit ON tribe_people;
+CREATE TRIGGER trg_tribe_people_audit AFTER UPDATE OR DELETE ON tribe_people FOR EACH ROW EXECUTE FUNCTION record_audit_log();
+DROP TRIGGER IF EXISTS trg_tribe_touchpoints_audit ON tribe_touchpoints;
+CREATE TRIGGER trg_tribe_touchpoints_audit AFTER UPDATE OR DELETE ON tribe_touchpoints FOR EACH ROW EXECUTE FUNCTION record_audit_log();
diff --git a/server/services/tribe.js b/server/services/tribe.js
new file mode 100644
index 0000000000..018ece741d
--- /dev/null
+++ b/server/services/tribe.js
@@ -0,0 +1,324 @@
+import { v4 as uuidv4 } from '../lib/uuid.js';
+import { ensureSchema, query, withTransaction } from '../lib/db.js';
+import { ServerError } from '../lib/errorHandler.js';
+import * as calendarSync from './calendarSync.js';
+
+const DEFAULT_RING_CADENCE = {
+ support: 7,
+ core: 21,
+ tribe: 45,
+ village: 90,
+};
+
+function isoDate(value) {
+ if (!value) return null;
+ if (value instanceof Date) return value.toISOString().slice(0, 10);
+ return String(value).slice(0, 10);
+}
+
+function isoDateTime(value) {
+ if (!value) return null;
+ if (value instanceof Date) return value.toISOString();
+ return new Date(value).toISOString();
+}
+
+function normalizeTags(tags) {
+ if (!tags) return [];
+ if (Array.isArray(tags)) return tags.map((tag) => String(tag).trim()).filter(Boolean);
+ return String(tags).split(',').map((tag) => tag.trim()).filter(Boolean);
+}
+
+function rowToPerson(row) {
+ return {
+ id: row.id,
+ name: row.name,
+ relationship: row.relationship || '',
+ ring: row.ring || 'tribe',
+ cadenceDays: row.cadence_days ?? DEFAULT_RING_CADENCE[row.ring] ?? 45,
+ lastContact: isoDate(row.last_contact_on),
+ channel: row.channel || '',
+ energy: row.energy || 'steady',
+ tags: row.tags || [],
+ nextMove: row.next_move || '',
+ notes: row.notes || '',
+ touchpointCount: Number(row.touchpoint_count || 0),
+ linkedMemoryCount: Number(row.linked_memory_count || 0),
+ createdAt: row.created_at?.toISOString?.() ?? row.created_at,
+ updatedAt: row.updated_at?.toISOString?.() ?? row.updated_at,
+ };
+}
+
+function rowToTouchpoint(row) {
+ return {
+ id: row.id,
+ personId: row.person_id,
+ happenedAt: isoDateTime(row.happened_at),
+ channel: row.channel || '',
+ summary: row.summary || '',
+ source: row.source || 'user',
+ calendarAccountId: row.calendar_account_id || null,
+ calendarEventId: row.calendar_event_id || null,
+ metadata: row.metadata || {},
+ createdAt: row.created_at?.toISOString?.() ?? row.created_at,
+ };
+}
+
+function rowToMemoryLink(row) {
+ return {
+ personId: row.person_id,
+ memoryId: row.memory_id,
+ note: row.note || '',
+ createdAt: row.created_at?.toISOString?.() ?? row.created_at,
+ memory: row.memory_id ? {
+ id: row.memory_id,
+ type: row.type,
+ summary: row.summary,
+ content: row.content,
+ category: row.category,
+ tags: row.memory_tags || [],
+ createdAt: row.memory_created_at?.toISOString?.() ?? row.memory_created_at,
+ } : null,
+ };
+}
+
+async function ensureReady() {
+ await ensureSchema();
+}
+
+export async function listPeople(options = {}) {
+ await ensureReady();
+ const conditions = ['deleted = FALSE'];
+ const params = [];
+ let idx = 1;
+ if (options.ring && options.ring !== 'all') {
+ conditions.push(`ring = $${idx++}`);
+ params.push(options.ring);
+ }
+ if (options.search) {
+ conditions.push(`(
+ name ILIKE $${idx} OR relationship ILIKE $${idx} OR channel ILIKE $${idx}
+ OR next_move ILIKE $${idx} OR notes ILIKE $${idx} OR array_to_string(tags, ' ') ILIKE $${idx}
+ )`);
+ params.push(`%${options.search}%`);
+ idx++;
+ }
+
+ const result = await query(
+ `SELECT p.*,
+ (SELECT COUNT(*) FROM tribe_touchpoints t WHERE t.person_id = p.id) AS touchpoint_count,
+ (SELECT COUNT(*) FROM tribe_memory_links ml WHERE ml.person_id = p.id) AS linked_memory_count
+ FROM tribe_people p
+ WHERE ${conditions.join(' AND ')}
+ ORDER BY
+ CASE ring WHEN 'support' THEN 1 WHEN 'core' THEN 2 WHEN 'tribe' THEN 3 WHEN 'village' THEN 4 ELSE 5 END,
+ COALESCE(last_contact_on, DATE '1900-01-01') ASC,
+ name ASC`,
+ params,
+ );
+ return result.rows.map(rowToPerson);
+}
+
+export async function getPerson(id) {
+ await ensureReady();
+ const result = await query(
+ `SELECT p.*,
+ (SELECT COUNT(*) FROM tribe_touchpoints t WHERE t.person_id = p.id) AS touchpoint_count,
+ (SELECT COUNT(*) FROM tribe_memory_links ml WHERE ml.person_id = p.id) AS linked_memory_count
+ FROM tribe_people p
+ WHERE p.id = $1 AND p.deleted = FALSE`,
+ [id],
+ );
+ return result.rows[0] ? rowToPerson(result.rows[0]) : null;
+}
+
+export async function createPerson(data) {
+ await ensureReady();
+ const id = data.id || uuidv4();
+ const ring = data.ring || 'tribe';
+ const cadenceDays = data.cadenceDays ?? DEFAULT_RING_CADENCE[ring] ?? 45;
+ const result = await query(
+ `INSERT INTO tribe_people (
+ id, name, relationship, ring, cadence_days, last_contact_on, channel,
+ energy, tags, next_move, notes, updated_at
+ ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,NOW())
+ RETURNING *, 0 AS touchpoint_count, 0 AS linked_memory_count`,
+ [
+ id,
+ data.name,
+ data.relationship || '',
+ ring,
+ cadenceDays,
+ data.lastContact || null,
+ data.channel || '',
+ data.energy || 'steady',
+ normalizeTags(data.tags),
+ data.nextMove || '',
+ data.notes || '',
+ ],
+ );
+ return rowToPerson(result.rows[0]);
+}
+
+export async function updatePerson(id, updates) {
+ await ensureReady();
+ const current = await getPerson(id);
+ if (!current) return null;
+ const next = { ...current, ...updates };
+ const result = await query(
+ `UPDATE tribe_people
+ SET name = $2,
+ relationship = $3,
+ ring = $4,
+ cadence_days = $5,
+ last_contact_on = $6,
+ channel = $7,
+ energy = $8,
+ tags = $9,
+ next_move = $10,
+ notes = $11,
+ updated_at = NOW()
+ WHERE id = $1 AND deleted = FALSE
+ RETURNING *,
+ (SELECT COUNT(*) FROM tribe_touchpoints t WHERE t.person_id = tribe_people.id) AS touchpoint_count,
+ (SELECT COUNT(*) FROM tribe_memory_links ml WHERE ml.person_id = tribe_people.id) AS linked_memory_count`,
+ [
+ id,
+ next.name,
+ next.relationship || '',
+ next.ring || 'tribe',
+ next.cadenceDays ?? DEFAULT_RING_CADENCE[next.ring] ?? 45,
+ next.lastContact || null,
+ next.channel || '',
+ next.energy || 'steady',
+ normalizeTags(next.tags),
+ next.nextMove || '',
+ next.notes || '',
+ ],
+ );
+ return result.rows[0] ? rowToPerson(result.rows[0]) : null;
+}
+
+export async function deletePerson(id) {
+ await ensureReady();
+ const result = await query(
+ `UPDATE tribe_people
+ SET deleted = TRUE, deleted_at = NOW(), updated_at = NOW()
+ WHERE id = $1 AND deleted = FALSE
+ RETURNING id`,
+ [id],
+ );
+ return result.rowCount > 0;
+}
+
+export async function listTouchpoints(personId, limit = 50) {
+ await ensureReady();
+ const result = await query(
+ `SELECT * FROM tribe_touchpoints
+ WHERE person_id = $1
+ ORDER BY happened_at DESC
+ LIMIT $2`,
+ [personId, limit],
+ );
+ return result.rows.map(rowToTouchpoint);
+}
+
+export async function createTouchpoint(personId, data = {}) {
+ await ensureReady();
+ const person = await getPerson(personId);
+ if (!person) throw new ServerError('Person not found', { status: 404 });
+
+ return withTransaction(async (client) => {
+ const result = await client.query(
+ `INSERT INTO tribe_touchpoints (
+ id, person_id, happened_at, channel, summary, source,
+ calendar_account_id, calendar_event_id, metadata
+ ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)
+ RETURNING *`,
+ [
+ data.id || uuidv4(),
+ personId,
+ data.happenedAt || new Date().toISOString(),
+ data.channel || '',
+ data.summary || '',
+ data.source || 'user',
+ data.calendarAccountId || null,
+ data.calendarEventId || null,
+ data.metadata || {},
+ ],
+ );
+
+ await client.query(
+ `UPDATE tribe_people
+ SET last_contact_on = GREATEST(COALESCE(last_contact_on, DATE '1900-01-01'), $2::date),
+ channel = CASE WHEN $3::text = '' THEN channel ELSE $3::text END,
+ updated_at = NOW()
+ WHERE id = $1`,
+ [personId, data.happenedAt || new Date().toISOString(), data.channel || ''],
+ );
+ return rowToTouchpoint(result.rows[0]);
+ });
+}
+
+export async function createCalendarTouchpoint(personId, { accountId, eventId, summary }) {
+ const event = await calendarSync.getEvent(accountId, eventId);
+ if (!event) throw new ServerError('Calendar event not found', { status: 404 });
+ return createTouchpoint(personId, {
+ happenedAt: event.startTime || event.endTime || new Date().toISOString(),
+ channel: event.location || 'Calendar',
+ summary: summary || event.title || 'Calendar touchpoint',
+ source: 'calendar',
+ calendarAccountId: accountId,
+ calendarEventId: eventId,
+ metadata: {
+ title: event.title,
+ description: event.description,
+ location: event.location,
+ startTime: event.startTime,
+ endTime: event.endTime,
+ organizer: event.organizer,
+ attendees: event.attendees,
+ subcalendarId: event.subcalendarId,
+ subcalendarName: event.subcalendarName,
+ },
+ });
+}
+
+export async function listMemoryLinks(personId) {
+ await ensureReady();
+ const result = await query(
+ `SELECT ml.*, m.type, m.summary, m.content, m.category, m.tags AS memory_tags, m.created_at AS memory_created_at
+ FROM tribe_memory_links ml
+ JOIN memories m ON m.id = ml.memory_id
+ WHERE ml.person_id = $1
+ ORDER BY ml.created_at DESC`,
+ [personId],
+ );
+ return result.rows.map(rowToMemoryLink);
+}
+
+export async function linkMemory(personId, memoryId, note = '') {
+ await ensureReady();
+ const person = await getPerson(personId);
+ if (!person) throw new ServerError('Person not found', { status: 404 });
+ const result = await query(
+ `INSERT INTO tribe_memory_links (person_id, memory_id, note)
+ VALUES ($1, $2, $3)
+ ON CONFLICT (person_id, memory_id)
+ DO UPDATE SET note = EXCLUDED.note
+ RETURNING *`,
+ [personId, memoryId, note],
+ ).catch((err) => {
+ if (err?.code === '23503') throw new ServerError('Memory not found', { status: 404 });
+ throw err;
+ });
+ return result.rows[0];
+}
+
+export async function unlinkMemory(personId, memoryId) {
+ await ensureReady();
+ const result = await query(
+ 'DELETE FROM tribe_memory_links WHERE person_id = $1 AND memory_id = $2',
+ [personId, memoryId],
+ );
+ return result.rowCount > 0;
+}