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 progress tracking, todos, velocity, and time tracking (M49 P1)
Adam Eivyc38e68a1757c
diff --git a/PLAN.md b/PLAN.mdindex 1ff0ca49a1..3e7aa5c131 100644--- a/PLAN.md+++ b/PLAN.md@@ -60,13 +60,13 @@ See [GOALS.md](./GOALS.md) for project goals and direction.- [x] **GSD Tab**: Smart State Detection, One-Click Agent Spawn, Actionable Dashboard- [x] **M55**: POST Enhancement — Memory builder, imagination drills, training mode, 5-min balanced sessions. See [POST](./docs/features/post.md)- [x] **M54**: MeatSpace Life Calendar — "4000 Weeks" mortality-aware time mapping with responsive grid, goal-activity linking, and time feasibility analysis+- [x] **M45**: Data Backup & Recovery - Rsync-based incremental backup with SHA-256 manifests, PostgreSQL pg_dump, configurable cron schedule, restore with dry-run preview and selective subdirectory restore, Dashboard widget with health status### Planned- [ ] **M50 P1-P4**: Email Management - Gmail + Outlook integration, AI categorization and priority extraction, Digital Twin voice drafting, review-before-send outbox, Brain knowledge capture- [ ] **M34 P5-P7**: Digital Twin - Multi-modal capture, advanced testing, personas- [ ] **M42 P5**: Unified Digital Twin Identity System - Cross-Insights Engine. See [Identity System](./docs/features/identity-system.md)-- [ ] **M45**: Data Backup & Recovery - Scheduled backup of `./data/` to external drive or NAS. All persistence is JSON files with zero redundancy — one bad write or disk failure loses brain, identity, health, and memory data. Incremental backup with restore verification.- [ ] **M47**: Push Notifications - Webhook-based alerts when agents complete tasks, critical errors occur, or goals stall. Discord/Telegram integration for mobile awareness without needing the dashboard open.- [x] **M48 P1-P5**: Google Calendar Integration - MCP push sync, subcalendar management, goal-calendar linking, daily review with auto-progress-logging, dormancy support- [x] **M48 P6**: Calendar Consolidation - Moved Life Calendar from MeatSpace to Calendar > Lifetime tab with accuracy improvement tips@@ -74,36 +74,14 @@ See [GOALS.md](./GOALS.md) for project goals and direction.- [x] **M48 P8**: Direct Google Calendar API Sync - `googleapis` npm with OAuth2, sync method selector, token auto-refresh- [x] **M48 P9**: Auto-Configure Google OAuth via CDP - one-click browser setup with Playwright-derived selectors- [x] **M48 P10**: Calendar UI Polish - subcalendar color coding in Day/Week/Month views with configurable colors, 15-min blocks in Week view, side-by-side overlap layout, declined/cancelled event filtering-- [ ] **M49 P1-P4**: Life Goals & Todo Planning - Enhanced goal model with todos and milestones, calendar time-blocking, AI-powered periodic check-ins, mortality-aware progress dashboard+- [x] **M49 P1**: Life Goals — Enhanced goal model with todos, progress percentage, velocity tracking, projected completion, time tracking aggregates+- [ ] **M49 P2-P4**: Life Goals — Calendar time-blocking, AI-powered periodic check-ins, mortality-aware progress dashboard- [ ] **M52**: Update Detection - Poll GitHub releases for new version tags, compare against local `package.json` version, surface update availability in dashboard and settings---## Planned Feature Details-### M45: Data Backup & Recovery--All PortOS data lives in `./data/` as JSON files with no redundancy. A corrupted write, accidental deletion, or disk failure loses everything — brain captures, digital identity, health records, memory embeddings, agent state, and run history.--**Scheduled Backup**-- Configurable backup target (external drive path, NAS mount, or rsync destination)-- Incremental backups using file modification timestamps — only copy changed files-- Configurable schedule (daily default) via existing automation scheduler-- Retention policy: keep N daily + N weekly snapshots, prune older-- Backup manifest with file checksums for integrity verification--**Restore**-- `POST /api/backup/restore` — restore from a named snapshot-- Dry-run mode that shows what would change before applying-- Per-directory selective restore (e.g., restore only `data/brain/` without touching `data/cos/`)--**Dashboard Widget**-- Last backup time, next scheduled backup, total backup size-- Backup health status (green/yellow/red based on age and integrity)-- One-click manual backup trigger--*Touches: new server/services/backup.js, server/routes/backup.js, Dashboard widget, settings.json, automation scheduler*-### M47: Push NotificationsExternal notification delivery for critical events when not actively viewing the dashboard.@@ -139,7 +117,7 @@ Extends the existing goal system in `server/services/identity.js` and `data/digi**Phases:**-- **P1: Enhanced Goal Model & Todos** — Extend goal schema with: progress percentage + history, velocity (percent/month + trend), projected completion date, todo sub-tasks with status/priority/time estimates, time tracking (total minutes, weekly average). Dedicated Goals page with goal list and detail view+- **P1: Enhanced Goal Model & Todos** *(Complete)* — Added `progress` (0-100), `progressHistory[]`, `todos[]` with priority/estimate/status to goal schema. Velocity (percent/month + trend) and projected completion computed at query time. Time tracking aggregated from progressLog. Progress bars in list view, todo CRUD in detail panel.- **P2: Calendar Time-Blocking** (depends on M48 P2) — Schedule recurring goal work sessions on calendar, link calendar events to goals/todos via IDs, track actual time spent from calendar event durations, per-goal calendar config (preferred days, time slot preference, session duration)- **P3: Check-in & Evaluation** — Periodic check-in prompts (weekly/monthly configurable per goal), AI evaluator uses Digital Twin + progress data to assess trajectory, timeline adjustment recommendations when behind schedule, CoS autonomous job `job-goal-check-in` for weekly evaluations, check-in history with mood/notes- **P4: Dashboard & Visualization** — Goal progress dashboard widget with urgency badges, burn-down / progress timeline charts, integration with existing mortality-aware urgency scoring (M42 P3), "on track" / "behind" / "at risk" status indicators@@ -321,10 +299,9 @@ Three audit passes identified remaining items across architecture, bugs, code qu## Next Actions-1. **M45**: Data Backup & Recovery — protect `./data/` from data loss (highest safety priority)-2. **M49 P1**: Life Goals — Enhanced goal model with todos, calendar time-blocking, progress tracking-3. **M42 P5**: Cross-Insights Engine — connect genome + taste + personality + goals into derived insights-4. **M50 P7-P9**: Messages — Digital Twin voice drafting, CoS automation, auto-send with AI review gate-5. **M34 P5-P7**: Digital Twin — Multi-modal capture, advanced testing, personas-6. **M47**: Push Notifications — Discord/Telegram alerts for agent completions and errors-7. **M52**: Update Detection — GitHub release polling and update notification+1. **M49 P1**: Life Goals — Enhanced goal model with todos, calendar time-blocking, progress tracking+2. **M42 P5**: Cross-Insights Engine — connect genome + taste + personality + goals into derived insights+3. **M50 P7-P9**: Messages — Digital Twin voice drafting, CoS automation, auto-send with AI review gate+4. **M34 P5-P7**: Digital Twin — Multi-modal capture, advanced testing, personas+5. **M47**: Push Notifications — Discord/Telegram alerts for agent completions and errors+6. **M52**: Update Detection — GitHub release polling and update notificationdiff --git a/client/src/components/goals/GoalDetailPanel.jsx b/client/src/components/goals/GoalDetailPanel.jsxindex d1ff21519f..50a2b05ac2 100644--- a/client/src/components/goals/GoalDetailPanel.jsx+++ b/client/src/components/goals/GoalDetailPanel.jsx@@ -2,7 +2,8 @@ import { useState, useEffect } from 'react';import {Target, X, Check, Trash2, Milestone, Calendar, CalendarDays, Clock,Heart, DollarSign, Lightbulb, Users, Flame, AlertTriangle, Tag,- Link2, Unlink, Activity, Plus, NotebookPen+ Link2, Unlink, Activity, Plus, NotebookPen, ListTodo, TrendingUp,+ TrendingDown, Minus, CircleDot} from 'lucide-react';import * as api from '../../services/api';@@ -29,6 +30,65 @@ const MAX_TAG_LENGTH = 50;export { CATEGORY_CONFIG, HORIZON_OPTIONS };+function ProgressSlider({ goal, onCommit }) {+ const [draft, setDraft] = useState(goal.progress ?? 0);+ const [dragging, setDragging] = useState(false);++ // Sync draft when goal changes externally (not during drag)+ useEffect(() => {+ if (!dragging) setDraft(goal.progress ?? 0);+ }, [goal.progress, dragging]);++ const commit = () => {+ setDragging(false);+ if (draft !== (goal.progress ?? 0)) onCommit(draft);+ };++ return (+ <div>+ <div className="flex items-center justify-between mb-1.5">+ <span className="text-xs font-medium text-gray-400">Progress</span>+ <span className="text-xs text-gray-300 font-mono">{draft}%</span>+ </div>+ <input+ type="range"+ min="0"+ max="100"+ value={draft}+ onChange={e => { setDragging(true); setDraft(parseInt(e.target.value, 10)); }}+ onMouseUp={commit}+ onTouchEnd={commit}+ className="w-full h-1.5 rounded-full appearance-none cursor-pointer bg-port-border accent-port-accent"+ />+ {goal.velocity && (+ <div className="flex items-center gap-2 mt-1.5 text-xs text-gray-500">+ <div className="flex items-center gap-1">+ {goal.velocity.trend === 'increasing' && <TrendingUp className="w-3 h-3 text-green-400" />}+ {goal.velocity.trend === 'decreasing' && <TrendingDown className="w-3 h-3 text-red-400" />}+ {goal.velocity.trend === 'stable' && <Minus className="w-3 h-3 text-gray-400" />}+ <span>{goal.velocity.percentPerMonth}%/mo</span>+ </div>+ {goal.velocity.projectedCompletion && (+ <span className="text-gray-600">+ ETA {new Date(goal.velocity.projectedCompletion + 'T00:00:00').toLocaleDateString()}+ </span>+ )}+ </div>+ )}+ {goal.timeTracking?.totalMinutes > 0 && (+ <div className="flex items-center gap-1 mt-1 text-xs text-gray-600">+ <Clock className="w-3 h-3" />+ {goal.timeTracking.totalMinutes >= 60+ ? `${Math.floor(goal.timeTracking.totalMinutes / 60)}h${goal.timeTracking.totalMinutes % 60 ? ` ${goal.timeTracking.totalMinutes % 60}m` : ''}`+ : `${goal.timeTracking.totalMinutes}m`}+ {' total'}+ {goal.timeTracking.weeklyAverage > 0 && ` · ${goal.timeTracking.weeklyAverage}m/wk`}+ </div>+ )}+ </div>+ );+}+export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh }) {const [editing, setEditing] = useState(false);const [form, setForm] = useState({});@@ -42,6 +102,9 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh })const [subcalendars, setSubcalendars] = useState([]);const [selectedCalendar, setSelectedCalendar] = useState('');const [calendarMatchPattern, setCalendarMatchPattern] = useState('');+ const [newTodoTitle, setNewTodoTitle] = useState('');+ const [newTodoPriority, setNewTodoPriority] = useState('medium');+ const [newTodoEstimate, setNewTodoEstimate] = useState('');useEffect(() => {api.getActivities().then(setActivities).catch(() => {});@@ -168,6 +231,35 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh })onRefresh();};+ const handleProgressChange = async (value) => {+ await api.updateGoalProgress(goal.id, value);+ onRefresh();+ };++ const handleAddTodo = async () => {+ if (!newTodoTitle.trim()) return;+ await api.addGoalTodo(goal.id, {+ title: newTodoTitle,+ priority: newTodoPriority,+ ...(newTodoEstimate ? { estimateMinutes: parseInt(newTodoEstimate, 10) } : {})+ });+ setNewTodoTitle('');+ setNewTodoPriority('medium');+ setNewTodoEstimate('');+ onRefresh();+ };++ const handleToggleTodo = async (todo) => {+ const nextStatus = todo.status === 'done' ? 'pending' : 'done';+ await api.updateGoalTodo(goal.id, todo.id, { status: nextStatus });+ onRefresh();+ };++ const handleDeleteTodo = async (todoId) => {+ await api.deleteGoalTodo(goal.id, todoId);+ onRefresh();+ };+const addTag = () => {const tag = tagInput.trim().slice(0, MAX_TAG_LENGTH);if (tag && form.tags.length < MAX_TAGS && !form.tags.includes(tag)) {@@ -331,6 +423,100 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh })</span></div>+ {/* Progress Bar */}+ <ProgressSlider goal={goal} onCommit={handleProgressChange} />++ {/* Todos */}+ <div>+ <div className="flex items-center gap-1 mb-2">+ <ListTodo className="w-3.5 h-3.5 text-gray-500" />+ <span className="text-xs font-medium text-gray-400">+ Todos ({goal.todos?.filter(t => t.status === 'done').length || 0}/{goal.todos?.length || 0})+ </span>+ </div>+ {goal.todos?.length > 0 && (+ <div className="space-y-1 mb-2">+ {goal.todos.map(todo => (+ <div key={todo.id} className="flex items-center gap-2 text-xs group">+ <button+ onClick={() => handleToggleTodo(todo)}+ className={`w-4 h-4 rounded border flex items-center justify-center shrink-0 ${+ todo.status === 'done'+ ? 'bg-green-500/20 border-green-500 text-green-400'+ : todo.status === 'in-progress'+ ? 'bg-port-accent/20 border-port-accent text-port-accent'+ : 'border-gray-600 hover:border-port-accent'+ }`}+ >+ {todo.status === 'done' && <Check className="w-3 h-3" />}+ {todo.status === 'in-progress' && <CircleDot className="w-2.5 h-2.5" />}+ </button>+ <span className={`flex-1 ${todo.status === 'done' ? 'text-gray-500 line-through' : 'text-gray-300'}`}>+ {todo.title}+ </span>+ <span className={`shrink-0 px-1 py-0.5 rounded text-[10px] ${+ todo.priority === 'high' ? 'bg-red-500/20 text-red-400' :+ todo.priority === 'low' ? 'bg-gray-700 text-gray-500' :+ 'bg-yellow-500/20 text-yellow-400'+ }`}>+ {todo.priority}+ </span>+ {todo.estimateMinutes && (+ <span className="shrink-0 text-gray-600">{todo.estimateMinutes}m</span>+ )}+ <button+ onClick={() => handleDeleteTodo(todo.id)}+ className="p-0.5 text-gray-700 hover:text-red-400 opacity-0 group-hover:opacity-100 shrink-0"+ title="Delete"+ >+ <Trash2 className="w-3 h-3" />+ </button>+ </div>+ ))}+ </div>+ )}+ <div className="space-y-1">+ <div className="flex gap-1">+ <input+ type="text"+ value={newTodoTitle}+ onChange={e => setNewTodoTitle(e.target.value)}+ onKeyDown={e => e.key === 'Enter' && handleAddTodo()}+ placeholder="Add todo..."+ className="flex-1 bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white"+ />+ <button+ onClick={handleAddTodo}+ disabled={!newTodoTitle.trim()}+ className="px-2 py-1 text-xs rounded bg-port-accent/20 text-port-accent disabled:opacity-50"+ >+ Add+ </button>+ </div>+ {newTodoTitle.trim() && (+ <div className="flex gap-1">+ <select+ value={newTodoPriority}+ onChange={e => setNewTodoPriority(e.target.value)}+ className="bg-port-bg border border-port-border rounded px-1.5 py-0.5 text-xs text-white"+ >+ <option value="low">Low</option>+ <option value="medium">Medium</option>+ <option value="high">High</option>+ </select>+ <input+ type="number"+ value={newTodoEstimate}+ onChange={e => setNewTodoEstimate(e.target.value)}+ placeholder="Est. min"+ min="1"+ className="w-20 bg-port-bg border border-port-border rounded px-1.5 py-0.5 text-xs text-white"+ />+ </div>+ )}+ </div>+ </div>+{/* Feasibility */}{goal.feasibility && (<div className="text-xs space-y-1">diff --git a/client/src/components/goals/GoalsListView.jsx b/client/src/components/goals/GoalsListView.jsxindex b364a69f39..dae9334297 100644--- a/client/src/components/goals/GoalsListView.jsx+++ b/client/src/components/goals/GoalsListView.jsx@@ -46,6 +46,21 @@ function GoalRow({ goal, depth, expandedIds, onToggle, onSelect, selectedId, onA<span className="text-sm text-white truncate flex-1">{goal.title}</span>+ {/* Progress pill */}+ {(goal.progress > 0 || goal.todos?.length > 0) && (+ <span className="shrink-0 flex items-center gap-1 text-xs text-gray-500">+ <div className="w-12 h-1.5 rounded-full bg-gray-700 overflow-hidden">+ <div+ className={`h-full rounded-full transition-all ${+ goal.progress >= 100 ? 'bg-port-success' : goal.progress >= 50 ? 'bg-port-accent' : 'bg-port-warning'+ }`}+ style={{ width: `${goal.progress ?? 0}%` }}+ />+ </div>+ <span className="w-7 text-right">{goal.progress ?? 0}%</span>+ </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>diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 37c9c00850..a63ce1a04b 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -1757,6 +1757,12 @@ export const getGoalCalendarEvents = (goalId, params = {}) => {return request(`/digital-twin/identity/goals/${goalId}/calendar-events${str ? `?${str}` : ''}`);};+// Goal Progress & Todos+export const updateGoalProgress = (goalId, value) => request(`/digital-twin/identity/goals/${goalId}/progress`, { method: 'PUT', body: JSON.stringify({ value }) });+export const addGoalTodo = (goalId, data) => request(`/digital-twin/identity/goals/${goalId}/todos`, { method: 'POST', body: JSON.stringify(data) });+export const updateGoalTodo = (goalId, todoId, data) => request(`/digital-twin/identity/goals/${goalId}/todos/${todoId}`, { method: 'PUT', body: JSON.stringify(data) });+export const deleteGoalTodo = (goalId, todoId) => request(`/digital-twin/identity/goals/${goalId}/todos/${todoId}`, { method: 'DELETE' });+// Default export for simplified importsexport default {get: (endpoint, options) => request(endpoint, { method: 'GET', ...options }),diff --git a/server/lib/identityValidation.js b/server/lib/identityValidation.jsindex dc0458ccb0..030ea9f66e 100644--- a/server/lib/identityValidation.js+++ b/server/lib/identityValidation.js@@ -80,6 +80,30 @@ export const addProgressEntrySchema = z.object({durationMinutes: z.number().int().min(1).max(1440).optional()});+// --- Goal Todo Schemas ---++export const todoPriorityEnum = z.enum(['low', 'medium', 'high']);+export const todoStatusEnum = z.enum(['pending', 'in-progress', 'done']);++export const addTodoInputSchema = z.object({+ title: z.string().min(1).max(200),+ priority: todoPriorityEnum.optional().default('medium'),+ estimateMinutes: z.number().int().min(1).max(14400).optional()+});++export const updateTodoInputSchema = z.object({+ title: z.string().min(1).max(200).optional(),+ status: todoStatusEnum.optional(),+ priority: todoPriorityEnum.optional(),+ estimateMinutes: z.number().int().min(1).max(14400).nullable().optional()+});++// --- Goal Progress Percentage Schema ---++export const updateProgressSchema = z.object({+ value: z.number().min(0).max(100)+});+// --- Goal-Activity Link Schemas ---export const linkActivityInputSchema = z.object({diff --git a/server/routes/identity.js b/server/routes/identity.jsindex c8786ed4c2..e82ee1194e 100644--- a/server/routes/identity.js+++ b/server/routes/identity.js@@ -10,7 +10,10 @@ import {addMilestoneInputSchema,addProgressEntrySchema,linkActivityInputSchema,- linkCalendarInputSchema+ linkCalendarInputSchema,+ addTodoInputSchema,+ updateTodoInputSchema,+ updateProgressSchema} from '../lib/identityValidation.js';const router = Router();@@ -196,4 +199,43 @@ router.get('/goals/:id/calendar-events', asyncHandler(async (req, res) => {res.json(events);}));+// PUT /api/digital-twin/identity/goals/:id/progress — Update progress percentage+router.put('/goals/:id/progress', asyncHandler(async (req, res) => {+ const { value } = validateRequest(updateProgressSchema, req.body);+ const goal = await identityService.updateGoalProgress(req.params.id, value);+ if (!goal) {+ throw new ServerError('Goal not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(goal);+}));++// POST /api/digital-twin/identity/goals/:id/todos — Add todo+router.post('/goals/:id/todos', asyncHandler(async (req, res) => {+ const data = validateRequest(addTodoInputSchema, req.body);+ const todo = await identityService.addTodo(req.params.id, data);+ if (!todo) {+ throw new ServerError('Goal not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.status(201).json(todo);+}));++// PUT /api/digital-twin/identity/goals/:id/todos/:todoId — Update todo+router.put('/goals/:id/todos/:todoId', asyncHandler(async (req, res) => {+ const data = validateRequest(updateTodoInputSchema, req.body);+ const todo = await identityService.updateTodo(req.params.id, req.params.todoId, data);+ if (!todo) {+ throw new ServerError('Goal or todo not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(todo);+}));++// DELETE /api/digital-twin/identity/goals/:id/todos/:todoId — Delete todo+router.delete('/goals/:id/todos/:todoId', asyncHandler(async (req, res) => {+ const result = await identityService.deleteTodo(req.params.id, req.params.todoId);+ if (!result) {+ throw new ServerError('Goal or todo not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(result);+}));+export default router;diff --git a/server/services/identity.js b/server/services/identity.jsindex e88f5f646f..6d8e4e9106 100644--- a/server/services/identity.js+++ b/server/services/identity.js@@ -697,6 +697,9 @@ export async function getGoals() {if (!Array.isArray(goal.tags)) { goal.tags = []; needsSave = true; }if (!Array.isArray(goal.linkedActivities)) { goal.linkedActivities = []; needsSave = true; }if (!Array.isArray(goal.linkedCalendars)) { goal.linkedCalendars = []; needsSave = true; }+ if (goal.progress === undefined) { goal.progress = 0; needsSave = true; }+ if (!Array.isArray(goal.progressHistory)) { goal.progressHistory = []; needsSave = true; }+ if (!Array.isArray(goal.todos)) { goal.todos = []; needsSave = true; }}if (needsSave) await saveJSON(GOALS_FILE, data);return data;@@ -752,6 +755,9 @@ export async function createGoal({ title, description, horizon, category, parenturgency: null,status: 'active',milestones: [],+ progress: 0,+ progressHistory: [],+ todos: [],createdAt: new Date().toISOString(),updatedAt: new Date().toISOString()};@@ -846,13 +852,15 @@ export async function getGoalsTree() {const longevity = await loadJSON(LONGEVITY_FILE, DEFAULT_LONGEVITY);const activities = await getActivities();- // Enrich goals with urgency and feasibility (shallow copies to avoid mutating persisted objects)+ // Enrich goals with urgency, feasibility, velocity, and time trackingconst enriched = goals.goals.map(goal => {const enrichedGoal = { ...goal };if (goal.status === 'active' && longevity.timeHorizons) {enrichedGoal.urgency = computeGoalUrgency(goal, longevity.timeHorizons);enrichedGoal.feasibility = computeGoalFeasibility(goal, longevity.timeHorizons, activities);}+ enrichedGoal.velocity = computeGoalVelocity(goal);+ enrichedGoal.timeTracking = computeTimeTracking(goal);return enrichedGoal;});@@ -1067,3 +1075,192 @@ export async function getGoalCalendarEvents(goalId, startDate, endDate) {return e.title?.toLowerCase().includes(pattern.toLowerCase());});}++// =============================================================================+// Goal Progress Percentage+// =============================================================================++export async function updateGoalProgress(goalId, value) {+ const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);+ const goal = goals.goals.find(g => g.id === goalId);+ if (!goal) return null;++ const prev = goal.progress ?? 0;+ goal.progress = value;+ if (!goal.progressHistory) goal.progressHistory = [];++ // Only log if value changed; deduplicate same-day entries to prevent bloat+ if (prev !== value) {+ const today = new Date().toISOString().slice(0, 10);+ const lastEntry = goal.progressHistory[goal.progressHistory.length - 1];+ if (lastEntry?.date === today) {+ lastEntry.value = value;+ lastEntry.timestamp = new Date().toISOString();+ } else {+ goal.progressHistory.push({ date: today, value, timestamp: new Date().toISOString() });+ }+ }++ goal.updatedAt = new Date().toISOString();+ goals.updatedAt = new Date().toISOString();+ await saveJSON(GOALS_FILE, goals);++ console.log(`📊 Progress for "${goal.title}": ${prev}% → ${value}%`);+ return goal;+}++// =============================================================================+// Goal Velocity & Projection (pure functions)+// =============================================================================++/**+ * Compute velocity (percent/month) and trend from progressHistory.+ * Returns { percentPerMonth, trend, projectedCompletion } or null if insufficient data.+ */+export function computeGoalVelocity(goal) {+ const history = goal.progressHistory;+ if (!history?.length || history.length < 2) return null;++ // Find earliest and latest entries in O(n) instead of sorting+ let first = history[0];+ let last = history[0];+ for (const entry of history) {+ if (entry.date < first.date) first = entry;+ if (entry.date >= last.date) last = entry;+ }++ const daysDiff = (new Date(last.date) - new Date(first.date)) / (1000 * 60 * 60 * 24);+ if (daysDiff < 1) return null;++ const monthsDiff = daysDiff / 30.44;+ const totalChange = last.value - first.value;+ const percentPerMonth = Math.round((totalChange / monthsDiff) * 10) / 10;++ // Trend: compare recent half vs first half velocity using median date+ let trend = 'stable';+ if (history.length >= 4) {+ const midDate = new Date((new Date(first.date).getTime() + new Date(last.date).getTime()) / 2);+ // Find entry closest to midpoint+ let midEntry = first;+ let minDist = Infinity;+ for (const entry of history) {+ const dist = Math.abs(new Date(entry.date) - midDate);+ if (dist < minDist) { minDist = dist; midEntry = entry; }+ }+ const firstHalfDays = (new Date(midEntry.date) - new Date(first.date)) / (1000 * 60 * 60 * 24);+ const secondHalfDays = (new Date(last.date) - new Date(midEntry.date)) / (1000 * 60 * 60 * 24);+ if (firstHalfDays > 0 && secondHalfDays > 0) {+ const firstVel = (midEntry.value - first.value) / firstHalfDays;+ const secondVel = (last.value - midEntry.value) / secondHalfDays;+ if (secondVel > firstVel * 1.2) trend = 'increasing';+ else if (secondVel < firstVel * 0.8) trend = 'decreasing';+ }+ }++ // Projected completion date+ let projectedCompletion = null;+ const remaining = 100 - (goal.progress ?? 0);+ if (percentPerMonth > 0 && remaining > 0) {+ const monthsToGo = remaining / percentPerMonth;+ const projected = new Date();+ projected.setDate(projected.getDate() + Math.round(monthsToGo * 30.44));+ projectedCompletion = projected.toISOString().slice(0, 10);+ }++ return { percentPerMonth, trend, projectedCompletion };+}++/**+ * Compute time tracking stats from progressLog entries.+ * Returns { totalMinutes, weeklyAverage, entriesCount }.+ */+export function computeTimeTracking(goal) {+ const log = goal.progressLog;+ if (!log?.length) return { totalMinutes: 0, weeklyAverage: 0, entriesCount: 0 };++ let totalMinutes = 0;+ let minDate = log[0].date;+ let maxDate = log[0].date;+ for (const e of log) {+ totalMinutes += e.durationMinutes || 0;+ if (e.date < minDate) minDate = e.date;+ if (e.date > maxDate) maxDate = e.date;+ }++ const daySpan = (new Date(maxDate) - new Date(minDate)) / (1000 * 60 * 60 * 24);+ const weeks = Math.max(1, daySpan / 7);+ const weeklyAverage = Math.round(totalMinutes / weeks);++ return { totalMinutes, weeklyAverage, entriesCount: log.length };+}++// =============================================================================+// Goal Todos+// =============================================================================++export async function addTodo(goalId, { title, priority, estimateMinutes }) {+ const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);+ const goal = goals.goals.find(g => g.id === goalId);+ if (!goal) return null;++ if (!goal.todos) goal.todos = [];++ const todo = {+ id: `todo-${uuidv4()}`,+ title,+ status: 'pending',+ priority: priority || 'medium',+ estimateMinutes: estimateMinutes || null,+ createdAt: new Date().toISOString(),+ completedAt: null+ };++ goal.todos.push(todo);+ goal.updatedAt = new Date().toISOString();+ goals.updatedAt = new Date().toISOString();+ await saveJSON(GOALS_FILE, goals);++ console.log(`✅ Todo added to "${goal.title}": "${title}"`);+ return todo;+}++export async function updateTodo(goalId, todoId, updates) {+ const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);+ const goal = goals.goals.find(g => g.id === goalId);+ if (!goal) return null;++ const todo = (goal.todos || []).find(t => t.id === todoId);+ if (!todo) return null;++ const allowed = ['title', 'status', 'priority', 'estimateMinutes'];+ for (const key of allowed) {+ if (updates[key] !== undefined) todo[key] = updates[key];+ }++ // Auto-set completedAt when marked done+ if (updates.status === 'done' && !todo.completedAt) {+ todo.completedAt = new Date().toISOString();+ } else if (updates.status && updates.status !== 'done') {+ todo.completedAt = null;+ }++ goal.updatedAt = new Date().toISOString();+ goals.updatedAt = new Date().toISOString();+ await saveJSON(GOALS_FILE, goals);+ return todo;+}++export async function deleteTodo(goalId, todoId) {+ const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);+ const goal = goals.goals.find(g => g.id === goalId);+ if (!goal) return null;++ const idx = (goal.todos || []).findIndex(t => t.id === todoId);+ if (idx === -1) return null;++ goal.todos.splice(idx, 1);+ goal.updatedAt = new Date().toISOString();+ goals.updatedAt = new Date().toISOString();+ await saveJSON(GOALS_FILE, goals);+ return { deleted: true };+}