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
feat([issue-819]): segment goal monuments by milestone and add goal-tree spire layout
[._.]/ Adam Eivycc8c295105fd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 5d8985ea43..f07f57d8ad 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -31,6 +31,7 @@- **[issue-705] CyberCity productivity district** — a streak monument now rises in a district southwest of downtown: a glowing obelisk that grows taller the longer your current task-completion streak runs, capped so a long streak still fits the skyline. Its color reads your recent pace at a glance — green when you're surging ahead, blue on pace, amber slowing, red when idle — and a ground readout shows how many tasks you finished today. With no productivity history yet it stands as a dim stub marked "NO DATA", so you can tell a fresh install from a genuine zero-streak day.- **[issue-705] CyberCity mini-map** — a top-down mini-map now sits in the CyberCity HUD's bottom-left corner, plotting every building as a status-colored dot at its real city position (so the map can't drift from the actual layout). Click a dot to jump straight to that app. It shows the building count and hides on small screens to keep phone views uncluttered.- **[issue-705] CyberCity goal monuments** — your life goals now stand as a row of monuments in a district northeast of downtown: each active goal is a construction site whose tower fills in as you make progress, completed goals become polished monuments that shimmer, and goals that have gone quiet or been abandoned dim into the background. The district label shows how many goals you've achieved, and if you have more than fit the row the rest fold into a "+N MORE" marker — so your ambitions read at a glance from across the city.+- **[issue-819] CyberCity goal monuments show milestones and goal trees** — a goal with milestones now builds its monument floor by floor: each milestone is a stacked segment that turns solid when you complete it and stays a translucent scaffold rung until then, with a "done/total steps" readout — so a half-built tower tells you *which* steps are finished. And when your goals nest under one another, the district rearranges into a goal tree: each top-level goal becomes a taller central spire with its sub-goals clustered around it and a glowing link drawn up to the parent, so you can see at a glance how your ambitions roll up.- **[issue-705] CyberCity energy overlay** — the city now breathes with your daily rhythm: it warms and brightens during your peak focus hours and quietly dims through your wind-down and recovery hours, following your chronotype. It's pure atmosphere, so a city with no chronotype set looks exactly as before.- **[issue-705] CyberCity earned artifacts** — a "Hall of Achievements" now appears east of downtown as a cluster of trophies on glowing pedestals — but only for milestones you've actually earned: leveling up your adventurer, completing life goals (your 1st, 5th, 10th), and building your best task-completion streak (3, 7, 30 days). Each trophy reads bronze, silver, or gold for how big the milestone is, and the whole cluster shimmers; nothing shows until you've earned your first, so the hall fills in as you make progress.diff --git a/client/src/components/city/CityGoalMonuments.jsx b/client/src/components/city/CityGoalMonuments.jsxindex 3cfce7885e..7e876628d5 100644--- a/client/src/components/city/CityGoalMonuments.jsx+++ b/client/src/components/city/CityGoalMonuments.jsx@@ -1,30 +1,66 @@import { useMemo, useRef } from 'react';import { useFrame } from '@react-three/fiber';-import { Text } from '@react-three/drei';+import { Text, Line } from '@react-three/drei';import { PIXEL_FONT_URL } from './cityConstants';-import { computeGoalMonuments, MONUMENTS } from '../../utils/cityGoalMonuments';+import { computeGoalMonuments, computeGoalForest, MONUMENTS } from '../../utils/cityGoalMonuments';// CyberCity's goal monuments (roadmap 2.7): each life goal is a structure in a-// northeast monument district (a row centered around [30,0,-40]). Active goals are-// construction sites — a solid built base topped by a translucent scaffold cage whose-// fill tracks progress. Completed goals are polished, fully-built monuments that shimmer.-// Stalled (active-but-quiet) and abandoned goals read dim. Goals past the cap fold into-// an overflow marker. Mirrors CityBackupVault / CityHealthTower.-function Monument({ monument, shimmerRef, isShimmer }) {- const { height, width, color, opacity, intensity, built, completeness, position } = monument;- // The "built" portion rises from the ground; the remaining height is scaffold.+// northeast monument district. Active goals are construction sites — a built base topped+// by a translucent scaffold cage whose fill tracks progress. Completed goals are polished,+// fully-built monuments that shimmer. Stalled (active-but-quiet) and abandoned goals read+// dim. When a goal carries milestones, the tower is segmented into ordered floors so a+// partially-built monument shows WHICH milestones are done (solid floor = complete,+// translucent scaffold rung = pending). When goals form a parent→child hierarchy, the+// district switches to a goal-tree layout: each root goal is a central spire with its+// children clustered in a ring and a link drawn up to the parent apex. Mirrors+// CityBackupVault / CityHealthTower.++// Render the body of a monument: either milestone floors (when the goal has milestones)+// or the plain built/scaffold split. `shimmerRef`/`isShimmer` wires the completed-monument+// pulse onto whichever mesh carries the topmost built portion.+function MonumentBody({ monument, shimmerRef, isShimmer }) {+ const { height, width, color, opacity, intensity, built, completeness, segments } = monument;++ // Milestone floors: one box per milestone, solid+emissive when done, wireframe scaffold+ // when pending. The highest done floor carries the shimmer for completed monuments.+ if (segments && segments.length > 0) {+ const lastDoneIdx = segments.reduce((acc, s, i) => (s.done ? i : acc), -1);+ return (+ <>+ {segments.map((seg, i) => {+ const doneFloor = seg.done || built;+ const floorH = Math.max(0.15, seg.segHeight * 0.86); // gap between floors+ const carriesShimmer = isShimmer && (built ? i === segments.length - 1 : i === lastDoneIdx);+ return (+ <mesh+ key={seg.id}+ ref={carriesShimmer ? shimmerRef : undefined}+ position={[0, 0.4 + seg.cy, 0]}+ >+ <boxGeometry args={doneFloor ? [width, floorH, width] : [width * 1.05, floorH, width * 1.05]} />+ <meshStandardMaterial+ color={doneFloor ? (built ? '#0d1a12' : '#0c1424') : color}+ emissive={color}+ emissiveIntensity={doneFloor ? intensity : intensity * 0.45}+ metalness={doneFloor ? (built ? 0.7 : 0.4) : 0.2}+ roughness={doneFloor ? (built ? 0.35 : 0.6) : 0.8}+ wireframe={!doneFloor}+ transparent={opacity < 1 || !doneFloor}+ opacity={doneFloor ? opacity : opacity * 0.55}+ toneMapped={false}+ />+ </mesh>+ );+ })}+ </>+ );+ }++ // No milestones: original built-base + scaffold-cap split.const builtHeight = Math.max(0.4, height * (built ? 1 : completeness));const scaffoldHeight = Math.max(0, height - builtHeight);-return (- <group position={position}>- {/* Plinth */}- <mesh position={[0, 0.2, 0]}>- <boxGeometry args={[width * 1.4, 0.4, width * 1.4]} />- <meshStandardMaterial color="#0a0e16" emissive={color} emissiveIntensity={0.1 * intensity + 0.04} metalness={0.6} roughness={0.5} />- </mesh>-- {/* Built portion — solid structure; completed monuments shimmer via ref */}+ <><mesh ref={isShimmer ? shimmerRef : undefined} position={[0, 0.4 + builtHeight / 2, 0]}><boxGeometry args={[width, builtHeight, width]} /><meshStandardMaterial@@ -38,47 +74,107 @@ function Monument({ monument, shimmerRef, isShimmer }) {toneMapped={false}/></mesh>-- {/* Scaffold cage over the still-unbuilt portion of a construction site */}{scaffoldHeight > 0.3 && (<mesh position={[0, 0.4 + builtHeight + scaffoldHeight / 2, 0]}><boxGeometry args={[width * 1.05, scaffoldHeight, width * 1.05]} /><meshStandardMaterial color={color} emissive={color} emissiveIntensity={intensity * 0.5} wireframe transparent opacity={opacity * 0.6} toneMapped={false} /></mesh>)}+ </>+ );+}++function Monument({ monument, shimmerRef, isShimmer }) {+ const { height, width, color, opacity, intensity, position, milestoneTotal, milestoneDone, isSpire } = monument;++ return (+ <group position={position}>+ {/* Plinth */}+ <mesh position={[0, 0.2, 0]}>+ <boxGeometry args={[width * 1.4, 0.4, width * 1.4]} />+ <meshStandardMaterial color="#0a0e16" emissive={color} emissiveIntensity={0.1 * intensity + 0.04} metalness={0.6} roughness={0.5} />+ </mesh>++ <MonumentBody monument={monument} shimmerRef={shimmerRef} isShimmer={isShimmer} />{/* Title + progress label above the structure */}- <Text position={[0, height + 1.4, 0]} fontSize={0.7} color={color} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={9} fillOpacity={opacity}>+ <Text position={[0, height + 1.4, 0]} fontSize={isSpire ? 0.85 : 0.7} color={color} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={9} fillOpacity={opacity}>{monument.title}</Text><Text position={[0, height + 0.7, 0]} fontSize={0.55} color="#94a3b8" anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={9} fillOpacity={opacity}>- {built ? 'COMPLETE' : `${Math.round(monument.progress)}%`}+ {monument.built ? 'COMPLETE' : milestoneTotal > 0 ? `${milestoneDone}/${milestoneTotal} STEPS` : `${Math.round(monument.progress)}%`}</Text></group>);}+// Goal-tree hierarchy: root spires + child rings + apex links. Used when goals form a+// parent→child structure; otherwise the flat row renders instead.+function GoalForest({ forest, shimmerRef, shimmerId }) {+ return (+ <group>+ {forest.clusters.map((cluster) => (+ <group key={cluster.spire.id}>+ <Monument monument={cluster.spire} shimmerRef={shimmerRef} isShimmer={cluster.spire.id === shimmerId} />+ {cluster.children.map((child) => (+ <Monument key={child.id} monument={child} shimmerRef={shimmerRef} isShimmer={child.id === shimmerId} />+ ))}+ {cluster.links.map((link) => (+ <Line+ key={link.childId}+ points={[link.from, link.to]}+ color={cluster.spire.color}+ lineWidth={1.5}+ transparent+ opacity={0.4}+ />+ ))}+ {cluster.childOverflow > 0 && (+ <Text position={[cluster.spire.position[0], cluster.spire.height + 2.1, cluster.spire.position[2]]} fontSize={0.5} color="#94a3b8" anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={9}>+ {`+${cluster.childOverflow} SUB-GOALS`}+ </Text>+ )}+ </group>+ ))}+ </group>+ );+}+export default function CityGoalMonuments({ goals, settings }) {// The API returns `{ goals: [...] }`; accept either the wrapper or a bare array.const list = Array.isArray(goals) ? goals : goals?.goals;const district = useMemo(() => computeGoalMonuments(list), [list]);+ const forest = useMemo(() => computeGoalForest(list), [list]);const shimmerRef = useRef();+ // Render the hierarchy view when goals actually form a parent→child tree; otherwise the+ // flat row. This keeps a flat goal set looking exactly as before while opting trees into+ // the spire layout automatically.+ const useForest = forest.hasHierarchy;+// Honor the quality dial: drop the completed-monument shimmer on the lowest preset,// but keep the static glow so each goal's status stays legible.const animate = (settings?.particleDensity ?? 1) >= 0.5;// Pick the first completed monument to carry the shimmer (one per-frame ref mutation).- const shimmerIndex = useMemo(- () => district.monuments.findIndex((m) => m.built),- [district.monuments],- );+ // In forest mode, scan spires then children; in row mode, scan the row.+ const shimmer = useMemo(() => {+ if (useForest) {+ for (const cluster of forest.clusters) {+ if (cluster.spire.built) return { id: cluster.spire.id, intensity: cluster.spire.intensity };+ const child = cluster.children.find((c) => c.built);+ if (child) return { id: child.id, intensity: child.intensity };+ }+ return null;+ }+ const m = district.monuments.find((x) => x.built);+ return m ? { id: m.id, intensity: m.intensity } : null;+ }, [useForest, forest.clusters, district.monuments]);useFrame(({ clock }) => {- if (!animate || !shimmerRef.current || shimmerIndex < 0) return;- const base = district.monuments[shimmerIndex].intensity;+ if (!animate || !shimmerRef.current || !shimmer) return;const pulse = (Math.sin(clock.getElapsedTime() * 1.6) + 1) / 2; // 0..1- shimmerRef.current.material.emissiveIntensity = base + pulse * 0.5;+ shimmerRef.current.material.emissiveIntensity = shimmer.intensity + pulse * 0.5;});if (!district.hasData) return null;@@ -87,26 +183,32 @@ export default function CityGoalMonuments({ goals, settings }) {return (<group>- {monuments.map((monument, i) => (- <Monument- key={monument.id}- monument={monument}- shimmerRef={shimmerRef}- isShimmer={i === shimmerIndex}- />- ))}+ {useForest ? (+ <GoalForest forest={forest} shimmerRef={shimmerRef} shimmerId={shimmer?.id} />+ ) : (+ <>+ {monuments.map((monument) => (+ <Monument+ key={monument.id}+ monument={monument}+ shimmerRef={shimmerRef}+ isShimmer={monument.id === shimmer?.id}+ />+ ))}- {/* Overflow marker — "+N MORE" past the end of the row */}- {overflow && (- <group position={overflow.position}>- <mesh position={[0, MONUMENTS.minHeight / 2, 0]}>- <boxGeometry args={[MONUMENTS.baseWidth, MONUMENTS.minHeight, MONUMENTS.baseWidth]} />- <meshStandardMaterial color="#0c1424" emissive="#64748b" emissiveIntensity={0.2} metalness={0.5} roughness={0.6} />- </mesh>- <Text position={[0, MONUMENTS.minHeight + 1, 0]} fontSize={0.6} color="#94a3b8" anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={9}>- {`+${overflow.count} MORE`}- </Text>- </group>+ {/* Overflow marker — "+N MORE" past the end of the row */}+ {overflow && (+ <group position={overflow.position}>+ <mesh position={[0, MONUMENTS.minHeight / 2, 0]}>+ <boxGeometry args={[MONUMENTS.baseWidth, MONUMENTS.minHeight, MONUMENTS.baseWidth]} />+ <meshStandardMaterial color="#0c1424" emissive="#64748b" emissiveIntensity={0.2} metalness={0.5} roughness={0.6} />+ </mesh>+ <Text position={[0, MONUMENTS.minHeight + 1, 0]} fontSize={0.6} color="#94a3b8" anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={9}>+ {`+${overflow.count} MORE`}+ </Text>+ </group>+ )}+ </>)}{/* District title behind the row */}diff --git a/client/src/utils/cityGoalMonuments.js b/client/src/utils/cityGoalMonuments.jsindex f4ca76e279..15aa707098 100644--- a/client/src/utils/cityGoalMonuments.js+++ b/client/src/utils/cityGoalMonuments.js@@ -78,9 +78,58 @@ export function buildCompleteness(goal, status) {return clamp01(progress / 100);}+// A milestone is "done" when it carries a completion timestamp (`completedAt`, the+// server's stored field) or an explicit `completed: true` flag. Absent both, it's+// pending. Kept tolerant so an older/foreign goal record doesn't crash the view.+export function isMilestoneDone(milestone) {+ if (!milestone || typeof milestone !== 'object') return false;+ if (milestone.completed === true) return true;+ return typeof milestone.completedAt === 'string' && milestone.completedAt.length > 0;+}++// Break a monument's height into ordered milestone segments (floors). Each segment+// reports its vertical extent (`y0`..`y1`, centered at `cy`) and whether the milestone+// is done — so the component can render completed floors solid and pending floors as+// translucent scaffold rungs. `height` is the monument's built+scaffold total; segments+// are sorted by the milestone `order` field (stable, ties keep input order) and split the+// height evenly. A goal with no milestones returns an empty array (the caller falls back+// to the plain built/scaffold split). Pure + deterministic — no three.js.+export function computeMilestoneSegments(goal, height) {+ const raw = Array.isArray(goal?.milestones) ? goal.milestones.filter((m) => m && typeof m === 'object') : [];+ if (raw.length === 0 || !(height > 0)) return [];++ // Stable order: by `order` field ascending, ties keep original index.+ const ordered = raw+ .map((milestone, i) => ({ milestone, i }))+ .sort((a, b) => {+ const oa = Number.isFinite(a.milestone.order) ? a.milestone.order : a.i;+ const ob = Number.isFinite(b.milestone.order) ? b.milestone.order : b.i;+ if (oa !== ob) return oa - ob;+ return a.i - b.i;+ });++ const segHeight = height / ordered.length;+ return ordered.map(({ milestone }, slot) => {+ const y0 = slot * segHeight;+ const y1 = y0 + segHeight;+ return {+ id: milestone.id || `ms-${slot}`,+ title: typeof milestone.title === 'string' && milestone.title ? milestone.title : `Milestone ${slot + 1}`,+ order: slot,+ done: isMilestoneDone(milestone),+ y0,+ y1,+ cy: (y0 + y1) / 2,+ segHeight,+ };+ });+}+// Map one goal to its placed monument view-model. `index` is the slot in the row (0-based);// `count` is how many monuments are actually placed, so the row is centered on MONUMENTS.base.-export function placeMonument(goal, index, count, now = Date.now()) {+// When `position` is supplied (goal-forest layout) it overrides the centered-row placement,+// so the same monument view-model serves both the flat row and the hierarchy spires.+export function placeMonument(goal, index, count, now = Date.now(), position = null) {const status = effectiveGoalStatus(goal, now);const style = STATUS_STYLES[status] || DEFAULT_STYLE;const completeness = buildCompleteness(goal, status);@@ -89,6 +138,7 @@ export function placeMonument(goal, index, count, now = Date.now()) {// Center the row: slot 0 sits at the leftmost, the middle slot aligns with base.x.const offset = (index - (count - 1) / 2) * MONUMENTS.spacing;const x = MONUMENTS.base[0] + offset;+ const segments = computeMilestoneSegments(goal, height);return {id: goal?.id || `goal-${index}`,@@ -103,7 +153,10 @@ export function placeMonument(goal, index, count, now = Date.now()) {built: style.built,height,width: MONUMENTS.baseWidth,- position: [x, 0, MONUMENTS.z],+ segments, // ordered milestone floors (empty when the goal has no milestones)+ milestoneTotal: segments.length,+ milestoneDone: segments.filter((s) => s.done).length,+ position: Array.isArray(position) ? position : [x, 0, MONUMENTS.z],};}@@ -156,3 +209,111 @@ export function computeGoalMonuments(goals, now = Date.now()) {hasData: ranked.length > 0,};}++// Goal-tree (hierarchy) layout. Goals carry `parentId`; the server's getGoalsTree()+// builds the same parent→child forest. Here we lay each ROOT goal out as a central spire+// (taller than a flat-row monument) with its direct children clustered in a ring around+// it and a link drawn from each child up to the parent apex — so a glance reads which+// goals roll up under which. Multiple roots are spread along the row depth so their+// clusters don't overlap. Pure + deterministic (no three.js): the component consumes the+// returned positions/links directly.+export const FOREST = {+ base: [30, 0, -40], // shared center with the flat row's MONUMENTS.base+ clusterSpacing: 26, // x-distance between adjacent root clusters+ childRadius: 7.5, // ring radius of children around their root spire+ spireBoost: 1.5, // root spires render this much taller than a flat monument+ maxRoots: 4, // cap root clusters so the district stays legible+ maxChildren: 6, // cap children per root (ring slots); extras fold into the root's count+};++// Build the { id -> goal, children: [...] } forest from a flat goals list using parentId.+// Mirrors getGoalsTree()'s tree builder: a goal whose parentId points at a present goal+// becomes that goal's child; everything else (null/dangling parentId) is a root. Cycles+// are impossible because the server validates parentId against ancestor cycles on write,+// but we still guard by only attaching when the parent exists and isn't the node itself.+export function buildGoalForest(goals) {+ const list = Array.isArray(goals) ? goals.filter((g) => g && typeof g === 'object' && g.id) : [];+ const byId = new Map(list.map((g) => [g.id, { goal: g, children: [] }]));+ const roots = [];+ for (const node of byId.values()) {+ const pid = node.goal.parentId;+ if (pid && pid !== node.goal.id && byId.has(pid)) {+ byId.get(pid).children.push(node);+ } else {+ roots.push(node);+ }+ }+ return { roots, byId };+}++// Full hierarchy view-model. Returns root spires (each a placed monument with extra+// height) plus their child monuments arranged in a ring, and `links` joining each child+// apex-ward to its root. Roots are ordered completed→active→stalled→abandoned (same as the+// flat row) so finished towers lead; ties broken by id for stable layout across refetches.+export function computeGoalForest(goals, now = Date.now()) {+ const { roots } = buildGoalForest(goals);++ const order = { completed: 0, active: 1, stalled: 2, abandoned: 3 };+ const rankedRoots = roots+ .map((node) => ({ node, status: effectiveGoalStatus(node.goal, now) }))+ .sort((a, b) => {+ const sa = order[a.status] ?? 9;+ const sb = order[b.status] ?? 9;+ if (sa !== sb) return sa - sb;+ return String(a.node.goal?.id || '').localeCompare(String(b.node.goal?.id || ''));+ });++ const visibleRoots = rankedRoots.slice(0, FOREST.maxRoots);+ const rootOverflow = Math.max(0, rankedRoots.length - visibleRoots.length);++ const clusters = visibleRoots.map(({ node }, rootIndex) => {+ // Spread root clusters along x, centered on FOREST.base.+ const clusterX = FOREST.base[0] + (rootIndex - (visibleRoots.length - 1) / 2) * FOREST.clusterSpacing;+ const clusterZ = FOREST.base[2];++ // Root spire — a placed monument boosted in height so it visually anchors the cluster.+ const spire = placeMonument(node.goal, 0, 1, now, [clusterX, 0, clusterZ]);+ spire.height *= FOREST.spireBoost;+ spire.isSpire = true;+ // Re-segment milestones against the boosted height so floors fill the taller tower.+ spire.segments = computeMilestoneSegments(node.goal, spire.height);+ spire.milestoneTotal = spire.segments.length;+ spire.milestoneDone = spire.segments.filter((s) => s.done).length;++ const childNodes = node.children.slice(0, FOREST.maxChildren);+ const childOverflow = Math.max(0, node.children.length - childNodes.length);++ // Children ring around the spire. A single child sits directly in front; multiple+ // children spread evenly across a forward-facing arc so links don't cross the spire.+ const children = childNodes.map((child, ci) => {+ const n = childNodes.length;+ const angle = n === 1 ? Math.PI / 2 : (Math.PI / (n + 1)) * (ci + 1); // 0..PI forward arc+ const cx = clusterX + Math.cos(angle) * FOREST.childRadius;+ const cz = clusterZ + Math.sin(angle) * FOREST.childRadius; // +z = toward the camera/front+ const m = placeMonument(child.goal, 0, 1, now, [cx, 0, cz]);+ m.parentId = node.goal.id;+ return m;+ });++ // Links: from each child's apex up to the root spire's apex.+ const links = children.map((child) => ({+ from: [child.position[0], child.height, child.position[2]],+ to: [spire.position[0], spire.height, spire.position[2]],+ childId: child.id,+ }));++ return { spire, children, links, childOverflow };+ });++ return {+ base: FOREST.base,+ clusters,+ rootOverflow,+ rootCount: rankedRoots.length,+ hasData: rankedRoots.length > 0,+ // A forest is only worth showing when at least one root actually has children;+ // otherwise it's just the flat row with extra spacing. The component uses this to+ // decide whether to render the hierarchy view vs. fall back to the flat row.+ hasHierarchy: clusters.some((c) => c.children.length > 0),+ };+}diff --git a/client/src/utils/cityGoalMonuments.test.js b/client/src/utils/cityGoalMonuments.test.jsindex d4f8796581..e86790f6e8 100644--- a/client/src/utils/cityGoalMonuments.test.js+++ b/client/src/utils/cityGoalMonuments.test.js@@ -1,12 +1,17 @@import { describe, it, expect } from 'vitest';import {MONUMENTS,+ FOREST,STALL_DAYS,daysSinceLastProgress,effectiveGoalStatus,buildCompleteness,placeMonument,computeGoalMonuments,+ isMilestoneDone,+ computeMilestoneSegments,+ buildGoalForest,+ computeGoalForest,} from './cityGoalMonuments';const NOW = Date.parse('2026-06-03T00:00:00Z');@@ -181,3 +186,185 @@ describe('computeGoalMonuments', () => {expect(vm.monuments[0].id).toBe('ok');});});++const milestone = (over = {}) => ({ id: `ms-${over.order ?? 0}`, title: `MS`, order: 0, completedAt: null, ...over });++describe('isMilestoneDone', () => {+ it('is true when completedAt is a non-empty string', () => {+ expect(isMilestoneDone(milestone({ completedAt: '2026-01-01T00:00:00Z' }))).toBe(true);+ });++ it('is true when the explicit completed flag is set', () => {+ expect(isMilestoneDone(milestone({ completed: true, completedAt: null }))).toBe(true);+ });++ it('is false when neither signal is present', () => {+ expect(isMilestoneDone(milestone({ completedAt: null }))).toBe(false);+ expect(isMilestoneDone(milestone({ completedAt: '' }))).toBe(false);+ expect(isMilestoneDone(null)).toBe(false);+ expect(isMilestoneDone('nope')).toBe(false);+ });+});++describe('computeMilestoneSegments', () => {+ it('returns an empty array for a goal with no milestones', () => {+ expect(computeMilestoneSegments(goal({ milestones: [] }), 10)).toEqual([]);+ expect(computeMilestoneSegments(goal({ milestones: undefined }), 10)).toEqual([]);+ expect(computeMilestoneSegments(goal(), 0)).toEqual([]);+ });++ it('splits the height evenly into ordered, stacked floors', () => {+ const g = goal({ milestones: [milestone({ order: 0 }), milestone({ order: 1 }), milestone({ order: 2 })] });+ const segs = computeMilestoneSegments(g, 12);+ expect(segs).toHaveLength(3);+ expect(segs.map((s) => s.segHeight)).toEqual([4, 4, 4]);+ expect(segs[0].y0).toBe(0);+ expect(segs[0].y1).toBe(4);+ expect(segs[1].y0).toBe(4);+ expect(segs[2].y1).toBeCloseTo(12);+ expect(segs[1].cy).toBe(6);+ });++ it('sorts by the order field, ties keep input order', () => {+ const g = goal({ milestones: [+ milestone({ id: 'c', order: 2, title: 'Third' }),+ milestone({ id: 'a', order: 0, title: 'First' }),+ milestone({ id: 'b', order: 1, title: 'Second' }),+ ] });+ const segs = computeMilestoneSegments(g, 9);+ expect(segs.map((s) => s.title)).toEqual(['First', 'Second', 'Third']);+ expect(segs.map((s) => s.order)).toEqual([0, 1, 2]); // re-indexed slot order+ });++ it('marks the done flag per milestone', () => {+ const g = goal({ milestones: [+ milestone({ order: 0, completedAt: '2026-01-01T00:00:00Z' }),+ milestone({ order: 1, completedAt: null }),+ ] });+ const segs = computeMilestoneSegments(g, 8);+ expect(segs[0].done).toBe(true);+ expect(segs[1].done).toBe(false);+ });++ it('skips non-object milestone entries', () => {+ const g = goal({ milestones: [null, milestone({ order: 0 }), 42] });+ expect(computeMilestoneSegments(g, 6)).toHaveLength(1);+ });+});++describe('placeMonument with milestones', () => {+ it('attaches milestone segments and done/total counts', () => {+ const g = goal({ status: 'active', progress: 60, progressHistory: [{ date: daysAgo(1) }], milestones: [+ milestone({ order: 0, completedAt: '2026-01-01T00:00:00Z' }),+ milestone({ order: 1, completedAt: '2026-02-01T00:00:00Z' }),+ milestone({ order: 2, completedAt: null }),+ ] });+ const m = placeMonument(g, 0, 1, NOW);+ expect(m.segments).toHaveLength(3);+ expect(m.milestoneTotal).toBe(3);+ expect(m.milestoneDone).toBe(2);+ });++ it('honors an explicit position override (forest layout)', () => {+ const m = placeMonument(goal(), 0, 1, NOW, [5, 0, -10]);+ expect(m.position).toEqual([5, 0, -10]);+ });++ it('reports zero milestones for a goal without any', () => {+ const m = placeMonument(goal({ milestones: [] }), 0, 1, NOW);+ expect(m.segments).toEqual([]);+ expect(m.milestoneTotal).toBe(0);+ expect(m.milestoneDone).toBe(0);+ });+});++describe('buildGoalForest', () => {+ it('attaches children under a present parent and leaves the rest as roots', () => {+ const goals = [+ goal({ id: 'root', parentId: null }),+ goal({ id: 'child-a', parentId: 'root' }),+ goal({ id: 'child-b', parentId: 'root' }),+ goal({ id: 'orphan', parentId: 'gone' }), // dangling parentId → root+ ];+ const { roots } = buildGoalForest(goals);+ const ids = roots.map((r) => r.goal.id).sort();+ expect(ids).toEqual(['orphan', 'root']);+ const root = roots.find((r) => r.goal.id === 'root');+ expect(root.children.map((c) => c.goal.id).sort()).toEqual(['child-a', 'child-b']);+ });++ it('does not attach a goal to itself', () => {+ const { roots } = buildGoalForest([goal({ id: 'self', parentId: 'self' })]);+ expect(roots).toHaveLength(1);+ expect(roots[0].children).toHaveLength(0);+ });++ it('ignores entries without an id or non-objects', () => {+ const { roots } = buildGoalForest([null, 'x', { parentId: 'p' }, goal({ id: 'ok' })]);+ expect(roots.map((r) => r.goal.id)).toEqual(['ok']);+ });+});++describe('computeGoalForest', () => {+ const tree = () => [+ goal({ id: 'apex', parentId: null, status: 'active', progressHistory: [{ date: daysAgo(1) }] }),+ goal({ id: 'c1', parentId: 'apex', progressHistory: [{ date: daysAgo(1) }] }),+ goal({ id: 'c2', parentId: 'apex', progressHistory: [{ date: daysAgo(1) }] }),+ ];++ it('reports hasHierarchy only when a root has children', () => {+ const flat = computeGoalForest([goal({ id: 'a' }), goal({ id: 'b' })], NOW);+ expect(flat.hasHierarchy).toBe(false);+ const nested = computeGoalForest(tree(), NOW);+ expect(nested.hasHierarchy).toBe(true);+ });++ it('places a root spire taller than a flat monument and clusters its children', () => {+ const vm = computeGoalForest(tree(), NOW);+ expect(vm.clusters).toHaveLength(1);+ const cluster = vm.clusters[0];+ expect(cluster.spire.isSpire).toBe(true);+ const flat = placeMonument(goal({ id: 'apex', status: 'active', progressHistory: [{ date: daysAgo(1) }] }), 0, 1, NOW);+ expect(cluster.spire.height).toBeCloseTo(flat.height * FOREST.spireBoost);+ expect(cluster.children).toHaveLength(2);+ // Children carry a parentId back-reference and one link each to the spire apex.+ expect(cluster.children.every((c) => c.parentId === 'apex')).toBe(true);+ expect(cluster.links).toHaveLength(2);+ expect(cluster.links[0].to).toEqual([cluster.spire.position[0], cluster.spire.height, cluster.spire.position[2]]);+ });++ it('centers a single root cluster on FOREST.base', () => {+ const vm = computeGoalForest(tree(), NOW);+ expect(vm.clusters[0].spire.position[0]).toBeCloseTo(FOREST.base[0]);+ expect(vm.clusters[0].spire.position[2]).toBe(FOREST.base[2]);+ });++ it('caps root clusters and reports the overflow', () => {+ const goals = [];+ for (let i = 0; i < FOREST.maxRoots + 2; i++) {+ goals.push(goal({ id: `r${i}`, parentId: null }));+ goals.push(goal({ id: `c${i}`, parentId: `r${i}` }));+ }+ const vm = computeGoalForest(goals, NOW);+ expect(vm.clusters).toHaveLength(FOREST.maxRoots);+ expect(vm.rootOverflow).toBe(2);+ expect(vm.rootCount).toBe(FOREST.maxRoots + 2);+ });++ it('caps children per root and reports childOverflow', () => {+ const goals = [goal({ id: 'apex', parentId: null })];+ for (let i = 0; i < FOREST.maxChildren + 3; i++) goals.push(goal({ id: `c${i}`, parentId: 'apex' }));+ const vm = computeGoalForest(goals, NOW);+ expect(vm.clusters[0].children).toHaveLength(FOREST.maxChildren);+ expect(vm.clusters[0].childOverflow).toBe(3);+ });++ it('handles missing / non-array input as an empty forest', () => {+ for (const bad of [null, undefined, 'nope', 42, {}]) {+ const vm = computeGoalForest(bad, NOW);+ expect(vm.clusters).toEqual([]);+ expect(vm.hasData).toBe(false);+ expect(vm.hasHierarchy).toBe(false);+ }+ });+});