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(goals): add apex goal hierarchy with LLM-powered organization

Adam Eivy0093d6821370
diff --git a/client/src/components/GoalProgressWidget.jsx b/client/src/components/GoalProgressWidget.jsx
index 8d7ba04519..01b44a69da 100644
--- a/client/src/components/GoalProgressWidget.jsx
+++ b/client/src/components/GoalProgressWidget.jsx
@@ -3,7 +3,7 @@ import { Link } from 'react-router-dom';
import { ChevronRight, AlertTriangle, Target } from 'lucide-react';
import * as api from '../services/api';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
-import { CATEGORY_CONFIG } from './goals/GoalDetailPanel';
+import { CATEGORY_CONFIG, GOAL_TYPE_CONFIG } from './goals/GoalDetailPanel';
const HORIZON_LABELS = {
'1-year': '1Y', '3-year': '3Y', '5-year': '5Y',
@@ -84,6 +84,11 @@ const GoalProgressWidget = memo(function GoalProgressWidget() {
<div className="flex items-center justify-between mb-1">
<div className="flex items-center gap-2 min-w-0">
<CatIcon size={14} className={`shrink-0 ${cat.color}`} aria-hidden="true" />
+ {goal.goalType && goal.goalType !== 'standard' && (
+ <span className={`shrink-0 text-[10px] px-1 py-0.5 rounded ${GOAL_TYPE_CONFIG[goal.goalType]?.bg} ${GOAL_TYPE_CONFIG[goal.goalType]?.color}`}>
+ {GOAL_TYPE_CONFIG[goal.goalType]?.label}
+ </span>
+ )}
<span className="text-sm font-medium text-gray-300 truncate group-hover:text-white transition-colors">
{goal.title}
</span>
diff --git a/client/src/components/goals/GoalDetailPanel.jsx b/client/src/components/goals/GoalDetailPanel.jsx
index d584089d7a..a2a01d2670 100644
--- a/client/src/components/goals/GoalDetailPanel.jsx
+++ b/client/src/components/goals/GoalDetailPanel.jsx
@@ -26,10 +26,18 @@ const HORIZON_OPTIONS = [
{ value: 'lifetime', label: 'Lifetime' }
];
+const GOAL_TYPE_CONFIG = {
+ apex: { label: 'Apex', color: 'text-amber-400', bg: 'bg-amber-500/20', description: 'North-star purpose' },
+ 'sub-apex': { label: 'Sub-Apex', color: 'text-purple-400', bg: 'bg-purple-500/20', description: 'Major life pillar' },
+ standard: { label: 'Standard', color: 'text-gray-400', bg: 'bg-gray-500/20', description: 'Regular goal' }
+};
+
+const GOAL_TYPE_OPTIONS = Object.entries(GOAL_TYPE_CONFIG).map(([value, cfg]) => ({ value, label: cfg.label }));
+
const MAX_TAGS = 20;
const MAX_TAG_LENGTH = 50;
-export { CATEGORY_CONFIG, HORIZON_OPTIONS };
+export { CATEGORY_CONFIG, HORIZON_OPTIONS, GOAL_TYPE_CONFIG, GOAL_TYPE_OPTIONS };
function ProgressSlider({ goal, onCommit }) {
const [draft, setDraft] = useState(goal.progress ?? 0);
@@ -144,6 +152,7 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh })
description: goal.description || '',
horizon: goal.horizon,
category: goal.category,
+ goalType: goal.goalType || 'standard',
parentId: goal.parentId || '',
tags: [...(goal.tags || [])],
targetDate: goal.targetDate || '',
@@ -347,13 +356,18 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh })
<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}`}>
+ <div className="flex items-center gap-2 min-w-0">
+ <div className={`p-1.5 rounded ${cat.bg} shrink-0`}>
<CatIcon className={`w-4 h-4 ${cat.color}`} />
</div>
<span className="text-sm font-medium text-white truncate">{goal.title}</span>
+ {goal.goalType && goal.goalType !== 'standard' && (
+ <span className={`shrink-0 text-xs px-1.5 py-0.5 rounded ${GOAL_TYPE_CONFIG[goal.goalType]?.bg} ${GOAL_TYPE_CONFIG[goal.goalType]?.color}`}>
+ {GOAL_TYPE_CONFIG[goal.goalType]?.label}
+ </span>
+ )}
</div>
- <button onClick={onClose} className="p-1 text-gray-500 hover:text-white">
+ <button onClick={onClose} className="p-1 text-gray-500 hover:text-white shrink-0">
<X className="w-4 h-4" />
</button>
</div>
@@ -394,6 +408,16 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh })
))}
</select>
</div>
+ <div>
+ <label className="text-xs text-gray-500">Goal Type</label>
+ <select
+ value={form.goalType || 'standard'}
+ onChange={e => setForm({ ...form, goalType: 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"
+ >
+ {GOAL_TYPE_OPTIONS.map(t => <option key={t.value} value={t.value}>{t.label}</option>)}
+ </select>
+ </div>
<div>
<label className="text-xs text-gray-500">Parent Goal</label>
<select
diff --git a/client/src/components/goals/GoalsListView.jsx b/client/src/components/goals/GoalsListView.jsx
index dae9334297..182e02acad 100644
--- a/client/src/components/goals/GoalsListView.jsx
+++ b/client/src/components/goals/GoalsListView.jsx
@@ -1,9 +1,11 @@
import { useState, useMemo } from 'react';
import {
- ChevronRight, ChevronDown, Plus, GripVertical, Search, Tag, Link2
+ ChevronRight, ChevronDown, Plus, GripVertical, Search, Tag, Link2, Crown, Star, Wand2
} from 'lucide-react';
+import toast from 'react-hot-toast';
import * as api from '../../services/api';
-import GoalDetailPanel, { CATEGORY_CONFIG, HORIZON_OPTIONS } from './GoalDetailPanel';
+import GoalDetailPanel, { CATEGORY_CONFIG, HORIZON_OPTIONS, GOAL_TYPE_CONFIG } from './GoalDetailPanel';
+import { applyOrganizationSuggestion } from './applyOrganization';
function urgencyIndicator(urgency) {
if (urgency == null) return null;
@@ -46,6 +48,13 @@ function GoalRow({ goal, depth, expandedIds, onToggle, onSelect, selectedId, onA
<span className="text-sm text-white truncate flex-1">{goal.title}</span>
+ {goal.goalType && goal.goalType !== 'standard' && (
+ <span className={`shrink-0 text-xs px-1.5 py-0.5 rounded ${GOAL_TYPE_CONFIG[goal.goalType]?.bg} ${GOAL_TYPE_CONFIG[goal.goalType]?.color}`}>
+ {goal.goalType === 'apex' ? <Crown className="w-3 h-3 inline mr-0.5" /> : <Star className="w-3 h-3 inline mr-0.5" />}
+ {GOAL_TYPE_CONFIG[goal.goalType]?.label}
+ </span>
+ )}
+
{/* Progress pill */}
{(goal.progress > 0 || goal.todos?.length > 0) && (
<span className="shrink-0 flex items-center gap-1 text-xs text-gray-500">
@@ -119,6 +128,7 @@ export default function GoalsListView({ data, onRefresh }) {
const [searchQuery, setSearchQuery] = useState('');
const [showNewGoal, setShowNewGoal] = useState(false);
const [newGoal, setNewGoal] = useState({ title: '', description: '', horizon: '5-year', category: 'mastery', parentId: null });
+ const [organizing, setOrganizing] = useState(false);
const toggleExpand = (id) => {
setExpandedIds(prev => {
@@ -160,6 +170,16 @@ export default function GoalsListView({ data, onRefresh }) {
onRefresh();
};
+ const handleOrganize = async () => {
+ setOrganizing(true);
+ const result = await api.organizeGoals().catch(() => null);
+ setOrganizing(false);
+ if (!result) { toast.error('Failed to organize goals'); return; }
+ await applyOrganizationSuggestion(result);
+ toast.success('Goal hierarchy applied');
+ onRefresh();
+ };
+
return (
<div className="h-full flex">
<div className="flex-1 flex flex-col overflow-hidden">
@@ -185,6 +205,17 @@ export default function GoalsListView({ data, onRefresh }) {
<Plus className="w-4 h-4" />
Add Root Goal
</button>
+ {(data?.flat?.length ?? 0) >= 2 && (
+ <button
+ onClick={handleOrganize}
+ disabled={organizing}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-lg bg-amber-500/20 text-amber-400 hover:bg-amber-500/30 disabled:opacity-50 min-h-[40px]"
+ title="Use AI to organize goals into a hierarchy"
+ >
+ <Wand2 className={`w-4 h-4 ${organizing ? 'animate-spin' : ''}`} />
+ {organizing ? 'Analyzing...' : 'Organize'}
+ </button>
+ )}
<button
onClick={() => {
if (expandedIds.size > 0) {
diff --git a/client/src/components/goals/GoalsTreeView.jsx b/client/src/components/goals/GoalsTreeView.jsx
index 384c8e73df..3039728a99 100644
--- a/client/src/components/goals/GoalsTreeView.jsx
+++ b/client/src/components/goals/GoalsTreeView.jsx
@@ -2,10 +2,12 @@ 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 { Search, Plus, Wand2, X, Check, Star, Crown } from 'lucide-react';
+import toast from 'react-hot-toast';
import * as api from '../../services/api';
import { layoutGoalNodes } from './goalTreeLayout';
-import GoalDetailPanel, { CATEGORY_CONFIG, HORIZON_OPTIONS } from './GoalDetailPanel';
+import GoalDetailPanel, { CATEGORY_CONFIG, HORIZON_OPTIONS, GOAL_TYPE_CONFIG } from './GoalDetailPanel';
+import { applyOrganizationSuggestion } from './applyOrganization';
const EDGE_COLORS = {
parent: '#3b82f6',
@@ -76,9 +78,10 @@ function GoalEdges({ edges, selectedId }) {
function GoalScene({ graph, selectedId, adjacentIds, onSelect, onHover }) {
const sphereGeo = useMemo(() => new THREE.SphereGeometry(1, 16, 12), []);
+ const octaGeo = useMemo(() => new THREE.OctahedronGeometry(1, 0), []);
const selNode = selectedId ? graph.idMap.get(selectedId) : null;
- const selRadius = selNode ? 0.5 + (selNode.urgency ?? 0.3) * 0.6 : 0;
+ const selRadius = selNode ? (selNode.goalType === 'apex' ? 1.6 : selNode.goalType === 'sub-apex' ? 1.1 : 0.5 + (selNode.urgency ?? 0.3) * 0.6) : 0;
return (
<>
@@ -89,17 +92,20 @@ function GoalScene({ graph, selectedId, adjacentIds, onSelect, onHover }) {
<GoalEdges edges={graph.edges} selectedId={selectedId} />
{graph.nodes.map(node => {
- const radius = 0.5 + (node.urgency ?? 0.3) * 0.6;
+ const isApex = node.goalType === 'apex';
+ const isSubApex = node.goalType === 'sub-apex';
+ const radius = isApex ? 1.6 : isSubApex ? 1.1 : 0.5 + (node.urgency ?? 0.3) * 0.6;
const cat = CATEGORY_CONFIG[node.category] || CATEGORY_CONFIG.mastery;
- const color = cat.hex;
+ const color = isApex ? '#fbbf24' : isSubApex ? '#c084fc' : cat.hex;
const isSelected = node.id === selectedId;
const isConnected = adjacentIds?.has(node.id);
const dimmed = selectedId && !isSelected && !isConnected;
+ const geo = isApex ? octaGeo : sphereGeo;
return (
<mesh
key={node.id}
- geometry={sphereGeo}
+ geometry={geo}
scale={radius}
position={[node.x, node.y, node.z]}
onClick={(e) => { e.stopPropagation(); onSelect(node); }}
@@ -109,7 +115,7 @@ function GoalScene({ graph, selectedId, adjacentIds, onSelect, onHover }) {
<meshStandardMaterial
color={dimmed ? '#1a1a1a' : color}
emissive={color}
- emissiveIntensity={isSelected ? 0.6 : (dimmed ? 0.03 : 0.15 + (node.urgency ?? 0) * 0.3)}
+ emissiveIntensity={isSelected ? 0.6 : (dimmed ? 0.03 : isApex ? 0.5 : isSubApex ? 0.35 : 0.15 + (node.urgency ?? 0) * 0.3)}
/>
</mesh>
);
@@ -126,6 +132,112 @@ function GoalScene({ graph, selectedId, adjacentIds, onSelect, onHover }) {
);
}
+function OrganizePanel({ suggestion, goals, onApply, onClose, applying }) {
+ const goalMap = useMemo(() => new Map((goals || []).map(g => [g.id, g])), [goals]);
+ if (!suggestion) return null;
+
+ return (
+ <div className="absolute top-12 right-3 z-20 bg-port-card border border-port-border rounded-lg p-4 w-96 max-h-[80vh] overflow-y-auto shadow-xl">
+ <div className="flex items-center justify-between mb-3">
+ <div className="flex items-center gap-2">
+ <Wand2 className="w-4 h-4 text-port-accent" />
+ <h3 className="text-sm font-semibold text-white">Goal Organization</h3>
+ </div>
+ <button onClick={onClose} className="p-1 text-gray-400 hover:text-white"><X className="w-4 h-4" /></button>
+ </div>
+
+ {suggestion.analysis && (
+ <p className="text-xs text-gray-400 mb-3 leading-relaxed">{suggestion.analysis}</p>
+ )}
+
+ {/* Apex goal suggestion */}
+ {suggestion.apexGoal && (
+ <div className="mb-3 p-2 rounded-lg bg-amber-500/10 border border-amber-500/20">
+ <div className="flex items-center gap-1.5 mb-1">
+ <Crown className="w-3.5 h-3.5 text-amber-400" />
+ <span className="text-xs font-medium text-amber-400">Apex Goal (North Star)</span>
+ </div>
+ {suggestion.apexGoal.existingId ? (
+ <p className="text-xs text-gray-300">{goalMap.get(suggestion.apexGoal.existingId)?.title || suggestion.apexGoal.existingId}</p>
+ ) : (
+ <div>
+ <p className="text-xs text-white font-medium">{suggestion.apexGoal.suggestedTitle}</p>
+ {suggestion.apexGoal.suggestedDescription && (
+ <p className="text-xs text-gray-400 mt-0.5">{suggestion.apexGoal.suggestedDescription}</p>
+ )}
+ <span className="text-xs text-amber-500/60 italic">New goal — will be created when applied</span>
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Organization */}
+ {suggestion.organization?.length > 0 && (
+ <div className="mb-3 space-y-1.5">
+ <h4 className="text-xs font-medium text-gray-400">Proposed Hierarchy</h4>
+ {suggestion.organization.map(item => {
+ const goal = goalMap.get(item.id);
+ const typeCfg = GOAL_TYPE_CONFIG[item.goalType] || GOAL_TYPE_CONFIG.standard;
+ const parent = item.suggestedParentId ? goalMap.get(item.suggestedParentId) : null;
+ return (
+ <div key={item.id} className="p-2 rounded bg-port-bg/50 border border-port-border/50">
+ <div className="flex items-center gap-1.5">
+ <span className={`text-xs px-1.5 py-0.5 rounded ${typeCfg.bg} ${typeCfg.color}`}>
+ {typeCfg.label}
+ </span>
+ <span className="text-xs text-white truncate">{goal?.title || item.id}</span>
+ </div>
+ {parent && (
+ <div className="text-xs text-gray-500 mt-0.5 ml-1">
+ under: {parent.title}
+ </div>
+ )}
+ {item.reasoning && (
+ <p className="text-xs text-gray-600 mt-0.5 ml-1">{item.reasoning}</p>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ {/* Suggested sub-apex goals */}
+ {suggestion.suggestedSubApex?.length > 0 && (
+ <div className="mb-3 space-y-1.5">
+ <h4 className="text-xs font-medium text-gray-400">Suggested Sub-Apex Goals</h4>
+ {suggestion.suggestedSubApex.map((sg, i) => (
+ <div key={i} className="p-2 rounded bg-purple-500/5 border border-purple-500/20">
+ <div className="flex items-center gap-1.5">
+ <Star className="w-3 h-3 text-purple-400" />
+ <span className="text-xs text-white font-medium">{sg.title}</span>
+ </div>
+ <p className="text-xs text-gray-400 mt-0.5">{sg.description}</p>
+ <span className="text-xs text-purple-500/60 italic">New goal — will be created when applied</span>
+ </div>
+ ))}
+ </div>
+ )}
+
+ <div className="flex gap-2 pt-2 border-t border-port-border">
+ <button
+ onClick={onApply}
+ disabled={applying}
+ className="flex-1 flex items-center justify-center gap-1.5 px-3 py-2 text-sm rounded-lg bg-port-accent text-white hover:bg-blue-600 disabled:opacity-50 min-h-[40px]"
+ >
+ <Check className="w-4 h-4" />
+ {applying ? 'Applying...' : 'Apply Changes'}
+ </button>
+ <button
+ onClick={onClose}
+ className="px-3 py-2 text-sm rounded-lg bg-port-border text-gray-300 hover:bg-gray-600 min-h-[40px]"
+ >
+ Dismiss
+ </button>
+ </div>
+ </div>
+ );
+}
+
export default function GoalsTreeView({ data, onRefresh }) {
const [selectedNode, setSelectedNode] = useState(null);
const [hoveredNode, setHoveredNode] = useState(null);
@@ -135,6 +247,9 @@ export default function GoalsTreeView({ data, onRefresh }) {
);
const [showNewGoal, setShowNewGoal] = useState(false);
const [newGoal, setNewGoal] = useState({ title: '', description: '', horizon: '5-year', category: 'mastery' });
+ const [organizing, setOrganizing] = useState(false);
+ const [orgSuggestion, setOrgSuggestion] = useState(null);
+ const [applyingOrg, setApplyingOrg] = useState(false);
const dragStartRef = useRef(null);
@@ -195,6 +310,27 @@ export default function GoalsTreeView({ data, onRefresh }) {
onRefresh();
};
+ const handleOrganize = async () => {
+ setOrganizing(true);
+ const result = await api.organizeGoals().catch(() => null);
+ setOrganizing(false);
+ if (result) {
+ setOrgSuggestion(result);
+ } else {
+ toast.error('Failed to organize goals');
+ }
+ };
+
+ const handleApplyOrganization = async () => {
+ if (!orgSuggestion) return;
+ setApplyingOrg(true);
+ await applyOrganizationSuggestion(orgSuggestion);
+ setApplyingOrg(false);
+ setOrgSuggestion(null);
+ toast.success('Goal hierarchy applied');
+ onRefresh();
+ };
+
return (
<div className="h-full flex">
<div className="flex-1 relative">
@@ -234,6 +370,17 @@ export default function GoalsTreeView({ data, onRefresh }) {
<Plus className="w-3 h-3" />
Add
</button>
+ {(data?.flat?.length ?? 0) >= 2 && (
+ <button
+ onClick={handleOrganize}
+ disabled={organizing}
+ className="flex items-center gap-1 px-2 py-1 rounded-lg text-xs font-medium bg-amber-500/20 text-amber-400 hover:bg-amber-500/30 disabled:opacity-50"
+ title="Use AI to organize goals into a hierarchy with an apex north-star goal"
+ >
+ <Wand2 className={`w-3 h-3 ${organizing ? 'animate-spin' : ''}`} />
+ {organizing ? 'Analyzing...' : 'Organize'}
+ </button>
+ )}
</div>
{/* New goal form */}
@@ -287,6 +434,15 @@ export default function GoalsTreeView({ data, onRefresh }) {
</div>
)}
+ {/* Organization panel */}
+ <OrganizePanel
+ suggestion={orgSuggestion}
+ goals={data?.flat}
+ onApply={handleApplyOrganization}
+ onClose={() => setOrgSuggestion(null)}
+ applying={applyingOrg}
+ />
+
{/* 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>
@@ -298,6 +454,14 @@ export default function GoalsTreeView({ data, onRefresh }) {
<div className="w-4 h-0.5 bg-yellow-500" />
<span className="text-gray-500">Shared tag</span>
</div>
+ <div className="flex items-center gap-2">
+ <div className="w-3 h-3 bg-amber-400 rotate-45" />
+ <span className="text-gray-500">Apex</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-3 h-3 rounded-full bg-purple-400" />
+ <span className="text-gray-500">Sub-apex</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
@@ -310,6 +474,11 @@ export default function GoalsTreeView({ data, onRefresh }) {
<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">
+ {hoveredNode.goalType && hoveredNode.goalType !== 'standard' && (
+ <span className={hoveredNode.goalType === 'apex' ? 'text-amber-400' : 'text-purple-400'}>
+ {GOAL_TYPE_CONFIG[hoveredNode.goalType]?.label} &middot;{' '}
+ </span>
+ )}
{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>
diff --git a/client/src/components/goals/applyOrganization.js b/client/src/components/goals/applyOrganization.js
new file mode 100644
index 0000000000..9648fe0426
--- /dev/null
+++ b/client/src/components/goals/applyOrganization.js
@@ -0,0 +1,43 @@
+import * as api from '../../services/api';
+
+export async function applyOrganizationSuggestion(suggestion) {
+ let apexId = null;
+
+ // Create apex goal if suggested as new
+ if (suggestion.apexGoal?.suggestedTitle && !suggestion.apexGoal?.existingId) {
+ const apex = await api.createGoal({
+ title: suggestion.apexGoal.suggestedTitle,
+ description: suggestion.apexGoal.suggestedDescription || '',
+ horizon: 'lifetime',
+ category: 'legacy',
+ goalType: 'apex'
+ }).catch(() => null);
+ apexId = apex?.id;
+ // Rewrite organization items that should parent under new apex
+ if (apexId && suggestion.organization) {
+ for (const item of suggestion.organization) {
+ if (item.suggestedParentId === '__new_apex__' || (!item.suggestedParentId && item.goalType === 'sub-apex')) {
+ item.suggestedParentId = apexId;
+ }
+ }
+ }
+ }
+
+ // Create suggested sub-apex goals in parallel
+ if (suggestion.suggestedSubApex?.length) {
+ await Promise.all(suggestion.suggestedSubApex.map(sg =>
+ api.createGoal({
+ title: sg.title,
+ description: sg.description || '',
+ horizon: 'lifetime',
+ category: sg.category || 'legacy',
+ goalType: 'sub-apex'
+ }).catch(() => null)
+ ));
+ }
+
+ // Apply organization to existing goals
+ if (suggestion.organization?.length) {
+ await api.applyGoalOrganization(suggestion.organization).catch(() => null);
+ }
+}
diff --git a/client/src/components/goals/goalTreeLayout.js b/client/src/components/goals/goalTreeLayout.js
index 21b3122af0..48a3b34013 100644
--- a/client/src/components/goals/goalTreeLayout.js
+++ b/client/src/components/goals/goalTreeLayout.js
@@ -32,9 +32,14 @@ export function layoutGoalNodes(flatGoals) {
const goalMap = new Map(flatGoals.map(g => [g.id, g]));
- // Group by ring tier
+ // Separate apex goals — they always go at the very center
+ const apexGoals = flatGoals.filter(g => g.goalType === 'apex');
+ const subApexGoals = flatGoals.filter(g => g.goalType === 'sub-apex');
+ const standardGoals = flatGoals.filter(g => !g.goalType || g.goalType === 'standard');
+
+ // Group standard goals by ring tier
const rings = {};
- for (const goal of flatGoals) {
+ for (const goal of standardGoals) {
const ring = HORIZON_RING[goal.horizon] ?? 3;
if (!rings[ring]) rings[ring] = [];
rings[ring].push(goal);
@@ -42,7 +47,36 @@ export function layoutGoalNodes(flatGoals) {
const positioned = new Map();
- // Position nodes ring by ring (sorted so parents at inner rings are positioned first)
+ // Position apex goals at dead center
+ apexGoals.forEach((goal, i) => {
+ const rng = seededRandom(goal.id);
+ positioned.set(goal.id, {
+ ...goal,
+ x: (i - (apexGoals.length - 1) / 2) * 2,
+ y: 0,
+ z: (rng() - 0.5) * 1.5,
+ vx: 0, vy: 0, vz: 0
+ });
+ });
+
+ // Position sub-apex goals in a tight inner ring around apex
+ const subApexRadius = apexGoals.length > 0 ? RING_RADIUS * 0.6 : 0;
+ subApexGoals.forEach((goal, i) => {
+ const rng = seededRandom(goal.id);
+ const parent = goal.parentId ? positioned.get(goal.parentId) : null;
+ const angle = (2 * Math.PI * i) / Math.max(subApexGoals.length, 1);
+ const baseX = parent?.x ?? 0;
+ const baseZ = parent?.z ?? 0;
+ positioned.set(goal.id, {
+ ...goal,
+ x: baseX + Math.cos(angle) * subApexRadius,
+ y: (rng() - 0.5) * Y_SPREAD * 0.5,
+ z: baseZ + Math.sin(angle) * subApexRadius,
+ vx: 0, vy: 0, vz: 0
+ });
+ });
+
+ // Position standard nodes ring by ring (sorted so parents at inner rings are positioned first)
for (const [ringStr, goals] of Object.entries(rings).sort((a, b) => Number(a[0]) - Number(b[0]))) {
const ring = Number(ringStr);
const radius = ring * RING_RADIUS;
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 7afb361c1c..15563a5472 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -1828,6 +1828,8 @@ export const deleteGoalTodo = (goalId, todoId) => request(`/digital-twin/identit
// Goal AI Planning & Scheduling
export const generateGoalPhases = (goalId, options = {}) => request(`/digital-twin/identity/goals/${goalId}/generate-phases`, { method: 'POST', body: JSON.stringify(options) });
export const acceptGoalPhases = (goalId, phases) => request(`/digital-twin/identity/goals/${goalId}/accept-phases`, { method: 'POST', body: JSON.stringify({ phases }) });
+export const organizeGoals = (options = {}) => request('/digital-twin/identity/goals/organize', { method: 'POST', body: JSON.stringify(options) });
+export const applyGoalOrganization = (organization) => request('/digital-twin/identity/goals/organize/apply', { method: 'POST', body: JSON.stringify({ organization }) });
export const scheduleGoalTimeBlocks = (goalId) => request(`/digital-twin/identity/goals/${goalId}/schedule`, { method: 'POST' });
export const removeGoalSchedule = (goalId) => request(`/digital-twin/identity/goals/${goalId}/schedule`, { method: 'DELETE' });
export const rescheduleGoalTimeBlocks = (goalId) => request(`/digital-twin/identity/goals/${goalId}/reschedule`, { method: 'POST' });
diff --git a/server/lib/identityValidation.js b/server/lib/identityValidation.js
index 35a8128f66..71cef57fa0 100644
--- a/server/lib/identityValidation.js
+++ b/server/lib/identityValidation.js
@@ -48,6 +48,8 @@ export const goalCategoryEnum = z.enum([
export const goalStatusEnum = z.enum(['active', 'completed', 'abandoned']);
+export const goalTypeEnum = z.enum(['apex', 'sub-apex', 'standard']);
+
const timeBlockConfigSchema = z.object({
preferredDays: z.array(z.enum(['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'])).min(1).max(7),
timeSlot: z.union([
@@ -63,6 +65,7 @@ export const createGoalInputSchema = z.object({
description: z.string().max(2000).optional(),
horizon: goalHorizonEnum.optional().default('5-year'),
category: goalCategoryEnum.optional().default('mastery'),
+ goalType: goalTypeEnum.optional().default('standard'),
parentId: z.string().min(1).nullable().optional().default(null),
tags: z.array(z.string().min(1).max(50)).max(20).optional().default([]),
targetDate: validCalendarDate.optional(),
@@ -74,6 +77,7 @@ export const updateGoalInputSchema = z.object({
description: z.string().max(2000).optional(),
horizon: goalHorizonEnum.optional(),
category: goalCategoryEnum.optional(),
+ goalType: goalTypeEnum.optional(),
status: goalStatusEnum.optional(),
parentId: z.string().min(1).nullable().optional(),
tags: z.array(z.string().min(1).max(50)).max(20).optional(),
@@ -86,11 +90,13 @@ export const addMilestoneInputSchema = z.object({
targetDate: validCalendarDate.optional()
});
-export const generatePhasesInputSchema = z.object({
+export const aiProviderInputSchema = z.object({
providerId: z.string().min(1).optional(),
model: z.string().min(1).optional()
});
+export const generatePhasesInputSchema = aiProviderInputSchema;
+
export const acceptPhasesInputSchema = z.object({
phases: z.array(z.object({
title: z.string().min(1).max(200),
@@ -147,3 +153,16 @@ export const linkCalendarInputSchema = z.object({
subcalendarName: z.string().min(1),
matchPattern: z.string().max(200).optional().default('')
});
+
+// --- Goal Organization Schemas ---
+
+export const organizeGoalsInputSchema = aiProviderInputSchema;
+
+export const applyOrganizationInputSchema = z.object({
+ organization: z.array(z.object({
+ id: z.string().min(1),
+ goalType: goalTypeEnum.optional(),
+ suggestedParentId: z.string().nullable().optional(),
+ reasoning: z.string().optional()
+ })).min(1)
+});
diff --git a/server/routes/identity.js b/server/routes/identity.js
index 121ead968e..7fc6e638b3 100644
--- a/server/routes/identity.js
+++ b/server/routes/identity.js
@@ -15,7 +15,9 @@ import {
updateTodoInputSchema,
updateProgressSchema,
generatePhasesInputSchema,
- acceptPhasesInputSchema
+ acceptPhasesInputSchema,
+ organizeGoalsInputSchema,
+ applyOrganizationInputSchema
} from '../lib/identityValidation.js';
import * as goalCalendarScheduler from '../services/goalCalendarScheduler.js';
@@ -265,6 +267,20 @@ router.post('/goals/:id/accept-phases', asyncHandler(async (req, res) => {
res.json(goal);
}));
+// POST /api/digital-twin/identity/goals/organize — AI-organize goals into hierarchy
+router.post('/goals/organize', asyncHandler(async (req, res) => {
+ const data = validateRequest(organizeGoalsInputSchema, req.body);
+ const result = await identityService.organizeGoals(data);
+ res.json(result);
+}));
+
+// POST /api/digital-twin/identity/goals/organize/apply — Apply organization suggestions
+router.post('/goals/organize/apply', asyncHandler(async (req, res) => {
+ const { organization } = validateRequest(applyOrganizationInputSchema, req.body);
+ const result = await identityService.applyGoalOrganization(organization);
+ res.json(result);
+}));
+
// POST /api/digital-twin/identity/goals/:id/schedule — Create time blocks
router.post('/goals/:id/schedule', asyncHandler(async (req, res) => {
const result = await goalCalendarScheduler.scheduleTimeBlocks(req.params.id);
diff --git a/server/services/identity.js b/server/services/identity.js
index 7b00f28720..f275244843 100644
--- a/server/services/identity.js
+++ b/server/services/identity.js
@@ -7,6 +7,7 @@ import { getGenomeSummary } from './genome.js';
import { getTasteProfile } from './taste-questionnaire.js';
import { getActivities } from './meatspaceCalendar.js';
import { callProviderAISimple, parseLLMJSON } from '../lib/aiProvider.js';
+import { goalTypeEnum } from '../lib/identityValidation.js';
const IDENTITY_DIR = PATHS.digitalTwin;
const IDENTITY_FILE = join(IDENTITY_DIR, 'identity.json');
@@ -705,6 +706,7 @@ export async function getGoals() {
if (goal.timeBlockConfig === undefined) { goal.timeBlockConfig = null; needsSave = true; }
if (!Array.isArray(goal.scheduledEvents)) { goal.scheduledEvents = []; needsSave = true; }
if (!Array.isArray(goal.checkIns)) { goal.checkIns = []; needsSave = true; }
+ if (!goal.goalType) { goal.goalType = 'standard'; needsSave = true; }
// Lazy-migrate milestones with description and order
for (const ms of (goal.milestones || [])) {
if (ms.description === undefined) { ms.description = ''; needsSave = true; }
@@ -743,7 +745,7 @@ export async function setBirthDate(birthDate) {
return goals;
}
-export async function createGoal({ title, description, horizon, category, parentId, tags, targetDate, timeBlockConfig }) {
+export async function createGoal({ title, description, horizon, category, goalType, parentId, tags, targetDate, timeBlockConfig }) {
const goals = await getGoals();
const longevity = await loadJSON(LONGEVITY_FILE, DEFAULT_LONGEVITY);
@@ -759,6 +761,7 @@ export async function createGoal({ title, description, horizon, category, parent
description: description || '',
horizon: horizon || '5-year',
category: category || 'mastery',
+ goalType: goalType || 'standard',
parentId: parentId || null,
tags: [...new Set((tags || []).map(t => t.trim()).filter(Boolean))],
linkedActivities: [],
@@ -820,7 +823,7 @@ export async function updateGoal(goalId, updates) {
}
}
- const allowed = ['title', 'description', 'horizon', 'category', 'status', 'parentId', 'tags', 'targetDate', 'timeBlockConfig'];
+ const allowed = ['title', 'description', 'horizon', 'category', 'goalType', 'status', 'parentId', 'tags', 'targetDate', 'timeBlockConfig'];
for (const key of allowed) {
if (updates[key] !== undefined) goal[key] = updates[key];
}
@@ -1163,6 +1166,96 @@ export async function acceptGoalPhases(goalId, phases) {
return goal;
}
+// =============================================================================
+// Goal Hierarchy Organization (LLM-powered)
+// =============================================================================
+
+export async function organizeGoals({ providerId, model } = {}) {
+ const { getActiveProvider, getProviderById } = await import('./providers.js');
+ const goals = await getGoals();
+ const activeGoals = goals.goals.filter(g => g.status === 'active');
+
+ if (activeGoals.length < 2) {
+ throw new ServerError('Need at least 2 active goals to organize', { status: 400, code: 'TOO_FEW_GOALS' });
+ }
+
+ const provider = providerId ? await getProviderById(providerId) : await getActiveProvider();
+ if (!provider) throw new ServerError('No AI provider available', { status: 503, code: 'NO_PROVIDER' });
+ const selectedModel = model ?? provider.defaultModel;
+
+ const goalSummaries = activeGoals.map(g => ({
+ id: g.id,
+ title: g.title,
+ description: g.description || '',
+ horizon: g.horizon,
+ category: g.category,
+ currentType: g.goalType || 'standard',
+ currentParentId: g.parentId
+ }));
+
+ const prompt = `You are a life purpose analyst. Given a list of personal goals, analyze them and organize them into a meaningful hierarchy.
+
+Your task:
+1. Identify the single APEX goal — the ultimate north-star purpose that all other goals serve. This is the person's deepest "why". If none of the existing goals captures this, suggest one.
+2. Identify SUB-APEX goals — major life pillars that directly support the apex goal (e.g., "Stay alive and healthy as long as possible", "Build lasting legacy").
+3. Organize remaining goals as STANDARD goals under the appropriate sub-apex or apex parent.
+4. Suggest a parentId hierarchy — which goal should be parent of which.
+
+Current goals:
+${JSON.stringify(goalSummaries, null, 2)}
+
+Respond with JSON only (no markdown fences). The response must be an object with:
+- "apexGoal": { "existingId": string|null, "suggestedTitle": string|null, "suggestedDescription": string|null } — if an existing goal IS the apex, set existingId. If no existing goal fits, suggest a new one.
+- "organization": array of { "id": string, "goalType": "apex"|"sub-apex"|"standard", "suggestedParentId": string|null, "reasoning": string }
+ - For each existing goal, assign its type and suggested parent. Use null parentId for apex and top-level sub-apex goals.
+ - The reasoning should be 1 sentence explaining why this goal fits where it does.
+- "suggestedSubApex": array of { "title": string, "description": string, "category": string } — suggest 0-3 sub-apex goals if the existing goals don't cover major life pillars well.
+- "analysis": string — 2-3 sentences summarizing the person's core purpose and how their goals connect.`;
+
+ const result = await callProviderAISimple(provider, selectedModel, prompt, { max_tokens: 3000, temperature: 0.4 });
+ if (result.error) throw new ServerError(`AI organization failed: ${result.error}`, { status: 502, code: 'AI_ERROR' });
+
+ let parsed;
+ try {
+ parsed = parseLLMJSON(result.text);
+ } catch (e) {
+ throw new ServerError(`AI returned invalid organization data: ${e.message}`, { status: 502, code: 'AI_PARSE_ERROR' });
+ }
+
+ console.log(`🎯 Organized ${activeGoals.length} goals into hierarchy`);
+ return parsed;
+}
+
+export async function applyGoalOrganization(organization) {
+ const goals = await getGoals();
+ const now = new Date().toISOString();
+ const goalMap = new Map(goals.goals.map(g => [g.id, g]));
+ let changed = 0;
+
+ for (const item of organization) {
+ const goal = goalMap.get(item.id);
+ if (!goal) continue;
+
+ if (item.goalType && goalTypeEnum.options.includes(item.goalType)) {
+ goal.goalType = item.goalType;
+ }
+ if (item.suggestedParentId !== undefined) {
+ if (item.suggestedParentId === null || goalMap.has(item.suggestedParentId)) {
+ if (!item.suggestedParentId || !hasAncestorCycle(goals.goals, goal.id, item.suggestedParentId)) {
+ goal.parentId = item.suggestedParentId;
+ }
+ }
+ }
+ goal.updatedAt = now;
+ changed++;
+ }
+
+ goals.updatedAt = now;
+ await saveJSON(GOALS_FILE, goals);
+ console.log(`🎯 Applied organization to ${changed} goals`);
+ return { applied: changed };
+}
+
// =============================================================================
// Goal Progress Percentage
// =============================================================================