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

feat: surface Tribe 'needs care' via server cadence check, alert + dashboard widget (#2032)

Adam Eivya93b5d3a9dd2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c585ed1bd2..2aa2f0d27a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -4,6 +4,10 @@
- **Switch project workspaces from ⌘K and voice, and CoS now auto-snapshots the workspace it leaves.** A new `workspace_switch` action ("switch workspace to BookLoom", "restore my PortOS context") saves a snapshot of the workspace you're leaving, then reconciles the target project's saved context — git branch, in-repo shell sessions, scoped tasks — and reports what's still live to re-attach; it appears in the ⌘K palette and resolves by voice. When CoS dispatches a coding agent against a different app/repo than it was last working in, it now silently snapshots the previous workspace's context first (snapshot-only — no auto-restore, no LLM calls), so switching between repos preserves what each project looked like, visible on the Workspace Contexts page (#2035).
+## Tribe
+
+- **"Who needs care" now surfaces outside the Tribe page — as a Proactive Alert and a dashboard widget (#2032).** Overdue-contact status is now computed server-side (`getCareSummary`/`personCadenceStatus` in `server/services/tribe.js`, exposed at `GET /api/tribe/care`) as a single source of truth mirroring the Tribe page's cadence logic. Proactive Alerts gains a `checkTribeCadence()` check that emits "N people are overdue for contact" linking to `/tribe` (quiet when none are), and a new gated `Tribe Care` dashboard widget lists the most-overdue people (or an "all caught up" state), hidden entirely on installs with no Tribe people.
+
## Delete confirmations
- **Destructive actions now show a clear "Delete? / Cancel" prompt instead of a hidden second click.** Deleting a round, universe, series, share bucket, issue/episode, or a Writers Room work/folder — and removing an Ask conversation or deleting a world in the Universe Builder — used to silently re-arm the same button on the first click, with nothing on screen telling you a second click was needed. Each of these now pops an explicit inline confirm/cancel affordance right where you clicked, so it's obvious what will happen and easy to back out. The pipeline's "replace existing scenes / pages / audio lines" extract buttons got the same treatment (an inline "Replace? / Cancel" row) instead of arming via a fleeting toast. Delete/confirm controls in the Writers Room library were also enlarged to a comfortable 44px touch target for mobile.
diff --git a/client/src/components/TribeCareWidget.jsx b/client/src/components/TribeCareWidget.jsx
new file mode 100644
index 0000000000..239f027b90
--- /dev/null
+++ b/client/src/components/TribeCareWidget.jsx
@@ -0,0 +1,62 @@
+import { Link } from 'react-router-dom';
+import { Users, ArrowRight } from 'lucide-react';
+
+// Surfaces who in the Tribe is overdue for contact on the dashboard. Reads the
+// server-computed care summary from dashboardState (no duplicate fetch — the
+// overdue/cadence logic is a single server-side source of truth in
+// server/services/tribe.js). Gated in the registry to hide when the Tribe has
+// no people; renders a positive "all caught up" state when nobody is overdue.
+export default function TribeCareWidget({ dashboardState }) {
+ const care = dashboardState?.tribeCare;
+ if (!care?.hasPeople) return null;
+
+ const overdue = care.overdue || [];
+ const remaining = care.overdueCount - overdue.length;
+
+ return (
+ <div className="bg-port-card border border-port-border rounded-xl p-4 h-full flex flex-col">
+ <div className="flex items-center gap-2 mb-3">
+ <Users size={16} className="text-gray-500" />
+ <h3 className="text-sm font-semibold text-white">Tribe Care</h3>
+ <Link to="/tribe" className="ml-auto flex items-center gap-1 text-xs text-port-accent hover:underline">
+ Open <ArrowRight size={12} />
+ </Link>
+ </div>
+
+ {care.overdueCount === 0 ? (
+ <div className="flex flex-1 flex-col items-center justify-center py-2 text-center">
+ <div className="text-2xl" aria-hidden="true">🤝</div>
+ <div className="mt-1 text-sm text-port-success">All caught up</div>
+ <div className="text-xs text-gray-500">No overdue check-ins across {care.peopleCount} {care.peopleCount === 1 ? 'person' : 'people'}</div>
+ </div>
+ ) : (
+ <>
+ <div className="mb-2 text-sm text-gray-300">
+ <span className="font-semibold text-port-warning">{care.overdueCount}</span>{' '}
+ {care.overdueCount === 1 ? 'person needs' : 'people need'} care
+ </div>
+ <ul className="flex flex-col gap-1">
+ {overdue.map((person) => (
+ <li key={person.id}>
+ <Link
+ to="/tribe"
+ className="flex items-center gap-2 rounded-lg px-2 py-1.5 hover:bg-port-bg transition-colors"
+ >
+ <span className="min-w-0 flex-1 truncate text-sm text-white">{person.name}</span>
+ <span className={`shrink-0 text-xs ${person.state === 'missing' ? 'text-gray-400' : 'text-port-error'}`}>
+ {person.state === 'missing' ? 'no touchpoint' : `${person.daysOverdue}d overdue`}
+ </span>
+ </Link>
+ </li>
+ ))}
+ </ul>
+ {remaining > 0 && (
+ <Link to="/tribe" className="mt-2 text-xs text-gray-500 hover:text-gray-300">
+ +{remaining} more overdue
+ </Link>
+ )}
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/TribeCareWidget.test.jsx b/client/src/components/TribeCareWidget.test.jsx
new file mode 100644
index 0000000000..ec34211cf3
--- /dev/null
+++ b/client/src/components/TribeCareWidget.test.jsx
@@ -0,0 +1,48 @@
+import { describe, it, expect } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+import TribeCareWidget from './TribeCareWidget';
+
+const renderWidget = (tribeCare) =>
+ render(
+ <MemoryRouter>
+ <TribeCareWidget dashboardState={{ tribeCare }} />
+ </MemoryRouter>
+ );
+
+describe('TribeCareWidget', () => {
+ it('renders nothing when the tribe has no people', () => {
+ const { container } = renderWidget({ hasPeople: false, overdueCount: 0, overdue: [] });
+ expect(container.firstChild).toBeNull();
+ });
+
+ it('renders nothing when the summary is absent (fetch failed)', () => {
+ const { container } = renderWidget(null);
+ expect(container.firstChild).toBeNull();
+ });
+
+ it('shows an all-caught-up state when nobody is overdue', () => {
+ renderWidget({ hasPeople: true, peopleCount: 3, overdueCount: 0, overdue: [] });
+ expect(screen.getByText('All caught up')).toBeTruthy();
+ });
+
+ it('lists overdue people with deep links and an overflow count', () => {
+ renderWidget({
+ hasPeople: true,
+ peopleCount: 5,
+ overdueCount: 4,
+ overdue: [
+ { id: 'a', name: 'Ada', state: 'overdue', daysOverdue: 12 },
+ { id: 'b', name: 'Bo', state: 'missing', daysOverdue: null },
+ ],
+ });
+ expect(screen.getByText('Ada')).toBeTruthy();
+ expect(screen.getByText('12d overdue')).toBeTruthy();
+ expect(screen.getByText('no touchpoint')).toBeTruthy();
+ // 4 overdue total, 2 shown → "+2 more overdue"
+ expect(screen.getByText('+2 more overdue')).toBeTruthy();
+ // Every row links into the Tribe page.
+ const links = screen.getAllByRole('link').map((a) => a.getAttribute('href'));
+ expect(links.every((href) => href === '/tribe')).toBe(true);
+ });
+});
diff --git a/client/src/components/dashboard/widgetRegistry.jsx b/client/src/components/dashboard/widgetRegistry.jsx
index f6945dcc74..0e738aeeb3 100644
--- a/client/src/components/dashboard/widgetRegistry.jsx
+++ b/client/src/components/dashboard/widgetRegistry.jsx
@@ -12,6 +12,7 @@ const UpcomingTasksWidget = lazyWithReload(() => import('../UpcomingTasksWidge
const DecisionLogWidget = lazyWithReload(() => import('../DecisionLogWidget'));
const DeathClockWidget = lazyWithReload(() => import('../DeathClockWidget'));
const DailyPostWidget = lazyWithReload(() => import('../DailyPostWidget'));
+const TribeCareWidget = lazyWithReload(() => import('../TribeCareWidget'));
const ProactiveAlertsWidget = lazyWithReload(() => import('../ProactiveAlertsWidget'));
const QuickBrainCapture = lazyWithReload(() => import('../QuickBrainCapture'));
const QuickIdeaCapture = lazyWithReload(() => import('../QuickIdeaCapture'));
@@ -56,6 +57,7 @@ export const WIDGETS = [
{ id: 'backup', label: 'Backup', Component: BackupWidget, width: 'quarter', defaultH: 5 },
{ id: 'death-clock', label: 'Death Clock', Component: DeathClockWidget, width: 'quarter', defaultH: 4 },
{ id: 'daily-post', label: 'Daily POST', Component: DailyPostWidget, width: 'quarter', defaultH: 3 },
+ { id: 'tribe-care', label: 'Tribe Care', Component: TribeCareWidget, width: 'quarter', defaultH: 4, gate: (s) => !!s.tribeCare?.hasPeople },
{ id: 'quick-stats', label: 'Quick Stats', Component: QuickStatsWidget, width: 'quarter', defaultH: 3, gate: (s) => s.apps.length > 0 },
{ id: 'decision-log', label: 'Decision Log', Component: DecisionLogWidget, width: 'quarter', defaultH: 4 },
{ id: 'activity-streak', label: 'Activity Streak', Component: ActivityStreakWidget, width: 'third', defaultH: 3, gate: (s) => s.usage?.currentStreak > 0 || s.usage?.longestStreak > 0, module: { id: '06', status: 'STREAK', glyph: 'spark' } },
diff --git a/client/src/pages/Dashboard.jsx b/client/src/pages/Dashboard.jsx
index dca7435248..d837622935 100644
--- a/client/src/pages/Dashboard.jsx
+++ b/client/src/pages/Dashboard.jsx
@@ -19,6 +19,7 @@ export default function Dashboard() {
const [apps, setApps] = useState([]);
const [health, setHealth] = useState(null);
const [usage, setUsage] = useState(null);
+ const [tribeCare, setTribeCare] = useState(null);
const [loading, setLoading] = useState(true);
const [dataError, setDataError] = useState(null);
const [layoutsError, setLayoutsError] = useState(null);
@@ -58,14 +59,16 @@ export default function Dashboard() {
const fetchData = useCallback(async () => {
setDataError(null);
- const [appsData, healthData, usageData] = await Promise.all([
+ const [appsData, healthData, usageData, tribeCareData] = await Promise.all([
api.getApps().catch((err) => { setDataError(err.message); return []; }),
api.checkHealth().catch(() => null),
api.getUsage().catch(() => null),
+ api.getTribeCareSummary({ silent: true }).catch(() => null),
]);
setApps(appsData);
setHealth(healthData);
setUsage(usageData);
+ setTribeCare(tribeCareData);
setLoading(false);
}, []);
@@ -162,8 +165,8 @@ export default function Dashboard() {
}), [activeApps]);
const dashboardState = useMemo(
- () => ({ apps, sortedApps, activeApps, appStats, health, usage, refetch: fetchData }),
- [apps, sortedApps, activeApps, appStats, health, usage, fetchData]
+ () => ({ apps, sortedApps, activeApps, appStats, health, usage, tribeCare, refetch: fetchData }),
+ [apps, sortedApps, activeApps, appStats, health, usage, tribeCare, fetchData]
);
// Falls back to a local minimal layout only AFTER the initial fetch has
diff --git a/client/src/services/apiTribe.js b/client/src/services/apiTribe.js
index 35062ecac5..d59f188087 100644
--- a/client/src/services/apiTribe.js
+++ b/client/src/services/apiTribe.js
@@ -8,6 +8,13 @@ export const getTribePeople = (options = {}) => {
return request(`/tribe/people${qs ? `?${qs}` : ''}`, { silent: options.silent });
};
+export const getTribeCareSummary = (options = {}) => {
+ const params = new URLSearchParams();
+ if (options.limit) params.set('limit', String(options.limit));
+ const qs = params.toString();
+ return request(`/tribe/care${qs ? `?${qs}` : ''}`, { silent: options.silent });
+};
+
export const createTribePerson = (data) => request('/tribe/people', {
method: 'POST',
body: JSON.stringify(data),
diff --git a/server/routes/tribe.js b/server/routes/tribe.js
index de379d1276..a1084dc164 100644
--- a/server/routes/tribe.js
+++ b/server/routes/tribe.js
@@ -76,6 +76,14 @@ router.get('/people', asyncHandler(async (req, res) => {
res.json({ people });
}));
+// Care summary — overdue-contact status computed server-side (single source of
+// truth) for the dashboard widget and proactive-alerts check.
+router.get('/care', asyncHandler(async (req, res) => {
+ const limit = Math.min(Math.max(parseInt(req.query.limit, 10) || 5, 1), 50);
+ const summary = await tribe.getCareSummary(limit);
+ res.json(summary);
+}));
+
router.post('/people', asyncHandler(async (req, res) => {
const data = validateRequest(personSchema, req.body);
const person = await tribe.createPerson(data);
diff --git a/server/routes/tribe.test.js b/server/routes/tribe.test.js
index b88164a023..7396fba206 100644
--- a/server/routes/tribe.test.js
+++ b/server/routes/tribe.test.js
@@ -11,6 +11,7 @@ errorEvents.on('error', () => {});
vi.mock('../services/tribe.js', () => ({
listPeople: vi.fn(),
+ getCareSummary: vi.fn(),
getPerson: vi.fn(),
createPerson: vi.fn(),
updatePerson: vi.fn(),
@@ -52,6 +53,16 @@ describe('Tribe Routes', () => {
expect(tribe.listPeople).toHaveBeenCalledWith({ search: 'ada', ring: 'core' });
});
+ it('returns the care summary with a clamped limit', async () => {
+ tribe.getCareSummary.mockResolvedValue({ hasPeople: true, peopleCount: 2, overdueCount: 1, overdue: [] });
+
+ const response = await request(app).get('/api/tribe/care?limit=999');
+
+ expect(response.status).toBe(200);
+ expect(response.body.overdueCount).toBe(1);
+ expect(tribe.getCareSummary).toHaveBeenCalledWith(50); // clamped from 999
+ });
+
it('creates a person and emits tribe changes', async () => {
tribe.createPerson.mockResolvedValue({ id: PERSON_ID, name: 'Ada', ring: 'core' });
diff --git a/server/services/dashboardLayouts.js b/server/services/dashboardLayouts.js
index 32fd198e61..35e6d4fd40 100644
--- a/server/services/dashboardLayouts.js
+++ b/server/services/dashboardLayouts.js
@@ -86,7 +86,7 @@ const DEFAULT_LAYOUTS = [
'apps',
'cos', 'goal-progress', 'upcoming-tasks',
'proactive-alerts', 'review-hub', 'while-away', 'system-health', 'network-exposure', 'backup', 'death-clock', 'quick-stats', 'decision-log',
- 'activity-streak', 'hourly-activity',
+ 'activity-streak', 'hourly-activity', 'tribe-care',
],
// Above-the-fold capture row stretches to h=5 so the Quick Task card
// can show its expanded options (worktree/PR/simplify/etc.) without
@@ -122,6 +122,8 @@ const DEFAULT_LAYOUTS = [
// doesn't collide with the tightly-packed above-the-fold rows.
// Reorderable via the Arrange button on the dashboard.
{ id: 'quick-idea', x: 0, y: 29, w: 4, h: 4 },
+ // Gated on the Tribe having people — hidden on installs that don't use it.
+ { id: 'tribe-care', x: 4, y: 29, w: 4, h: 4 },
],
},
{
diff --git a/server/services/proactiveAlerts.js b/server/services/proactiveAlerts.js
index 5a7dcc8392..a4ff6d025d 100644
--- a/server/services/proactiveAlerts.js
+++ b/server/services/proactiveAlerts.js
@@ -17,6 +17,7 @@ import { getGoals } from './identity.js';
import { getPerformanceSummary, getLearningSummary } from './taskLearning.js';
import { listProcesses } from './pm2.js';
import { getUsage } from './usage.js';
+import { getCareSummary } from './tribe.js';
import { getMemoryStats } from '../lib/memoryStats.js';
const STALL_THRESHOLD_DAYS = 14;
@@ -238,6 +239,26 @@ async function checkUsageSpikes() {
return alerts;
}
+/**
+ * Detect Tribe relationships overdue for contact (or never contacted).
+ * Quiet when nobody is overdue. Reuses the server-side cadence source of truth.
+ */
+async function checkTribeCadence() {
+ const summary = await getCareSummary(3).catch(() => null);
+ if (!summary || summary.overdueCount === 0) return [];
+
+ const names = summary.overdue.map((p) => p.name).filter(Boolean).join(', ');
+ const overflow = summary.overdueCount > summary.overdue.length ? ', …' : '';
+ return [{
+ type: 'tribe_cadence',
+ severity: summary.overdueCount >= 3 ? 'high' : 'medium',
+ title: `${summary.overdueCount} ${summary.overdueCount === 1 ? 'person is' : 'people are'} overdue for contact`,
+ detail: names ? `Reach out to ${names}${overflow}` : 'Overdue check-ins in your Tribe',
+ link: '/tribe',
+ metadata: { overdueCount: summary.overdueCount, peopleCount: summary.peopleCount }
+ }];
+}
+
/**
* Generate all proactive alerts by running all checks.
* Returns a sorted list with critical/high items first.
@@ -245,15 +266,16 @@ async function checkUsageSpikes() {
export async function generateAlerts() {
const startMs = Date.now();
- const [goalAlerts, successAlerts, systemAlerts, learningAlerts, usageAlerts] = await Promise.all([
+ const [goalAlerts, successAlerts, systemAlerts, learningAlerts, usageAlerts, tribeAlerts] = await Promise.all([
checkGoalStalls(),
checkSuccessRates(),
checkSystemHealth(),
checkLearningHealth(),
- checkUsageSpikes()
+ checkUsageSpikes(),
+ checkTribeCadence()
]);
- const all = [...goalAlerts, ...successAlerts, ...systemAlerts, ...learningAlerts, ...usageAlerts];
+ const all = [...goalAlerts, ...successAlerts, ...systemAlerts, ...learningAlerts, ...usageAlerts, ...tribeAlerts];
// Sort by severity: critical > high > medium > low
const severityOrder = { critical: 0, high: 1, medium: 2, low: 3 };
diff --git a/server/services/tribe.js b/server/services/tribe.js
index 1557a919f2..de54a88046 100644
--- a/server/services/tribe.js
+++ b/server/services/tribe.js
@@ -109,6 +109,72 @@ async function ensureReady() {
await ensureSchema();
}
+// Whole days from an ISO date (YYYY-MM-DD) to today, or null when unparseable.
+// Mirrors `daysBetween` in client/src/lib/tribe.js — keep in sync.
+export function daysSinceDate(dateStr) {
+ if (!dateStr) return null;
+ const start = new Date(`${String(dateStr).slice(0, 10)}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);
+}
+
+// Cadence health for a person — the single server-side source of truth for
+// "who needs care." Mirrors `contactStatus` in client/src/lib/tribe.js (state
+// names match: external / missing / overdue / soon / steady). `daysOverdue` is
+// 0 unless overdue, and null for a missing (never-contacted) person so callers
+// can sort those to the top without a magic number.
+export function personCadenceStatus(person) {
+ // External people carry no care cadence — never nag about a drifted contact.
+ if (person.ring === 'external') return { state: 'external', daysRemaining: null, daysOverdue: 0 };
+ const elapsed = daysSinceDate(person.lastContact);
+ if (elapsed == null) return { state: 'missing', daysRemaining: null, daysOverdue: null };
+ const daysRemaining = Number(person.cadenceDays || 45) - elapsed;
+ if (daysRemaining < 0) return { state: 'overdue', daysRemaining, daysOverdue: Math.abs(daysRemaining) };
+ if (daysRemaining <= 7) return { state: 'soon', daysRemaining, daysOverdue: 0 };
+ return { state: 'steady', daysRemaining, daysOverdue: 0 };
+}
+
+// Care summary for the dashboard widget + proactive alert: who in the active
+// tribe (external excluded) is overdue or has no touchpoint yet, most-overdue
+// first. `missing` (never contacted) sorts above any dated-overdue person.
+export async function getCareSummary(limit = 5) {
+ const people = await listPeople();
+ const tribe = people.filter((person) => person.ring !== 'external');
+ const overdue = [];
+ for (const person of tribe) {
+ const status = personCadenceStatus(person);
+ if (status.state === 'overdue' || status.state === 'missing') {
+ overdue.push({ person, status });
+ }
+ }
+ // missing (daysOverdue null) first, then by daysOverdue desc, then by name.
+ overdue.sort((a, b) => {
+ const aMissing = a.status.daysOverdue == null;
+ const bMissing = b.status.daysOverdue == null;
+ if (aMissing !== bMissing) return aMissing ? -1 : 1;
+ if (!aMissing && b.status.daysOverdue !== a.status.daysOverdue) {
+ return b.status.daysOverdue - a.status.daysOverdue;
+ }
+ return String(a.person.name).localeCompare(String(b.person.name));
+ });
+ return {
+ hasPeople: tribe.length > 0,
+ peopleCount: tribe.length,
+ overdueCount: overdue.length,
+ overdue: overdue.slice(0, Math.max(0, limit)).map(({ person, status }) => ({
+ id: person.id,
+ name: person.name,
+ ring: person.ring,
+ channel: person.channel,
+ lastContact: person.lastContact,
+ state: status.state,
+ daysOverdue: status.daysOverdue,
+ })),
+ };
+}
+
export async function listPeople(options = {}) {
await ensureReady();
const conditions = ['deleted = FALSE'];
diff --git a/server/services/tribe.test.js b/server/services/tribe.test.js
index dec61087dc..b0dbbc0432 100644
--- a/server/services/tribe.test.js
+++ b/server/services/tribe.test.js
@@ -18,9 +18,18 @@ import {
isoDateTime,
rowToPerson,
rowToTouchpoint,
+ personCadenceStatus,
+ getCareSummary,
DEFAULT_RING_CADENCE,
} from './tribe.js';
+// ISO date (YYYY-MM-DD) `n` whole days before local today.
+function daysAgo(n) {
+ const d = new Date();
+ d.setDate(d.getDate() - n);
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
+}
+
describe('tribe service — pure helpers', () => {
describe('normalizeTags', () => {
it('splits a comma string, trimming and dropping empties', () => {
@@ -156,6 +165,79 @@ describe('tribe service — listPeople query builder', () => {
});
});
+describe('tribe service — personCadenceStatus', () => {
+ it('external people are never overdue', () => {
+ expect(personCadenceStatus({ ring: 'external', lastContact: daysAgo(999), cadenceDays: 7 }))
+ .toMatchObject({ state: 'external', daysOverdue: 0 });
+ });
+
+ it('no touchpoint → missing with null daysOverdue', () => {
+ const s = personCadenceStatus({ ring: 'core', lastContact: null, cadenceDays: 21 });
+ expect(s.state).toBe('missing');
+ expect(s.daysOverdue).toBeNull();
+ });
+
+ it('elapsed beyond cadence → overdue with positive daysOverdue', () => {
+ const s = personCadenceStatus({ ring: 'support', lastContact: daysAgo(10), cadenceDays: 7 });
+ expect(s.state).toBe('overdue');
+ expect(s.daysOverdue).toBe(3);
+ });
+
+ it('within a week of cadence → soon', () => {
+ expect(personCadenceStatus({ ring: 'core', lastContact: daysAgo(18), cadenceDays: 21 }).state).toBe('soon');
+ });
+
+ it('comfortably inside cadence → steady', () => {
+ expect(personCadenceStatus({ ring: 'village', lastContact: daysAgo(2), cadenceDays: 90 }).state).toBe('steady');
+ });
+});
+
+describe('tribe service — getCareSummary', () => {
+ beforeEach(() => {
+ query.mockReset();
+ });
+
+ // listPeople maps DB rows via rowToPerson, so mock rows use snake_case columns.
+ const row = (over) => ({
+ id: over.id, name: over.name, ring: over.ring,
+ cadence_days: over.cadence_days, last_contact_on: over.last_contact_on ?? null,
+ channel: '', tags: [], touchpoint_count: '0', linked_memory_count: '0',
+ });
+
+ it('excludes external people and sorts missing first, then most-overdue', async () => {
+ query.mockResolvedValue({ rows: [
+ row({ id: 'a', name: 'Overdue Small', ring: 'support', cadence_days: 7, last_contact_on: daysAgo(10) }), // 3d overdue
+ row({ id: 'b', name: 'Never', ring: 'core', cadence_days: 21, last_contact_on: null }), // missing
+ row({ id: 'c', name: 'Overdue Big', ring: 'core', cadence_days: 21, last_contact_on: daysAgo(60) }), // 39d overdue
+ row({ id: 'd', name: 'Steady', ring: 'village', cadence_days: 90, last_contact_on: daysAgo(1) }), // steady
+ row({ id: 'e', name: 'Nemesis', ring: 'external', cadence_days: 7, last_contact_on: daysAgo(999) }), // excluded
+ ] });
+
+ const summary = await getCareSummary();
+ expect(summary.hasPeople).toBe(true);
+ expect(summary.peopleCount).toBe(4); // external excluded
+ expect(summary.overdueCount).toBe(3); // missing + 2 overdue
+ expect(summary.overdue.map((p) => p.id)).toEqual(['b', 'c', 'a']);
+ });
+
+ it('respects the limit while still reporting the full overdueCount', async () => {
+ query.mockResolvedValue({ rows: [
+ row({ id: 'a', name: 'A', ring: 'core', cadence_days: 21, last_contact_on: daysAgo(60) }),
+ row({ id: 'b', name: 'B', ring: 'core', cadence_days: 21, last_contact_on: daysAgo(50) }),
+ ] });
+ const summary = await getCareSummary(1);
+ expect(summary.overdueCount).toBe(2);
+ expect(summary.overdue).toHaveLength(1);
+ });
+
+ it('reports hasPeople false for an empty tribe', async () => {
+ query.mockResolvedValue({ rows: [] });
+ const summary = await getCareSummary();
+ expect(summary.hasPeople).toBe(false);
+ expect(summary.overdueCount).toBe(0);
+ });
+});
+
describe('tribe service — createPerson', () => {
beforeEach(() => {
query.mockReset();