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: AI phase planning, calendar time-blocking, and automated goal check-ins (M49 P2-P4)

Adam Eivyc5277717f63d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 2c2225329a..8cf6d933b5 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -3,6 +3,7 @@
- **M50 P7: Gmail API Sync** — Gmail integration via Google API (same OAuth as Calendar). Syncs inbox messages with full body extraction, thread grouping, label mapping, and starred/read status. Sends email via Gmail API with RFC 2822 formatting and reply threading. Archive/delete via API (no browser needed). HTML email rendering in sandboxed iframe. Compact message detail header. Gmail setup checklist in Config with OAuth and API enable controls.
- **M56: Telegram Bot Integration** — Telegram bot for external notifications and conversational commands. Configure bot token and chat ID in Settings. Forwards PortOS notifications (filterable by type) to Telegram with rate limiting. Bot commands: `/status`, `/goals`, `/agents`, `/checkin`, `/help`. Check-in responses are persisted for goal tracking.
- **M49 P1: Goal Todos & Progress Tracking** — Enhanced goal model with explicit progress percentage, todo sub-tasks (with priority and time estimates), velocity tracking (percent/month with trend), projected completion dates, and time tracking aggregates. Progress bar and todos visible in both goal list rows and detail panel.
+- **M49 P2-P4: Goal Planning, Calendar & Check-ins** — Set target dates on goals, generate AI-powered phase plans (3-7 milestones with dates), edit/reorder/accept proposed phases. Schedule time blocks on Google Calendar based on preferred days, time slots, and session duration. Automated weekly goal check-ins via autonomous job: computes expected vs actual progress, determines on-track/behind/at-risk status, generates AI assessment and recommendations, sends Telegram notification. Google Calendar OAuth upgraded to read-write scope with upgrade detection.
## Changed
diff --git a/PLAN.md b/PLAN.md
index 9c6abe115d..4530aeaa8a 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -61,58 +61,23 @@ See [GOALS.md](./GOALS.md) for project goals and direction.
- [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
+- [x] **M48 P1-P10**: Google Calendar Integration - MCP push sync, direct Google API via OAuth2, subcalendar management, goal-calendar linking, daily review, auto-configure via CDP, color-coded events, 15-min Day/Week views, Life Calendar consolidated under Calendar > Lifetime
+- [x] **M49 P1**: Life Goals — Enhanced goal model with todos, progress percentage, velocity tracking, projected completion, time tracking aggregates
+- [x] **M50 P1-P7**: Email Management - Outlook API+Playwright sync, AI triage with security hardening, draft generation, thread capture, per-action models, full Messages UI, Gmail API sync+send
+- [x] **M52**: Update Detection - GitHub release polling with semver comparison, auto-check every 30 min, Socket.IO real-time notifications, Update tab UI with progress tracking, update executor with health polling
+- [x] **M56**: Telegram Bot Integration - External notification channel via Telegram bot with conversational commands, goal check-in persistence. Replaces M47.
### Planned
-- [x] **M50 P1-P6**: Email Management - Outlook API+Playwright sync, AI triage with security hardening, draft generation, thread capture, per-action models, full Messages UI (Inbox/Drafts/Sync/Config)
-- [x] **M50 P7**: Email Management - Gmail API sync (same OAuth as Calendar), full body extraction, thread grouping, send via Gmail API
-- [ ] **M50 P8-P9**: Email Management - Digital Twin voice drafting, CoS automation & rules, auto-send with AI review gate
+- [ ] **M50 P8-P10**: Email Management - Digital Twin voice drafting, CoS automation & rules, auto-send with AI review gate
+- [x] **M49 P2-P4**: Life Goals — AI phase planning, calendar time-blocking, automated weekly check-ins with status tracking
- [ ] **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)
-- [x] **M56**: Telegram Bot Integration - External notification channel via Telegram bot. ChatId allowlisting, notification forwarding with rate limiting and type filtering, conversational commands (/status, /goals, /agents, /checkin, /help), goal check-in persistence. Replaces M47.
-- [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
-- [x] **M48 P7**: UI-Triggered Google Calendar Sync - "Sync Google" button in Sync tab + "Discover Calendars" in Config tab
-- [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
-- [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
-### M47: Push Notifications
-
-External notification delivery for critical events when not actively viewing the dashboard.
-
-**Notification Channels**
-- Discord webhook (post to a private channel)
-- Telegram bot (send to chat ID)
-- Generic webhook (POST JSON to any URL)
-- Configurable per-channel: which event types to send
-
-**Events**
-- Agent task completed (with success/failure status and summary)
-- Critical errors (PM2 crash, autofixer triggered)
-- Goal milestone reached
-- CoS health alert (agent stuck, high failure rate)
-- Backup completed or failed (M45)
-
-**Configuration**
-- Settings page section for notification channels
-- Per-channel event type toggles
-- Test button to verify delivery
-- Rate limiting to prevent notification spam (max N per hour per channel)
-
-*Touches: new server/services/pushNotify.js, server/routes/settings.js, Settings UI, cosEvents.js, errorRecovery.js*
-
-### M48: Google Calendar Integration (Complete)
-
-**All phases complete (P1-P10).** Full Google Calendar integration with two sync methods (Claude MCP zero-config + direct Google API via OAuth2), subcalendar management, goal-calendar linking, daily review, auto-configure via CDP browser, color-coded events, 15-min Day/Week views with overlap layout, declined/cancelled event filtering, and Life Calendar consolidated under Calendar > Lifetime.
-
### M49: Life Goals & Todo Planning
Extends the existing goal system in `server/services/identity.js` and `data/digital-twin/goals.json`. Adds rich progress tracking, todo sub-tasks, calendar time-blocking, and AI-powered check-ins. Gets its own top-level Goals page (not buried under Digital Twin).
@@ -120,9 +85,9 @@ Extends the existing goal system in `server/services/identity.js` and `data/digi
**Phases:**
- **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
+- **P2: Calendar Time-Blocking** *(Complete)* — Schedule time blocks on Google Calendar based on phase milestones and time block config (preferred days, time slot, session duration). Google Calendar OAuth upgraded from readonly to read-write scope with upgrade detection. Calendar event CRUD via googleapis.
+- **P3: Check-in & Evaluation** *(Complete)* — Automated weekly goal check-ins via `job-goal-check-in` autonomous job with gate. Computes expected vs actual progress, determines on-track/behind/at-risk status, generates AI assessment and recommendations via LLM, sends Telegram notification. Check-in history displayed in goal detail panel.
+- **P4: AI Phase Planning** *(Complete)* — AI-powered phase generation (3-7 milestones with target dates) via LLM. Editable proposed phases with reorder, add/remove. Accept to persist as milestones with description and order fields.
**Data:** Extended `data/digital-twin/goals.json` with `todos[]`, `progressHistory[]`, `velocity{}`, `checkIns[]`, `calendarConfig{}`, `timeTracking{}` per goal. `checkInSchedule{}` at root level.
@@ -138,13 +103,13 @@ Multi-provider email integration — Gmail via Google API (shared OAuth with Cal
Always review before send — AI-generated drafts go to an outbox queue. The user reviews, edits, and approves each response before it's sent. No auto-send.
-**Completed:** P1-P7 (Email sync, AI triage, reply generation, thread capture, config, per-action models, prompt injection hardening, per-message re-fetch, Gmail API sync+send). See git history for details.
+**Completed:** P1-P7 (Email sync, AI triage, reply generation, thread capture, config, per-action models, prompt injection hardening, per-message re-fetch, Gmail API sync+send).
**Remaining:**
- [ ] **P8: Digital Twin voice drafting** — Draft responses using Digital Twin voice/style (reads COMMUNICATION.md, PERSONALITY.md, VALUES.md + recent thread context)
- [ ] **P9: CoS Automation & Rules** — Automated classification on new emails via CoS job, rule-based pre-filtering, email-to-task pipeline, priority email notifications
-- [ ] **P10: Auto-Send with AI Review Gate** — Remove human-in-the-loop for trusted accounts. Before auto-sending, a second LLM call reviews the draft against the original email for: prompt injection artifacts, off-topic content, tone/identity drift, leaked system instructions. Configurable per-account trust level (manual → review-assisted → auto-send). See [Messages Security](./docs/features/messages-security.md) for threat model.
+- [ ] **P10: Auto-Send with AI Review Gate** — Configurable per-account trust level (manual → review-assisted → auto-send). Second LLM reviews drafts for prompt injection, tone drift, leaked instructions. See [Messages Security](./docs/features/messages-security.md)
**Data:** `data/messages/accounts.json`, `data/messages/cache/{accountId}.json`, `data/messages/selectors.json`, `settings.json` (messages key for AI config + templates)
@@ -152,32 +117,6 @@ Always review before send — AI-generated drafts go to an outbox queue. The use
**Nav:** Collapsible "Messages" sidebar section with Drafts, Inbox, Sync, Config sub-pages
-### M52: Update Detection
-
-Check for new PortOS releases on GitHub and notify the user when an update is available.
-
-**Version Check**
-- Scheduled service polls `GET https://api.github.com/repos/atomantic/PortOS/releases/latest` (or tags endpoint) on a configurable interval (default: daily)
-- Compare remote latest tag against local version from `package.json`
-- Semver comparison — only flag when remote is newer (ignore pre-release tags unless opted in)
-- Cache last-checked timestamp and latest remote version in `data/settings.json` or `data/update-check.json`
-
-**UI Notifications**
-- Dashboard widget: subtle banner when update available showing current vs. latest version
-- Settings page: "Check for Updates" button with last-checked timestamp, auto-check toggle, and interval config
-- Sidebar badge or indicator on Settings nav item when update is pending
-
-**Update Action**
-- Display release notes summary (fetched from GitHub release body)
-- "View Release" link opens GitHub release page
-- Optional: show one-liner shell command to pull the update (`git pull && npm run install:all && pm2 restart ecosystem.config.cjs`)
-
-**Routes:** `GET /api/system/update-check` (returns current version, latest version, update available boolean, release notes), `POST /api/system/update-check` (trigger manual check)
-
-**Nav:** No new nav item — surfaces in Dashboard widget and Settings page
-
-*Touches: new server/services/updateCheck.js, server/routes/system.js, Dashboard.jsx (update banner widget), Settings page (update check section), data/update-check.json*
-
### Tier 1: Identity Integration (aligns with M42 direction)
- **Chronotype-Aware Scheduling** — Chronotype derivation exists (M42 P1) but isn't applied to task scheduling yet. Use peak-focus windows from genome sleep markers to schedule deep-work tasks during peak hours, routine tasks during low-energy. Display energy curve on Schedule tab. *Touches: taskSchedule.js, genome.js, CoS Schedule tab*
@@ -301,9 +240,6 @@ Three audit passes identified remaining items across architecture, bugs, code qu
## Next Actions
-1. **M49 P1**: Life Goals — Enhanced goal model with todos, calendar time-blocking, progress tracking
+1. **M50 P8**: Messages — Digital Twin voice drafting for email responses
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 notification
diff --git a/client/src/components/goals/GoalDetailPanel.jsx b/client/src/components/goals/GoalDetailPanel.jsx
index 50a2b05ac2..d584089d7a 100644
--- a/client/src/components/goals/GoalDetailPanel.jsx
+++ b/client/src/components/goals/GoalDetailPanel.jsx
@@ -3,7 +3,8 @@ import {
Target, X, Check, Trash2, Milestone, Calendar, CalendarDays, Clock,
Heart, DollarSign, Lightbulb, Users, Flame, AlertTriangle, Tag,
Link2, Unlink, Activity, Plus, NotebookPen, ListTodo, TrendingUp,
- TrendingDown, Minus, CircleDot
+ TrendingDown, Minus, CircleDot, Wand2, ArrowUp, ArrowDown, CalendarPlus,
+ CalendarX, RefreshCw, ChevronDown, ChevronRight, ClipboardCheck
} from 'lucide-react';
import * as api from '../../services/api';
@@ -105,6 +106,12 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh })
const [newTodoTitle, setNewTodoTitle] = useState('');
const [newTodoPriority, setNewTodoPriority] = useState('medium');
const [newTodoEstimate, setNewTodoEstimate] = useState('');
+ // Plan & scheduling state
+ const [planOpen, setPlanOpen] = useState(false);
+ const [generatingPhases, setGeneratingPhases] = useState(false);
+ const [proposedPhases, setProposedPhases] = useState(null);
+ const [schedulingBusy, setSchedulingBusy] = useState(false);
+ const [checkInsOpen, setCheckInsOpen] = useState(false);
useEffect(() => {
api.getActivities().then(setActivities).catch(() => {});
@@ -138,7 +145,9 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh })
horizon: goal.horizon,
category: goal.category,
parentId: goal.parentId || '',
- tags: [...(goal.tags || [])]
+ tags: [...(goal.tags || [])],
+ targetDate: goal.targetDate || '',
+ timeBlockConfig: goal.timeBlockConfig || null
});
setEditing(true);
};
@@ -146,12 +155,49 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh })
const saveEdit = async () => {
await api.updateGoal(goal.id, {
...form,
- parentId: form.parentId || null
+ parentId: form.parentId || null,
+ targetDate: form.targetDate || null,
+ timeBlockConfig: form.timeBlockConfig || null
});
setEditing(false);
onRefresh();
};
+ const handleGeneratePhases = async () => {
+ setGeneratingPhases(true);
+ const phases = await api.generateGoalPhases(goal.id).catch(() => null);
+ setGeneratingPhases(false);
+ if (phases) setProposedPhases(phases);
+ };
+
+ const handleAcceptPhases = async () => {
+ if (!proposedPhases?.length) return;
+ await api.acceptGoalPhases(goal.id, proposedPhases);
+ setProposedPhases(null);
+ onRefresh();
+ };
+
+ const handleSchedule = async () => {
+ setSchedulingBusy(true);
+ await api.scheduleGoalTimeBlocks(goal.id);
+ setSchedulingBusy(false);
+ onRefresh();
+ };
+
+ const handleRemoveSchedule = async () => {
+ setSchedulingBusy(true);
+ await api.removeGoalSchedule(goal.id);
+ setSchedulingBusy(false);
+ onRefresh();
+ };
+
+ const handleReschedule = async () => {
+ setSchedulingBusy(true);
+ await api.rescheduleGoalTimeBlocks(goal.id);
+ setSchedulingBusy(false);
+ onRefresh();
+ };
+
const handleDelete = async () => {
await api.deleteGoal(goal.id);
onClose();
@@ -361,6 +407,77 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh })
))}
</select>
</div>
+ <div>
+ <label className="text-xs text-gray-500">Target Date</label>
+ <input
+ type="date"
+ value={form.targetDate || ''}
+ onChange={e => setForm({ ...form, targetDate: 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"
+ />
+ </div>
+ <div>
+ <label className="text-xs text-gray-500">Time Block Config</label>
+ <div className="mt-1 space-y-2">
+ <div>
+ <span className="text-[10px] text-gray-600">Preferred days</span>
+ <div className="flex flex-wrap gap-1 mt-0.5">
+ {['mon','tue','wed','thu','fri','sat','sun'].map(d => {
+ const days = form.timeBlockConfig?.preferredDays || [];
+ const active = days.includes(d);
+ return (
+ <button
+ key={d}
+ type="button"
+ onClick={() => {
+ const next = active ? days.filter(x => x !== d) : [...days, d];
+ setForm({ ...form, timeBlockConfig: { ...(form.timeBlockConfig || { timeSlot: 'morning', sessionDurationMinutes: 60 }), preferredDays: next } });
+ }}
+ className={`px-1.5 py-0.5 text-[10px] rounded ${active ? 'bg-port-accent text-white' : 'bg-port-bg border border-port-border text-gray-400'}`}
+ >
+ {d}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ <div className="flex gap-2">
+ <div className="flex-1">
+ <span className="text-[10px] text-gray-600">Time slot</span>
+ <select
+ value={form.timeBlockConfig?.timeSlot || 'morning'}
+ onChange={e => setForm({ ...form, timeBlockConfig: { ...(form.timeBlockConfig || { preferredDays: ['mon','wed','fri'], sessionDurationMinutes: 60 }), timeSlot: e.target.value } })}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white mt-0.5"
+ >
+ <option value="morning">Morning</option>
+ <option value="afternoon">Afternoon</option>
+ <option value="evening">Evening</option>
+ </select>
+ </div>
+ <div className="w-20">
+ <span className="text-[10px] text-gray-600">Duration</span>
+ <input
+ type="number"
+ min="15"
+ max="480"
+ value={form.timeBlockConfig?.sessionDurationMinutes || 60}
+ onChange={e => setForm({ ...form, timeBlockConfig: { ...(form.timeBlockConfig || { preferredDays: ['mon','wed','fri'], timeSlot: 'morning' }), sessionDurationMinutes: parseInt(e.target.value, 10) || 60 } })}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white mt-0.5"
+ />
+ <span className="text-[10px] text-gray-600">min</span>
+ </div>
+ </div>
+ {form.timeBlockConfig?.preferredDays?.length > 0 && (
+ <button
+ type="button"
+ onClick={() => setForm({ ...form, timeBlockConfig: null })}
+ className="text-[10px] text-red-400 hover:text-red-300"
+ >
+ Clear config
+ </button>
+ )}
+ </div>
+ </div>
<div>
<label className="text-xs text-gray-500">Tags</label>
<div className="flex flex-wrap gap-1 mt-1 mb-2">
@@ -620,6 +737,231 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh })
</div>
</div>
+ {/* Target Date */}
+ {goal.targetDate && (
+ <div className="flex items-center gap-1.5 text-xs text-gray-400">
+ <Calendar className="w-3.5 h-3.5" />
+ <span>Target: {new Date(goal.targetDate + 'T00:00:00').toLocaleDateString()}</span>
+ </div>
+ )}
+
+ {/* Plan Section */}
+ <div>
+ <button
+ onClick={() => setPlanOpen(!planOpen)}
+ className="flex items-center gap-1 text-xs font-medium text-gray-400 hover:text-white w-full"
+ >
+ {planOpen ? <ChevronDown className="w-3.5 h-3.5" /> : <ChevronRight className="w-3.5 h-3.5" />}
+ <Wand2 className="w-3.5 h-3.5" />
+ <span>Plan</span>
+ </button>
+ {planOpen && (
+ <div className="mt-2 space-y-2">
+ <button
+ onClick={handleGeneratePhases}
+ disabled={!goal.targetDate || generatingPhases}
+ className="w-full px-3 py-1.5 text-xs rounded bg-port-accent/20 text-port-accent disabled:opacity-50 flex items-center justify-center gap-1"
+ >
+ <Wand2 className="w-3 h-3" />
+ {generatingPhases ? 'Generating...' : 'Generate Plan'}
+ </button>
+ {!goal.targetDate && (
+ <p className="text-[10px] text-gray-600">Set a target date first to generate phases</p>
+ )}
+ {proposedPhases && (
+ <div className="space-y-1.5">
+ <p className="text-[10px] text-gray-500">{proposedPhases.length} phases proposed</p>
+ {proposedPhases.map((phase, idx) => (
+ <div key={idx} className="p-2 rounded bg-port-bg border border-port-border space-y-1">
+ <div className="flex items-center gap-2">
+ <div className="flex flex-col gap-0.5">
+ <button
+ onClick={() => {
+ if (idx === 0) return;
+ const next = [...proposedPhases];
+ [next[idx - 1], next[idx]] = [next[idx], next[idx - 1]];
+ next.forEach((p, i) => { p.order = i; });
+ setProposedPhases(next);
+ }}
+ disabled={idx === 0}
+ className="text-gray-600 hover:text-white disabled:opacity-30"
+ >
+ <ArrowUp className="w-2.5 h-2.5" />
+ </button>
+ <button
+ onClick={() => {
+ if (idx === proposedPhases.length - 1) return;
+ const next = [...proposedPhases];
+ [next[idx], next[idx + 1]] = [next[idx + 1], next[idx]];
+ next.forEach((p, i) => { p.order = i; });
+ setProposedPhases(next);
+ }}
+ disabled={idx === proposedPhases.length - 1}
+ className="text-gray-600 hover:text-white disabled:opacity-30"
+ >
+ <ArrowDown className="w-2.5 h-2.5" />
+ </button>
+ </div>
+ <div className="flex-1 min-w-0">
+ <input
+ type="text"
+ value={phase.title}
+ onChange={e => {
+ const next = [...proposedPhases];
+ next[idx] = { ...next[idx], title: e.target.value };
+ setProposedPhases(next);
+ }}
+ className="w-full bg-port-card border border-port-border rounded px-2 py-0.5 text-xs text-white"
+ />
+ <input
+ type="text"
+ value={phase.description || ''}
+ onChange={e => {
+ const next = [...proposedPhases];
+ next[idx] = { ...next[idx], description: e.target.value };
+ setProposedPhases(next);
+ }}
+ placeholder="Description..."
+ className="w-full bg-port-card border border-port-border rounded px-2 py-0.5 text-xs text-gray-400 mt-0.5"
+ />
+ </div>
+ <div className="flex flex-col items-end gap-0.5">
+ <input
+ type="date"
+ value={phase.targetDate}
+ onChange={e => {
+ const next = [...proposedPhases];
+ next[idx] = { ...next[idx], targetDate: e.target.value };
+ setProposedPhases(next);
+ }}
+ className="bg-port-card border border-port-border rounded px-1 py-0.5 text-[10px] text-white"
+ />
+ <button
+ onClick={() => setProposedPhases(proposedPhases.filter((_, i) => i !== idx).map((p, i) => ({ ...p, order: i })))}
+ className="text-gray-600 hover:text-red-400"
+ >
+ <Trash2 className="w-3 h-3" />
+ </button>
+ </div>
+ </div>
+ </div>
+ ))}
+ <button
+ onClick={() => setProposedPhases([...proposedPhases, { title: '', description: '', targetDate: goal.targetDate, order: proposedPhases.length }])}
+ className="text-xs text-port-accent hover:text-blue-300 flex items-center gap-1"
+ >
+ <Plus className="w-3 h-3" /> Add phase
+ </button>
+ <div className="flex gap-2">
+ <button
+ onClick={handleAcceptPhases}
+ className="px-3 py-1.5 text-xs rounded bg-port-accent text-white hover:bg-blue-600"
+ >
+ Accept Plan
+ </button>
+ <button
+ onClick={() => setProposedPhases(null)}
+ className="px-3 py-1.5 text-xs rounded bg-port-border text-gray-300"
+ >
+ Discard
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* Schedule Controls */}
+ {goal.milestones?.length > 0 && goal.timeBlockConfig && (
+ <div className="pt-2 border-t border-port-border space-y-2">
+ <div className="text-[10px] text-gray-500">
+ <CalendarPlus className="w-3 h-3 inline mr-1" />
+ {goal.scheduledEvents?.length
+ ? `${goal.scheduledEvents.length} events scheduled`
+ : 'No events scheduled'}
+ </div>
+ {!goal.scheduledEvents?.length ? (
+ <button
+ onClick={handleSchedule}
+ disabled={schedulingBusy}
+ className="w-full px-3 py-1.5 text-xs rounded bg-green-500/20 text-green-400 disabled:opacity-50 flex items-center justify-center gap-1"
+ >
+ <CalendarPlus className="w-3 h-3" />
+ {schedulingBusy ? 'Scheduling...' : 'Schedule Time Blocks'}
+ </button>
+ ) : (
+ <div className="flex gap-1">
+ <button
+ onClick={handleReschedule}
+ disabled={schedulingBusy}
+ className="flex-1 px-2 py-1 text-xs rounded bg-port-accent/20 text-port-accent disabled:opacity-50 flex items-center justify-center gap-1"
+ >
+ <RefreshCw className="w-3 h-3" />
+ Reschedule
+ </button>
+ <button
+ onClick={handleRemoveSchedule}
+ disabled={schedulingBusy}
+ className="px-2 py-1 text-xs rounded bg-red-500/20 text-red-400 disabled:opacity-50 flex items-center justify-center gap-1"
+ >
+ <CalendarX className="w-3 h-3" />
+ Remove
+ </button>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* Check-ins */}
+ {goal.checkIns?.length > 0 && (
+ <div>
+ <button
+ onClick={() => setCheckInsOpen(!checkInsOpen)}
+ className="flex items-center gap-1 text-xs font-medium text-gray-400 hover:text-white w-full"
+ >
+ {checkInsOpen ? <ChevronDown className="w-3.5 h-3.5" /> : <ChevronRight className="w-3.5 h-3.5" />}
+ <ClipboardCheck className="w-3.5 h-3.5" />
+ <span>Check-ins ({goal.checkIns.length})</span>
+ {goal.checkIns.length > 0 && (() => {
+ const latest = goal.checkIns[goal.checkIns.length - 1];
+ const statusColors = { 'on-track': 'bg-green-500', 'behind': 'bg-yellow-500', 'at-risk': 'bg-red-500' };
+ return <span className={`ml-auto w-2 h-2 rounded-full ${statusColors[latest.status] || 'bg-gray-500'}`} />;
+ })()}
+ </button>
+ {checkInsOpen && (
+ <div className="mt-2 space-y-2 max-h-48 overflow-y-auto">
+ {[...goal.checkIns].reverse().map(ci => {
+ const statusConfig = {
+ 'on-track': { color: 'text-green-400', bg: 'bg-green-500/20', label: 'On Track' },
+ 'behind': { color: 'text-yellow-400', bg: 'bg-yellow-500/20', label: 'Behind' },
+ 'at-risk': { color: 'text-red-400', bg: 'bg-red-500/20', label: 'At Risk' }
+ };
+ const sc = statusConfig[ci.status] || statusConfig['behind'];
+ return (
+ <div key={ci.id} className="p-2 rounded bg-port-bg border border-port-border space-y-1">
+ <div className="flex items-center justify-between">
+ <span className="text-[10px] text-gray-500">{new Date(ci.date + 'T00:00:00').toLocaleDateString()}</span>
+ <span className={`px-1.5 py-0.5 rounded text-[10px] ${sc.bg} ${sc.color}`}>{sc.label}</span>
+ </div>
+ <div className="text-[10px] text-gray-500">
+ Progress: {ci.actualProgress}% / {ci.expectedProgress}% expected
+ {ci.attendanceRate != null && ` · ${ci.attendanceRate}% activity`}
+ </div>
+ {ci.assessment && <p className="text-xs text-gray-300">{ci.assessment}</p>}
+ {ci.recommendations?.length > 0 && (
+ <ul className="text-[10px] text-gray-400 list-disc pl-3 space-y-0.5">
+ {ci.recommendations.map((r, i) => <li key={i}>{r}</li>)}
+ </ul>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ )}
+
{/* Progress Log */}
<div>
<div className="flex items-center justify-between mb-2">
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 5e8984d1d1..65a3a6137f 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -1780,6 +1780,13 @@ export const addGoalTodo = (goalId, data) => request(`/digital-twin/identity/goa
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' });
+// 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 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' });
+
// Default export for simplified imports
export default {
get: (endpoint, options) => request(endpoint, { method: 'GET', ...options }),
diff --git a/server/lib/aiProvider.js b/server/lib/aiProvider.js
new file mode 100644
index 0000000000..8e23c86b34
--- /dev/null
+++ b/server/lib/aiProvider.js
@@ -0,0 +1,64 @@
+/**
+ * Shared AI provider utilities for LLM calls.
+ * Used by insightsService, identity, goalCheckIn, taste-questionnaire, etc.
+ */
+
+/**
+ * Call an API-based AI provider with a simple prompt.
+ * Returns { text } on success, { error } on failure.
+ */
+export async function callProviderAISimple(provider, model, prompt, { temperature = 0.3, max_tokens = 1000 } = {}) {
+ const timeout = provider.timeout || 300000;
+
+ if (provider.type === 'api') {
+ const headers = { 'Content-Type': 'application/json' };
+ if (provider.apiKey) headers['Authorization'] = `Bearer ${provider.apiKey}`;
+
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), timeout);
+
+ const response = await fetch(`${provider.endpoint}/chat/completions`, {
+ method: 'POST',
+ headers,
+ signal: controller.signal,
+ body: JSON.stringify({
+ model,
+ messages: [{ role: 'user', content: prompt }],
+ temperature,
+ max_tokens
+ })
+ });
+
+ clearTimeout(timer);
+
+ if (!response.ok) {
+ const errorText = await response.text().catch(() => 'Unknown error');
+ return { error: `Provider returned ${response.status}: ${errorText}` };
+ }
+
+ const data = await response.json();
+ return { text: data.choices?.[0]?.message?.content || '' };
+ }
+
+ return { error: 'This operation requires an API-based provider' };
+}
+
+/**
+ * Strip markdown code fences from LLM output before JSON.parse.
+ */
+export function stripCodeFences(raw) {
+ return raw.replace(/^```(?:json)?\n?/, '').replace(/\n?```$/, '').trim();
+}
+
+/**
+ * Parse JSON from LLM output, stripping code fences first.
+ * Throws a descriptive error on parse failure.
+ */
+export function parseLLMJSON(raw) {
+ const cleaned = stripCodeFences(raw);
+ try {
+ return JSON.parse(cleaned);
+ } catch (e) {
+ throw new Error(`Invalid JSON from AI: ${e.message}`);
+ }
+}
diff --git a/server/lib/identityValidation.js b/server/lib/identityValidation.js
index 030ea9f66e..35a8128f66 100644
--- a/server/lib/identityValidation.js
+++ b/server/lib/identityValidation.js
@@ -48,13 +48,25 @@ export const goalCategoryEnum = z.enum([
export const goalStatusEnum = z.enum(['active', 'completed', 'abandoned']);
+const timeBlockConfigSchema = z.object({
+ preferredDays: z.array(z.enum(['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'])).min(1).max(7),
+ timeSlot: z.union([
+ z.enum(['morning', 'afternoon', 'evening']),
+ z.string().regex(hhmmRegex, 'Must be HH:MM format')
+ ]),
+ sessionDurationMinutes: z.number().int().min(15).max(480),
+ subcalendarId: z.string().min(1).optional()
+});
+
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'),
parentId: z.string().min(1).nullable().optional().default(null),
- tags: z.array(z.string().min(1).max(50)).max(20).optional().default([])
+ tags: z.array(z.string().min(1).max(50)).max(20).optional().default([]),
+ targetDate: validCalendarDate.optional(),
+ timeBlockConfig: timeBlockConfigSchema.optional()
});
export const updateGoalInputSchema = z.object({
@@ -64,7 +76,9 @@ export const updateGoalInputSchema = z.object({
category: goalCategoryEnum.optional(),
status: goalStatusEnum.optional(),
parentId: z.string().min(1).nullable().optional(),
- tags: z.array(z.string().min(1).max(50)).max(20).optional()
+ tags: z.array(z.string().min(1).max(50)).max(20).optional(),
+ targetDate: validCalendarDate.nullable().optional(),
+ timeBlockConfig: timeBlockConfigSchema.nullable().optional()
});
export const addMilestoneInputSchema = z.object({
@@ -72,6 +86,20 @@ export const addMilestoneInputSchema = z.object({
targetDate: validCalendarDate.optional()
});
+export const generatePhasesInputSchema = z.object({
+ providerId: z.string().min(1).optional(),
+ model: z.string().min(1).optional()
+});
+
+export const acceptPhasesInputSchema = z.object({
+ phases: z.array(z.object({
+ title: z.string().min(1).max(200),
+ description: z.string().max(2000).optional().default(''),
+ targetDate: validCalendarDate,
+ order: z.number().int().min(0)
+ })).min(1).max(20)
+});
+
// --- Goal Progress Log Schemas ---
export const addProgressEntrySchema = z.object({
diff --git a/server/routes/identity.js b/server/routes/identity.js
index e82ee1194e..9aa3989b28 100644
--- a/server/routes/identity.js
+++ b/server/routes/identity.js
@@ -13,8 +13,11 @@ import {
linkCalendarInputSchema,
addTodoInputSchema,
updateTodoInputSchema,
- updateProgressSchema
+ updateProgressSchema,
+ generatePhasesInputSchema,
+ acceptPhasesInputSchema
} from '../lib/identityValidation.js';
+import * as goalCalendarScheduler from '../services/goalCalendarScheduler.js';
const router = Router();
@@ -238,4 +241,36 @@ router.delete('/goals/:id/todos/:todoId', asyncHandler(async (req, res) => {
res.json(result);
}));
+// POST /api/digital-twin/identity/goals/:id/generate-phases — AI-generate phases
+router.post('/goals/:id/generate-phases', asyncHandler(async (req, res) => {
+ const data = validateRequest(generatePhasesInputSchema, req.body);
+ const phases = await identityService.generateGoalPhases(req.params.id, data);
+ res.json(phases);
+}));
+
+// POST /api/digital-twin/identity/goals/:id/accept-phases — Persist phases as milestones
+router.post('/goals/:id/accept-phases', asyncHandler(async (req, res) => {
+ const data = validateRequest(acceptPhasesInputSchema, req.body);
+ const goal = await identityService.acceptGoalPhases(req.params.id, data.phases);
+ res.json(goal);
+}));
+
+// 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);
+ res.json(result);
+}));
+
+// DELETE /api/digital-twin/identity/goals/:id/schedule — Remove scheduled events
+router.delete('/goals/:id/schedule', asyncHandler(async (req, res) => {
+ const result = await goalCalendarScheduler.removeScheduledEvents(req.params.id);
+ res.json(result);
+}));
+
+// POST /api/digital-twin/identity/goals/:id/reschedule — Rebuild schedule
+router.post('/goals/:id/reschedule', asyncHandler(async (req, res) => {
+ const result = await goalCalendarScheduler.rescheduleTimeBlocks(req.params.id);
+ res.json(result);
+}));
+
export default router;
diff --git a/server/services/autonomousJobs.js b/server/services/autonomousJobs.js
index 67f64fcbb1..ef389e4ded 100644
--- a/server/services/autonomousJobs.js
+++ b/server/services/autonomousJobs.js
@@ -24,6 +24,7 @@ import { cosEvents } from './cosEvents.js'
import { DAY, ensureDir, HOUR, PATHS, readJSONFile } from '../lib/fileUtils.js'
import { createMutex } from '../lib/asyncMutex.js'
import { checkAndPrompt as autobiographyCheckAndPrompt } from './autobiography.js'
+import { runGoalCheckIn } from './goalCheckIn.js'
import { validateCommand, redactOutput, ALLOWED_COMMANDS_SORTED } from '../lib/commandSecurity.js'
/**
@@ -105,7 +106,8 @@ async function agentDataCleanup() {
const SCRIPT_HANDLERS = {
'autobiography-prompt': autobiographyCheckAndPrompt,
'moltworld-exploration': runMoltworldExploration,
- 'agent-data-cleanup': agentDataCleanup
+ 'agent-data-cleanup': agentDataCleanup,
+ 'goal-check-in': runGoalCheckIn
}
const __filename = fileURLToPath(import.meta.url)
@@ -390,6 +392,23 @@ Phase 4 — Report:
createdAt: null,
updatedAt: null
},
+ {
+ id: 'job-goal-check-in',
+ name: 'Goal Check-in',
+ description: 'Weekly check-in on active goals with target dates. Computes progress, determines status, and sends assessment via Telegram.',
+ category: 'goal-check-in',
+ interval: 'weekly',
+ intervalMs: WEEK,
+ scheduledTime: '09:00',
+ enabled: false,
+ priority: 'MEDIUM',
+ type: 'script',
+ scriptHandler: 'goal-check-in',
+ lastRun: null,
+ runCount: 0,
+ createdAt: null,
+ updatedAt: null
+ },
]
let initPromise = null
diff --git a/server/services/goalCalendarScheduler.js b/server/services/goalCalendarScheduler.js
new file mode 100644
index 0000000000..193844523b
--- /dev/null
+++ b/server/services/goalCalendarScheduler.js
@@ -0,0 +1,162 @@
+import { google } from 'googleapis';
+import { writeFile } from 'fs/promises';
+import { v4 as uuidv4 } from 'uuid';
+import { join } from 'path';
+import { PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { getAuthenticatedClient, needsScopeUpgrade, getTokens } from './googleAuth.js';
+
+const GOALS_FILE = join(PATHS.digitalTwin, 'goals.json');
+
+const TIME_SLOT_HOURS = {
+ morning: 9,
+ afternoon: 13,
+ evening: 18
+};
+
+const DAY_MAP = {
+ sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6
+};
+
+function resolveTimeSlotHour(timeSlot) {
+ if (TIME_SLOT_HOURS[timeSlot] !== undefined) return TIME_SLOT_HOURS[timeSlot];
+ return parseInt(timeSlot.split(':')[0], 10);
+}
+
+function resolveTimeSlotMinute(timeSlot) {
+ if (TIME_SLOT_HOURS[timeSlot] !== undefined) return 0;
+ return parseInt(timeSlot.split(':')[1], 10) || 0;
+}
+
+async function loadGoals() {
+ return readJSONFile(GOALS_FILE, { goals: [] });
+}
+
+async function saveGoals(data) {
+ await writeFile(GOALS_FILE, JSON.stringify(data, null, 2));
+}
+
+export async function scheduleTimeBlocks(goalId) {
+ const tokens = await getTokens();
+ if (needsScopeUpgrade(tokens)) {
+ throw new ServerError('Calendar write access required. Please re-authorize Google Calendar.', { status: 403, code: 'SCOPE_UPGRADE_NEEDED' });
+ }
+
+ const auth = await getAuthenticatedClient();
+ if (!auth) throw new ServerError('Google OAuth not configured', { status: 401, code: 'NO_AUTH' });
+
+ const goals = await loadGoals();
+ const goal = goals.goals.find(g => g.id === goalId);
+ if (!goal) throw new ServerError('Goal not found', { status: 404, code: 'NOT_FOUND' });
+ if (!goal.timeBlockConfig) throw new ServerError('Time block config not set', { status: 400, code: 'NO_CONFIG' });
+ if (!goal.targetDate) throw new ServerError('Target date not set', { status: 400, code: 'NO_TARGET_DATE' });
+
+ const milestones = [...(goal.milestones || [])].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
+ if (!milestones.length) throw new ServerError('No milestones/phases to schedule', { status: 400, code: 'NO_MILESTONES' });
+
+ const calendar = google.calendar({ version: 'v3', auth });
+ const { preferredDays, timeSlot, sessionDurationMinutes, subcalendarId } = goal.timeBlockConfig;
+ const calendarId = subcalendarId || 'primary';
+ const preferredDayNums = new Set(preferredDays.map(d => DAY_MAP[d]));
+ const hour = resolveTimeSlotHour(timeSlot);
+ const minute = resolveTimeSlotMinute(timeSlot);
+ const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
+
+ const today = new Date();
+ today.setHours(0, 0, 0, 0);
+
+ // Collect all events to create
+ const eventDefs = [];
+ for (let i = 0; i < milestones.length; i++) {
+ const ms = milestones[i];
+ if (ms.completedAt) continue;
+
+ const rangeStart = i === 0 ? today : new Date(milestones[i - 1].targetDate + 'T00:00:00');
+ const rangeEnd = ms.targetDate ? new Date(ms.targetDate + 'T00:00:00') : new Date(goal.targetDate + 'T00:00:00');
+
+ const cursor = new Date(Math.max(rangeStart.getTime(), today.getTime()));
+ while (cursor <= rangeEnd) {
+ if (preferredDayNums.has(cursor.getDay())) {
+ const startTime = new Date(cursor);
+ startTime.setHours(hour, minute, 0, 0);
+ const endTime = new Date(startTime);
+ endTime.setMinutes(endTime.getMinutes() + sessionDurationMinutes);
+
+ eventDefs.push({
+ milestoneId: ms.id,
+ date: cursor.toISOString().slice(0, 10),
+ requestBody: {
+ summary: `${goal.title} - ${ms.title}`,
+ description: `${ms.description || ''}\n\nGoal: ${goal.title}`.trim(),
+ start: { dateTime: startTime.toISOString(), timeZone: tz },
+ end: { dateTime: endTime.toISOString(), timeZone: tz }
+ }
+ });
+ }
+ cursor.setDate(cursor.getDate() + 1);
+ }
+ }
+
+ // Create events in parallel batches of 10 to avoid rate limiting
+ const BATCH_SIZE = 10;
+ const scheduledEvents = [];
+ for (let i = 0; i < eventDefs.length; i += BATCH_SIZE) {
+ const batch = eventDefs.slice(i, i + BATCH_SIZE);
+ const results = await Promise.all(batch.map(def =>
+ calendar.events.insert({ calendarId, requestBody: def.requestBody })
+ ));
+ for (let j = 0; j < results.length; j++) {
+ scheduledEvents.push({
+ id: `sched-${uuidv4()}`,
+ googleEventId: results[j].data.id,
+ calendarId,
+ milestoneId: batch[j].milestoneId,
+ date: batch[j].date,
+ createdAt: new Date().toISOString()
+ });
+ }
+ }
+
+ goal.scheduledEvents = scheduledEvents;
+ goal.updatedAt = new Date().toISOString();
+ goals.updatedAt = new Date().toISOString();
+ await saveGoals(goals);
+
+ console.log(`📅 Scheduled ${scheduledEvents.length} time blocks for goal "${goal.title}"`);
+ return { count: scheduledEvents.length, events: scheduledEvents };
+}
+
+export async function removeScheduledEvents(goalId) {
+ const auth = await getAuthenticatedClient();
+ if (!auth) throw new ServerError('Google OAuth not configured', { status: 401, code: 'NO_AUTH' });
+
+ const goals = await loadGoals();
+ const goal = goals.goals.find(g => g.id === goalId);
+ if (!goal) throw new ServerError('Goal not found', { status: 404, code: 'NOT_FOUND' });
+
+ const calendar = google.calendar({ version: 'v3', auth });
+ const events = goal.scheduledEvents || [];
+
+ // Delete events in parallel
+ await Promise.all(events.map(evt =>
+ calendar.events.delete({
+ calendarId: evt.calendarId || 'primary',
+ eventId: evt.googleEventId
+ }).catch(err => {
+ if (err.code !== 410 && err.code !== 404) console.log(`📅 Failed to delete event ${evt.googleEventId}: ${err.message}`);
+ })
+ ));
+
+ goal.scheduledEvents = [];
+ goal.updatedAt = new Date().toISOString();
+ goals.updatedAt = new Date().toISOString();
+ await saveGoals(goals);
+
+ console.log(`📅 Removed ${events.length} scheduled events for goal "${goal.title}"`);
+ return { deleted: events.length };
+}
+
+export async function rescheduleTimeBlocks(goalId) {
+ await removeScheduledEvents(goalId);
+ return scheduleTimeBlocks(goalId);
+}
diff --git a/server/services/goalCheckIn.js b/server/services/goalCheckIn.js
new file mode 100644
index 0000000000..c95853bc0c
--- /dev/null
+++ b/server/services/goalCheckIn.js
@@ -0,0 +1,131 @@
+import { writeFile } from 'fs/promises';
+import { join } from 'path';
+import { v4 as uuidv4 } from 'uuid';
+import { PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { callProviderAISimple, parseLLMJSON } from '../lib/aiProvider.js';
+import { addNotification, NOTIFICATION_TYPES } from './notifications.js';
+
+const GOALS_FILE = join(PATHS.digitalTwin, 'goals.json');
+
+function computeExpectedProgress(goal) {
+ const start = new Date(goal.createdAt);
+ const target = new Date(goal.targetDate + 'T00:00:00');
+ const now = new Date();
+ const totalDays = (target - start) / (1000 * 60 * 60 * 24);
+ const elapsed = (now - start) / (1000 * 60 * 60 * 24);
+ if (totalDays <= 0) return 100;
+ return Math.min(100, Math.round((elapsed / totalDays) * 100));
+}
+
+function determineStatus(actual, expected) {
+ const ratio = expected > 0 ? actual / expected : 1;
+ if (ratio >= 0.8) return 'on-track';
+ if (ratio >= 0.5) return 'behind';
+ return 'at-risk';
+}
+
+function buildCheckInPrompt(goal, expectedProgress, actualProgress, status, recentEntries) {
+ return `You are a goal accountability coach. Give a brief assessment (2-3 sentences) and 1-3 specific recommendations.
+
+Goal: ${goal.title}
+Description: ${goal.description || 'None'}
+Target date: ${goal.targetDate}
+Expected progress: ${expectedProgress}%
+Actual progress: ${actualProgress}%
+Status: ${status}
+Recent activity entries (last 7 days): ${recentEntries.length}
+Milestones completed: ${goal.milestones?.filter(m => m.completedAt).length || 0}/${goal.milestones?.length || 0}
+
+Respond with JSON only (no markdown fences): { "assessment": "string", "recommendations": ["string", ...] }`;
+}
+
+export async function runGoalCheckIn() {
+ const { getActiveProvider } = await import('./providers.js');
+ const goals = await readJSONFile(GOALS_FILE, { goals: [] });
+ const activeGoals = goals.goals.filter(g => g.status === 'active' && g.targetDate);
+
+ if (!activeGoals.length) {
+ console.log('📊 Goal check-in: no active goals with target dates');
+ return { checked: 0 };
+ }
+
+ const provider = await getActiveProvider();
+ if (!provider) {
+ console.log('📊 Goal check-in: no AI provider available');
+ return { checked: 0, error: 'No AI provider' };
+ }
+
+ const sevenDaysAgo = new Date();
+ sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
+
+ // Build check-in data and LLM prompts for all goals
+ const checkInData = activeGoals.map(goal => {
+ const expectedProgress = computeExpectedProgress(goal);
+ const actualProgress = goal.progress ?? 0;
+ const status = determineStatus(actualProgress, expectedProgress);
+ const recentEntries = (goal.progressLog || []).filter(e => new Date(e.date) >= sevenDaysAgo);
+ const attendanceRate = Math.min(100, Math.round((recentEntries.length / 7) * 100));
+ const prompt = buildCheckInPrompt(goal, expectedProgress, actualProgress, status, recentEntries);
+ return { goal, expectedProgress, actualProgress, status, attendanceRate, prompt };
+ });
+
+ // Parallelize LLM calls
+ const llmResults = await Promise.all(
+ checkInData.map(d => callProviderAISimple(provider, provider.defaultModel, d.prompt))
+ );
+
+ const results = [];
+ const now = new Date().toISOString();
+ const today = now.slice(0, 10);
+
+ for (let i = 0; i < checkInData.length; i++) {
+ const d = checkInData[i];
+ const llmResult = llmResults[i];
+
+ let assessment = '';
+ let recommendations = [];
+ if (!llmResult.error) {
+ try {
+ const parsed = parseLLMJSON(llmResult.text);
+ assessment = parsed.assessment || '';
+ recommendations = parsed.recommendations || [];
+ } catch {
+ // LLM returned invalid JSON — continue with empty assessment
+ }
+ }
+
+ const checkIn = {
+ id: `ci-${uuidv4()}`,
+ date: today,
+ status: d.status,
+ expectedProgress: d.expectedProgress,
+ actualProgress: d.actualProgress,
+ attendanceRate: d.attendanceRate,
+ assessment,
+ recommendations,
+ createdAt: now
+ };
+
+ if (!d.goal.checkIns) d.goal.checkIns = [];
+ d.goal.checkIns.push(checkIn);
+ d.goal.updatedAt = now;
+ results.push({ goalId: d.goal.id, title: d.goal.title, status: d.status, checkIn });
+ }
+
+ goals.updatedAt = now;
+ await writeFile(GOALS_FILE, JSON.stringify(goals, null, 2));
+
+ // Send Telegram notification
+ const statusEmoji = { 'on-track': '🟢', 'behind': '🟡', 'at-risk': '🔴' };
+ const summary = results.map(r => `${statusEmoji[r.status] || '⚪'} ${r.title}: ${r.status} (${r.checkIn.actualProgress}%/${r.checkIn.expectedProgress}%)`).join('\n');
+
+ await addNotification({
+ type: NOTIFICATION_TYPES.SYSTEM,
+ title: 'Goal Check-in',
+ message: `Weekly check-in for ${results.length} goal(s):\n${summary}`,
+ priority: results.some(r => r.status === 'at-risk') ? 'high' : 'medium'
+ });
+
+ console.log(`📊 Goal check-in complete: ${results.length} goals checked`);
+ return { checked: results.length, results };
+}
diff --git a/server/services/googleAuth.js b/server/services/googleAuth.js
index 28669bcdf1..551772353b 100644
--- a/server/services/googleAuth.js
+++ b/server/services/googleAuth.js
@@ -7,7 +7,7 @@ const AUTH_DIR = join(PATHS.calendar, 'google-auth');
const CREDENTIALS_FILE = join(AUTH_DIR, 'credentials.json');
const TOKENS_FILE = join(AUTH_DIR, 'tokens.json');
const SCOPES = [
- 'https://www.googleapis.com/auth/calendar.readonly',
+ 'https://www.googleapis.com/auth/calendar',
'https://www.googleapis.com/auth/gmail.modify'
];
export const OAUTH_REDIRECT_URI = `http://localhost:${process.env.PORT || 5555}/api/calendar/google/oauth/callback`;
@@ -118,12 +118,21 @@ export async function getAuthenticatedClient() {
return oAuth2Client;
}
+export function needsScopeUpgrade(tokens) {
+ if (!tokens?.scope) return true;
+ const scopes = tokens.scope.split(' ');
+ // Has readonly but not full calendar scope
+ return scopes.includes('https://www.googleapis.com/auth/calendar.readonly') &&
+ !scopes.includes('https://www.googleapis.com/auth/calendar');
+}
+
export async function getAuthStatus() {
const credentials = await getCredentials();
const tokens = await getTokens();
return {
hasCredentials: !!credentials?.clientId,
hasTokens: !!tokens?.access_token,
- expiryDate: tokens?.expiry_date ? new Date(tokens.expiry_date).toISOString() : null
+ expiryDate: tokens?.expiry_date ? new Date(tokens.expiry_date).toISOString() : null,
+ needsCalendarScopeUpgrade: needsScopeUpgrade(tokens)
};
}
diff --git a/server/services/identity.js b/server/services/identity.js
index 6d8e4e9106..cf5bc0d9a1 100644
--- a/server/services/identity.js
+++ b/server/services/identity.js
@@ -6,6 +6,7 @@ import { ServerError } from '../lib/errorHandler.js';
import { getGenomeSummary } from './genome.js';
import { getTasteProfile } from './taste-questionnaire.js';
import { getActivities } from './meatspaceCalendar.js';
+import { callProviderAISimple, parseLLMJSON } from '../lib/aiProvider.js';
const IDENTITY_DIR = PATHS.digitalTwin;
const IDENTITY_FILE = join(IDENTITY_DIR, 'identity.json');
@@ -700,6 +701,15 @@ export async function getGoals() {
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 (goal.targetDate === undefined) { goal.targetDate = null; needsSave = true; }
+ 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; }
+ // Lazy-migrate milestones with description and order
+ for (const ms of (goal.milestones || [])) {
+ if (ms.description === undefined) { ms.description = ''; needsSave = true; }
+ if (ms.order === undefined) { ms.order = 0; needsSave = true; }
+ }
}
if (needsSave) await saveJSON(GOALS_FILE, data);
return data;
@@ -733,7 +743,7 @@ export async function setBirthDate(birthDate) {
return goals;
}
-export async function createGoal({ title, description, horizon, category, parentId, tags }) {
+export async function createGoal({ title, description, horizon, category, parentId, tags, targetDate, timeBlockConfig }) {
const goals = await getGoals();
const longevity = await loadJSON(LONGEVITY_FILE, DEFAULT_LONGEVITY);
@@ -752,6 +762,11 @@ export async function createGoal({ title, description, horizon, category, parent
parentId: parentId || null,
tags: [...new Set((tags || []).map(t => t.trim()).filter(Boolean))],
linkedActivities: [],
+ linkedCalendars: [],
+ targetDate: targetDate || null,
+ timeBlockConfig: timeBlockConfig || null,
+ scheduledEvents: [],
+ checkIns: [],
urgency: null,
status: 'active',
milestones: [],
@@ -805,7 +820,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', 'targetDate', 'timeBlockConfig'];
for (const key of allowed) {
if (updates[key] !== undefined) goal[key] = updates[key];
}
@@ -1076,6 +1091,78 @@ export async function getGoalCalendarEvents(goalId, startDate, endDate) {
});
}
+// =============================================================================
+// AI Phase Planning
+// =============================================================================
+
+export async function generateGoalPhases(goalId, { providerId, model } = {}) {
+ const { getActiveProvider, getProviderById } = await import('./providers.js');
+ const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);
+ const goal = goals.goals.find(g => g.id === goalId);
+ if (!goal) throw new ServerError('Goal not found', { status: 404, code: 'NOT_FOUND' });
+ if (!goal.targetDate) throw new ServerError('Goal must have a target date to generate phases', { status: 400, code: 'MISSING_TARGET_DATE' });
+
+ 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 today = new Date().toISOString().slice(0, 10);
+ const prompt = `You are a goal planning assistant. Given a goal with a target completion date, generate 3-7 ordered phases that break this goal into achievable milestones.
+
+Goal title: ${goal.title}
+Goal description: ${goal.description || 'No description provided'}
+Today's date: ${today}
+Target completion date: ${goal.targetDate}
+
+Generate phases that:
+- Are ordered chronologically with evenly distributed target dates between now and the target date
+- Have clear, actionable titles
+- Include brief descriptions of what each phase involves
+- The last phase's target date should match or be near the goal's target date
+
+Respond with a JSON array only (no markdown fences, no explanation). Each element must have:
+- "title": string (phase name)
+- "description": string (1-2 sentences)
+- "targetDate": string (YYYY-MM-DD format)
+- "order": number (0-based index)`;
+
+ const result = await callProviderAISimple(provider, selectedModel, prompt, { max_tokens: 2000 });
+ if (result.error) throw new ServerError(`AI generation failed: ${result.error}`, { status: 502, code: 'AI_ERROR' });
+
+ let parsed;
+ try {
+ parsed = parseLLMJSON(result.text);
+ } catch (e) {
+ throw new ServerError(`AI returned invalid phase data: ${e.message}`, { status: 502, code: 'AI_PARSE_ERROR' });
+ }
+ if (!Array.isArray(parsed)) throw new ServerError('AI returned invalid phase data', { status: 502, code: 'AI_PARSE_ERROR' });
+
+ console.log(`🎯 Generated ${parsed.length} phases for goal "${goal.title}"`);
+ return parsed;
+}
+
+export async function acceptGoalPhases(goalId, phases) {
+ const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);
+ const goal = goals.goals.find(g => g.id === goalId);
+ if (!goal) throw new ServerError('Goal not found', { status: 404, code: 'NOT_FOUND' });
+
+ goal.milestones = phases.map((phase, idx) => ({
+ id: `ms-${uuidv4()}`,
+ title: phase.title,
+ description: phase.description || '',
+ targetDate: phase.targetDate || null,
+ order: phase.order ?? idx,
+ completedAt: null,
+ createdAt: new Date().toISOString()
+ }));
+
+ goal.updatedAt = new Date().toISOString();
+ goals.updatedAt = new Date().toISOString();
+ await saveJSON(GOALS_FILE, goals);
+ console.log(`🎯 Accepted ${phases.length} phases for goal "${goal.title}"`);
+ return goal;
+}
+
// =============================================================================
// Goal Progress Percentage
// =============================================================================
diff --git a/server/services/jobGates.js b/server/services/jobGates.js
index 011319dcc7..cf5d2fe9dc 100644
--- a/server/services/jobGates.js
+++ b/server/services/jobGates.js
@@ -51,8 +51,19 @@ async function brainReviewGate() {
* Registry of gate functions keyed by job ID.
* Jobs without a gate entry always run (no precondition).
*/
+async function goalCheckInGate() {
+ const { getGoals } = await import('./identity.js');
+ const data = await getGoals();
+ const activeWithTarget = (data.goals || []).filter(g => g.status === 'active' && g.targetDate);
+ if (activeWithTarget.length > 0) {
+ return { shouldRun: true, reason: `${activeWithTarget.length} active goal(s) with target dates`, context: { count: activeWithTarget.length } };
+ }
+ return { shouldRun: false, reason: 'No active goals with target dates' };
+}
+
const GATES = Object.assign(Object.create(null), {
- 'job-brain-review': brainReviewGate
+ 'job-brain-review': brainReviewGate,
+ 'job-goal-check-in': goalCheckInGate
});
/**