Skip to content

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

feat: add standalone Goal Tree page with 3D tree and list views

Adam Eivy5512d25a0da5
diff --git a/client/src/App.jsx b/client/src/App.jsx
index f9b845065b..b94a55a4a0 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -52,6 +52,7 @@ const AppDetail = lazyWithReload(() => import('./pages/AppDetail'));
const FeatureAgents = lazyWithReload(() => import('./pages/FeatureAgents'));
const FeatureAgentDetail = lazyWithReload(() => import('./pages/FeatureAgentDetail'));
const Messages = lazyWithReload(() => import('./pages/Messages'));
+const Goals = lazyWithReload(() => import('./pages/Goals'));
// Loading fallback for lazy-loaded pages
const PageLoader = () => (
@@ -89,6 +90,8 @@ export default function App() {
<Route path="brain/:tab" element={<Brain />} />
<Route path="digital-twin" element={<Navigate to="/digital-twin/overview" replace />} />
<Route path="digital-twin/:tab" element={<DigitalTwin />} />
+ <Route path="goals" element={<Navigate to="/goals/tree" replace />} />
+ <Route path="goals/:tab" element={<Goals />} />
<Route path="feature-agents" element={<FeatureAgents />} />
<Route path="feature-agents/create" element={<FeatureAgentDetail />} />
<Route path="feature-agents/:id" element={<Navigate to="overview" replace />} />
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index d2ab2d8bda..d0af73eebf 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -156,6 +156,7 @@ const navItems = [
]
},
{ to: '/feature-agents', label: 'Feature Agents', icon: Wand2, single: true },
+ { to: '/goals/tree', label: 'Goals', icon: Target, single: true },
{ to: '/insights/overview', label: 'Insights', icon: Lightbulb, single: true },
{ to: '/instances', label: 'Instances', icon: Network, single: true },
{
@@ -616,6 +617,7 @@ export default function Layout() {
location.pathname.startsWith('/brain') ||
location.pathname.startsWith('/digital-twin') ||
location.pathname.startsWith('/feature-agents') ||
+ location.pathname.startsWith('/goals') ||
location.pathname.startsWith('/insights') ||
location.pathname.startsWith('/meatspace') ||
location.pathname.startsWith('/messages') ||
diff --git a/client/src/components/goals/GoalDetailPanel.jsx b/client/src/components/goals/GoalDetailPanel.jsx
new file mode 100644
index 0000000000..6ff52143bb
--- /dev/null
+++ b/client/src/components/goals/GoalDetailPanel.jsx
@@ -0,0 +1,356 @@
+import { useState } from 'react';
+import {
+ Target, X, Check, Trash2, Milestone, Calendar,
+ Heart, DollarSign, Lightbulb, Users, Flame, AlertTriangle, Tag
+} from 'lucide-react';
+import * as api from '../../services/api';
+
+const CATEGORY_CONFIG = {
+ creative: { label: 'Creative', icon: Lightbulb, color: 'text-purple-400', bg: 'bg-purple-500/20', hex: '#a855f7' },
+ family: { label: 'Family', icon: Users, color: 'text-pink-400', bg: 'bg-pink-500/20', hex: '#ec4899' },
+ health: { label: 'Health', icon: Heart, color: 'text-green-400', bg: 'bg-green-500/20', hex: '#22c55e' },
+ financial: { label: 'Financial', icon: DollarSign, color: 'text-yellow-400', bg: 'bg-yellow-500/20', hex: '#eab308' },
+ legacy: { label: 'Legacy', icon: Flame, color: 'text-orange-400', bg: 'bg-orange-500/20', hex: '#f97316' },
+ mastery: { label: 'Mastery', icon: Target, color: 'text-blue-400', bg: 'bg-blue-500/20', hex: '#3b82f6' }
+};
+
+const HORIZON_OPTIONS = [
+ { value: '1-year', label: '1 Year' },
+ { value: '3-year', label: '3 Years' },
+ { value: '5-year', label: '5 Years' },
+ { value: '10-year', label: '10 Years' },
+ { value: '20-year', label: '20 Years' },
+ { value: 'lifetime', label: 'Lifetime' }
+];
+
+export { CATEGORY_CONFIG, HORIZON_OPTIONS };
+
+export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh }) {
+ const [editing, setEditing] = useState(false);
+ const [form, setForm] = useState({});
+ const [tagInput, setTagInput] = useState('');
+ const [newMilestone, setNewMilestone] = useState({ title: '', targetDate: '' });
+
+ if (!goal) return null;
+
+ const cat = CATEGORY_CONFIG[goal.category] || CATEGORY_CONFIG.mastery;
+ const CatIcon = cat.icon;
+ const parent = goal.parentId ? allGoals?.find(g => g.id === goal.parentId) : null;
+ const children = allGoals?.filter(g => g.parentId === goal.id) || [];
+
+ const startEdit = () => {
+ setForm({
+ title: goal.title,
+ description: goal.description || '',
+ horizon: goal.horizon,
+ category: goal.category,
+ parentId: goal.parentId || '',
+ tags: [...(goal.tags || [])]
+ });
+ setEditing(true);
+ };
+
+ const saveEdit = async () => {
+ await api.updateGoal(goal.id, {
+ ...form,
+ parentId: form.parentId || null
+ });
+ setEditing(false);
+ onRefresh();
+ };
+
+ const handleDelete = async () => {
+ await api.deleteGoal(goal.id);
+ onClose();
+ onRefresh();
+ };
+
+ const handleComplete = async () => {
+ await api.updateGoal(goal.id, { status: 'completed' });
+ onRefresh();
+ };
+
+ const handleAddMilestone = async () => {
+ if (!newMilestone.title.trim()) return;
+ await api.addGoalMilestone(goal.id, {
+ title: newMilestone.title,
+ ...(newMilestone.targetDate ? { targetDate: newMilestone.targetDate } : {})
+ });
+ setNewMilestone({ title: '', targetDate: '' });
+ onRefresh();
+ };
+
+ const handleCompleteMilestone = async (milestoneId) => {
+ await api.completeGoalMilestone(goal.id, milestoneId);
+ onRefresh();
+ };
+
+ const addTag = () => {
+ const tag = tagInput.trim();
+ if (tag && !form.tags.includes(tag)) {
+ setForm({ ...form, tags: [...form.tags, tag] });
+ }
+ setTagInput('');
+ };
+
+ const removeTag = (tag) => {
+ setForm({ ...form, tags: form.tags.filter(t => t !== tag) });
+ };
+
+ const urgencyColor = (u) => {
+ if (u == null) return 'text-gray-500';
+ if (u >= 0.7) return 'text-red-400';
+ if (u >= 0.4) return 'text-yellow-400';
+ return 'text-green-400';
+ };
+
+ // Exclude self and descendants from parent options to prevent cycles
+ const getDescendantIds = (id) => {
+ const ids = new Set([id]);
+ const queue = [id];
+ while (queue.length) {
+ const current = queue.shift();
+ for (const g of (allGoals || [])) {
+ if (g.parentId === current && !ids.has(g.id)) {
+ ids.add(g.id);
+ queue.push(g.id);
+ }
+ }
+ }
+ return ids;
+ };
+ const excludedIds = getDescendantIds(goal.id);
+ const parentOptions = (allGoals || []).filter(g => !excludedIds.has(g.id));
+
+ return (
+ <div className="w-80 bg-port-card border-l border-port-border h-full overflow-y-auto p-4 space-y-4">
+ {/* Header */}
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <div className={`p-1.5 rounded ${cat.bg}`}>
+ <CatIcon className={`w-4 h-4 ${cat.color}`} />
+ </div>
+ <span className="text-sm font-medium text-white truncate">{goal.title}</span>
+ </div>
+ <button onClick={onClose} className="p-1 text-gray-500 hover:text-white">
+ <X className="w-4 h-4" />
+ </button>
+ </div>
+
+ {editing ? (
+ <div className="space-y-3">
+ <input
+ type="text"
+ value={form.title}
+ onChange={e => setForm({ ...form, title: e.target.value })}
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-1.5 text-sm text-white"
+ />
+ <textarea
+ value={form.description}
+ onChange={e => setForm({ ...form, description: e.target.value })}
+ rows={3}
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-1.5 text-sm text-white resize-none"
+ />
+ <div>
+ <label className="text-xs text-gray-500">Horizon</label>
+ <select
+ value={form.horizon}
+ onChange={e => setForm({ ...form, horizon: e.target.value })}
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-1.5 text-sm text-white mt-1"
+ >
+ {HORIZON_OPTIONS.map(h => <option key={h.value} value={h.value}>{h.label}</option>)}
+ </select>
+ </div>
+ <div>
+ <label className="text-xs text-gray-500">Category</label>
+ <select
+ value={form.category}
+ onChange={e => setForm({ ...form, category: e.target.value })}
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-1.5 text-sm text-white mt-1"
+ >
+ {Object.entries(CATEGORY_CONFIG).map(([k, v]) => (
+ <option key={k} value={k}>{v.label}</option>
+ ))}
+ </select>
+ </div>
+ <div>
+ <label className="text-xs text-gray-500">Parent Goal</label>
+ <select
+ value={form.parentId}
+ onChange={e => setForm({ ...form, parentId: e.target.value })}
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-1.5 text-sm text-white mt-1"
+ >
+ <option value="">None (root)</option>
+ {parentOptions.map(g => (
+ <option key={g.id} value={g.id}>{g.title}</option>
+ ))}
+ </select>
+ </div>
+ <div>
+ <label className="text-xs text-gray-500">Tags</label>
+ <div className="flex flex-wrap gap-1 mt-1 mb-2">
+ {form.tags.map(tag => (
+ <span key={tag} className="flex items-center gap-1 px-2 py-0.5 rounded bg-port-accent/20 text-port-accent text-xs">
+ {tag}
+ <button onClick={() => removeTag(tag)} className="hover:text-white">
+ <X className="w-3 h-3" />
+ </button>
+ </span>
+ ))}
+ </div>
+ <div className="flex gap-1">
+ <input
+ type="text"
+ value={tagInput}
+ onChange={e => setTagInput(e.target.value)}
+ onKeyDown={e => e.key === 'Enter' && (e.preventDefault(), addTag())}
+ placeholder="Add tag..."
+ className="flex-1 bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white"
+ />
+ <button onClick={addTag} className="px-2 py-1 text-xs rounded bg-port-accent/20 text-port-accent">
+ Add
+ </button>
+ </div>
+ </div>
+ <div className="flex gap-2">
+ <button onClick={saveEdit} className="px-3 py-1.5 text-sm rounded bg-port-accent text-white hover:bg-blue-600">
+ Save
+ </button>
+ <button onClick={() => setEditing(false)} className="px-3 py-1.5 text-sm rounded bg-port-border text-gray-300">
+ Cancel
+ </button>
+ </div>
+ </div>
+ ) : (
+ <>
+ {/* Info */}
+ {goal.description && (
+ <p className="text-sm text-gray-400">{goal.description}</p>
+ )}
+
+ <div className="flex flex-wrap gap-2 text-xs">
+ <span className={`px-2 py-0.5 rounded ${cat.bg} ${cat.color}`}>{cat.label}</span>
+ <span className="px-2 py-0.5 rounded bg-gray-700 text-gray-300">
+ {HORIZON_OPTIONS.find(h => h.value === goal.horizon)?.label}
+ </span>
+ {goal.urgency != null && (
+ <span className={`flex items-center gap-1 px-2 py-0.5 rounded bg-gray-700 ${urgencyColor(goal.urgency)}`}>
+ {goal.urgency >= 0.7 && <AlertTriangle className="w-3 h-3" />}
+ {Math.round(goal.urgency * 100)}% urgency
+ </span>
+ )}
+ <span className="px-2 py-0.5 rounded bg-gray-700 text-gray-400">
+ {goal.status}
+ </span>
+ </div>
+
+ {/* Tags */}
+ {goal.tags?.length > 0 && (
+ <div className="flex flex-wrap gap-1">
+ {goal.tags.map(tag => (
+ <span key={tag} className="flex items-center gap-1 px-2 py-0.5 rounded bg-port-accent/20 text-port-accent text-xs">
+ <Tag className="w-3 h-3" />
+ {tag}
+ </span>
+ ))}
+ </div>
+ )}
+
+ {/* Parent */}
+ {parent && (
+ <div className="text-xs text-gray-500">
+ Parent: <span className="text-gray-300">{parent.title}</span>
+ </div>
+ )}
+
+ {/* Children */}
+ {children.length > 0 && (
+ <div className="text-xs text-gray-500">
+ Sub-goals: {children.map(c => c.title).join(', ')}
+ </div>
+ )}
+
+ {/* Milestones */}
+ <div>
+ <div className="flex items-center gap-1 mb-2">
+ <Milestone className="w-3.5 h-3.5 text-gray-500" />
+ <span className="text-xs font-medium text-gray-400">
+ Milestones ({goal.milestones?.filter(m => m.completedAt).length || 0}/{goal.milestones?.length || 0})
+ </span>
+ </div>
+ {goal.milestones?.length > 0 && (
+ <div className="space-y-1 mb-2">
+ {goal.milestones.map(ms => (
+ <div key={ms.id} className="flex items-center gap-2 text-sm">
+ <button
+ onClick={() => !ms.completedAt && handleCompleteMilestone(ms.id)}
+ className={`w-4 h-4 rounded border flex items-center justify-center shrink-0 ${
+ ms.completedAt
+ ? 'bg-green-500/20 border-green-500 text-green-400'
+ : 'border-gray-600 hover:border-port-accent'
+ }`}
+ >
+ {ms.completedAt && <Check className="w-3 h-3" />}
+ </button>
+ <span className={`text-xs ${ms.completedAt ? 'text-gray-500 line-through' : 'text-gray-300'}`}>
+ {ms.title}
+ </span>
+ {ms.targetDate && (
+ <span className="text-xs text-gray-600 ml-auto flex items-center gap-1">
+ <Calendar className="w-3 h-3" />
+ {new Date(ms.targetDate).toLocaleDateString()}
+ </span>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+ <div className="flex gap-1">
+ <input
+ type="text"
+ value={newMilestone.title}
+ onChange={e => setNewMilestone({ ...newMilestone, title: e.target.value })}
+ onKeyDown={e => e.key === 'Enter' && handleAddMilestone()}
+ placeholder="Add milestone..."
+ className="flex-1 bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white"
+ />
+ <button
+ onClick={handleAddMilestone}
+ disabled={!newMilestone.title.trim()}
+ className="px-2 py-1 text-xs rounded bg-port-accent/20 text-port-accent disabled:opacity-50"
+ >
+ Add
+ </button>
+ </div>
+ </div>
+
+ {/* Actions */}
+ <div className="flex gap-2 pt-2 border-t border-port-border">
+ <button
+ onClick={startEdit}
+ className="px-3 py-1.5 text-xs rounded bg-port-border text-gray-300 hover:bg-gray-600"
+ >
+ Edit
+ </button>
+ {goal.status === 'active' && (
+ <button
+ onClick={handleComplete}
+ className="flex items-center gap-1 px-3 py-1.5 text-xs rounded bg-green-500/20 text-green-400 hover:bg-green-500/30"
+ >
+ <Check className="w-3 h-3" />
+ Complete
+ </button>
+ )}
+ <button
+ onClick={handleDelete}
+ className="flex items-center gap-1 px-3 py-1.5 text-xs rounded bg-red-500/20 text-red-400 hover:bg-red-500/30"
+ >
+ <Trash2 className="w-3 h-3" />
+ Delete
+ </button>
+ </div>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/goals/GoalsListView.jsx b/client/src/components/goals/GoalsListView.jsx
new file mode 100644
index 0000000000..86977b6755
--- /dev/null
+++ b/client/src/components/goals/GoalsListView.jsx
@@ -0,0 +1,277 @@
+import { useState, useMemo } from 'react';
+import {
+ ChevronRight, ChevronDown, Plus, GripVertical, Search, Tag
+} from 'lucide-react';
+import * as api from '../../services/api';
+import GoalDetailPanel, { CATEGORY_CONFIG, HORIZON_OPTIONS } from './GoalDetailPanel';
+
+function urgencyIndicator(urgency) {
+ if (urgency == null) return null;
+ const color = urgency >= 0.7 ? 'bg-red-400' : urgency >= 0.4 ? 'bg-yellow-400' : 'bg-green-400';
+ return <div className={`w-2 h-2 rounded-full ${color}`} title={`${Math.round(urgency * 100)}% urgency`} />;
+}
+
+function GoalRow({ goal, depth, expanded, onToggle, onSelect, selectedId, allGoals, onAddChild }) {
+ const cat = CATEGORY_CONFIG[goal.category] || CATEGORY_CONFIG.mastery;
+ const CatIcon = cat.icon;
+ const hasChildren = goal.children?.length > 0;
+ const isSelected = selectedId === goal.id;
+
+ return (
+ <>
+ <div
+ className={`flex items-center gap-2 px-3 py-2 hover:bg-port-border/30 cursor-pointer transition-colors border-b border-port-border/50 ${
+ isSelected ? 'bg-port-accent/10' : ''
+ }`}
+ style={{ paddingLeft: `${depth * 24 + 12}px` }}
+ onClick={() => onSelect(goal)}
+ >
+ <GripVertical className="w-3.5 h-3.5 text-gray-600 shrink-0 cursor-grab" />
+
+ {hasChildren ? (
+ <button
+ onClick={(e) => { e.stopPropagation(); onToggle(goal.id); }}
+ className="p-0.5 text-gray-500 hover:text-white shrink-0"
+ >
+ {expanded ? <ChevronDown className="w-3.5 h-3.5" /> : <ChevronRight className="w-3.5 h-3.5" />}
+ </button>
+ ) : (
+ <div className="w-4.5 shrink-0" />
+ )}
+
+ <div className={`p-1 rounded ${cat.bg} shrink-0`}>
+ <CatIcon className={`w-3.5 h-3.5 ${cat.color}`} />
+ </div>
+
+ <span className="text-sm text-white truncate flex-1">{goal.title}</span>
+
+ <span className="text-xs text-gray-500 shrink-0 px-1.5 py-0.5 rounded bg-gray-800">
+ {HORIZON_OPTIONS.find(h => h.value === goal.horizon)?.label}
+ </span>
+
+ {urgencyIndicator(goal.urgency)}
+
+ {goal.tags?.length > 0 && (
+ <div className="flex items-center gap-1 shrink-0">
+ {goal.tags.slice(0, 3).map(tag => (
+ <span key={tag} className="flex items-center gap-0.5 px-1.5 py-0.5 rounded bg-port-accent/10 text-port-accent text-xs">
+ <Tag className="w-2.5 h-2.5" />
+ {tag}
+ </span>
+ ))}
+ {goal.tags.length > 3 && (
+ <span className="text-xs text-gray-500">+{goal.tags.length - 3}</span>
+ )}
+ </div>
+ )}
+
+ <button
+ onClick={(e) => { e.stopPropagation(); onAddChild(goal.id); }}
+ className="p-1 text-gray-600 hover:text-port-accent shrink-0"
+ title="Add sub-goal"
+ >
+ <Plus className="w-3.5 h-3.5" />
+ </button>
+ </div>
+
+ {hasChildren && expanded && goal.children.map(child => (
+ <GoalRow
+ key={child.id}
+ goal={child}
+ depth={depth + 1}
+ expanded={expanded}
+ onToggle={onToggle}
+ onSelect={onSelect}
+ selectedId={selectedId}
+ allGoals={allGoals}
+ onAddChild={onAddChild}
+ />
+ ))}
+ </>
+ );
+}
+
+export default function GoalsListView({ data, onRefresh }) {
+ const [expandedIds, setExpandedIds] = useState(new Set());
+ const [selectedGoal, setSelectedGoal] = useState(null);
+ const [searchQuery, setSearchQuery] = useState('');
+ const [showNewGoal, setShowNewGoal] = useState(false);
+ const [newGoal, setNewGoal] = useState({ title: '', description: '', horizon: '5-year', category: 'mastery', parentId: null });
+
+ const toggleExpand = (id) => {
+ setExpandedIds(prev => {
+ const next = new Set(prev);
+ if (next.has(id)) next.delete(id); else next.add(id);
+ return next;
+ });
+ };
+
+ // Build tree from roots, filtering by search
+ const filteredRoots = useMemo(() => {
+ if (!data?.roots) return [];
+ if (!searchQuery) return data.roots;
+ const query = searchQuery.toLowerCase();
+ const matchesSearch = (goal) => {
+ if (goal.title.toLowerCase().includes(query)) return true;
+ if (goal.description?.toLowerCase().includes(query)) return true;
+ if (goal.tags?.some(t => t.toLowerCase().includes(query))) return true;
+ return goal.children?.some(matchesSearch) || false;
+ };
+ return data.roots.filter(matchesSearch);
+ }, [data, searchQuery]);
+
+ const handleSelect = (goal) => {
+ const full = data?.flat?.find(g => g.id === goal.id);
+ setSelectedGoal(prev => prev?.id === goal.id ? null : full || goal);
+ };
+
+ const handleAddChild = (parentId) => {
+ setNewGoal({ title: '', description: '', horizon: '5-year', category: 'mastery', parentId });
+ setShowNewGoal(true);
+ };
+
+ const handleCreateGoal = async () => {
+ if (!newGoal.title.trim()) return;
+ await api.createGoal(newGoal);
+ setNewGoal({ title: '', description: '', horizon: '5-year', category: 'mastery', parentId: null });
+ setShowNewGoal(false);
+ onRefresh();
+ };
+
+ return (
+ <div className="h-full flex">
+ <div className="flex-1 flex flex-col overflow-hidden">
+ {/* Toolbar */}
+ <div className="flex items-center gap-3 px-4 py-3 border-b border-port-border bg-port-card/50">
+ <div className="relative flex-1 max-w-xs">
+ <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
+ <input
+ type="text"
+ value={searchQuery}
+ onChange={e => setSearchQuery(e.target.value)}
+ placeholder="Search goals..."
+ className="w-full bg-port-bg border border-port-border rounded-lg pl-8 pr-3 py-1.5 text-sm text-white"
+ />
+ </div>
+ <button
+ onClick={() => {
+ setNewGoal({ title: '', description: '', horizon: '5-year', category: 'mastery', parentId: null });
+ setShowNewGoal(true);
+ }}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-lg bg-port-accent text-white hover:bg-blue-600"
+ >
+ <Plus className="w-4 h-4" />
+ Add Root Goal
+ </button>
+ <button
+ onClick={() => {
+ if (expandedIds.size > 0) {
+ setExpandedIds(new Set());
+ } else {
+ const allIds = new Set();
+ const collect = (goals) => {
+ for (const g of goals) {
+ if (g.children?.length) { allIds.add(g.id); collect(g.children); }
+ }
+ };
+ collect(data?.roots || []);
+ setExpandedIds(allIds);
+ }
+ }}
+ className="px-3 py-1.5 text-sm rounded-lg bg-port-border text-gray-300 hover:bg-gray-600"
+ >
+ {expandedIds.size > 0 ? 'Collapse All' : 'Expand All'}
+ </button>
+ </div>
+
+ {/* New goal form */}
+ {showNewGoal && (
+ <div className="bg-port-card border-b border-port-border px-4 py-3 space-y-2">
+ <div className="flex items-center gap-2 text-sm text-gray-400">
+ <Plus className="w-4 h-4" />
+ {newGoal.parentId
+ ? `New sub-goal under "${data?.flat?.find(g => g.id === newGoal.parentId)?.title}"`
+ : 'New root goal'}
+ </div>
+ <div className="flex gap-2">
+ <input
+ type="text"
+ value={newGoal.title}
+ onChange={e => setNewGoal({ ...newGoal, title: e.target.value })}
+ placeholder="Goal title..."
+ className="flex-1 bg-port-bg border border-port-border rounded px-3 py-1.5 text-sm text-white"
+ onKeyDown={e => e.key === 'Enter' && handleCreateGoal()}
+ autoFocus
+ />
+ <select
+ value={newGoal.horizon}
+ onChange={e => setNewGoal({ ...newGoal, horizon: e.target.value })}
+ className="bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"
+ >
+ {HORIZON_OPTIONS.map(h => <option key={h.value} value={h.value}>{h.label}</option>)}
+ </select>
+ <select
+ value={newGoal.category}
+ onChange={e => setNewGoal({ ...newGoal, category: e.target.value })}
+ className="bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"
+ >
+ {Object.entries(CATEGORY_CONFIG).map(([k, v]) => (
+ <option key={k} value={k}>{v.label}</option>
+ ))}
+ </select>
+ <button
+ onClick={handleCreateGoal}
+ disabled={!newGoal.title.trim()}
+ className="px-3 py-1.5 text-sm rounded bg-port-accent text-white disabled:opacity-50"
+ >
+ Create
+ </button>
+ <button
+ onClick={() => setShowNewGoal(false)}
+ className="px-3 py-1.5 text-sm rounded bg-port-border text-gray-300"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* Tree list */}
+ <div className="flex-1 overflow-y-auto">
+ {filteredRoots.length === 0 ? (
+ <div className="flex items-center justify-center h-full text-gray-500 text-sm">
+ {searchQuery ? 'No matching goals found.' : 'No goals yet. Add a root goal to get started.'}
+ </div>
+ ) : (
+ filteredRoots.map(root => (
+ <GoalRow
+ key={root.id}
+ goal={root}
+ depth={0}
+ expanded={expandedIds.has(root.id)}
+ onToggle={toggleExpand}
+ onSelect={handleSelect}
+ selectedId={selectedGoal?.id}
+ allGoals={data?.flat}
+ onAddChild={handleAddChild}
+ />
+ ))
+ )}
+ </div>
+ </div>
+
+ {/* Detail panel */}
+ {selectedGoal && (
+ <GoalDetailPanel
+ goal={selectedGoal}
+ allGoals={data?.flat}
+ onClose={() => setSelectedGoal(null)}
+ onRefresh={() => {
+ setSelectedGoal(null);
+ onRefresh();
+ }}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/goals/GoalsTreeView.jsx b/client/src/components/goals/GoalsTreeView.jsx
new file mode 100644
index 0000000000..efa483c063
--- /dev/null
+++ b/client/src/components/goals/GoalsTreeView.jsx
@@ -0,0 +1,333 @@
+import { useState, useEffect, useMemo, useRef, useCallback } from 'react';
+import { Canvas } from '@react-three/fiber';
+import { OrbitControls } from '@react-three/drei';
+import * as THREE from 'three';
+import { Search, Plus } from 'lucide-react';
+import * as api from '../../services/api';
+import { layoutGoalNodes } from './goalTreeLayout';
+import GoalDetailPanel, { CATEGORY_CONFIG, HORIZON_OPTIONS } from './GoalDetailPanel';
+
+const EDGE_COLORS = {
+ parent: '#3b82f6',
+ tag: '#f59e0b'
+};
+
+function GoalEdges({ edges, selectedId }) {
+ const geoRef = useRef();
+
+ useEffect(() => {
+ const geo = geoRef.current;
+ if (!geo || !edges.length) return;
+
+ const count = edges.length;
+ const positions = new Float32Array(count * 6);
+ const colors = new Float32Array(count * 6);
+ const tmpColor = new THREE.Color();
+
+ edges.forEach((e, i) => {
+ const a = e.sourceNode, b = e.targetNode;
+ const off = i * 6;
+ positions[off] = a.x; positions[off + 1] = a.y; positions[off + 2] = a.z;
+ positions[off + 3] = b.x; positions[off + 4] = b.y; positions[off + 5] = b.z;
+
+ const dimmed = selectedId && e.source !== selectedId && e.target !== selectedId;
+ tmpColor.set(EDGE_COLORS[e.type] || '#6b7280');
+ const intensity = dimmed ? 0.06 : (e.type === 'parent' ? 0.5 : 0.2);
+ colors[off] = tmpColor.r * intensity;
+ colors[off + 1] = tmpColor.g * intensity;
+ colors[off + 2] = tmpColor.b * intensity;
+ colors[off + 3] = tmpColor.r * intensity;
+ colors[off + 4] = tmpColor.g * intensity;
+ colors[off + 5] = tmpColor.b * intensity;
+ });
+
+ geo.setAttribute('position', new THREE.BufferAttribute(positions, 3));
+ geo.setAttribute('color', new THREE.BufferAttribute(colors, 3));
+ geo.computeBoundingSphere();
+ }, [edges, selectedId]);
+
+ return (
+ <lineSegments>
+ <bufferGeometry ref={geoRef} />
+ <lineBasicMaterial vertexColors />
+ </lineSegments>
+ );
+}
+
+function GoalScene({ graph, selectedId, adjacentIds, onSelect, onHover }) {
+ const sphereGeo = useMemo(() => new THREE.SphereGeometry(1, 16, 12), []);
+
+ const selNode = selectedId ? graph.idMap.get(selectedId) : null;
+ const selRadius = selNode ? 0.5 + (selNode.urgency ?? 0.3) * 0.6 : 0;
+
+ return (
+ <>
+ <ambientLight intensity={0.4} />
+ <pointLight position={[50, 50, 50]} intensity={0.8} />
+ <pointLight position={[-30, -30, -30]} intensity={0.3} />
+
+ <GoalEdges edges={graph.edges} selectedId={selectedId} />
+
+ {graph.nodes.map(node => {
+ const radius = 0.5 + (node.urgency ?? 0.3) * 0.6;
+ const cat = CATEGORY_CONFIG[node.category] || CATEGORY_CONFIG.mastery;
+ const color = cat.hex;
+ const isSelected = node.id === selectedId;
+ const isConnected = adjacentIds?.has(node.id);
+ const dimmed = selectedId && !isSelected && !isConnected;
+
+ return (
+ <mesh
+ key={node.id}
+ geometry={sphereGeo}
+ scale={radius}
+ position={[node.x, node.y, node.z]}
+ onClick={(e) => { e.stopPropagation(); onSelect(node); }}
+ onPointerOver={(e) => { e.stopPropagation(); onHover(node); }}
+ onPointerOut={() => onHover(null)}
+ >
+ <meshStandardMaterial
+ color={dimmed ? '#1a1a1a' : color}
+ emissive={color}
+ emissiveIntensity={isSelected ? 0.6 : (dimmed ? 0.03 : 0.15 + (node.urgency ?? 0) * 0.3)}
+ />
+ </mesh>
+ );
+ })}
+
+ {selNode && (
+ <mesh geometry={sphereGeo} position={[selNode.x, selNode.y, selNode.z]} scale={selRadius + 0.2}>
+ <meshBasicMaterial color="#ffffff" transparent opacity={0.15} wireframe />
+ </mesh>
+ )}
+
+ <OrbitControls enableDamping dampingFactor={0.05} minDistance={5} maxDistance={150} />
+ </>
+ );
+}
+
+export default function GoalsTreeView({ data, onRefresh }) {
+ const [selectedNode, setSelectedNode] = useState(null);
+ const [hoveredNode, setHoveredNode] = useState(null);
+ const [searchQuery, setSearchQuery] = useState('');
+ const [categoryFilters, setCategoryFilters] = useState(() =>
+ Object.fromEntries(Object.keys(CATEGORY_CONFIG).map(k => [k, true]))
+ );
+ const [showNewGoal, setShowNewGoal] = useState(false);
+ const [newGoal, setNewGoal] = useState({ title: '', description: '', horizon: '5-year', category: 'mastery' });
+
+ const dragStartRef = useRef(null);
+
+ const filteredGoals = useMemo(() => {
+ if (!data?.flat?.length) return [];
+ const query = searchQuery.toLowerCase();
+ return data.flat.filter(g => {
+ if (!categoryFilters[g.category]) return false;
+ if (query && !g.title.toLowerCase().includes(query) && !g.description?.toLowerCase().includes(query)) return false;
+ return true;
+ });
+ }, [data, categoryFilters, searchQuery]);
+
+ const graph = useMemo(() => {
+ if (!filteredGoals.length) return null;
+ return layoutGoalNodes(filteredGoals);
+ }, [filteredGoals]);
+
+ const adjacentIds = useMemo(() => {
+ if (!selectedNode || !graph) return null;
+ const set = new Set();
+ for (const e of graph.edges) {
+ if (e.source === selectedNode.id) set.add(e.target);
+ if (e.target === selectedNode.id) set.add(e.source);
+ }
+ return set;
+ }, [selectedNode, graph]);
+
+ // Find the full goal data for the selected node
+ const selectedGoal = selectedNode ? data?.flat?.find(g => g.id === selectedNode.id) : null;
+
+ const handleSelect = useCallback((node) => {
+ setSelectedNode(prev => prev?.id === node.id ? null : node);
+ }, []);
+
+ const handleHover = useCallback((node) => {
+ setHoveredNode(node);
+ }, []);
+
+ const handlePointerMissed = useCallback((e) => {
+ const start = dragStartRef.current;
+ if (!start) return;
+ if (Math.abs(e.clientX - start.x) < 5 && Math.abs(e.clientY - start.y) < 5) {
+ setSelectedNode(null);
+ }
+ }, []);
+
+ const toggleCategory = (cat) => {
+ setCategoryFilters(prev => ({ ...prev, [cat]: !prev[cat] }));
+ setSelectedNode(null);
+ };
+
+ const handleCreateGoal = async () => {
+ if (!newGoal.title.trim()) return;
+ await api.createGoal(newGoal);
+ setNewGoal({ title: '', description: '', horizon: '5-year', category: 'mastery' });
+ setShowNewGoal(false);
+ onRefresh();
+ };
+
+ return (
+ <div className="h-full flex">
+ <div className="flex-1 relative">
+ {/* Filter bar */}
+ <div className="absolute top-3 left-3 right-3 z-10 flex items-center gap-2 flex-wrap">
+ <div className="relative">
+ <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-500" />
+ <input
+ type="text"
+ value={searchQuery}
+ onChange={e => setSearchQuery(e.target.value)}
+ placeholder="Search goals..."
+ className="bg-port-card/90 backdrop-blur border border-port-border rounded-lg pl-7 pr-3 py-1.5 text-sm text-white w-48"
+ />
+ </div>
+ {Object.entries(CATEGORY_CONFIG).map(([key, cfg]) => {
+ const Icon = cfg.icon;
+ return (
+ <button
+ key={key}
+ onClick={() => toggleCategory(key)}
+ className={`flex items-center gap-1 px-2 py-1 rounded-lg text-xs font-medium border transition-colors ${
+ categoryFilters[key]
+ ? `${cfg.bg} ${cfg.color} border-transparent`
+ : 'bg-port-card/60 text-gray-600 border-port-border'
+ }`}
+ >
+ <Icon className="w-3 h-3" />
+ {cfg.label}
+ </button>
+ );
+ })}
+ <button
+ onClick={() => setShowNewGoal(!showNewGoal)}
+ className="flex items-center gap-1 px-2 py-1 rounded-lg text-xs font-medium bg-port-accent text-white"
+ >
+ <Plus className="w-3 h-3" />
+ Add
+ </button>
+ </div>
+
+ {/* New goal form */}
+ {showNewGoal && (
+ <div className="absolute top-12 left-3 z-10 bg-port-card border border-port-border rounded-lg p-3 w-72 space-y-2 shadow-lg">
+ <input
+ type="text"
+ value={newGoal.title}
+ onChange={e => setNewGoal({ ...newGoal, title: e.target.value })}
+ placeholder="Goal title..."
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"
+ onKeyDown={e => e.key === 'Enter' && handleCreateGoal()}
+ />
+ <textarea
+ value={newGoal.description}
+ onChange={e => setNewGoal({ ...newGoal, description: e.target.value })}
+ placeholder="Description..."
+ rows={2}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white resize-none"
+ />
+ <div className="flex gap-2">
+ <select
+ value={newGoal.horizon}
+ onChange={e => setNewGoal({ ...newGoal, horizon: e.target.value })}
+ className="flex-1 bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white"
+ >
+ {HORIZON_OPTIONS.map(h => <option key={h.value} value={h.value}>{h.label}</option>)}
+ </select>
+ <select
+ value={newGoal.category}
+ onChange={e => setNewGoal({ ...newGoal, category: e.target.value })}
+ className="flex-1 bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white"
+ >
+ {Object.entries(CATEGORY_CONFIG).map(([k, v]) => (
+ <option key={k} value={k}>{v.label}</option>
+ ))}
+ </select>
+ </div>
+ <div className="flex gap-2">
+ <button
+ onClick={handleCreateGoal}
+ disabled={!newGoal.title.trim()}
+ className="px-3 py-1 text-sm rounded bg-port-accent text-white disabled:opacity-50"
+ >
+ Create
+ </button>
+ <button onClick={() => setShowNewGoal(false)} className="px-3 py-1 text-sm rounded bg-port-border text-gray-300">
+ Cancel
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* Legend */}
+ <div className="absolute bottom-3 left-3 z-10 bg-port-card/90 backdrop-blur border border-port-border rounded-lg px-3 py-2 text-xs space-y-1">
+ <div className="text-gray-400 font-medium mb-1">Legend</div>
+ <div className="flex items-center gap-2">
+ <div className="w-4 h-0.5 bg-blue-500" />
+ <span className="text-gray-500">Parent-child</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-4 h-0.5 bg-yellow-500" />
+ <span className="text-gray-500">Shared tag</span>
+ </div>
+ {graph && (
+ <div className="text-gray-600 pt-1 border-t border-port-border mt-1">
+ {graph.nodes.length} nodes, {graph.edges.length} edges
+ </div>
+ )}
+ </div>
+
+ {/* Tooltip */}
+ {hoveredNode && !selectedNode && (
+ <div className="absolute top-14 left-1/2 -translate-x-1/2 z-10 bg-port-card border border-port-border rounded-lg px-3 py-2 text-sm pointer-events-none shadow-lg">
+ <div className="text-white font-medium">{hoveredNode.title}</div>
+ <div className="text-gray-500 text-xs">
+ {CATEGORY_CONFIG[hoveredNode.category]?.label} &middot; {HORIZON_OPTIONS.find(h => h.value === hoveredNode.horizon)?.label}
+ {hoveredNode.urgency != null && ` &middot; ${Math.round(hoveredNode.urgency * 100)}% urgency`}
+ </div>
+ </div>
+ )}
+
+ {/* 3D Canvas */}
+ {graph?.nodes?.length ? (
+ <Canvas
+ camera={{ position: [0, 15, 40], fov: 60 }}
+ onPointerDown={(e) => { dragStartRef.current = { x: e.clientX, y: e.clientY }; }}
+ onPointerMissed={handlePointerMissed}
+ style={{ background: '#0f0f0f' }}
+ >
+ <GoalScene
+ graph={graph}
+ selectedId={selectedNode?.id}
+ adjacentIds={adjacentIds}
+ onSelect={handleSelect}
+ onHover={handleHover}
+ />
+ </Canvas>
+ ) : (
+ <div className="flex items-center justify-center h-full text-gray-500">
+ No goals to display. Add a goal to get started.
+ </div>
+ )}
+ </div>
+
+ {/* Detail panel */}
+ {selectedGoal && (
+ <GoalDetailPanel
+ goal={selectedGoal}
+ allGoals={data?.flat}
+ onClose={() => setSelectedNode(null)}
+ onRefresh={onRefresh}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/goals/goalTreeLayout.js b/client/src/components/goals/goalTreeLayout.js
new file mode 100644
index 0000000000..f6d32ed67a
--- /dev/null
+++ b/client/src/components/goals/goalTreeLayout.js
@@ -0,0 +1,120 @@
+// Tiered radial layout: lifetime/north-star goals at center, shorter horizons in outer rings
+// Sub-goals cluster near their parents
+
+const HORIZON_RING = {
+ 'lifetime': 0,
+ '20-year': 1,
+ '10-year': 2,
+ '5-year': 3,
+ '3-year': 4,
+ '1-year': 5
+};
+
+const RING_RADIUS = 8;
+const Y_SPREAD = 4;
+
+export function layoutGoalNodes(flatGoals) {
+ if (!flatGoals?.length) return { nodes: [], edges: [] };
+
+ const goalMap = new Map(flatGoals.map(g => [g.id, g]));
+
+ // Group by ring tier
+ const rings = {};
+ for (const goal of flatGoals) {
+ const ring = HORIZON_RING[goal.horizon] ?? 3;
+ if (!rings[ring]) rings[ring] = [];
+ rings[ring].push(goal);
+ }
+
+ const positioned = new Map();
+
+ // Position nodes ring by ring
+ for (const [ringStr, goals] of Object.entries(rings)) {
+ const ring = Number(ringStr);
+ const radius = ring * RING_RADIUS;
+ const count = goals.length;
+
+ goals.forEach((goal, i) => {
+ const angle = (2 * Math.PI * i) / Math.max(count, 1);
+ // If goal has parent that's already positioned, cluster near it
+ const parent = goal.parentId ? positioned.get(goal.parentId) : null;
+ let x, y, z;
+
+ if (parent && radius > 0) {
+ // Offset from parent position with some spread
+ const parentAngle = Math.atan2(parent.z, parent.x);
+ const spread = Math.PI / (count + 2);
+ const childAngle = parentAngle + (i - count / 2) * spread;
+ x = Math.cos(childAngle) * radius;
+ z = Math.sin(childAngle) * radius;
+ y = parent.y + (Math.random() - 0.5) * Y_SPREAD;
+ } else if (radius === 0) {
+ // Center ring - small spread
+ x = (Math.random() - 0.5) * 3;
+ z = (Math.random() - 0.5) * 3;
+ y = (Math.random() - 0.5) * Y_SPREAD;
+ } else {
+ x = Math.cos(angle) * radius;
+ z = Math.sin(angle) * radius;
+ y = (Math.random() - 0.5) * Y_SPREAD;
+ }
+
+ positioned.set(goal.id, {
+ ...goal,
+ x, y, z,
+ vx: 0, vy: 0, vz: 0
+ });
+ });
+ }
+
+ const nodes = Array.from(positioned.values());
+
+ // Build edges: parent-child (solid) and tag-based cross-links (dotted)
+ const edges = [];
+
+ // Parent-child edges
+ for (const goal of flatGoals) {
+ if (goal.parentId && positioned.has(goal.parentId)) {
+ edges.push({
+ source: goal.parentId,
+ target: goal.id,
+ type: 'parent',
+ sourceNode: positioned.get(goal.parentId),
+ targetNode: positioned.get(goal.id)
+ });
+ }
+ }
+
+ // Tag cross-link edges (goals sharing tags)
+ const tagMap = {};
+ for (const goal of flatGoals) {
+ for (const tag of (goal.tags || [])) {
+ if (!tagMap[tag]) tagMap[tag] = [];
+ tagMap[tag].push(goal.id);
+ }
+ }
+ const seenPairs = new Set();
+ for (const ids of Object.values(tagMap)) {
+ for (let i = 0; i < ids.length; i++) {
+ for (let j = i + 1; j < ids.length; j++) {
+ const key = [ids[i], ids[j]].sort().join(':');
+ if (seenPairs.has(key)) continue;
+ seenPairs.add(key);
+ // Don't add tag edge if parent-child edge already exists
+ const a = goalMap.get(ids[i]), b = goalMap.get(ids[j]);
+ if (a?.parentId === ids[j] || b?.parentId === ids[i]) continue;
+ if (positioned.has(ids[i]) && positioned.has(ids[j])) {
+ edges.push({
+ source: ids[i],
+ target: ids[j],
+ type: 'tag',
+ sourceNode: positioned.get(ids[i]),
+ targetNode: positioned.get(ids[j])
+ });
+ }
+ }
+ }
+ }
+
+ return { nodes, edges, idMap: positioned };
+}
diff --git a/client/src/pages/Goals.jsx b/client/src/pages/Goals.jsx
new file mode 100644
index 0000000000..b5b093a8cf
--- /dev/null
+++ b/client/src/pages/Goals.jsx
@@ -0,0 +1,89 @@
+import { useState, useEffect, useCallback } from 'react';
+import { useParams, useNavigate } from 'react-router-dom';
+import { Target, TreePine, List, RefreshCw } from 'lucide-react';
+import * as api from '../services/api';
+import GoalsTreeView from '../components/goals/GoalsTreeView';
+import GoalsListView from '../components/goals/GoalsListView';
+
+const TABS = [
+ { id: 'tree', label: 'Tree', icon: TreePine },
+ { id: 'list', label: 'List', icon: List }
+];
+
+export default function Goals() {
+ const { tab = 'tree' } = useParams();
+ const navigate = useNavigate();
+ const [data, setData] = useState(null);
+ const [loading, setLoading] = useState(true);
+
+ const loadData = useCallback(async () => {
+ const tree = await api.getGoalsTree().catch(() => null);
+ setData(tree);
+ setLoading(false);
+ }, []);
+
+ useEffect(() => { loadData(); }, [loadData]);
+
+ const handleTabChange = (tabId) => {
+ navigate(`/goals/${tabId}`, { replace: true });
+ };
+
+ return (
+ <div className="h-full flex flex-col overflow-hidden">
+ {/* Header */}
+ <div className="flex items-center justify-between px-6 py-4 border-b border-port-border bg-port-card">
+ <div className="flex items-center gap-3">
+ <Target className="w-6 h-6 text-port-accent" />
+ <h1 className="text-xl font-semibold text-white">Goal Tree</h1>
+ {data && (
+ <span className="text-sm text-gray-500">
+ {data.flat?.length || 0} goals
+ </span>
+ )}
+ </div>
+ <div className="flex items-center gap-3">
+ <button
+ onClick={() => { setLoading(true); loadData(); }}
+ className="p-2 rounded-lg text-gray-400 hover:text-white hover:bg-port-border/50"
+ title="Refresh"
+ >
+ <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
+ </button>
+ <div className="flex bg-port-bg rounded-lg p-0.5">
+ {TABS.map(t => {
+ const Icon = t.icon;
+ const active = tab === t.id;
+ return (
+ <button
+ key={t.id}
+ onClick={() => handleTabChange(t.id)}
+ className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${
+ active
+ ? 'bg-port-accent text-white'
+ : 'text-gray-400 hover:text-white'
+ }`}
+ >
+ <Icon className="w-4 h-4" />
+ {t.label}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ </div>
+
+ {/* Content */}
+ <div className="flex-1 overflow-hidden">
+ {loading ? (
+ <div className="flex items-center justify-center h-full">
+ <RefreshCw className="w-6 h-6 text-port-accent animate-spin" />
+ </div>
+ ) : tab === 'tree' ? (
+ <GoalsTreeView data={data} onRefresh={loadData} />
+ ) : (
+ <GoalsListView data={data} onRefresh={loadData} />
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 634f4c7a7e..76355d1868 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -1381,6 +1381,7 @@ export const updateGoal = (id, data) => request(`/digital-twin/identity/goals/${
body: JSON.stringify(data)
});
export const deleteGoal = (id) => request(`/digital-twin/identity/goals/${id}`, { method: 'DELETE' });
+export const getGoalsTree = () => request('/digital-twin/identity/goals/tree');
export const addGoalMilestone = (goalId, data) => request(`/digital-twin/identity/goals/${goalId}/milestones`, {
method: 'POST',
body: JSON.stringify(data)
diff --git a/server/lib/identityValidation.js b/server/lib/identityValidation.js
index c4324827e4..0496bf7ddc 100644
--- a/server/lib/identityValidation.js
+++ b/server/lib/identityValidation.js
@@ -52,7 +52,9 @@ export const createGoalInputSchema = z.object({
title: z.string().min(1).max(200),
description: z.string().max(2000).optional(),
horizon: goalHorizonEnum.optional().default('5-year'),
- category: goalCategoryEnum.optional().default('mastery')
+ category: goalCategoryEnum.optional().default('mastery'),
+ parentId: z.string().nullable().optional().default(null),
+ tags: z.array(z.string().min(1).max(50)).max(20).optional().default([])
});
export const updateGoalInputSchema = z.object({
@@ -60,7 +62,9 @@ export const updateGoalInputSchema = z.object({
description: z.string().max(2000).optional(),
horizon: goalHorizonEnum.optional(),
category: goalCategoryEnum.optional(),
- status: goalStatusEnum.optional()
+ status: goalStatusEnum.optional(),
+ parentId: z.string().nullable().optional(),
+ tags: z.array(z.string().min(1).max(50)).max(20).optional()
});
export const addMilestoneInputSchema = z.object({
diff --git a/server/routes/identity.js b/server/routes/identity.js
index 04ed9958d5..2f6e296b4c 100644
--- a/server/routes/identity.js
+++ b/server/routes/identity.js
@@ -71,6 +71,12 @@ router.get('/goals', asyncHandler(async (req, res) => {
res.json(goals);
}));
+// GET /api/digital-twin/identity/goals/tree — Hierarchical goals tree
+router.get('/goals/tree', asyncHandler(async (req, res) => {
+ const tree = await identityService.getGoalsTree();
+ res.json(tree);
+}));
+
// PUT /api/digital-twin/identity/goals/birth-date — Set birth date
router.put('/goals/birth-date', asyncHandler(async (req, res) => {
const { birthDate } = validateRequest(birthDateInputSchema, req.body);
diff --git a/server/services/identity.js b/server/services/identity.js
index 598a8c20d3..02b70ddbc8 100644
--- a/server/services/identity.js
+++ b/server/services/identity.js
@@ -653,7 +653,15 @@ export async function deriveLongevity(birthDate) {
// === Goal Service Functions ===
export async function getGoals() {
- return loadJSON(GOALS_FILE, DEFAULT_GOALS);
+ const data = await loadJSON(GOALS_FILE, DEFAULT_GOALS);
+ // Lazy migration: backfill parentId and tags on goals missing them
+ let needsSave = false;
+ for (const goal of data.goals) {
+ if (goal.parentId === undefined) { goal.parentId = null; needsSave = true; }
+ if (!Array.isArray(goal.tags)) { goal.tags = []; needsSave = true; }
+ }
+ if (needsSave) await saveJSON(GOALS_FILE, data);
+ return data;
}
export async function setBirthDate(birthDate) {
@@ -680,10 +688,15 @@ export async function setBirthDate(birthDate) {
return goals;
}
-export async function createGoal({ title, description, horizon, category }) {
- const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);
+export async function createGoal({ title, description, horizon, category, parentId, tags }) {
+ const goals = await getGoals();
const longevity = await loadJSON(LONGEVITY_FILE, DEFAULT_LONGEVITY);
+ // Validate parentId references an existing goal
+ if (parentId && !goals.goals.find(g => g.id === parentId)) {
+ throw new Error('Parent goal not found');
+ }
+
const id = `goal-${uuidv4()}`;
const goal = {
id,
@@ -691,6 +704,8 @@ export async function createGoal({ title, description, horizon, category }) {
description: description || '',
horizon: horizon || '5-year',
category: category || 'mastery',
+ parentId: parentId || null,
+ tags: tags || [],
urgency: null,
status: 'active',
milestones: [],
@@ -711,13 +726,37 @@ export async function createGoal({ title, description, horizon, category }) {
return goal;
}
+function hasAncestorCycle(goals, goalId, newParentId) {
+ let current = newParentId;
+ const visited = new Set();
+ while (current) {
+ if (current === goalId) return true;
+ if (visited.has(current)) return true;
+ visited.add(current);
+ const parent = goals.find(g => g.id === current);
+ current = parent?.parentId || null;
+ }
+ return false;
+}
+
export async function updateGoal(goalId, updates) {
- const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);
+ const goals = await getGoals();
const idx = goals.goals.findIndex(g => g.id === goalId);
if (idx === -1) return null;
const goal = goals.goals[idx];
- const allowed = ['title', 'description', 'horizon', 'category', 'status'];
+
+ // Validate parentId doesn't create a cycle
+ if (updates.parentId !== undefined && updates.parentId !== null) {
+ if (!goals.goals.find(g => g.id === updates.parentId)) {
+ throw new Error('Parent goal not found');
+ }
+ if (hasAncestorCycle(goals.goals, goalId, updates.parentId)) {
+ throw new Error('Cannot set parent: would create a cycle');
+ }
+ }
+
+ const allowed = ['title', 'description', 'horizon', 'category', 'status', 'parentId', 'tags'];
for (const key of allowed) {
if (updates[key] !== undefined) goal[key] = updates[key];
}
@@ -735,16 +774,65 @@ export async function updateGoal(goalId, updates) {
}
export async function deleteGoal(goalId) {
- const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);
+ const goals = await getGoals();
const idx = goals.goals.findIndex(g => g.id === goalId);
if (idx === -1) return false;
+ const deletedGoal = goals.goals[idx];
+ // Orphan children: reparent to deleted goal's parent (or root)
+ for (const goal of goals.goals) {
+ if (goal.parentId === goalId) {
+ goal.parentId = deletedGoal.parentId || null;
+ }
+ }
+
goals.goals.splice(idx, 1);
goals.updatedAt = new Date().toISOString();
await saveJSON(GOALS_FILE, goals);
return true;
}
+export async function getGoalsTree() {
+ const goals = await getGoals();
+ const longevity = await loadJSON(LONGEVITY_FILE, DEFAULT_LONGEVITY);
+
+ // Enrich goals with urgency
+ for (const goal of goals.goals) {
+ if (goal.status === 'active' && longevity.timeHorizons) {
+ goal.urgency = computeGoalUrgency(goal, longevity.timeHorizons);
+ }
+ }
+
+ // Build hierarchical tree
+ const goalMap = new Map(goals.goals.map(g => [g.id, { ...g, children: [] }]));
+ const roots = [];
+ for (const node of goalMap.values()) {
+ if (node.parentId && goalMap.has(node.parentId)) {
+ goalMap.get(node.parentId).children.push(node);
+ } else {
+ roots.push(node);
+ }
+ }
+
+ // Build tag index
+ const tagIndex = {};
+ for (const goal of goals.goals) {
+ for (const tag of (goal.tags || [])) {
+ if (!tagIndex[tag]) tagIndex[tag] = [];
+ tagIndex[tag].push(goal.id);
+ }
+ }
+
+ return {
+ roots,
+ flat: goals.goals,
+ tagIndex,
+ birthDate: goals.birthDate,
+ lifeExpectancy: longevity.lifeExpectancy || goals.lifeExpectancy,
+ timeHorizons: longevity.timeHorizons || goals.timeHorizons
+ };
+}
+
export async function addMilestone(goalId, { title, targetDate }) {
const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);
const goal = goals.goals.find(g => g.id === goalId);