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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
add Tribe Map view: concentric ring nodes + External classification
[._.]/ Adam Eivydea2dca1846c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex aec7130f4b..893129c1cb 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -12,6 +12,8 @@- **[issue-911] Mood Boards — an inspiration canvas that feeds the Create suite.** A new **Mood Boards** page (Create → Mood Boards, deep-linkable at `/mood-boards` and `/mood-boards/:id`, reachable via ⌘K / voice as "mood board" / "inspiration" / "references") for collecting visual + textual references, distinct from raw Media History. Create named boards with a description, then pin items: an **image** (external/pinned URL, or an app path like `/data/images/…`) or a **text note**, each with an optional caption and source backref. Items live inline in the board record; the canvas renders an image grid with inline-editable captions and an inline-confirm delete. Boards are **db-primary and local-only** — one row per board in the new `mood_boards` Postgres table (full record in `data` JSONB, modeled on `creative_director_projects`: no sync cursor/tombstone in v1), provisioned by both the boot-time `ensureSchema()` upgrade and `init-db.sql` with an audit trigger, registered via migration 108. Every write locks the board row (`SELECT … FOR UPDATE`) so concurrent add/edit affordances can't clobber each other. Cross-surface "Pin to mood board" affordances and a board picker in the universe/scene/treatment creation flows are tracked as a follow-up. (`server/services/moodBoard/`, `server/routes/moodBoard.js`, `server/lib/moodBoardValidation.js`, `client/src/pages/{MoodBoards,MoodBoardDetail}.jsx`, `client/src/services/apiMoodBoard.js`, #911)+- **Tribe gains a concentric-circles Map view + an "External" classification.** A new **Map** tab on the Tribe page (Brain → Tribe) renders your relationships as nodes orbiting a central **"Me"** hub: each Dunbar ring is a concentric band (Support innermost → Village outermost), subtly tinted in its theme color, and each person is placed *inside* their ring's band — using an equal-area, golden-angle (sunflower) distribution so a crowded ring thickens into an organic cluster instead of cramming nodes onto a line. Each node's **fill encodes energy** (nourishing/steady/complex/draining) and its **outline encodes cadence status** (overdue/due-soon/on-track/no-touchpoint), so a glance shows both who's close and who needs care. Hover a node for a name/relationship/status tooltip and a one-click "log touchpoint"; click it to jump to the Circle tab with that person selected for editing. A new **External** classification covers people *outside* the active tribe — those known or previously known who've moved out of your circle (drifted acquaintances, a nemesis): it's uncapped, carries **no care cadence** (excluded from the Care Queue and the overdue/coming-up/capacity counts, and its nodes show a neutral status outline that never nags). On the map, external people aren't a ring — they fill the open canvas *outside* the solid "edge of tribe" perimeter (the annulus and the square's corners), packed with a clipped sunflower whose node size auto-shrinks as the population grows, so the layout stays uniformly dense and on-canvas even with hundreds of external contacts. Pure SVG — it scales, prints, and works on mobile with no WebGL/canvas dependency. The shared ring/energy/cadence logic was extracted into `client/src/lib/tribe.js` (with `hex` swatches, `TRIBE_RINGS`, and an `initialsFor` node-glyph helper) so the page and the map share one source of truth; the `external` ring value is additive on the app-layer enum (`server/routes/tribe.js`, `server/services/tribe.js` `DEFAULT_RING_CADENCE`) with no DB migration since `tribe_people.ring` is an unconstrained `VARCHAR`. (`client/src/components/tribe/TribeCircleMap.jsx`, `client/src/lib/tribe.js`, `client/src/pages/Tribe.jsx`, `server/routes/tribe.js`, `server/services/tribe.js`)+- **The series pipeline list now shows a cover thumbnail on each series card.** Like the reference-image thumbnail on the Universe list, each series in **Pipeline** now leads with a small thumbnail of its graphic-novel cover — the first rendered **volume (trade-paperback) cover**, falling back to the earliest rendered **issue cover** — so you can recognize a series at a glance instead of reading names. The thumbnail filename is **persisted onto the series record** (`series.coverImage`) rather than computed at list time, so the list stays cheap (no per-series issue scan): the two cover filename hooks stamp it when a cover render completes, and a one-time, marker-gated boot backfill (`data/series-cover-backfill.applied.json`) derives it for series whose covers rendered before this shipped. Volume covers come straight off the series record (free); the issue fallback is only scanned when no volume cover exists. The field is wire-gated (`pipelineSeries` schema v5) so an older peer can't strip-then-LWW the pointer back, and the card falls back to a book icon when no cover exists yet (or 404s on a peer that synced the pointer but not the bytes). (`server/services/pipeline/seriesCoverImage.js`, `server/services/pipeline/series.js`, `server/services/pipeline/{comicPagesFilenameHook,seasonCoverFilenameHook}.js`, `server/scripts/backfillSeriesCoverImages.js`, `client/src/pages/Pipeline.jsx`)- **Enrich a Universe noun — and refine a Universe style — from a reference image.** The Universe Bible's "Describe from image" modal now takes reference images from your **gallery** as well as uploads, and for **characters** it can do more than write the descriptor paragraph: a new **Build character details** action has a vision model read the reference image(s) and *propose* values for the character's still-blank structured fields (pronouns, age, visual notes, color palette, expressions, …). The proposals are shown for review — uncheck any, edit the text inline — and applied through the normal entry-patch path, so existing values are never overwritten (no-clobber, characters-only). Separately, the **Refine Prompts** form gains an optional **style-reference image**: pick one from the gallery and the refiner runs through a vision-capable provider, folding the image's palette/lighting/mood into the universe's `influences` + `styleNotes`. Both vision paths require an API provider with a vision model and reject a silent fallback to a non-vision provider rather than hallucinating from text alone; the vision provider/model pickers scope local (Ollama/LM Studio) backends to vision-capable models. Relatedly, a **model-not-found error no longer benches the whole provider** — that's a bad model id in one request, not a provider outage, so (like a content refusal) the single call still falls back but the provider stays available for its other working models (previously one bad model id could take Ollama offline for 30 minutes). (`server/services/universeVisionExpand.js`, `server/services/universeBuilderRefine.js`, `server/routes/universeBuilder.js`, `server/lib/promptRunner.js`, `client/src/components/universe/VisionDescribeModal.jsx`, `client/src/pages/UniverseBuilder.jsx`)diff --git a/client/src/components/tribe/TribeCircleMap.jsx b/client/src/components/tribe/TribeCircleMap.jsxnew file mode 100644index 0000000000..7763f5c3cf--- /dev/null+++ b/client/src/components/tribe/TribeCircleMap.jsx@@ -0,0 +1,342 @@+import { useMemo, useState } from 'react';++import { RINGS, TRIBE_RINGS, ENERGY, STATUS_HEX, contactStatus, energyFor, initialsFor } from '../../lib/tribe.js';++// Concentric-circles map of the Tribe: "Me" at the center, each Dunbar ring is a+// tinted band (support innermost → village outermost) and every person is a node+// placed inside their band. People classed `external` (former contacts, a nemesis)+// are NOT a ring — they fill the open canvas OUTSIDE the tribe perimeter (annulus+// + square corners), packed so the layout scales to a lot of them. Node fill+// encodes energy, the stroke encodes cadence status. Pure SVG — scales, prints,+// and works on mobile without a WebGL/canvas dependency.++const VIEW = 880;+const CENTER = VIEW / 2;+const HUB_R = 30; // the "Me" hub disk+const INNER_GAP = 54; // radius reserved around the hub before the first band+const EDGE_PAD = 16; // usable inset from the viewBox edge (external nodes stay inside this)+const DUNBAR_MAX = 290; // outer radius of the village ring = the tribe perimeter++// The map draws ONLY the four Dunbar rings; `external` is handled as the open+// outer region, not a band.+const DUNBAR = TRIBE_RINGS;+const RING_RADII = DUNBAR.map((_, i) => INNER_GAP + ((DUNBAR_MAX - INNER_GAP) * (i + 1)) / DUNBAR.length);+const VILLAGE_OUTER = RING_RADII[RING_RADII.length - 1];+const TRIBE_EDGE_INDEX = RING_RADII.length - 1; // village — its outer edge is the perimeter++// Node radius shrinks for the wider outer rings so they don't overlap.+const NODE_R = [15, 13, 11, 9];+const nodeRadius = (i) => NODE_R[i] ?? NODE_R[NODE_R.length - 1];++// Golden angle — successive nodes placed this far apart spread evenly (sunflower+// packing) instead of stacking into spokes.+const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5));+const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));++// Place node `slot` of `total` inside ring `ringIndex`'s annular band — the empty+// disk just inside its labeled circle — rather than on the ring line itself.+// Equal-area radius (sqrt-spaced) keeps the band evenly filled as a person count+// grows, so a crowded ring thickens into a cluster instead of cramming a line.+function nodePosition(ringIndex, slot, total) {+ const outerEdge = RING_RADII[ringIndex];+ const innerEdge = ringIndex === 0 ? INNER_GAP : RING_RADII[ringIndex - 1];+ const pad = nodeRadius(ringIndex) + 4; // keep nodes off the dashed boundary circles+ const rIn = innerEdge + pad;+ const rOut = Math.max(rIn, outerEdge - pad);+ const f = total <= 1 ? 0.5 : (slot + 0.5) / total;+ const radius = Math.sqrt(rIn * rIn + f * (rOut * rOut - rIn * rIn));+ // Per-ring phase so adjacent bands don't share a seam.+ const angle = slot * GOLDEN_ANGLE + ringIndex * 1.4;+ return {+ x: CENTER + Math.cos(angle) * radius,+ y: CENTER + Math.sin(angle) * radius,+ };+}++const EXTERNAL_GAP = 16; // clearance between the tribe perimeter and the nearest external node++// Lay out `total` external people across the open region outside the tribe+// perimeter — the annulus from the village edge to the canvas, including the four+// square corners. A sunflower over a disk that reaches the corners is clipped to+// that region (drop points inside the perimeter or past the usable square), giving+// a uniform fill that scales: the node radius auto-shrinks as the count climbs, so+// a LOT of external people stay packed and on-canvas instead of overflowing.+function externalLayout(total) {+ if (total <= 0) return { nodes: [], r: 9 };+ const half = CENTER - EDGE_PAD;+ const cornerDist = Math.hypot(half, half);+ const rMin = VILLAGE_OUTER + EXTERNAL_GAP;+ const diskArea = Math.PI * cornerDist * cornerDist;+ const regionArea = Math.max(1, 4 * half * half - Math.PI * rMin * rMin);+ const keepRatio = clamp(regionArea / diskArea, 0.05, 1);+ const M = Math.ceil(total / keepRatio) + 24; // disk-point budget sized to yield `total` kept+ const nodes = [];+ for (let i = 0; i < M && nodes.length < total; i += 1) {+ const radius = cornerDist * Math.sqrt((i + 0.5) / M);+ if (radius < rMin) continue; // inside the tribe — skip+ const angle = i * GOLDEN_ANGLE;+ const x = CENTER + Math.cos(angle) * radius;+ const y = CENTER + Math.sin(angle) * radius;+ if (x < EDGE_PAD || x > VIEW - EDGE_PAD || y < EDGE_PAD || y > VIEW - EDGE_PAD) continue; // past the canvas+ nodes.push({ x, y });+ }+ // Uniform-density node size from the disk packing, clamped to a legible range.+ const r = clamp(0.42 * Math.sqrt(diskArea / M), 3, 9);+ return { nodes, r };+}++export default function TribeCircleMap({ contacts, selectedId, onSelect, onLogTouch }) {+ const [hovered, setHovered] = useState(null);++ // Split contacts: Dunbar rings get banded placement; external people get the+ // open outer region. Incoming order is preserved for stable positions.+ const placed = useMemo(() => {+ const dunbarIdx = Object.fromEntries(DUNBAR.map((ring, i) => [ring.id, i]));+ const dunbarGroups = DUNBAR.map(() => []);+ const external = [];+ for (const contact of contacts) {+ if (contact.ring === 'external') external.push(contact);+ else dunbarGroups[dunbarIdx[contact.ring] ?? dunbarIdx.tribe].push(contact);+ }+ const nodes = [];+ dunbarGroups.forEach((group, ringIdx) => {+ group.forEach((contact, slot) => {+ nodes.push({ contact, ringIdx, r: nodeRadius(ringIdx), isExternal: false, ...nodePosition(ringIdx, slot, group.length) });+ });+ });+ const ext = externalLayout(external.length);+ external.forEach((contact, idx) => {+ const pos = ext.nodes[idx];+ if (pos) nodes.push({ contact, ringIdx: -1, r: ext.r, isExternal: true, ...pos });+ });+ return { nodes, externalR: ext.r, externalCount: external.length };+ }, [contacts]);++ // External glyphs only carry initials when the nodes are large enough to read.+ const showExternalText = placed.externalR >= 8;+ const hoveredNode = hovered ? placed.nodes.find((n) => n.contact.id === hovered) : null;++ return (+ <div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(220px,300px)]">+ <div className="relative min-w-0 rounded border border-port-border bg-port-card p-2">+ <svg+ viewBox={`0 0 ${VIEW} ${VIEW}`}+ className="h-auto w-full select-none"+ role="img"+ aria-label="Concentric map of tribe relationships by ring"+ >+ {/* Subtle tinted band fills in each Dunbar ring's theme color, behind the+ dashed lines and nodes. Drawn as a thick stroke at the band's mid+ radius = a clean annulus (no overlap, so z-order among them is moot). */}+ {DUNBAR.map((ring, i) => {+ const outerEdge = RING_RADII[i];+ const innerEdge = i === 0 ? 0 : RING_RADII[i - 1];+ return (+ <circle+ key={`band-${ring.id}`}+ cx={CENTER}+ cy={CENTER}+ r={(outerEdge + innerEdge) / 2}+ fill="none"+ stroke={ring.hex}+ strokeOpacity="0.06"+ strokeWidth={outerEdge - innerEdge}+ />+ );+ })}++ {/* Ring boundary lines + labels, outermost first so inner rings paint on top.+ The village outer edge is the tribe perimeter (external people live beyond+ it), so it's drawn as a solid, brighter line instead of a faint dash. */}+ {DUNBAR.map((_, i) => DUNBAR.length - 1 - i).map((i) => {+ const ring = DUNBAR[i];+ const isTribeEdge = i === TRIBE_EDGE_INDEX;+ return (+ <g key={ring.id}>+ <circle+ cx={CENTER}+ cy={CENTER}+ r={RING_RADII[i]}+ fill="none"+ stroke={ring.hex}+ strokeOpacity={isTribeEdge ? 0.5 : 0.28}+ strokeWidth={isTribeEdge ? 2 : 1.5}+ strokeDasharray={isTribeEdge ? undefined : '2 6'}+ />+ <text+ x={CENTER}+ y={CENTER - RING_RADII[i] - 6}+ textAnchor="middle"+ fill={ring.hex}+ fillOpacity="0.85"+ fontSize="13"+ fontWeight="600"+ className="uppercase tracking-wider"+ // Halo (card-bg stroke painted under the fill) keeps the label+ // legible over any node that lands near it on a dense ring.+ stroke="#1a1a1a"+ strokeWidth="3"+ style={{ paintOrder: 'stroke' }}+ >+ {ring.label}+ </text>+ </g>+ );+ })}++ {/* External zone label — the whole open region outside the perimeter. */}+ <text+ x={CENTER}+ y={EDGE_PAD + 14}+ textAnchor="middle"+ fill="#94a3b8"+ fillOpacity="0.8"+ fontSize="13"+ fontWeight="600"+ className="uppercase tracking-wider"+ stroke="#1a1a1a"+ strokeWidth="3"+ style={{ paintOrder: 'stroke' }}+ >+ External+ </text>++ {/* Center "Me" hub. */}+ <circle cx={CENTER} cy={CENTER} r={HUB_R} fill="#3b82f6" fillOpacity="0.15" stroke="#3b82f6" strokeOpacity="0.6" />+ <text x={CENTER} y={CENTER + 5} textAnchor="middle" fill="#bfdbfe" fontSize="15" fontWeight="700">Me</text>++ {/* People nodes — Dunbar rings (banded) and external (open outer region). */}+ {placed.nodes.map(({ contact, ringIdx, isExternal, r: baseR, x, y }) => {+ const status = contactStatus(contact);+ const energy = energyFor(contact.energy);+ const isSelected = selectedId === contact.id;+ const isHovered = hovered === contact.id;+ const r = baseR + (isSelected || isHovered ? 3 : 0);+ const ringLabel = isExternal ? 'External' : DUNBAR[ringIdx].label;+ const showText = isExternal ? showExternalText : true;+ return (+ <g+ key={contact.id}+ transform={`translate(${x} ${y})`}+ className="cursor-pointer"+ onClick={() => onSelect?.(contact)}+ onMouseEnter={() => setHovered(contact.id)}+ onMouseLeave={() => setHovered((cur) => (cur === contact.id ? null : cur))}+ tabIndex={0}+ role="button"+ aria-label={`${contact.name || 'Unnamed'} — ${ringLabel}, ${status.label}`}+ onKeyDown={(e) => {+ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onSelect?.(contact); }+ }}+ >+ {isSelected && (+ <circle r={r + 5} fill="none" stroke="#3b82f6" strokeWidth="2" strokeOpacity="0.9" />+ )}+ <circle+ r={r}+ fill={energy.hex}+ fillOpacity="0.22"+ stroke={STATUS_HEX[status.state] || STATUS_HEX.missing}+ strokeWidth={status.state === 'overdue' || status.state === 'missing' ? 2.5 : 2}+ />+ {showText && (+ <text+ textAnchor="middle"+ dy="0.35em"+ fill="#e5e7eb"+ fontSize={isExternal ? 8 : (ringIdx < 2 ? 11 : 9)}+ fontWeight="600"+ pointerEvents="none"+ >+ {initialsFor(contact.name)}+ </text>+ )}+ </g>+ );+ })}+ </svg>++ {/* Hover tooltip — absolutely positioned card driven by the hovered node. */}+ {hoveredNode && (+ <div+ className="pointer-events-none absolute z-10 max-w-[220px] rounded border border-port-border bg-port-bg/95 px-3 py-2 text-xs shadow-lg"+ style={{+ left: `${(hoveredNode.x / VIEW) * 100}%`,+ top: `${(hoveredNode.y / VIEW) * 100}%`,+ transform: 'translate(-50%, calc(-100% - 14px))',+ }}+ >+ <p className="font-semibold text-white">{hoveredNode.contact.name || 'Unnamed person'}</p>+ {hoveredNode.contact.relationship && (+ <p className="mt-0.5 text-gray-400">{hoveredNode.contact.relationship}</p>+ )}+ <p className={`mt-1 ${contactStatus(hoveredNode.contact).tone}`}>+ {contactStatus(hoveredNode.contact).label}+ </p>+ </div>+ )}+ </div>++ {/* Legend + at-a-glance ring counts. */}+ <aside className="grid content-start gap-4">+ <div className="rounded border border-port-border bg-port-card p-4">+ <h3 className="text-sm font-semibold text-white">Rings</h3>+ <p className="mt-1 text-xs text-gray-500">Closer rings need more frequent care.</p>+ <div className="mt-3 grid gap-2">+ {RINGS.map((ring) => {+ const count = contacts.filter((c) => c.ring === ring.id).length;+ return (+ <div key={ring.id} className="flex items-center justify-between gap-3 text-xs">+ <span className="flex items-center gap-2">+ <span className="inline-block h-2.5 w-2.5 rounded-full" style={{ backgroundColor: ring.hex }} aria-hidden="true" />+ <span className={ring.tone}>{ring.label}</span>+ </span>+ <span className="text-gray-400">{ring.cap == null ? count : `${count} / ${ring.cap}`}</span>+ </div>+ );+ })}+ </div>+ </div>++ <div className="rounded border border-port-border bg-port-card p-4">+ <h3 className="text-sm font-semibold text-white">Node fill — energy</h3>+ <div className="mt-3 grid gap-2">+ {ENERGY.map((energy) => (+ <div key={energy.id} className="flex items-center gap-2 text-xs text-gray-400">+ <span className="inline-block h-2.5 w-2.5 rounded-full" style={{ backgroundColor: energy.hex }} aria-hidden="true" />+ {energy.label}+ </div>+ ))}+ </div>+ </div>++ <div className="rounded border border-port-border bg-port-card p-4">+ <h3 className="text-sm font-semibold text-white">Node outline — cadence</h3>+ <div className="mt-3 grid gap-2">+ {[+ { state: 'overdue', label: 'Overdue' },+ { state: 'soon', label: 'Due soon' },+ { state: 'steady', label: 'On track' },+ { state: 'missing', label: 'No touchpoint' },+ ].map((row) => (+ <div key={row.state} className="flex items-center gap-2 text-xs text-gray-400">+ <span className="inline-block h-3 w-3 rounded-full border-2" style={{ borderColor: STATUS_HEX[row.state] }} aria-hidden="true" />+ {row.label}+ </div>+ ))}+ </div>+ </div>++ {hoveredNode && onLogTouch && (+ <button+ type="button"+ onClick={() => onLogTouch(hoveredNode.contact.id)}+ className="rounded border border-port-border px-3 py-2 text-xs text-port-accent hover:bg-port-accent/10"+ >+ Log touchpoint for {hoveredNode.contact.name || 'this person'}+ </button>+ )}+ </aside>+ </div>+ );+}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 9cef06c331..f00c00244b 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -106,6 +106,7 @@ 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`. || `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. || `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. || `writingGuide.js` | Canonical Writers Room reference data + craft principles rendered by the Guide page (`/writers-room/guide`): `WRITING_LENGTH_TARGETS` (microfiction→novel word/char bands), `BOOK_LENGTH_ESTIMATES` (page-based), `WRITING_PRINCIPLES`, `PLANNED_ANALYSES` (e.g. the emotional-roadmap evaluator), and `classifyByWordCount(n)` for labelling a draft's length. Future word-count gauges / length checks read from here so targets don't drift from the docs. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex a302a6fed7..29d47c4377 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -74,6 +74,7 @@ export * from './songCraft.js';export * from './songPlayback.js';export * from './songProgress.js';export * from './syncCounts.js';+export * from './tribe.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.jsnew file mode 100644index 0000000000..4380b1ba1b--- /dev/null+++ b/client/src/lib/tribe.js@@ -0,0 +1,86 @@+// Pure Tribe domain helpers shared by the Tribe page and its circle-map+// 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 four inner rings are the Dunbar tribe (capped, care-cadenced). `external` is+// a fifth, uncapped classification OUTSIDE the tribe — people known or previously+// known who've moved out of your circle (drifted acquaintances, a nemesis). It+// carries no care cadence (`cap: null`, and `contactStatus` returns an 'external'+// state instead of overdue/soon), and the UI keeps it out of the care queue.+export const RINGS = [+ { id: 'support', label: 'Support', cap: 5, cadenceDays: 7, tone: 'text-rose-300', bg: 'bg-rose-500/10', border: 'border-rose-500/30', hex: '#fda4af' },+ { id: 'core', label: 'Core', cap: 15, cadenceDays: 21, tone: 'text-amber-300', bg: 'bg-amber-500/10', border: 'border-amber-500/30', hex: '#fcd34d' },+ { id: 'tribe', label: 'Tribe', cap: 50, cadenceDays: 45, tone: 'text-teal-300', bg: 'bg-teal-500/10', border: 'border-teal-500/30', hex: '#5eead4' },+ { id: 'village', label: 'Village', cap: 150, cadenceDays: 90, tone: 'text-sky-300', bg: 'bg-sky-500/10', border: 'border-sky-500/30', hex: '#7dd3fc' },+ { id: 'external', label: 'External', cap: null, cadenceDays: 365, tone: 'text-slate-400', bg: 'bg-slate-500/10', border: 'border-slate-500/30', hex: '#94a3b8' },+];++// Rings inside the active tribe (everything except `external`) — the set the care+// queue, capacity, and overdue/soon counts operate over.+export const TRIBE_RINGS = RINGS.filter((ring) => ring.id !== 'external');++export const ENERGY = [+ { id: 'nourishing', label: 'Nourishing', className: 'text-emerald-300 bg-emerald-500/10 border-emerald-500/30', hex: '#6ee7b7' },+ { id: 'steady', label: 'Steady', className: 'text-sky-300 bg-sky-500/10 border-sky-500/30', hex: '#7dd3fc' },+ { id: 'complex', label: 'Complex', className: 'text-amber-300 bg-amber-500/10 border-amber-500/30', hex: '#fcd34d' },+ { id: 'draining', label: 'Draining', className: 'text-rose-300 bg-rose-500/10 border-rose-500/30', hex: '#fda4af' },+];++// 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);+}++// 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).+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 };+}++// Status → SVG stroke color for the circle-map nodes.+export const STATUS_HEX = {+ missing: '#9ca3af',+ overdue: '#f87171',+ soon: '#fbbf24',+ steady: '#34d399',+ external: '#94a3b8',+};++export function ringFor(id) {+ return RINGS.find((ring) => ring.id === id) || RINGS[2];+}++export function energyFor(id) {+ return ENERGY.find((energy) => energy.id === id) || ENERGY[1];+}++export 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);+}++export function tagsToInput(tags) {+ return tagsToArray(tags).join(', ');+}++// Up to two uppercase initials for a node glyph; falls back to '?'.+export function initialsFor(name) {+ const parts = String(name || '').trim().split(/\s+/).filter(Boolean);+ if (!parts.length) return '?';+ if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();+ return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();+}diff --git a/client/src/lib/tribe.test.js b/client/src/lib/tribe.test.jsnew file mode 100644index 0000000000..619d61cd9c--- /dev/null+++ b/client/src/lib/tribe.test.js@@ -0,0 +1,117 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ RINGS,+ TRIBE_RINGS,+ ENERGY,+ STATUS_HEX,+ contactStatus,+ daysBetween,+ ringFor,+ energyFor,+ tagsToArray,+ tagsToInput,+ initialsFor,+} from './tribe.js';++describe('tribe ring/energy lookups', () => {+ it('exposes the four Dunbar rings + the uncapped external classification', () => {+ expect(RINGS.map((r) => r.id)).toEqual(['support', 'core', 'tribe', 'village', 'external']);+ expect(RINGS.map((r) => r.cap)).toEqual([5, 15, 50, 150, null]);+ // Every ring carries an SVG hex for the map nodes/labels.+ expect(RINGS.every((r) => /^#[0-9a-f]{6}$/i.test(r.hex))).toBe(true);+ });++ it('TRIBE_RINGS is the four inner rings (excludes external)', () => {+ expect(TRIBE_RINGS.map((r) => r.id)).toEqual(['support', 'core', 'tribe', 'village']);+ expect(TRIBE_RINGS.some((r) => r.id === 'external')).toBe(false);+ });++ it('ringFor falls back to tribe for unknown ids', () => {+ expect(ringFor('core').id).toBe('core');+ expect(ringFor('nope').id).toBe('tribe');+ });++ it('energyFor falls back to steady and every tier has a hex', () => {+ expect(energyFor('draining').id).toBe('draining');+ expect(energyFor('???').id).toBe('steady');+ expect(ENERGY.every((e) => /^#[0-9a-f]{6}$/i.test(e.hex))).toBe(true);+ });++ it('STATUS_HEX covers every cadence state (incl. external)', () => {+ expect(Object.keys(STATUS_HEX).sort()).toEqual(['external', 'missing', 'overdue', 'soon', 'steady']);+ });+});++describe('tagsToArray / tagsToInput', () => {+ it('splits comma strings and trims, dropping empties', () => {+ expect(tagsToArray(' a, b ,,c ')).toEqual(['a', 'b', 'c']);+ });+ it('passes through arrays', () => {+ expect(tagsToArray(['x', ' y '])).toEqual(['x', 'y']);+ });+ it('round-trips to a comma-joined input', () => {+ expect(tagsToInput([' a ', 'b'])).toBe('a, b');+ });+});++describe('initialsFor', () => {+ it('uses first+last initials for multi-word names', () => {+ expect(initialsFor('Ada Lovelace')).toBe('AL');+ expect(initialsFor(' jean luc picard ')).toBe('JP');+ });+ it('uses first two letters for a single word', () => {+ expect(initialsFor('madonna')).toBe('MA');+ });+ it('falls back to ? for blank names', () => {+ expect(initialsFor('')).toBe('?');+ expect(initialsFor(' ')).toBe('?');+ expect(initialsFor(null)).toBe('?');+ });+});++describe('contactStatus / daysBetween', () => {+ // Pin "today" so cadence math is deterministic.+ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-06-19T12:00:00'));+ });+ afterEach(() => vi.useRealTimers());++ it('returns null days for missing/unparseable dates', () => {+ expect(daysBetween(null)).toBeNull();+ expect(daysBetween('not-a-date')).toBeNull();+ expect(daysBetween('2026-06-09')).toBe(10);+ });++ it('flags missing when no last contact', () => {+ const s = contactStatus({ cadenceDays: 7 });+ expect(s.state).toBe('missing');+ expect(s.daysRemaining).toBeNull();+ });++ it('flags overdue past the cadence window', () => {+ const s = contactStatus({ lastContact: '2026-06-01', cadenceDays: 7 });+ expect(s.state).toBe('overdue');+ expect(s.daysRemaining).toBe(7 - 18);+ });++ it('flags soon within 7 days', () => {+ const s = contactStatus({ lastContact: '2026-06-15', cadenceDays: 10 });+ expect(s.state).toBe('soon');+ expect(s.daysRemaining).toBe(6);+ });++ it('flags steady when comfortably ahead', () => {+ const s = contactStatus({ lastContact: '2026-06-18', cadenceDays: 45 });+ expect(s.state).toBe('steady');+ expect(s.daysRemaining).toBe(44);+ });++ it('external people carry no cadence — never overdue, even with a stale contact', () => {+ const s = contactStatus({ ring: 'external', lastContact: '2020-01-01', cadenceDays: 7 });+ expect(s.state).toBe('external');+ expect(s.daysRemaining).toBeNull();+ expect(STATUS_HEX.external).toMatch(/^#[0-9a-f]{6}$/i);+ });+});diff --git a/client/src/pages/Tribe.jsx b/client/src/pages/Tribe.jsxindex a475ca44a7..3ad6a6a8b7 100644--- a/client/src/pages/Tribe.jsx+++ b/client/src/pages/Tribe.jsx@@ -7,6 +7,7 @@ import {Heart,MessageCircle,Network,+ Orbit,Plus,Save,Search,@@ -22,25 +23,22 @@ import BrailleSpinner from '../components/BrailleSpinner';import PageHeader from '../components/PageHeader';import toast from '../components/ui/Toast';import TabPills from '../components/ui/TabPills';+import TribeCircleMap from '../components/tribe/TribeCircleMap.jsx';+import {+ RINGS,+ ENERGY,+ contactStatus,+ ringFor,+ energyFor,+ tagsToArray,+ tagsToInput,+} from '../lib/tribe.js';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: 'map', label: 'Map', icon: Orbit },{ id: 'care', label: 'Care Queue', icon: Clock },{ id: 'focus', label: 'Focus', icon: Heart },];@@ -63,41 +61,6 @@ 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 {@@ -143,7 +106,10 @@ function StatTile({ icon: Icon, label, value, detail, className = '' }) {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));+ // `external` is uncapped (cap === null): show a count only, no fill bar or+ // cadence, since it's outside the tribe and carries no care commitment.+ const uncapped = ring.cap == null;+ const fill = uncapped ? 0 : Math.min(100, Math.round((count / ring.cap) * 100));return (<buttontype="button"@@ -153,13 +119,15 @@ function RingMeter({ ring, contacts, active, onClick }) {<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>+ <p className="text-xs text-gray-500">{uncapped ? `${count}` : `${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}%` }} />+ <span className="text-xs text-gray-400">{uncapped ? 'outside tribe' : `${ring.cadenceDays}d`}</span></div>+ {!uncapped && (+ <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>);}@@ -539,7 +507,10 @@ function EmptyState({ onNew }) {}function CareQueue({ contacts, onSelect, onLogTouch, onNew }) {- const queue = [...contacts].sort((a, b) => {+ // External people are outside the tribe — no care cadence is owed, so they+ // never appear in the queue (otherwise their null daysRemaining would sort+ // them to the top alongside genuinely-overdue contacts).+ const queue = contacts.filter((contact) => contact.ring !== 'external').sort((a, b) => {const aStatus = contactStatus(a);const bStatus = contactStatus(b);const aScore = aStatus.daysRemaining == null ? -999 : aStatus.daysRemaining;@@ -745,9 +716,13 @@ export default function Tribe() {});}, [contacts, query, ringFilter]);+ // overdue/soon already exclude external (its status state is 'external', not in+ // these lists). Capacity is the Dunbar tribe horizon, so it excludes external too.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 tribeCount = contacts.filter((contact) => contact.ring !== 'external').length;+ const externalCount = contacts.length - tribeCount;const selectContact = (contact) => setDraft({...emptyDraft(),@@ -868,10 +843,10 @@ export default function Tribe() {{!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={Users} label="Relationships" value={contacts.length} detail={externalCount ? `${supportCount} support · ${externalCount} external` : `${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" />+ <StatTile icon={Heart} label="Capacity" value={`${tribeCount}/150`} detail="village horizon" /></div>{activeTab === 'circle' && (@@ -963,6 +938,19 @@ export default function Tribe() {</div>)}+ {activeTab === 'map' && (+ contacts.length === 0 ? (+ <EmptyState onNew={startNewRelationship} />+ ) : (+ <TribeCircleMap+ contacts={contacts}+ selectedId={selectedId}+ onSelect={(contact) => { selectContact(contact); setActiveTab('circle'); }}+ onLogTouch={logTouch}+ />+ )+ )}+{activeTab === 'care' && (<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(330px,420px)]"><CareQueuediff --git a/server/routes/tribe.js b/server/routes/tribe.jsindex 9d7cf0d9e9..de379d1276 100644--- a/server/routes/tribe.js+++ b/server/routes/tribe.js@@ -8,7 +8,7 @@ import * as tribe from '../services/tribe.js';const router = Router();-const ringSchema = z.enum(['support', 'core', 'tribe', 'village']);+const ringSchema = z.enum(['support', 'core', 'tribe', 'village', 'external']);const energySchema = z.enum(['nourishing', 'steady', 'complex', 'draining']);const personSchema = z.object({diff --git a/server/services/tribe.js b/server/services/tribe.jsindex 7f57fd49a9..4b635df2eb 100644--- a/server/services/tribe.js+++ b/server/services/tribe.js@@ -12,6 +12,10 @@ export const DEFAULT_RING_CADENCE = {core: 21,tribe: 45,village: 90,+ // `external` is for people outside the active tribe (former contacts, a nemesis):+ // no care cadence is owed, so this default is a neutral yearly nudge and the UI+ // excludes external people from the care queue entirely.+ external: 365,};export function isoDate(value) {@@ -116,7 +120,7 @@ export async function listPeople(options = {}) {FROM tribe_people pWHERE ${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,+ CASE ring WHEN 'support' THEN 1 WHEN 'core' THEN 2 WHEN 'tribe' THEN 3 WHEN 'village' THEN 4 WHEN 'external' THEN 5 ELSE 6 END,COALESCE(last_contact_on, DATE '1900-01-01') ASC,name ASC`,params,