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

refactor: single-source Tribe cadence rules shared by page, widget, and alert (#2060)

Adam Eivy4da931264bd0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 2aa2f0d27a..f96e785257 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -36,4 +36,5 @@
- Fixed a POST daily-reminder false-nudge after a global timezone change (#2040). `settings.js` now stamps a `timezoneUpdatedAt` timestamp whenever the `timezone` value actually changes (unrelated saves leave it untouched), exposed via `getTimezoneUpdatedAt()` in `timezone.js`. The reminder's boot-time missed-slot catch-up (`catchUpMissedSlot`) now skips a slot that predates the LATER of the reminder's own config save (#2015) or the last timezone change — so switching timezones and then restarting the server the same day can no longer replay a slot that was never scheduled under the active zone. The new field is reusable by any other timezone-dependent scheduler.
- Fixed double error toasts across ~50 call sites that owned a custom `.catch` toast: they now pass `{ silent: true }` so the `apiCore.request()` default toast no longer fires alongside the component's own, per the "Silent vs. toasting API requests" convention (#2026). Also added the missing trailing `options = {}` passthrough to ~40 `api*.js` wrappers (CoS tasks/agents/jobs, Brain people/projects/ideas/admin/memories/buckets/inbox, GSD, memory approve/reject, app task-type overrides, feature-agent controls, browser/backup/system, MeatSpace POST drills, goals, messages) so callers can actually suppress the built-in toast. Sites whose `.catch` only reverts state (no toast) were intentionally left on the default single toast.
- Audited the cross-domain insights engine against the no-cold-bootstrap LLM policy and documented the trigger contract at the two generation entry points (#2037). Verified the only functions that call an AI provider — `generateThemeAnalysis` (INS-02) and `refreshCrossDomainNarrative` (INS-04) — are reached solely from user-triggered POST endpoints (`/api/insights/themes/refresh`, `/api/insights/narrative/refresh`, both fired by an explicit "Refresh" click); the page-mount and cached-read paths (`getThemeAnalysis`/`getCrossDomainNarrative`) are disk-only, boot (`server/index.js`) mounts the router without generating, and no scheduler references insights. No violation found — added a contract comment block plus a regression test asserting the read paths never call a provider.
+- Single-sourced the Tribe care-cadence rules so the page, the Care dashboard widget, and the proactive alert can no longer drift (#2060). The Tribe page's `contactStatus` (client) and the server's `personCadenceStatus`/`getCareSummary` (added in #2032) previously carried two hand-mirrored copies of the same "external-excluded / missing-vs-overdue / <=7d soon" state machine. The rules now live in one authoritative pure module, `server/lib/tribeCadence.js` (`cadenceStatus`, `daysSinceDate`), mirrored to `client/src/lib/tribeCadence.js`; `personCadenceStatus` re-exports it and the client `contactStatus` is now a thin presentation wrapper that only attaches label/tone. A cross-boundary contract test imports both copies and fails CI if they ever diverge. Semantics are unchanged — the Tribe page header counts, the widget, and the alert all compute identically to before.
- Refreshed GOALS.md status to reflect shipped Apple Health integration (#2039). The Health & Longevity status-table row said "Apple Health integration planned," but the integration shipped: `server/routes/appleHealth.js` (ingest/metrics/correlation/XML+clinical import) is wired through `apiHealth.js` into the MeatSpace Alcohol/Health/Nicotine tabs. The row now marks it shipped, and the stale "Apple Health Integration" bullet was removed from Secondary Goals. Documentation only; other status rows spot-checked against code (Sketch & Annotation Canvas confirmed genuinely unshipped, left as planned).
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 98529a6573..86845deb4e 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -115,7 +115,8 @@ grep -i "what you want to do" client/src/lib/README.md
| `songCraft.js` | Canonical a cappella song-craft reference data rendered by the Songs Guide (`/songs/guide`) and reused by the Song editor: `RHYTHM_SHAPES` / `DIRGE_RHYTHM_SHAPES` (dirge & ballad pulse feels with BPM bands), `VOICE_LAYERS` (foundation-first harmony build ladder), `LEARNING_STEPS` (practice sequence), `NOTATION_HELP` (lead-sheet/notation primers), `SOLFEGE_DEGREES` + `solfegeForDegree(n)`, and `rhythmShapeLabel(id)` (human-readable "Slow 4/4 ballad · dirge (56–76 BPM)" label shared by the editor's picker and read view). Pure data; pickers and docs read the same source so they can't drift. |
| `songPlayback.js` | `createLayeredPlayer(takes)` — decode N recorded vocal takes and start them together on one shared `AudioContext` so they stack into a layered a cappella performance (sample-aligned, per-layer mute). Used by the Song editor's recording mixer. |
| `songProgress.js` | Pure training-progress core for the song system's memorize/learn/track mode. `deriveTrainingSections(score, lyricSections?)` slices a lead-sheet score into blank-line-separated trainable sections (each a self-contained header+block score, positional stable id, lyric-matched label); `recordAttempt(progress, scope, summary)` appends a graded take to a scope's bounded rolling history (drops zero-note takes); `scopeStats(progress, scope)`/`wholeSongStats` derive `{ attempts, best, average, last, streak, learned }` (learned = streak of ≥`LEARNED_PERCENT` takes ≥`LEARNED_STREAK`); `weakestSections(progress, sections)` ranks weak/un-attempted sections for spaced-repetition; `memorizationPercent` is the learned-section share; `hideLevelFor(average)` maps a rolling average to a progressive lyric/note-hiding level (`show`/`dim`/`hide`/`blind`). No React/audio — `useSongTraining` drives it. |
-| `tribe.js` | Pure Tribe domain helpers shared by the Tribe page and its `TribeCircleMap` visualization: `RINGS` (support→core→tribe→village Dunbar rings + the uncapped `external` "outside the tribe" classification — caps, cadence defaults, Tailwind tones + `hex`), `TRIBE_RINGS` (the four inner rings the care queue/capacity/overdue counts operate over, excluding `external`), `ENERGY` (energy tiers + `hex`), `STATUS_HEX` (cadence-status → SVG stroke color), `contactStatus(contact)` / `daysBetween(date)` (cadence health: missing/overdue/soon/steady, plus an `external` state that never nags), `ringFor` / `energyFor` lookups, `tagsToArray` / `tagsToInput`, and `initialsFor(name)` (node glyph). Ring `cadenceDays` mirror `DEFAULT_RING_CADENCE` in `server/services/tribe.js`. |
+| `tribe.js` | Pure Tribe domain helpers shared by the Tribe page and its `TribeCircleMap` visualization: `RINGS` (support→core→tribe→village Dunbar rings + the uncapped `external` "outside the tribe" classification — caps, cadence defaults, Tailwind tones + `hex`), `TRIBE_RINGS` (the four inner rings the care queue/capacity/overdue counts operate over, excluding `external`), `ENERGY` (energy tiers + `hex`), `STATUS_HEX` (cadence-status → SVG stroke color), `contactStatus(contact)` (presentation wrapper over the shared `cadenceStatus` — attaches label/tone to the missing/overdue/soon/steady/`external` state) / `daysBetween(date)` (alias of the shared `daysSinceDate`), `ringFor` / `energyFor` lookups, `tagsToArray` / `tagsToInput`, and `initialsFor(name)` (node glyph). Ring `cadenceDays` mirror `DEFAULT_RING_CADENCE` in `server/services/tribe.js`; the cadence STATE MACHINE lives in `tribeCadence.js`. |
+| `tribeCadence.js` | Mirror of `server/lib/tribeCadence.js` — the single authoritative Tribe care-cadence rules shared by the page, the Care dashboard widget, and the proactive alert: `cadenceStatus(entity)` → `{ state, daysRemaining, daysOverdue }`, `daysSinceDate(dateStr)`, `DEFAULT_CADENCE_DAYS`, `SOON_WINDOW_DAYS`. A cross-boundary contract test asserts it never drifts from the server copy. |
| `syncCounts.js` | Directional pending-sync counts for the Instances federation cards. `directionalCounts({ localMax, peerMax, ourCursor, peerCursorForUs })` → `{ toPull, toPush }` (each a non-negative Number, or `null` when unknown) from monotonic change-log seqs; `diffSeq(ahead, behind)` is the BigInt-safe clamp-at-zero subtraction (handles numeric strings past `MAX_SAFE_INTEGER`); `describeDirectional({ toPull, toPush })` renders the plain-language `{ state, text }` ("in sync" / "N to pull · M to push" / "checking…"). No React — `SyncStatusBadge` drives it. |
| `terminalTheme.js` | Pure xterm.js palette builder for the Shell terminal. `buildTerminalTheme({ bg, fg, accent, card, error, success, warning }, mode)` assembles the xterm `theme` object — base ANSI colors from the active theme's CSS vars, the rest from mode-tuned literals (`ANSI_NIGHT` bright/pastel for dark backgrounds, `ANSI_DAY` darkened/saturated so colored CLI output stays legible on daytime themes). `parseCssColorToHex(raw, fallback)` normalizes both the `15 15 15` triple form and the `rgb(7 7 7 / 0.86)` function form (used by `--port-terminal-*` tokens) to `#rrggbb`, dropping alpha. No DOM reads — `Shell.jsx` resolves CSS vars and re-applies on theme switch. |
| `wrSceneCursor.js` | Resolve which script scene the editor caret sits in (`sceneAtCursor`, `sceneAnchorIndex`) — inverse of WorkEditor's jump-to-scene text search; drives the live render preview's "scene at cursor" target. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index c4c8c777e7..d7db01ee26 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -85,6 +85,7 @@ export * from './songProgress.js';
export * from './syncCounts.js';
export * from './terminalTheme.js';
export * from './tribe.js';
+export * from './tribeCadence.js';
export * from './universeBuilderExpand.js';
export * from './wrSceneCursor.js';
export * from './writingGuide.js';
diff --git a/client/src/lib/tribe.js b/client/src/lib/tribe.js
index 4380b1ba1b..c3ceae5b6c 100644
--- a/client/src/lib/tribe.js
+++ b/client/src/lib/tribe.js
@@ -2,6 +2,13 @@
// visualization. Rings are Dunbar-inspired concentric circles (support is the
// innermost / closest, village the outermost / weak ties). The ring `cadenceDays`
// defaults mirror DEFAULT_RING_CADENCE in server/services/tribe.js — keep in sync.
+//
+// The cadence STATE MACHINE (external/missing/overdue/soon/steady) lives in the
+// shared, authoritative `tribeCadence.js` (mirrored from server/lib/tribeCadence.js)
+// so the page, the Tribe Care dashboard widget, and the proactive-alert check all
+// route through one implementation. `contactStatus` below only layers presentation
+// (label/tone) on top of that shared `cadenceStatus` — do not re-implement the rules.
+import { cadenceStatus, daysSinceDate } from './tribeCadence.js';
// The four inner rings are the Dunbar tribe (capped, care-cadenced). `external` is
// a fifth, uncapped classification OUTSIDE the tribe — people known or previously
@@ -28,27 +35,27 @@ export const ENERGY = [
];
// Whole days from an ISO date (YYYY-MM-DD) to today, or null if unparseable.
-export 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);
-}
+// Backed by the shared `daysSinceDate` so the client and server compute
+// elapsed days identically.
+export const daysBetween = daysSinceDate;
-// Cadence health for a contact: missing / overdue / soon (<=7d) / steady.
-// `daysRemaining` is cadenceDays - elapsed (negative once overdue); null when
-// there's no recorded last contact (distinct from a 0-days-remaining contact).
+// Cadence health for a contact: missing / overdue / soon (<=7d) / steady, plus
+// an `external` state that never nags. The state/`daysRemaining` come straight
+// from the shared `cadenceStatus`; this wrapper only attaches the UI label +
+// Tailwind tone so there is exactly one implementation of the cadence rules.
+const STATUS_PRESENTATION = {
+ external: { label: 'External', tone: 'text-slate-400' },
+ missing: { label: 'No touchpoint', tone: 'text-gray-300' },
+ overdue: { tone: 'text-rose-300' },
+ soon: { tone: 'text-amber-300' },
+ steady: { tone: 'text-emerald-300' },
+};
export function contactStatus(contact) {
- // External people carry no care cadence — never nag about an overdue nemesis.
- if (contact.ring === 'external') return { label: 'External', tone: 'text-slate-400', state: 'external', daysRemaining: null };
- 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 };
+ const { state, daysRemaining } = cadenceStatus(contact);
+ const { label, tone } = STATUS_PRESENTATION[state];
+ if (label) return { label, tone, state, daysRemaining };
+ const dueLabel = state === 'overdue' ? `${Math.abs(daysRemaining)}d overdue` : `${daysRemaining}d left`;
+ return { label: dueLabel, tone, state, daysRemaining };
}
// Status → SVG stroke color for the circle-map nodes.
diff --git a/client/src/lib/tribeCadence.contract.test.js b/client/src/lib/tribeCadence.contract.test.js
new file mode 100644
index 0000000000..723d245945
--- /dev/null
+++ b/client/src/lib/tribeCadence.contract.test.js
@@ -0,0 +1,80 @@
+import { describe, it, expect } from 'vitest';
+import {
+ cadenceStatus as clientCadenceStatus,
+ daysSinceDate as clientDaysSinceDate,
+ DEFAULT_CADENCE_DAYS as CLIENT_DEFAULT,
+ SOON_WINDOW_DAYS as CLIENT_SOON,
+} from './tribeCadence.js';
+// The server copy is authoritative; the client copy is a mirror. Importing both
+// here (vitest resolves the cross-boundary path, same as providers.test.js) and
+// asserting identical output is the anti-drift guarantee for issue #2060 — if
+// either file's cadence rules change without the other, this suite fails.
+import {
+ cadenceStatus as serverCadenceStatus,
+ daysSinceDate as serverDaysSinceDate,
+ DEFAULT_CADENCE_DAYS as SERVER_DEFAULT,
+ SOON_WINDOW_DAYS as SERVER_SOON,
+} from '../../../server/lib/tribeCadence.js';
+
+// N days before today as a YYYY-MM-DD string, so the suite is date-independent.
+function daysAgo(n) {
+ const d = new Date();
+ d.setDate(d.getDate() - n);
+ return d.toISOString().slice(0, 10);
+}
+
+describe('tribeCadence — client/server mirror is byte-identical', () => {
+ it('exposes identical tuning constants', () => {
+ expect(CLIENT_DEFAULT).toBe(SERVER_DEFAULT);
+ expect(CLIENT_SOON).toBe(SERVER_SOON);
+ expect(CLIENT_DEFAULT).toBe(45);
+ expect(CLIENT_SOON).toBe(7);
+ });
+
+ const entities = [
+ { ring: 'external', lastContact: daysAgo(999), cadenceDays: 7 }, // external excluded
+ { ring: 'core', lastContact: null, cadenceDays: 21 }, // missing
+ { ring: 'core', lastContact: undefined, cadenceDays: 21 }, // missing (undefined)
+ { ring: 'support', lastContact: 'not-a-date', cadenceDays: 7 }, // unparseable → missing
+ { ring: 'support', lastContact: daysAgo(10), cadenceDays: 7 }, // overdue
+ { ring: 'core', lastContact: daysAgo(21), cadenceDays: 21 }, // 0 remaining → soon boundary
+ { ring: 'core', lastContact: daysAgo(14), cadenceDays: 21 }, // 7 remaining → soon upper boundary
+ { ring: 'core', lastContact: daysAgo(13), cadenceDays: 21 }, // 8 remaining → steady
+ { ring: 'village', lastContact: daysAgo(2), cadenceDays: 90 }, // steady
+ { ring: 'tribe', lastContact: daysAgo(45), cadenceDays: 0 }, // cadenceDays 0 → default 45
+ ];
+
+ it.each(entities)('cadenceStatus matches across boundary for %o', (entity) => {
+ expect(clientCadenceStatus(entity)).toEqual(serverCadenceStatus(entity));
+ });
+
+ it.each([null, undefined, '', 'garbage', daysAgo(0), daysAgo(3)])(
+ 'daysSinceDate matches across boundary for %o',
+ (value) => {
+ expect(clientDaysSinceDate(value)).toBe(serverDaysSinceDate(value));
+ },
+ );
+});
+
+describe('tribeCadence — cadence rules (semantics preserved from #2032)', () => {
+ it('external members are excluded from care (never nagged)', () => {
+ expect(clientCadenceStatus({ ring: 'external', lastContact: daysAgo(999), cadenceDays: 7 }))
+ .toEqual({ state: 'external', daysRemaining: null, daysOverdue: 0 });
+ });
+
+ it('distinguishes missing (never contacted) from overdue', () => {
+ const missing = clientCadenceStatus({ ring: 'core', lastContact: null, cadenceDays: 21 });
+ expect(missing.state).toBe('missing');
+ expect(missing.daysRemaining).toBeNull();
+ expect(missing.daysOverdue).toBeNull(); // missing sorts above dated-overdue
+
+ const overdue = clientCadenceStatus({ ring: 'support', lastContact: daysAgo(10), cadenceDays: 7 });
+ expect(overdue.state).toBe('overdue');
+ expect(overdue.daysOverdue).toBe(3);
+ });
+
+ it('treats <=7 days remaining as soon, >7 as steady', () => {
+ expect(clientCadenceStatus({ ring: 'core', lastContact: daysAgo(14), cadenceDays: 21 }).state).toBe('soon');
+ expect(clientCadenceStatus({ ring: 'core', lastContact: daysAgo(13), cadenceDays: 21 }).state).toBe('steady');
+ });
+});
diff --git a/client/src/lib/tribeCadence.js b/client/src/lib/tribeCadence.js
new file mode 100644
index 0000000000..08c4d58f64
--- /dev/null
+++ b/client/src/lib/tribeCadence.js
@@ -0,0 +1,36 @@
+// Mirror of server/lib/tribeCadence.js — the single source of truth for the
+// Tribe care cadence rules. The server copy is authoritative; port logic
+// changes verbatim and keep the two byte-identical in behavior. The
+// cross-boundary contract test (client/src/lib/tribeCadence.contract.test.js)
+// imports BOTH this mirror and the server module and fails CI if they drift.
+// The client `contactStatus` (lib/tribe.js) layers presentation (label/tone)
+// on top of `cadenceStatus`; it must not re-implement the state machine.
+
+// The four inner rings owe a care cadence; `external` is never nagged.
+export const DEFAULT_CADENCE_DAYS = 45;
+// A member with <= this many days left before their next check-in is "soon".
+export const SOON_WINDOW_DAYS = 7;
+
+// Whole days from an ISO date (YYYY-MM-DD…) to today, or null when unparseable.
+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 tribe member: external / missing / overdue / soon /
+// steady. `daysRemaining` is cadenceDays - elapsed (negative once overdue);
+// null when there's no recorded last contact. `daysOverdue` is 0 unless
+// overdue, and null for a `missing` member. External members carry no cadence.
+export function cadenceStatus(entity) {
+ if (entity.ring === 'external') return { state: 'external', daysRemaining: null, daysOverdue: 0 };
+ const elapsed = daysSinceDate(entity.lastContact);
+ if (elapsed == null) return { state: 'missing', daysRemaining: null, daysOverdue: null };
+ const daysRemaining = Number(entity.cadenceDays || DEFAULT_CADENCE_DAYS) - elapsed;
+ if (daysRemaining < 0) return { state: 'overdue', daysRemaining, daysOverdue: Math.abs(daysRemaining) };
+ if (daysRemaining <= SOON_WINDOW_DAYS) return { state: 'soon', daysRemaining, daysOverdue: 0 };
+ return { state: 'steady', daysRemaining, daysOverdue: 0 };
+}
diff --git a/server/lib/README.md b/server/lib/README.md
index 4037a92caa..169f1438c5 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -229,6 +229,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `ports.js` | Canonical PORTS object (re-exported from `ecosystem.config.cjs`). |
| `platform.js` | Platform/OS detection helpers — listening-port probes plus `isAppleSilicon()` (arm64 darwin; gates MLX model features, detect at the route boundary). |
| `timezone.js` | Timezone utilities for scheduling. |
+| `tribeCadence.js` | Authoritative, pure Tribe care-cadence rules (single source of truth, mirrored to `client/src/lib/tribeCadence.js`): `cadenceStatus(entity)` → `{ state: external/missing/overdue/soon/steady, daysRemaining, daysOverdue }`, `daysSinceDate(dateStr)`, `DEFAULT_CADENCE_DAYS` (45), `SOON_WINDOW_DAYS` (7). Consumed by `personCadenceStatus` / `getCareSummary` in `services/tribe.js` (proactive alert + Care widget) and by the client Tribe page/map. |
| `viteAllowedHosts.js` | Detect and remediate a managed app's Vite `server.allowedHosts`. `findViteConfig(repoPath)` locates the config; `parseAllowedHosts(src)` / `hostIsAllowed(parsed, host)` decide whether a Tailscale/IP host would be accepted (mirrors Vite's localhost+IP-always-allowed and leading-dot-suffix rules); `rewriteAllowedHosts(src)` deterministically injects `allowedHosts: true` (or bails `ok:false` on ambiguous shapes so the caller can fall back to an LLM fix); `checkViteHost(repoPath, host)` is the one-shot status used by `GET /api/apps/:id/vite-host-check`. |
| `buildId.js` | Build-ID derived from the built client bundle. |
diff --git a/server/lib/index.js b/server/lib/index.js
index ef17b6fc77..b11e85d472 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -203,6 +203,7 @@ export * from './pgTools.js';
export * from './platform.js';
export * from './ports.js';
export * from './timezone.js';
+export * from './tribeCadence.js';
export * from './viteAllowedHosts.js';
// === General utilities ===
diff --git a/server/lib/tribeCadence.js b/server/lib/tribeCadence.js
new file mode 100644
index 0000000000..2a81397590
--- /dev/null
+++ b/server/lib/tribeCadence.js
@@ -0,0 +1,40 @@
+// Authoritative, pure cadence rules for the Tribe care system — the single
+// source of truth for "who needs care." Consumed on the server by
+// `personCadenceStatus` / `getCareSummary` (server/services/tribe.js → the
+// proactive-alerts check + the Tribe Care dashboard widget) and mirrored to
+// `client/src/lib/tribeCadence.js` for the client bundle (Tribe page + circle
+// map). The mirror must produce IDENTICAL output; the cross-boundary contract
+// test (client/src/lib/tribeCadence.contract.test.js) imports both copies and
+// asserts they never drift. No Node-only deps — keep this file pure.
+
+// The four inner rings owe a care cadence; `external` (former contacts, a
+// nemesis) is outside the tribe and is never nagged.
+export const DEFAULT_CADENCE_DAYS = 45;
+// A member with <= this many days left before their next check-in is "soon".
+export const SOON_WINDOW_DAYS = 7;
+
+// Whole days from an ISO date (YYYY-MM-DD…) to today, or null when unparseable.
+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 tribe member: external / missing / overdue / soon /
+// steady. `daysRemaining` is cadenceDays - elapsed (negative once overdue);
+// null when there's no recorded last contact (distinct from a 0-days-remaining
+// member). `daysOverdue` is 0 unless overdue, and null for a `missing`
+// (never-contacted) member so callers can sort those to the top without a
+// magic number. External members carry no cadence.
+export function cadenceStatus(entity) {
+ if (entity.ring === 'external') return { state: 'external', daysRemaining: null, daysOverdue: 0 };
+ const elapsed = daysSinceDate(entity.lastContact);
+ if (elapsed == null) return { state: 'missing', daysRemaining: null, daysOverdue: null };
+ const daysRemaining = Number(entity.cadenceDays || DEFAULT_CADENCE_DAYS) - elapsed;
+ if (daysRemaining < 0) return { state: 'overdue', daysRemaining, daysOverdue: Math.abs(daysRemaining) };
+ if (daysRemaining <= SOON_WINDOW_DAYS) return { state: 'soon', daysRemaining, daysOverdue: 0 };
+ return { state: 'steady', daysRemaining, daysOverdue: 0 };
+}
diff --git a/server/services/tribe.js b/server/services/tribe.js
index de54a88046..86c3b04091 100644
--- a/server/services/tribe.js
+++ b/server/services/tribe.js
@@ -15,6 +15,7 @@
import { v4 as uuidv4 } from '../lib/uuid.js';
import { ensureSchema, query, withTransaction } from '../lib/db.js';
import { ServerError } from '../lib/errorHandler.js';
+import { cadenceStatus } from '../lib/tribeCadence.js';
import * as calendarSync from './calendarSync.js';
// Default check-in cadence (days) per ring. Mirrored on the client in
@@ -109,32 +110,12 @@ 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 };
-}
+// Cadence health for a person — the server-side entry point into the shared,
+// authoritative cadence rules in server/lib/tribeCadence.js (mirrored to the
+// client). Kept as a named re-export so existing callers/tests importing
+// `personCadenceStatus` from this service stay stable while the rules live in
+// exactly one place. See tribeCadence.js for the state semantics.
+export const personCadenceStatus = cadenceStatus;
// Care summary for the dashboard widget + proactive alert: who in the active
// tribe (external excluded) is overdue or has no touchpoint yet, most-overdue