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: goal-activity linking with time feasibility analysis (M54 P7)
Adam Eivybdc41f4e6d18
diff --git a/PLAN.md b/PLAN.mdindex a18b85362b..02e033ce8e 100644--- a/PLAN.md+++ b/PLAN.md@@ -97,7 +97,7 @@ pm2 logs- [x] P4b: Life Calendar multi-unit views — renamed "Life in Weeks" to "Life Calendar" with Years/Months/Weeks/Days toggle. Year grid (10 cols), Month grid (12 cols/year), Week grid (existing layouts), Day grid (calendar-style per-year with navigation).- [x] P5: Additional event types — holidays, vacations, milestones, health, custom events with color coding (amber/cyan/purple/red/emerald) on the life grid, collapsible events panel with CRUD, enable/disable toggle, yearly/one-time recurrence, default US holidays- [x] P6: Mobile responsive cell size auto-detection- - [ ] P7: Goal Tree integration — connect activities to goals, time feasibility analysis ("Can I finish this goal with my remaining time budget?")+ - [x] P7: Goal Tree integration — connect activities to goals, time feasibility analysis ("Can I finish this goal with my remaining time budget?")### Planneddiff --git a/client/src/components/goals/GoalDetailPanel.jsx b/client/src/components/goals/GoalDetailPanel.jsxindex ca6660ade5..797e969fe5 100644--- a/client/src/components/goals/GoalDetailPanel.jsx+++ b/client/src/components/goals/GoalDetailPanel.jsx@@ -1,7 +1,8 @@-import { useState } from 'react';+import { useState, useEffect } from 'react';import {Target, X, Check, Trash2, Milestone, Calendar,- Heart, DollarSign, Lightbulb, Users, Flame, AlertTriangle, Tag+ Heart, DollarSign, Lightbulb, Users, Flame, AlertTriangle, Tag,+ Link2, Unlink, Activity} from 'lucide-react';import * as api from '../../services/api';@@ -33,6 +34,12 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh })const [form, setForm] = useState({});const [tagInput, setTagInput] = useState('');const [newMilestone, setNewMilestone] = useState({ title: '', targetDate: '' });+ const [activities, setActivities] = useState([]);+ const [selectedActivity, setSelectedActivity] = useState('');++ useEffect(() => {+ api.getActivities().then(setActivities);+ }, []);if (!goal) return null;@@ -88,6 +95,18 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh })onRefresh();};+ const handleLinkActivity = async () => {+ if (!selectedActivity) return;+ await api.linkGoalActivity(goal.id, { activityName: selectedActivity });+ setSelectedActivity('');+ onRefresh();+ };++ const handleUnlinkActivity = async (activityName) => {+ await api.unlinkGoalActivity(goal.id, activityName);+ onRefresh();+ };+const addTag = () => {const tag = tagInput.trim().slice(0, MAX_TAG_LENGTH);if (tag && form.tags.length < MAX_TAGS && !form.tags.includes(tag)) {@@ -251,6 +270,29 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh })</span></div>+ {/* Feasibility */}+ {goal.feasibility && (+ <div className="text-xs space-y-1">+ <div className="flex items-center gap-1.5 text-gray-400">+ <Activity className="w-3.5 h-3.5" />+ <span className="font-medium">Activity Budget</span>+ </div>+ <div className="pl-5 space-y-0.5">+ <div className="text-gray-300">+ {goal.feasibility.totalPerWeek}/week across {goal.feasibility.links.length} {goal.feasibility.links.length === 1 ? 'activity' : 'activities'}+ </div>+ {goal.feasibility.links.map(l => (+ <div key={l.activityName} className="text-gray-500">+ {l.activityName}: {l.perWeek}/wk ({l.totalOverHorizon.toLocaleString()} total)+ </div>+ ))}+ <div className="text-gray-500">+ {goal.feasibility.weeksAvailable.toLocaleString()} weeks available+ </div>+ </div>+ </div>+ )}+{/* Tags */}{goal.tags?.length > 0 && (<div className="flex flex-wrap gap-1">@@ -331,6 +373,54 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh })</div></div>+ {/* Linked Activities */}+ <div>+ <div className="flex items-center gap-1 mb-2">+ <Link2 className="w-3.5 h-3.5 text-gray-500" />+ <span className="text-xs font-medium text-gray-400">+ Activities ({goal.linkedActivities?.length || 0})+ </span>+ </div>+ {goal.linkedActivities?.length > 0 && (+ <div className="space-y-1 mb-2">+ {goal.linkedActivities.map(link => (+ <div key={link.activityName} className="flex items-center gap-2 text-xs">+ <span className="text-gray-300 flex-1">{link.activityName}</span>+ {link.note && <span className="text-gray-600 truncate max-w-[100px]" title={link.note}>{link.note}</span>}+ <button+ onClick={() => handleUnlinkActivity(link.activityName)}+ className="p-0.5 text-gray-600 hover:text-red-400"+ title="Unlink"+ >+ <Unlink className="w-3 h-3" />+ </button>+ </div>+ ))}+ </div>+ )}+ {activities.length > 0 && (+ <div className="flex gap-1">+ <select+ value={selectedActivity}+ onChange={e => setSelectedActivity(e.target.value)}+ className="flex-1 bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white"+ >+ <option value="">Link activity...</option>+ {activities+ .filter(a => !goal.linkedActivities?.some(l => l.activityName === a.name))+ .map(a => <option key={a.name} value={a.name}>{a.name}</option>)}+ </select>+ <button+ onClick={handleLinkActivity}+ disabled={!selectedActivity}+ className="px-2 py-1 text-xs rounded bg-port-accent/20 text-port-accent disabled:opacity-50"+ >+ Link+ </button>+ </div>+ )}+ </div>+{/* Actions */}<div className="flex gap-2 pt-2 border-t border-port-border"><buttondiff --git a/client/src/components/goals/GoalsListView.jsx b/client/src/components/goals/GoalsListView.jsxindex 32864fba26..b364a69f39 100644--- a/client/src/components/goals/GoalsListView.jsx+++ b/client/src/components/goals/GoalsListView.jsx@@ -1,6 +1,6 @@import { useState, useMemo } from 'react';import {- ChevronRight, ChevronDown, Plus, GripVertical, Search, Tag+ ChevronRight, ChevronDown, Plus, GripVertical, Search, Tag, Link2} from 'lucide-react';import * as api from '../../services/api';import GoalDetailPanel, { CATEGORY_CONFIG, HORIZON_OPTIONS } from './GoalDetailPanel';@@ -52,6 +52,13 @@ function GoalRow({ goal, depth, expandedIds, onToggle, onSelect, selectedId, onA{urgencyIndicator(goal.urgency)}+ {goal.linkedActivities?.length > 0 && (+ <span className="flex items-center gap-0.5 text-xs text-gray-500 shrink-0" title={`${goal.linkedActivities.length} linked ${goal.linkedActivities.length === 1 ? 'activity' : 'activities'}`}>+ <Link2 className="w-3 h-3" />+ {goal.linkedActivities.length}+ </span>+ )}+{goal.tags?.length > 0 && (<div className="flex items-center gap-1 shrink-0">{goal.tags.slice(0, 3).map(tag => (diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 2295a8bf95..bdfaf92153 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -1388,6 +1388,12 @@ export const addGoalMilestone = (goalId, data) => request(`/digital-twin/identit});export const completeGoalMilestone = (goalId, milestoneId) =>request(`/digital-twin/identity/goals/${goalId}/milestones/${milestoneId}/complete`, { method: 'PUT' });+export const linkGoalActivity = (goalId, data) => request(`/digital-twin/identity/goals/${goalId}/activities`, {+ method: 'POST',+ body: JSON.stringify(data)+});+export const unlinkGoalActivity = (goalId, activityName) =>+ request(`/digital-twin/identity/goals/${goalId}/activities/${encodeURIComponent(activityName)}`, { method: 'DELETE' });// Feature Agentsexport const getFeatureAgents = () => request('/feature-agents');diff --git a/server/lib/identityValidation.js b/server/lib/identityValidation.jsindex 4f1e463427..60d80c9e00 100644--- a/server/lib/identityValidation.js+++ b/server/lib/identityValidation.js@@ -71,3 +71,11 @@ export const addMilestoneInputSchema = z.object({title: z.string().min(1).max(200),targetDate: validCalendarDate.optional()});++// --- Goal-Activity Link Schemas ---++export const linkActivityInputSchema = z.object({+ activityName: z.string().min(1).max(200),+ requiredFrequency: z.number().positive().optional(),+ note: z.string().max(500).optional().default('')+});diff --git a/server/routes/identity.js b/server/routes/identity.jsindex 2f6e296b4c..d083e7c8d7 100644--- a/server/routes/identity.js+++ b/server/routes/identity.js@@ -7,7 +7,8 @@ import {birthDateInputSchema,createGoalInputSchema,updateGoalInputSchema,- addMilestoneInputSchema+ addMilestoneInputSchema,+ linkActivityInputSchema} from '../lib/identityValidation.js';const router = Router();@@ -129,4 +130,23 @@ router.put('/goals/:id/milestones/:milestoneId/complete', asyncHandler(async (reres.json(milestone);}));+// POST /api/digital-twin/identity/goals/:id/activities — Link activity to goal+router.post('/goals/:id/activities', asyncHandler(async (req, res) => {+ const data = validateRequest(linkActivityInputSchema, req.body);+ const goal = await identityService.linkActivity(req.params.id, data);+ if (!goal) {+ throw new ServerError('Goal not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(goal);+}));++// DELETE /api/digital-twin/identity/goals/:id/activities/:activityName — Unlink activity from goal+router.delete('/goals/:id/activities/:activityName', asyncHandler(async (req, res) => {+ const goal = await identityService.unlinkActivity(req.params.id, decodeURIComponent(req.params.activityName));+ if (!goal) {+ throw new ServerError('Goal not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(goal);+}));+export default router;diff --git a/server/services/identity.js b/server/services/identity.jsindex c73aa52548..594a06898e 100644--- a/server/services/identity.js+++ b/server/services/identity.js@@ -318,6 +318,48 @@ export function computeLifeExpectancy(longevityMarkers, cardiovascularMarkers, b};}+/**+ * Compute time feasibility for a goal based on its linked activities.+ * Returns { feasible, hoursPerWeek, weeksNeeded, weeksAvailable } or null if no links.+ */+export function computeGoalFeasibility(goal, timeHorizons, activities) {+ if (!goal.linkedActivities?.length || !timeHorizons) return null;++ const horizonMap = {+ '1-year': 1, '3-year': 3, '5-year': 5,+ '10-year': 10, '20-year': 20, 'lifetime': timeHorizons.yearsRemaining+ };+ const horizonYears = horizonMap[goal.horizon] ?? 5;+ const weeksAvailable = Math.floor(Math.min(horizonYears, timeHorizons.yearsRemaining) * 52);++ let totalPerWeek = 0;+ const links = [];+ for (const link of goal.linkedActivities) {+ const activity = activities.find(a => a.name === link.activityName);+ if (!activity) continue;+ const freq = link.requiredFrequency ?? activity.frequency;+ // Normalize to per-week+ let perWeek;+ switch (activity.cadence) {+ case 'day': perWeek = freq * 7; break;+ case 'week': perWeek = freq; break;+ case 'month': perWeek = freq / 4.35; break;+ case 'year': perWeek = freq / 52; break;+ default: perWeek = 0;+ }+ totalPerWeek += perWeek;+ const totalOverHorizon = Math.floor(perWeek * weeksAvailable);+ links.push({ activityName: link.activityName, perWeek: Math.round(perWeek * 10) / 10, totalOverHorizon });+ }++ return {+ feasible: weeksAvailable > 0,+ weeksAvailable,+ totalPerWeek: Math.round(totalPerWeek * 10) / 10,+ links+ };+}+export function computeGoalUrgency(goal, timeHorizons) {if (!timeHorizons || !goal.horizon) return null;@@ -655,11 +697,12 @@ export async function deriveLongevity(birthDate) {export async function getGoals() {const data = await loadJSON(GOALS_FILE, DEFAULT_GOALS);- // Lazy migration: backfill parentId and tags on goals missing them+ // Lazy migration: backfill parentId, tags, linkedActivities on goals missing themlet 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 (!Array.isArray(goal.linkedActivities)) { goal.linkedActivities = []; needsSave = true; }}if (needsSave) await saveJSON(GOALS_FILE, data);return data;@@ -711,6 +754,7 @@ export async function createGoal({ title, description, horizon, category, parentcategory: category || 'mastery',parentId: parentId || null,tags: [...new Set((tags || []).map(t => t.trim()).filter(Boolean))],+ linkedActivities: [],urgency: null,status: 'active',milestones: [],@@ -761,7 +805,7 @@ export async function updateGoal(goalId, updates) {}}- const allowed = ['title', 'description', 'horizon', 'category', 'status', 'parentId', 'tags'];+ const allowed = ['title', 'description', 'horizon', 'category', 'status', 'parentId', 'tags', 'linkedActivities'];for (const key of allowed) {if (updates[key] !== undefined) goal[key] = updates[key];}@@ -806,13 +850,17 @@ export async function deleteGoal(goalId) {export async function getGoalsTree() {const goals = await getGoals();const longevity = await loadJSON(LONGEVITY_FILE, DEFAULT_LONGEVITY);+ const { getActivities } = await import('./meatspaceCalendar.js');+ const activities = await getActivities();- // Enrich goals with urgency (shallow copies to avoid mutating persisted objects)+ // Enrich goals with urgency and feasibility (shallow copies to avoid mutating persisted objects)const enriched = goals.goals.map(goal => {+ const enrichedGoal = { ...goal };if (goal.status === 'active' && longevity.timeHorizons) {- return { ...goal, urgency: computeGoalUrgency(goal, longevity.timeHorizons) };+ enrichedGoal.urgency = computeGoalUrgency(goal, longevity.timeHorizons);+ enrichedGoal.feasibility = computeGoalFeasibility(goal, longevity.timeHorizons, activities);}- return { ...goal };+ return enrichedGoal;});// Build hierarchical tree@@ -845,6 +893,47 @@ export async function getGoalsTree() {};}+export async function linkActivity(goalId, { activityName, requiredFrequency, note }) {+ const goals = await getGoals();+ const goal = goals.goals.find(g => g.id === goalId);+ if (!goal) return null;++ // Prevent duplicates+ if (goal.linkedActivities.some(l => l.activityName === activityName)) {+ // Update existing link+ const link = goal.linkedActivities.find(l => l.activityName === activityName);+ if (requiredFrequency !== undefined) link.requiredFrequency = requiredFrequency;+ if (note !== undefined) link.note = note;+ } else {+ goal.linkedActivities.push({+ activityName,+ requiredFrequency: requiredFrequency || null,+ note: note || ''+ });+ }+ goal.updatedAt = new Date().toISOString();+ goals.updatedAt = new Date().toISOString();+ await saveJSON(GOALS_FILE, goals);+ console.log(`🔗 Activity "${activityName}" linked to goal "${goal.title}"`);+ return goal;+}++export async function unlinkActivity(goalId, activityName) {+ const goals = await getGoals();+ const goal = goals.goals.find(g => g.id === goalId);+ if (!goal) return null;++ const idx = goal.linkedActivities.findIndex(l => l.activityName === activityName);+ if (idx === -1) return goal;++ goal.linkedActivities.splice(idx, 1);+ goal.updatedAt = new Date().toISOString();+ goals.updatedAt = new Date().toISOString();+ await saveJSON(GOALS_FILE, goals);+ console.log(`🔗 Activity "${activityName}" unlinked from goal "${goal.title}"`);+ return goal;+}+export async function addMilestone(goalId, { title, targetDate }) {const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);const goal = goals.goals.find(g => g.id === goalId);