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: Google Calendar integration with MCP push sync, direct API, goal linking, and daily review
Adam Eivya4f7c19206c9
diff --git a/PLAN.md b/PLAN.mdindex 061e1d254f..6c5d1e4d19 100644--- a/PLAN.md+++ b/PLAN.md@@ -68,7 +68,11 @@ See [GOALS.md](./GOALS.md) for project goals and direction.- [ ] **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.-- [ ] **M48 P1-P4**: Google Calendar Integration - OAuth2, two-way event sync, chronotype-aware smart scheduling, CoS autonomous rescheduling, calendar UI with week/month views+- [x] **M48 P1-P5**: Google Calendar Integration - MCP push sync, subcalendar management, goal-calendar linking, daily review with auto-progress-logging, dormancy support+- [ ] **M48 P6**: Calendar Consolidation - Merge MeatSpace > Calendar (Life Calendar / "4000 Weeks") under top-level Calendar as a "Lifetime" sub-tab, eliminating the confusing dual-calendar navigation+- [x] **M48 P7**: UI-Triggered Google Calendar Sync - "Sync Google" button in Sync tab + "Discover Calendars" in Config tab, both spawn headless Claude CLI with MCP to fetch events/calendar list. Works as zero-config fallback using user's existing Claude MCP auth.+- [x] **M48 P8**: Direct Google Calendar API Sync - `googleapis` npm with OAuth2 setup in Config tab, sync method selector (Claude MCP vs Google API), tokens cached in `data/calendar/google-auth/` with auto-refresh+- [ ] **M48 P9**: Auto-Configure Google OAuth via CDP - "Auto-Configure" button in Config tab launches Google Cloud Console in PortOS CDP browser. User logs in manually, then a Playwright script automates: create project, enable Calendar API, configure OAuth consent screen (add user as test user), create Web app credentials with redirect URI, extract client ID/secret, save to PortOS, and initiate the OAuth consent flow. Reduces multi-step manual setup to one click + Google login.- [ ] **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- [ ] **M52**: Update Detection - Poll GitHub releases for new version tags, compare against local `package.json` version, surface update availability in dashboard and settings@@ -126,22 +130,11 @@ External notification delivery for critical events when not actively viewing the### M48: Google Calendar Integration-Shared Google OAuth2 foundation — `server/services/googleAuth.js` handles OAuth2 consent flow, token storage/refresh, scope management. Tokens stored in `data/google/auth.json`. Reused by both Calendar and Gmail.+**Completed (P1-P5):** MCP push sync architecture — instead of OAuth2 complexity, Google Calendar events are synced via Claude Code MCP tools pushing to PortOS endpoints. Subcalendar management with enable/disable/dormant states, goal-calendar linking with match patterns, daily review UI for confirming events and auto-logging progress, dormancy support for inactive calendars.-**Phases:**--- **P1: Calendar Read & OAuth** — Google OAuth2 service, calendar event listing, basic week/month calendar UI, settings page for Google connection-- **P2: Calendar Write & Sync** — Event CRUD (create/update/delete synced to Google), two-way incremental sync using Google's `syncToken`, conflict detection (last-writer-wins, Google as source of truth for external events), configurable sync interval (default 5min)-- **P3: Smart Scheduling & CoS** — Free slot finder API, chronotype-aware slot selection (reads `data/digital-twin/chronotype.json` for peak-focus windows), auto-schedule human tasks during optimal windows, CoS autonomous job `job-calendar-schedule` for rescheduling when conflicts arise-- **P4: Calendar UI Polish** — Week/day/month views, color coding by source/type, dashboard calendar widget (today's events), linked goal/todo indicators on events--**Data:** `data/google/auth.json` (OAuth tokens), `data/calendar/events.json` (local event cache with Google sync tokens), `data/calendar/config.json` (sync settings, working hours, chronotype preferences)--**Routes:** `GET/POST/PUT/DELETE /api/calendar/events`, `POST /api/calendar/sync`, `GET /api/calendar/free-slots`, `POST /api/calendar/schedule-task`, `GET /api/google/oauth/start`, `GET /api/google/oauth/callback`, `GET /api/google/status`--**Nav:** Top-level sidebar item "Calendar" (alphabetically between Chief of Staff and Dev Tools)+**Remaining:**-*Touches: new server/services/googleAuth.js, server/services/calendar.js, server/services/calendarScheduler.js, server/routes/google.js, server/routes/calendar.js, client/src/pages/Calendar.jsx, client/src/components/calendar/tabs/, Layout.jsx, autonomousJobs.js, data/digital-twin/chronotype.json*+- **P6: Calendar Consolidation** — MeatSpace > Calendar ("4000 Weeks" Life Calendar) and top-level Calendar are confusing dual navigation. Move the Life Calendar view under top-level Calendar as a "Lifetime" sub-tab. Remove the MeatSpace > Calendar nav entry. Ensure route `/calendar/lifetime` renders the existing Life Calendar component. Update Layout.jsx nav items accordingly.### M49: Life Goals & Todo Planning@@ -335,7 +328,7 @@ Three audit passes identified remaining items across architecture, bugs, code qu2. **M45**: Data Backup & Recovery — protect `./data/` from data loss3. **M50 P7-P9**: Messages — Digital Twin voice drafting, CoS automation, auto-send with AI review gate4. **M34 P5-P7**: Digital Twin — Multi-modal capture, advanced testing, personas-5. **M48 P1**: Google Calendar — OAuth2 foundation + calendar read+5. **M48 P6**: Calendar Consolidation — Move MeatSpace Life Calendar under top-level Calendar as "Lifetime" tab6. **M49 P1**: Life Goals — Enhanced goal model with todos and progress tracking7. **M47**: Push Notifications — Discord/Telegram alerts for agent completions and errors8. **M52**: Update Detection — GitHub release polling and update notificationdiff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 059ddc3590..43234ba718 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -110,6 +110,7 @@ const navItems = [{ to: '/calendar/config', label: 'Config', icon: Settings },{ to: '/calendar/day', label: 'Day', icon: Calendar },{ to: '/calendar/month', label: 'Month', icon: CalendarDays },+ { to: '/calendar/review', label: 'Review', icon: ClipboardList },{ to: '/calendar/sync', label: 'Sync', icon: RefreshCw },{ to: '/calendar/week', label: 'Week', icon: CalendarDays }]diff --git a/client/src/components/calendar/ConfigTab.jsx b/client/src/components/calendar/ConfigTab.jsxindex 28316f4f24..470df9c0f8 100644--- a/client/src/components/calendar/ConfigTab.jsx+++ b/client/src/components/calendar/ConfigTab.jsx@@ -1,16 +1,68 @@-import { useState } from 'react';-import { Plus, Trash2, RefreshCw, Globe } from 'lucide-react';+import { useState, useEffect } from 'react';+import { Plus, Trash2, RefreshCw, Globe, Calendar, Eye, EyeOff, ChevronDown, ChevronRight, Search, Key, ExternalLink } from 'lucide-react';import toast from 'react-hot-toast';import * as api from '../../services/api';-const TYPE_ICONS = { 'outlook-calendar': Globe };-const TYPE_LABELS = { 'outlook-calendar': 'Outlook Calendar (API)' };+const TYPE_ICONS = { 'outlook-calendar': Globe, 'google-calendar': Calendar };+const TYPE_LABELS = { 'outlook-calendar': 'Outlook Calendar (API)', 'google-calendar': 'Google Calendar (MCP Push)' };export default function ConfigTab({ accounts, setAccounts }) {const [showForm, setShowForm] = useState(false);const [form, setForm] = useState({ name: '', type: 'outlook-calendar', email: '' });const [saving, setSaving] = useState(false);const [deleting, setDeleting] = useState(null);+ const [expandedAccounts, setExpandedAccounts] = useState({});+ const [savingSubcals, setSavingSubcals] = useState(null);+ const [discovering, setDiscovering] = useState(null);+ const [googleAuth, setGoogleAuth] = useState(null);+ const [showOAuthSetup, setShowOAuthSetup] = useState(null);+ const [oauthForm, setOauthForm] = useState({ clientId: '', clientSecret: '' });+ const [savingOAuth, setSavingOAuth] = useState(false);++ const fetchGoogleAuth = async () => {+ const status = await api.getGoogleAuthStatus().catch(() => null);+ setGoogleAuth(status);+ };++ useEffect(() => { fetchGoogleAuth(); }, []);++ const handleSaveOAuthCredentials = async () => {+ if (!oauthForm.clientId || !oauthForm.clientSecret) return toast.error('Both Client ID and Client Secret are required');+ setSavingOAuth(true);+ const result = await api.saveGoogleAuthCredentials(oauthForm).catch(() => null);+ setSavingOAuth(false);+ if (!result) return toast.error('Failed to save credentials');+ toast.success('OAuth credentials saved');+ fetchGoogleAuth();+ const authResult = await api.getGoogleAuthUrl().catch(() => null);+ if (authResult?.url) {+ window.open(authResult.url, '_blank');+ toast.success('Complete authorization in the opened browser tab');+ }+ };++ const handleStartOAuth = async () => {+ const result = await api.getGoogleAuthUrl().catch(() => null);+ if (result?.url) {+ window.open(result.url, '_blank');+ toast.success('Complete authorization in the opened browser tab');+ } else {+ toast.error(result?.error || 'Failed to get auth URL');+ }+ };++ const handleClearGoogleAuth = async () => {+ await api.clearGoogleAuth().catch(() => null);+ toast.success('Google auth cleared');+ fetchGoogleAuth();+ };++ const handleSyncMethodChange = async (account, method) => {+ const result = await api.updateCalendarAccount(account.id, { syncMethod: method }).catch(() => null);+ if (!result) return toast.error('Failed to update sync method');+ setAccounts(prev => prev.map(a => a.id === account.id ? { ...a, syncMethod: method } : a));+ toast.success(`Sync method set to ${method === 'google-api' ? 'Google API' : 'Claude MCP'}`);+ };const handleCreate = async () => {if (!form.name) return toast.error('Name is required');@@ -22,6 +74,10 @@ export default function ConfigTab({ accounts, setAccounts }) {setForm({ name: '', type: 'outlook-calendar', email: '' });toast.success('Account created');setAccounts(prev => [...prev, result]);+ // Auto-expand google-calendar accounts so user can discover calendars+ if (form.type === 'google-calendar') {+ setExpandedAccounts(prev => ({ ...prev, [result.id]: true }));+ }};const handleDelete = async (id) => {@@ -40,9 +96,53 @@ export default function ConfigTab({ accounts, setAccounts }) {setAccounts(prev => prev.map(a => a.id === account.id ? { ...a, enabled: !a.enabled } : a));};+ const toggleExpand = (id) => {+ setExpandedAccounts(prev => ({ ...prev, [id]: !prev[id] }));+ };++ const handleSubcalendarToggle = async (account, calendarId, field, value) => {+ const subcalendars = (account.subcalendars || []).map(sc =>+ sc.calendarId === calendarId ? { ...sc, [field]: value } : sc+ );+ setSavingSubcals(account.id);+ const result = await api.updateSubcalendars(account.id, { subcalendars }).catch(() => null);+ setSavingSubcals(null);+ if (!result) return toast.error('Failed to update subcalendars');+ setAccounts(prev => prev.map(a => a.id === account.id ? { ...a, subcalendars } : a));+ };++ const handleDiscoverCalendars = async (account) => {+ setDiscovering(account.id);+ const useApi = account.syncMethod === 'google-api' && googleAuth?.hasTokens;+ const result = useApi+ ? await api.apiDiscoverCalendars(account.id).catch(() => null)+ : await api.mcpDiscoverCalendars(account.id).catch(() => null);+ setDiscovering(null);+ if (!result || result.error) {+ if (result?.error?.includes('spawn Claude')) {+ return toast.error('Claude CLI not found. Ensure Claude Code is installed and in your PATH.');+ }+ if (result?.error?.includes('OAuth')) {+ return toast.error('Google OAuth not configured. Set up credentials below.');+ }+ return;+ }+ toast.success(`Discovered ${result.calendars?.length || 0} calendars`);+ setAccounts(prev => prev.map(a => a.id === account.id ? { ...a, subcalendars: result.calendars } : a));+ };++ const handleEnableAll = async (account) => {+ const subcalendars = (account.subcalendars || []).map(sc => ({ ...sc, enabled: true, dormant: false }));+ setSavingSubcals(account.id);+ const result = await api.updateSubcalendars(account.id, { subcalendars }).catch(() => null);+ setSavingSubcals(null);+ if (!result) return toast.error('Failed to update');+ setAccounts(prev => prev.map(a => a.id === account.id ? { ...a, subcalendars } : a));+ toast.success('All calendars enabled');+ };+return (<div className="space-y-8">- {/* Accounts */}<section><div className="flex items-center justify-between mb-3"><h2 className="text-lg font-semibold text-white">Calendar Accounts</h2>@@ -75,18 +175,21 @@ export default function ConfigTab({ accounts, setAccounts }) {className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white focus:outline-none focus:border-port-accent"><option value="outlook-calendar">Outlook Calendar (API)</option>+ <option value="google-calendar">Google Calendar (MCP Push)</option></select></div>- <div>- <label className="block text-sm text-gray-400 mb-1">Email</label>- <input- type="email"- value={form.email}- onChange={(e) => setForm(f => ({ ...f, email: e.target.value }))}- placeholder="[email protected]"- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"- />- </div>+ {form.type === 'outlook-calendar' && (+ <div>+ <label className="block text-sm text-gray-400 mb-1">Email</label>+ <input+ type="email"+ value={form.email}+ onChange={(e) => setForm(f => ({ ...f, email: e.target.value }))}+ placeholder="[email protected]"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"+ />+ </div>+ )}<div className="flex gap-2"><buttononClick={handleCreate}@@ -116,49 +219,282 @@ export default function ConfigTab({ accounts, setAccounts }) {<div className="space-y-2">{accounts.map((account) => {const Icon = TYPE_ICONS[account.type] || Globe;+ const isExpanded = expandedAccounts[account.id];+ const isGoogle = account.type === 'google-calendar';+ const subcals = account.subcalendars || [];+ const enabledCount = subcals.filter(s => s.enabled && !s.dormant).length;return (- <div- key={account.id}- className="flex items-center justify-between p-4 bg-port-card rounded-lg border border-port-border"- >- <div className="flex items-center gap-3">- <Icon size={20} className={account.enabled ? 'text-port-accent' : 'text-gray-600'} />- <div>- <div className="text-sm font-medium text-white">{account.name}</div>- <div className="text-xs text-gray-500">- {TYPE_LABELS[account.type]} · {account.email || 'No email set'}- </div>- {account.lastSyncAt && (- <div className="text-xs text-gray-600">- Last sync: {new Date(account.lastSyncAt).toLocaleString()} ({account.lastSyncStatus})- </div>+ <div key={account.id} className="bg-port-card rounded-lg border border-port-border">+ <div className="flex items-center justify-between p-4">+ <div className="flex items-center gap-3">+ {isGoogle && (+ <button onClick={() => toggleExpand(account.id)} className="p-0.5 text-gray-500 hover:text-white">+ {isExpanded ? <ChevronDown size={16} /> : <ChevronRight size={16} />}+ </button>)}+ <Icon size={20} className={account.enabled ? 'text-port-accent' : 'text-gray-600'} />+ <div>+ <div className="text-sm font-medium text-white">{account.name}</div>+ <div className="text-xs text-gray-500">+ {TYPE_LABELS[account.type]} {account.email ? `· ${account.email}` : ''}+ {isGoogle && subcals.length > 0 && ` · ${enabledCount}/${subcals.length} active`}+ {isGoogle && subcals.length === 0 && ' · No calendars discovered'}+ </div>+ {account.lastSyncAt && (+ <div className="text-xs text-gray-600">+ Last sync: {new Date(account.lastSyncAt).toLocaleString()} ({account.lastSyncStatus})+ </div>+ )}+ </div>+ </div>+ <div className="flex items-center gap-2">+ <button+ onClick={() => handleToggle(account)}+ className={`px-2 py-1 rounded text-xs transition-colors ${+ account.enabled+ ? 'bg-port-success/20 text-port-success'+ : 'bg-gray-700 text-gray-400'+ }`}+ >+ {account.enabled ? 'Enabled' : 'Disabled'}+ </button>+ <button+ onClick={() => handleDelete(account.id)}+ disabled={deleting === account.id}+ className="p-1 text-gray-500 hover:text-port-error transition-colors"+ title="Delete account"+ >+ {deleting === account.id ? (+ <RefreshCw size={16} className="animate-spin" />+ ) : (+ <Trash2 size={16} />+ )}+ </button></div></div>- <div className="flex items-center gap-2">- <button- onClick={() => handleToggle(account)}- className={`px-2 py-1 rounded text-xs transition-colors ${- account.enabled- ? 'bg-port-success/20 text-port-success'- : 'bg-gray-700 text-gray-400'- }`}- >- {account.enabled ? 'Enabled' : 'Disabled'}- </button>- <button- onClick={() => handleDelete(account.id)}- disabled={deleting === account.id}- className="p-1 text-gray-500 hover:text-port-error transition-colors"- title="Delete account"- >- {deleting === account.id ? (- <RefreshCw size={16} className="animate-spin" />- ) : (- <Trash2 size={16} />- )}- </button>- </div>++ {/* Google Calendar expanded settings */}+ {isGoogle && isExpanded && (+ <div className="border-t border-port-border px-4 py-3 space-y-3">+ {/* Sync Method & OAuth Setup — first so user configures before discovering */}+ <div className="space-y-3">+ <div className="flex items-center justify-between">+ <span className="text-xs text-gray-500 font-medium">Sync Method</span>+ <select+ value={account.syncMethod || 'claude-mcp'}+ onChange={(e) => handleSyncMethodChange(account, e.target.value)}+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white"+ >+ <option value="claude-mcp">Claude MCP (zero config)</option>+ <option value="google-api">Google API (direct, faster)</option>+ </select>+ </div>++ {(account.syncMethod || 'claude-mcp') === 'claude-mcp' && (+ <div className="text-xs text-gray-600 px-2 py-1.5 bg-port-bg/50 rounded">+ Uses your Claude Code CLI with Google Calendar MCP integration.+ Requires <span className="text-gray-400">claude</span> CLI installed and Google Calendar connected in Claude > Settings > Integrations.+ </div>+ )}++ {account.syncMethod === 'google-api' && (+ <div className="space-y-2">+ {googleAuth?.hasCredentials && googleAuth?.hasTokens ? (+ <div className="flex items-center justify-between px-2 py-1.5 bg-port-success/5 rounded">+ <div className="flex items-center gap-1.5 text-xs text-port-success">+ <Key size={12} />+ <span>Google API authenticated</span>+ {googleAuth.expiryDate && (+ <span className="text-gray-600">+ (expires {new Date(googleAuth.expiryDate).toLocaleDateString()})+ </span>+ )}+ </div>+ <button+ onClick={handleClearGoogleAuth}+ className="px-2 py-0.5 text-xs rounded text-gray-600 hover:text-port-error hover:bg-gray-800"+ >+ Clear+ </button>+ </div>+ ) : googleAuth?.hasCredentials ? (+ <div className="space-y-2 px-2 py-1.5 bg-port-warning/5 rounded">+ <div className="text-xs text-port-warning">Credentials saved but not authorized yet.</div>+ <button+ onClick={handleStartOAuth}+ className="flex items-center gap-1 px-2.5 py-1 text-xs rounded bg-port-accent/20 text-port-accent hover:bg-port-accent/30"+ >+ <ExternalLink size={12} /> Authorize with Google+ </button>+ </div>+ ) : (+ <div className="space-y-2">+ <div className="text-xs text-gray-500">+ Connect directly to Google Calendar API for fast, reliable syncing without Claude.+ </div>+ <details className="text-xs text-gray-600" open>+ <summary className="cursor-pointer text-gray-400 hover:text-white font-medium">How to set up Google OAuth</summary>+ <div className="mt-2 space-y-2 pl-1">+ <div className="font-medium text-gray-400">Step 1: Create a Google Cloud Project</div>+ <ol className="space-y-0.5 pl-4 list-decimal text-gray-600">+ <li>Go to <span className="text-gray-400">console.cloud.google.com</span></li>+ <li>Click the project dropdown at the top → <span className="text-gray-400">New Project</span></li>+ <li>Name it anything (e.g. "PortOS Calendar") → <span className="text-gray-400">Create</span></li>+ </ol>++ <div className="font-medium text-gray-400">Step 2: Enable the Calendar API</div>+ <ol className="space-y-0.5 pl-4 list-decimal text-gray-600">+ <li>In your project, go to <span className="text-gray-400">APIs & Services → Library</span></li>+ <li>Search for <span className="text-gray-400">Google Calendar API</span> → click it → <span className="text-gray-400">Enable</span></li>+ </ol>++ <div className="font-medium text-gray-400">Step 3: Configure OAuth Consent Screen</div>+ <ol className="space-y-0.5 pl-4 list-decimal text-gray-600">+ <li>Go to <span className="text-gray-400">APIs & Services → OAuth consent screen</span></li>+ <li>Select <span className="text-gray-400">External</span> → Create</li>+ <li>Fill in app name (e.g. "PortOS"), your email for support/developer contact</li>+ <li>Skip scopes, add your Google email as a <span className="text-gray-400">Test user</span></li>+ <li>Save and continue through the remaining steps</li>+ </ol>++ <div className="font-medium text-gray-400">Step 4: Create OAuth Credentials</div>+ <ol className="space-y-0.5 pl-4 list-decimal text-gray-600">+ <li>Go to <span className="text-gray-400">APIs & Services → Credentials</span></li>+ <li>Click <span className="text-gray-400">+ Create Credentials → OAuth client ID</span></li>+ <li>Application type: <span className="text-gray-400">Web application</span></li>+ <li>Under <span className="text-gray-400">Authorized redirect URIs</span>, add:</li>+ </ol>+ <code className="block px-2 py-1 bg-port-bg rounded text-gray-400 select-all">+ http://localhost:5555/api/calendar/google/oauth/callback+ </code>+ <ol className="space-y-0.5 pl-4 list-decimal text-gray-600" start={5}>+ <li>Click <span className="text-gray-400">Create</span>, then copy the Client ID and Client Secret below</li>+ </ol>+ </div>+ </details>+ <div className="space-y-1.5 pt-1">+ <input+ type="text"+ value={oauthForm.clientId}+ onChange={e => setOauthForm(f => ({ ...f, clientId: e.target.value }))}+ placeholder="Client ID (e.g. 123456789-abc.apps.googleusercontent.com)"+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white placeholder-gray-600"+ />+ <input+ type="password"+ value={oauthForm.clientSecret}+ onChange={e => setOauthForm(f => ({ ...f, clientSecret: e.target.value }))}+ placeholder="Client Secret (e.g. GOCSPX-...)"+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white placeholder-gray-600"+ />+ <button+ onClick={handleSaveOAuthCredentials}+ disabled={savingOAuth || !oauthForm.clientId || !oauthForm.clientSecret}+ className="flex items-center gap-1 px-2.5 py-1 text-xs rounded bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50"+ >+ {savingOAuth ? 'Saving...' : 'Save & Authorize'}+ </button>+ </div>+ </div>+ )}+ </div>+ )}+ </div>++ {/* Sub-calendars */}+ <div className="border-t border-port-border pt-3 space-y-2">+ <div className="flex items-center justify-between">+ <div className="text-xs text-gray-500 font-medium">+ Sub-calendars {subcals.length > 0 && `(${subcals.length})`}+ </div>+ <div className="flex items-center gap-2">+ {subcals.length > 0 && (+ <button+ onClick={() => handleEnableAll(account)}+ disabled={savingSubcals === account.id}+ className="px-2 py-0.5 text-xs rounded text-gray-500 hover:text-white hover:bg-gray-800"+ >+ Enable All+ </button>+ )}+ <button+ onClick={() => handleDiscoverCalendars(account)}+ disabled={discovering === account.id}+ className="flex items-center gap-1 px-2 py-0.5 text-xs rounded bg-port-accent/20 text-port-accent hover:bg-port-accent/30 disabled:opacity-50"+ >+ {discovering === account.id ? (+ <RefreshCw size={12} className="animate-spin" />+ ) : (+ <Search size={12} />+ )}+ {discovering === account.id ? 'Discovering...' : subcals.length > 0 ? 'Refresh' : 'Discover Calendars'}+ </button>+ </div>+ </div>++ {subcals.length === 0 && discovering !== account.id && (+ <div className="text-xs text-gray-600 py-2">+ Click "Discover Calendars" to fetch your Google Calendar list.+ </div>+ )}++ {subcals.map(sc => (+ <div+ key={sc.calendarId}+ className={`flex items-center justify-between py-1.5 px-2 rounded ${+ sc.dormant ? 'opacity-50' : ''+ }`}+ >+ <div className="flex items-center gap-2 min-w-0">+ {sc.color && (+ <div className="w-3 h-3 rounded-full shrink-0" style={{ backgroundColor: sc.color }} />+ )}+ <div className="min-w-0">+ <div className={`text-xs font-medium truncate ${sc.dormant ? 'text-gray-500' : 'text-gray-300'}`}>+ {sc.name}+ </div>+ <div className="text-xs text-gray-600 truncate">{sc.calendarId}</div>+ </div>+ </div>+ <div className="flex items-center gap-1.5 shrink-0">+ {sc.dormant ? (+ <button+ onClick={() => handleSubcalendarToggle(account, sc.calendarId, 'dormant', false)}+ disabled={savingSubcals === account.id}+ className="px-2 py-0.5 text-xs rounded bg-port-accent/20 text-port-accent hover:bg-port-accent/30"+ >+ Activate+ </button>+ ) : (+ <>+ <button+ onClick={() => handleSubcalendarToggle(account, sc.calendarId, 'enabled', !sc.enabled)}+ disabled={savingSubcals === account.id}+ className="p-0.5"+ title={sc.enabled ? 'Disable' : 'Enable'}+ >+ {sc.enabled ? (+ <Eye size={14} className="text-port-success" />+ ) : (+ <EyeOff size={14} className="text-gray-600" />+ )}+ </button>+ <button+ onClick={() => handleSubcalendarToggle(account, sc.calendarId, 'dormant', true)}+ disabled={savingSubcals === account.id}+ className="px-1.5 py-0.5 text-xs rounded text-gray-600 hover:text-gray-400 hover:bg-gray-800"+ title="Mark dormant"+ >+ Dormant+ </button>+ </>+ )}+ </div>+ </div>+ ))}+ </div>+ </div>+ )}</div>);})}diff --git a/client/src/components/calendar/DayView.jsx b/client/src/components/calendar/DayView.jsxindex 971fcfb5f6..a487907bc3 100644--- a/client/src/components/calendar/DayView.jsx+++ b/client/src/components/calendar/DayView.jsx@@ -4,7 +4,12 @@ import * as api from '../../services/api';import socket from '../../services/socket';import EventDetail from './EventDetail';-const HOURS = Array.from({ length: 17 }, (_, i) => i + 6); // 6am to 10pm+const START_HOUR = 6;+const END_HOUR = 23;+const HOURS = Array.from({ length: END_HOUR - START_HOUR }, (_, i) => i + START_HOUR); // 6am to 10pm+const PX_PER_HOUR = 64;+const PX_PER_15MIN = PX_PER_HOUR / 4; // 16px per 15-min block+const START_MINUTES = START_HOUR * 60;function formatHour(hour) {if (hour === 0) return '12 AM';@@ -18,8 +23,8 @@ function getEventPosition(event) {const end = new Date(event.endTime);const startMinutes = start.getHours() * 60 + start.getMinutes();const endMinutes = end.getHours() * 60 + end.getMinutes();- const top = ((startMinutes - 360) / 60) * 64; // 64px per hour, starting at 6am (360min)- const height = Math.max(((endMinutes - startMinutes) / 60) * 64, 24);+ const top = ((startMinutes - START_MINUTES) / 60) * PX_PER_HOUR;+ const height = Math.max(((endMinutes - startMinutes) / 60) * PX_PER_HOUR, PX_PER_15MIN);return { top: Math.max(top, 0), height };}@@ -74,7 +79,7 @@ export default function DayView() {const now = new Date();const isToday = date.toDateString() === now.toDateString();const nowMinutes = now.getHours() * 60 + now.getMinutes();- const nowTop = ((nowMinutes - 360) / 60) * 64;+ const nowTop = ((nowMinutes - START_MINUTES) / 60) * PX_PER_HOUR;return (<div className="space-y-4">@@ -119,11 +124,21 @@ export default function DayView() {{/* Time grid */}<div className="relative border border-port-border rounded-lg overflow-hidden bg-port-card">{HOURS.map(hour => (- <div key={hour} className="flex border-b border-port-border last:border-b-0" style={{ height: 64 }}>- <div className="w-16 shrink-0 text-xs text-gray-500 text-right pr-2 pt-1">- {formatHour(hour)}+ <div key={hour} className="border-b border-port-border last:border-b-0" style={{ height: PX_PER_HOUR }}>+ <div className="flex h-full">+ <div className="w-16 shrink-0 text-xs text-gray-500 text-right pr-2 pt-1">+ {formatHour(hour)}+ </div>+ <div className="flex-1 border-l border-port-border flex flex-col">+ {[0, 1, 2, 3].map(q => (+ <div+ key={q}+ className={`flex-1 ${q > 0 ? 'border-t border-port-border/30' : ''}`}+ style={{ height: PX_PER_15MIN }}+ />+ ))}+ </div></div>- <div className="flex-1 border-l border-port-border" /></div>))}@@ -149,7 +164,7 @@ export default function DayView() {})}{/* Current time line */}- {isToday && nowTop >= 0 && nowTop <= HOURS.length * 64 && (+ {isToday && nowTop >= 0 && nowTop <= HOURS.length * PX_PER_HOUR && (<div className="absolute left-0 right-0 flex items-center pointer-events-none" style={{ top: nowTop }}><div className="w-2 h-2 rounded-full bg-port-error -ml-1" /><div className="flex-1 h-px bg-port-error" />diff --git a/client/src/components/calendar/ReviewTab.jsx b/client/src/components/calendar/ReviewTab.jsxnew file mode 100644index 0000000000..1f4ac99f24--- /dev/null+++ b/client/src/components/calendar/ReviewTab.jsx@@ -0,0 +1,367 @@+import { useState, useEffect, useCallback } from 'react';+import { Check, X, ChevronLeft, ChevronRight, Clock, Target, AlertTriangle, RefreshCw } from 'lucide-react';+import toast from 'react-hot-toast';+import * as api from '../../services/api';++function formatDuration(minutes) {+ if (!minutes) return '';+ if (minutes >= 60) {+ const h = Math.floor(minutes / 60);+ const m = minutes % 60;+ return m ? `${h}h ${m}m` : `${h}h`;+ }+ return `${minutes}m`;+}++function formatTime(isoString) {+ if (!isoString) return '';+ const d = new Date(isoString);+ return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });+}++export default function ReviewTab() {+ const [date, setDate] = useState(new Date().toISOString().slice(0, 10));+ const [review, setReview] = useState(null);+ const [loading, setLoading] = useState(true);+ const [confirming, setConfirming] = useState(null);+ const [editingEvent, setEditingEvent] = useState(null);+ const [editForm, setEditForm] = useState({ durationMinutes: '', note: '', goalId: '' });++ const fetchReview = useCallback(async () => {+ setLoading(true);+ const data = await api.getDailyReview(date).catch(() => null);+ setReview(data);+ setLoading(false);+ }, [date]);++ useEffect(() => {+ fetchReview();+ }, [fetchReview]);++ const changeDate = (delta) => {+ const d = new Date(date + 'T12:00:00');+ d.setDate(d.getDate() + delta);+ setDate(d.toISOString().slice(0, 10));+ };++ const handleConfirm = async (event, happened) => {+ const eventId = event.id || event.externalId;+ setConfirming(eventId);++ // If event has matching goals and happened, show edit form+ if (happened && event.matchingGoals?.length > 0 && !editingEvent) {+ const startTime = event.startTime ? new Date(event.startTime) : null;+ const endTime = event.endTime ? new Date(event.endTime) : null;+ const durationMinutes = startTime && endTime && !event.isAllDay+ ? Math.round((endTime - startTime) / 60000)+ : '';+ setEditingEvent(eventId);+ setEditForm({+ durationMinutes: durationMinutes || '',+ note: event.title || '',+ goalId: event.matchingGoals[0]?.goalId || ''+ });+ setConfirming(null);+ return;+ }++ const data = { eventId, happened };+ if (happened && editingEvent === eventId) {+ data.goalId = editForm.goalId || undefined;+ data.durationMinutes = editForm.durationMinutes ? parseInt(editForm.durationMinutes, 10) : undefined;+ data.note = editForm.note || undefined;+ }++ const result = await api.confirmDailyReviewEvent(date, data).catch(() => null);+ setConfirming(null);+ setEditingEvent(null);++ if (!result) return toast.error('Failed to confirm event');+ if (result.progressEntry) {+ toast.success('Event confirmed & progress logged');+ } else {+ toast.success(happened ? 'Event confirmed' : 'Event skipped');+ }+ fetchReview();+ };++ const handleConfirmWithEdit = async (event) => {+ const eventId = event.id || event.externalId;+ setConfirming(eventId);++ const data = {+ eventId,+ happened: true,+ goalId: editForm.goalId || undefined,+ durationMinutes: editForm.durationMinutes ? parseInt(editForm.durationMinutes, 10) : undefined,+ note: editForm.note || undefined+ };++ const result = await api.confirmDailyReviewEvent(date, data).catch(() => null);+ setConfirming(null);+ setEditingEvent(null);++ if (!result) return toast.error('Failed to confirm event');+ toast.success(result.progressEntry ? 'Event confirmed & progress logged' : 'Event confirmed');+ fetchReview();+ };++ const isToday = date === new Date().toISOString().slice(0, 10);+ const isSyncStale = review?.lastSyncAt+ ? (Date.now() - new Date(review.lastSyncAt).getTime()) > 12 * 60 * 60 * 1000+ : true;++ if (loading) {+ return (+ <div className="flex items-center justify-center py-12">+ <RefreshCw className="w-6 h-6 text-port-accent animate-spin" />+ </div>+ );+ }++ return (+ <div className="space-y-4 max-w-3xl">+ {/* Date Navigation */}+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2">+ <button onClick={() => changeDate(-1)} className="p-1.5 rounded hover:bg-port-card text-gray-400 hover:text-white">+ <ChevronLeft size={18} />+ </button>+ <input+ type="date"+ value={date}+ onChange={e => setDate(e.target.value)}+ className="bg-port-bg border border-port-border rounded px-3 py-1.5 text-sm text-white focus:outline-none focus:border-port-accent"+ />+ <button onClick={() => changeDate(1)} className="p-1.5 rounded hover:bg-port-card text-gray-400 hover:text-white">+ <ChevronRight size={18} />+ </button>+ {!isToday && (+ <button+ onClick={() => setDate(new Date().toISOString().slice(0, 10))}+ className="px-2 py-1 text-xs rounded bg-port-accent/20 text-port-accent"+ >+ Today+ </button>+ )}+ </div>+ {isSyncStale && (+ <div className="flex items-center gap-1.5 text-xs text-port-warning">+ <AlertTriangle size={14} />+ <span>{review?.lastSyncAt ? 'Sync data may be stale' : 'No sync data'}</span>+ </div>+ )}+ </div>++ {/* Summary */}+ {review && (+ <div className="flex gap-4 text-xs">+ <span className="text-gray-500">{review.summary.totalEvents} events</span>+ {review.summary.confirmed > 0 && (+ <span className="text-port-success">{review.summary.confirmed} confirmed</span>+ )}+ {review.summary.skipped > 0 && (+ <span className="text-gray-500">{review.summary.skipped} skipped</span>+ )}+ {review.summary.unreviewed > 0 && (+ <span className="text-port-accent">{review.summary.unreviewed} to review</span>+ )}+ {review.progressEntries?.length > 0 && (+ <span className="text-port-accent">+ {review.progressEntries.reduce((sum, e) => sum + (e.durationMinutes || 0), 0)}min logged+ </span>+ )}+ </div>+ )}++ {/* Events */}+ {(!review?.events?.length) ? (+ <div className="text-center py-12 text-gray-500">+ <p>No events for this date</p>+ <p className="text-sm mt-1">Sync your calendar to see events here</p>+ </div>+ ) : (+ <div className="space-y-2">+ {review.events+ .sort((a, b) => {+ if (a.isAllDay && !b.isAllDay) return -1;+ if (!a.isAllDay && b.isAllDay) return 1;+ return (a.startTime || '').localeCompare(b.startTime || '');+ })+ .map(event => {+ const eventId = event.id || event.externalId;+ const isConfirmed = event.confirmation?.happened === true;+ const isSkipped = event.confirmation?.happened === false;+ const isReviewed = isConfirmed || isSkipped;+ const isEditing = editingEvent === eventId;++ return (+ <div+ key={eventId}+ className={`p-3 rounded-lg border transition-colors ${+ isConfirmed+ ? 'bg-port-success/5 border-port-success/30'+ : isSkipped+ ? 'bg-gray-900/50 border-gray-700 opacity-60'+ : 'bg-port-card border-port-border'+ }`}+ >+ <div className="flex items-start justify-between gap-3">+ <div className="flex items-start gap-2 min-w-0 flex-1">+ {event.subcalendarColor && (+ <div+ className="w-2 h-2 rounded-full mt-1.5 shrink-0"+ style={{ backgroundColor: event.subcalendarColor }}+ />+ )}+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2">+ <span className={`text-sm font-medium ${isSkipped ? 'line-through text-gray-500' : 'text-white'}`}>+ {event.title}+ </span>+ {event.matchingGoals?.length > 0 && (+ <Target size={12} className="text-port-accent shrink-0" />+ )}+ </div>+ <div className="flex items-center gap-2 text-xs text-gray-500 mt-0.5">+ {event.isAllDay ? (+ <span>All day</span>+ ) : (+ <span>{formatTime(event.startTime)} - {formatTime(event.endTime)}</span>+ )}+ {event.subcalendarName && (+ <span>· {event.subcalendarName}</span>+ )}+ {event.source && event.source !== 'google-calendar' && (+ <span>· {event.source}</span>+ )}+ </div>+ {event.location && (+ <div className="text-xs text-gray-600 mt-0.5">{event.location}</div>+ )}+ {event.matchingGoals?.length > 0 && (+ <div className="flex flex-wrap gap-1 mt-1">+ {event.matchingGoals.map(mg => (+ <span key={mg.goalId} className="text-xs px-1.5 py-0.5 rounded bg-port-accent/10 text-port-accent">+ {mg.goalTitle}+ </span>+ ))}+ </div>+ )}+ </div>+ </div>++ {!isReviewed && !isEditing && (+ <div className="flex items-center gap-1 shrink-0">+ <button+ onClick={() => handleConfirm(event, true)}+ disabled={confirming === eventId}+ className="p-1.5 rounded hover:bg-port-success/20 text-gray-500 hover:text-port-success transition-colors"+ title="Confirm - it happened"+ >+ <Check size={16} />+ </button>+ <button+ onClick={() => handleConfirm(event, false)}+ disabled={confirming === eventId}+ className="p-1.5 rounded hover:bg-red-500/20 text-gray-500 hover:text-red-400 transition-colors"+ title="Skip - didn't happen"+ >+ <X size={16} />+ </button>+ </div>+ )}++ {isReviewed && (+ <div className="shrink-0">+ {isConfirmed ? (+ <Check size={16} className="text-port-success" />+ ) : (+ <X size={16} className="text-gray-600" />+ )}+ </div>+ )}+ </div>++ {/* Edit form for goal-linked events */}+ {isEditing && (+ <div className="mt-2 pt-2 border-t border-port-border space-y-2">+ <div className="text-xs text-gray-400">Log progress for this event:</div>+ <div className="flex gap-2">+ <select+ value={editForm.goalId}+ onChange={e => setEditForm(f => ({ ...f, goalId: e.target.value }))}+ className="flex-1 bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white"+ >+ <option value="">No goal</option>+ {event.matchingGoals?.map(mg => (+ <option key={mg.goalId} value={mg.goalId}>{mg.goalTitle}</option>+ ))}+ </select>+ <div className="flex items-center gap-1">+ <Clock size={12} className="text-gray-500" />+ <input+ type="number"+ value={editForm.durationMinutes}+ onChange={e => setEditForm(f => ({ ...f, durationMinutes: e.target.value }))}+ placeholder="min"+ min="1"+ max="1440"+ className="w-16 bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white"+ />+ </div>+ </div>+ <input+ type="text"+ value={editForm.note}+ onChange={e => setEditForm(f => ({ ...f, note: e.target.value }))}+ placeholder="Note (optional)"+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white"+ />+ <div className="flex gap-1.5">+ <button+ onClick={() => handleConfirmWithEdit(event)}+ disabled={confirming === eventId}+ className="px-2.5 py-1 text-xs rounded bg-port-success/20 text-port-success hover:bg-port-success/30"+ >+ Confirm+ </button>+ <button+ onClick={() => { setEditingEvent(null); }}+ className="px-2.5 py-1 text-xs rounded bg-port-border text-gray-400"+ >+ Cancel+ </button>+ </div>+ </div>+ )}+ </div>+ );+ })}+ </div>+ )}++ {/* Progress Entries */}+ {review?.progressEntries?.length > 0 && (+ <div>+ <h3 className="text-sm font-medium text-gray-400 mb-2">Progress Logged Today</h3>+ <div className="space-y-1">+ {review.progressEntries.map(entry => (+ <div key={entry.id} className="flex items-center gap-2 text-xs py-1">+ <Target size={12} className="text-port-accent shrink-0" />+ <span className="text-gray-400">{entry.goalTitle}</span>+ <span className="text-gray-300">{entry.note}</span>+ {entry.durationMinutes && (+ <span className="text-gray-500 flex items-center gap-0.5">+ <Clock size={10} />+ {formatDuration(entry.durationMinutes)}+ </span>+ )}+ </div>+ ))}+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/calendar/SyncTab.jsx b/client/src/components/calendar/SyncTab.jsxindex 30e8ff99d4..6888ecf8ec 100644--- a/client/src/components/calendar/SyncTab.jsx+++ b/client/src/components/calendar/SyncTab.jsx@@ -1,5 +1,5 @@import { useState, useEffect, useCallback } from 'react';-import { RefreshCw, AlertCircle, Trash2, TestTube } from 'lucide-react';+import { RefreshCw, AlertCircle, Trash2, TestTube, Calendar } from 'lucide-react';import toast from 'react-hot-toast';import * as api from '../../services/api';import socket from '../../services/socket';@@ -8,6 +8,7 @@ export default function SyncTab({ accounts, onRefresh }) {const [syncing, setSyncing] = useState({});const [tokenStatus, setTokenStatus] = useState(null);const [tokenLoading, setTokenLoading] = useState(true);+ const [mcpProgress, setMcpProgress] = useState(null);const fetchTokenStatus = useCallback(async () => {const data = await api.getCalendarTokenStatus().catch(() => null);@@ -31,14 +32,20 @@ export default function SyncTab({ accounts, onRefresh }) {toast.error(`Calendar sync failed: ${error ?? 'unknown error'}`);};+ const onSyncProgress = ({ accountId, message }) => {+ setMcpProgress(message);+ };+socket.on('calendar:sync:started', onSyncStarted);socket.on('calendar:sync:completed', onSyncCompleted);socket.on('calendar:sync:failed', onSyncFailed);+ socket.on('calendar:sync:progress', onSyncProgress);return () => {socket.off('calendar:sync:started', onSyncStarted);socket.off('calendar:sync:completed', onSyncCompleted);socket.off('calendar:sync:failed', onSyncFailed);+ socket.off('calendar:sync:progress', onSyncProgress);};}, [fetchTokenStatus, onRefresh]);@@ -49,6 +56,26 @@ export default function SyncTab({ accounts, onRefresh }) {});};+ const handleGoogleSync = async (account) => {+ setSyncing(prev => ({ ...prev, [account.id]: 'syncing' }));+ setMcpProgress('Starting Google Calendar sync...');++ const useApi = account.syncMethod === 'google-api';+ const result = useApi+ ? await api.apiSyncGoogleCalendar(account.id).catch(() => null)+ : await api.mcpSyncGoogleCalendar(account.id).catch(() => null);++ setMcpProgress(null);+ if (!result || result.error) {+ setSyncing(prev => ({ ...prev, [account.id]: null }));+ if (result?.error?.includes('spawn Claude')) {+ toast.error('Claude CLI not found. Ensure Claude Code is installed and in your PATH.');+ } else if (result?.error?.includes('OAuth')) {+ toast.error('Google OAuth not configured. Set up in Config tab.');+ }+ }+ };+const handleTestToken = async (provider) => {const result = await api.testCalendarToken(provider).catch(() => null);if (result?.token) {@@ -95,7 +122,21 @@ export default function SyncTab({ accounts, onRefresh }) {</span>)}{syncing[account.id] === 'syncing' ? (- <RefreshCw size={16} className="text-port-accent animate-spin" />+ <div className="flex items-center gap-2">+ <RefreshCw size={16} className="text-port-accent animate-spin" />+ {mcpProgress && account.type === 'google-calendar' && (+ <span className="text-xs text-gray-500">{mcpProgress}</span>+ )}+ </div>+ ) : account.type === 'google-calendar' ? (+ <button+ onClick={() => handleGoogleSync(account)}+ disabled={!account.enabled}+ className="flex items-center gap-1 px-3 py-1.5 bg-port-accent/10 text-port-accent rounded text-sm hover:bg-port-accent/20 transition-colors disabled:opacity-50"+ title={account.syncMethod === 'google-api' ? 'Sync via Google API' : 'Sync via Claude MCP'}+ >+ <Calendar size={14} /> {account.syncMethod === 'google-api' ? 'Sync (API)' : 'Sync (Claude)'}+ </button>) : (<buttononClick={() => handleSync(account.id)}diff --git a/client/src/components/goals/GoalDetailPanel.jsx b/client/src/components/goals/GoalDetailPanel.jsxindex 5beea8f8eb..d1ff21519f 100644--- a/client/src/components/goals/GoalDetailPanel.jsx+++ b/client/src/components/goals/GoalDetailPanel.jsx@@ -1,6 +1,6 @@import { useState, useEffect } from 'react';import {- Target, X, Check, Trash2, Milestone, Calendar, Clock,+ Target, X, Check, Trash2, Milestone, Calendar, CalendarDays, Clock,Heart, DollarSign, Lightbulb, Users, Flame, AlertTriangle, Tag,Link2, Unlink, Activity, Plus, NotebookPen} from 'lucide-react';@@ -39,11 +39,28 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh })const [showProgressForm, setShowProgressForm] = useState(false);const todayISO = new Date().toISOString().slice(0, 10);const [progressForm, setProgressForm] = useState({ date: todayISO, note: '', durationMinutes: '' });+ const [subcalendars, setSubcalendars] = useState([]);+ const [selectedCalendar, setSelectedCalendar] = useState('');+ const [calendarMatchPattern, setCalendarMatchPattern] = useState('');useEffect(() => {api.getActivities().then(setActivities).catch(() => {});}, []);+ useEffect(() => {+ api.getCalendarAccounts().then(accounts => {+ const scs = [];+ for (const account of (accounts || [])) {+ for (const sc of (account.subcalendars || [])) {+ if (sc.enabled && !sc.dormant) {+ scs.push({ ...sc, accountName: account.name });+ }+ }+ }+ setSubcalendars(scs);+ }).catch(() => {});+ }, []);+if (!goal) return null;const cat = CATEGORY_CONFIG[goal.category] || CATEGORY_CONFIG.mastery;@@ -132,6 +149,25 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh })onRefresh();};+ const handleLinkCalendar = async () => {+ if (!selectedCalendar) return;+ const sc = subcalendars.find(s => s.calendarId === selectedCalendar);+ if (!sc) return;+ await api.linkGoalCalendar(goal.id, {+ subcalendarId: sc.calendarId,+ subcalendarName: sc.name,+ matchPattern: calendarMatchPattern+ });+ setSelectedCalendar('');+ setCalendarMatchPattern('');+ onRefresh();+ };++ const handleUnlinkCalendar = async (subcalendarId) => {+ await api.unlinkGoalCalendar(goal.id, subcalendarId);+ onRefresh();+ };+const addTag = () => {const tag = tagInput.trim().slice(0, MAX_TAG_LENGTH);if (tag && form.tags.length < MAX_TAGS && !form.tags.includes(tag)) {@@ -543,6 +579,69 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh }))}</div>+ {/* Linked Calendars */}+ <div>+ <div className="flex items-center gap-1 mb-2">+ <CalendarDays className="w-3.5 h-3.5 text-gray-500" />+ <span className="text-xs font-medium text-gray-400">+ Calendars ({goal.linkedCalendars?.length || 0})+ </span>+ </div>+ {goal.linkedCalendars?.length > 0 && (+ <div className="space-y-1 mb-2">+ {goal.linkedCalendars.map(lc => (+ <div key={lc.subcalendarId} className="flex items-center gap-2 text-xs">+ <span className="text-gray-300 flex-1 truncate">{lc.subcalendarName}</span>+ {lc.matchPattern && (+ <span className="text-gray-600 truncate max-w-[80px]" title={`Pattern: ${lc.matchPattern}`}>+ /{lc.matchPattern}/+ </span>+ )}+ <button+ onClick={() => handleUnlinkCalendar(lc.subcalendarId)}+ className="p-0.5 text-gray-600 hover:text-red-400"+ title="Unlink"+ >+ <Unlink className="w-3 h-3" />+ </button>+ </div>+ ))}+ </div>+ )}+ {subcalendars.length > 0 && (+ <div className="space-y-1">+ <div className="flex gap-1">+ <select+ value={selectedCalendar}+ onChange={e => setSelectedCalendar(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 calendar...</option>+ {subcalendars+ .filter(sc => !goal.linkedCalendars?.some(lc => lc.subcalendarId === sc.calendarId))+ .map(sc => <option key={sc.calendarId} value={sc.calendarId}>{sc.name}</option>)}+ </select>+ <button+ onClick={handleLinkCalendar}+ disabled={!selectedCalendar}+ className="px-2 py-1 text-xs rounded bg-port-accent/20 text-port-accent disabled:opacity-50"+ >+ Link+ </button>+ </div>+ {selectedCalendar && (+ <input+ type="text"+ value={calendarMatchPattern}+ onChange={e => setCalendarMatchPattern(e.target.value)}+ placeholder="Match pattern (optional)"+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white"+ />+ )}+ </div>+ )}+ </div>+{/* Actions */}<div className="flex gap-2 pt-2 border-t border-port-border"><buttondiff --git a/client/src/pages/Calendar.jsx b/client/src/pages/Calendar.jsxindex eba44627e3..ccbdf42e2a 100644--- a/client/src/pages/Calendar.jsx+++ b/client/src/pages/Calendar.jsx@@ -1,5 +1,5 @@import { useParams, useNavigate } from 'react-router-dom';-import { CalendarDays, Calendar as CalendarIcon, Columns, LayoutGrid, RefreshCw, Settings } from 'lucide-react';+import { CalendarDays, Calendar as CalendarIcon, ClipboardList, Columns, LayoutGrid, RefreshCw, Settings } from 'lucide-react';import { useState, useEffect, useCallback } from 'react';import * as api from '../services/api';@@ -8,6 +8,7 @@ import DayView from '../components/calendar/DayView';import WeekView from '../components/calendar/WeekView';import MonthView from '../components/calendar/MonthView';import ConfigTab from '../components/calendar/ConfigTab';+import ReviewTab from '../components/calendar/ReviewTab';import SyncTab from '../components/calendar/SyncTab';const TABS = [@@ -15,6 +16,7 @@ const TABS = [{ id: 'day', label: 'Day', icon: CalendarIcon },{ id: 'week', label: 'Week', icon: Columns },{ id: 'month', label: 'Month', icon: LayoutGrid },+ { id: 'review', label: 'Review', icon: ClipboardList },{ id: 'sync', label: 'Sync', icon: RefreshCw },{ id: 'config', label: 'Config', icon: Settings }];@@ -51,6 +53,8 @@ export default function Calendar() {return <WeekView accounts={accounts} />;case 'month':return <MonthView accounts={accounts} />;+ case 'review':+ return <ReviewTab />;case 'config':return <ConfigTab accounts={accounts} setAccounts={setAccounts} />;case 'sync':diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 280fa7ed4f..1f35e9b0c3 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -1730,6 +1730,29 @@ export const getCalendarEvent = (accountId, eventId) => request(`/calendar/eventexport const getCalendarTokenStatus = () => request('/calendar/debug/token-status');export const testCalendarToken = (provider) => request('/calendar/debug/test-token', { method: 'POST', body: JSON.stringify({ provider }) });export const clearCalendarToken = (provider) => request('/calendar/debug/clear-token', { method: 'POST', body: JSON.stringify({ provider }) });+export const getSubcalendars = (accountId) => request(`/calendar/accounts/${accountId}/subcalendars`);+export const updateSubcalendars = (accountId, data) => request(`/calendar/accounts/${accountId}/subcalendars`, { method: 'PUT', body: JSON.stringify(data) });+export const pushSyncCalendar = (accountId, data) => request(`/calendar/sync/${accountId}/push`, { method: 'POST', body: JSON.stringify(data) });+export const mcpSyncGoogleCalendar = (accountId) => request(`/calendar/sync/${accountId}/google`, { method: 'POST' });+export const mcpDiscoverCalendars = (accountId) => request(`/calendar/sync/${accountId}/discover`, { method: 'POST' });+export const getGoogleAuthStatus = () => request('/calendar/google/auth/status');+export const saveGoogleAuthCredentials = (data) => request('/calendar/google/auth/credentials', { method: 'POST', body: JSON.stringify(data) });+export const getGoogleAuthUrl = () => request('/calendar/google/auth/url');+export const clearGoogleAuth = () => request('/calendar/google/auth/clear', { method: 'POST' });+export const apiSyncGoogleCalendar = (accountId) => request(`/calendar/sync/${accountId}/api`, { method: 'POST' });+export const apiDiscoverCalendars = (accountId) => request(`/calendar/sync/${accountId}/discover-api`, { method: 'POST' });+export const getDailyReview = (date) => request(`/calendar/review/${date}`);+export const confirmDailyReviewEvent = (date, data) => request(`/calendar/review/${date}/confirm`, { method: 'POST', body: JSON.stringify(data) });+export const getDailyReviewHistory = (params = {}) => {+ const str = new URLSearchParams(Object.entries(params).filter(([, v]) => v)).toString();+ return request(`/calendar/review/history${str ? `?${str}` : ''}`);+};+export const linkGoalCalendar = (goalId, data) => request(`/digital-twin/identity/goals/${goalId}/calendars`, { method: 'POST', body: JSON.stringify(data) });+export const unlinkGoalCalendar = (goalId, subcalendarId) => request(`/digital-twin/identity/goals/${goalId}/calendars/${encodeURIComponent(subcalendarId)}`, { method: 'DELETE' });+export const getGoalCalendarEvents = (goalId, params = {}) => {+ const str = new URLSearchParams(Object.entries(params).filter(([, v]) => v)).toString();+ return request(`/digital-twin/identity/goals/${goalId}/calendar-events${str ? `?${str}` : ''}`);+};// Default export for simplified importsexport default {diff --git a/package-lock.json b/package-lock.jsonindex 3d386dc823..034e7ccfae 100644--- a/package-lock.json+++ b/package-lock.json@@ -8,6 +8,9 @@"name": "portos","version": "1.32.0","license": "MIT",+ "dependencies": {+ "googleapis": "^171.4.0"+ },"devDependencies": {"pm2": "^6.0.14"}@@ -45,6 +48,33 @@"vite": "^7.3.1"}},+ "node_modules/@isaacs/cliui": {+ "version": "8.0.2",+ "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",+ "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==",+ "license": "ISC",+ "dependencies": {+ "string-width": "^5.1.2",+ "string-width-cjs": "npm:string-width@^4.2.0",+ "strip-ansi": "^7.0.1",+ "strip-ansi-cjs": "npm:strip-ansi@^6.0.1",+ "wrap-ansi": "^8.1.0",+ "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@pkgjs/parseargs": {+ "version": "0.11.0",+ "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",+ "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==",+ "license": "MIT",+ "optional": true,+ "engines": {+ "node": ">=14"+ }+ },"node_modules/@pm2/agent": {"version": "2.1.1","resolved": "https://registry.npmjs.org/@pm2/agent/-/agent-2.1.1.tgz",@@ -334,7 +364,6 @@"version": "7.1.4","resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz","integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",- "dev": true,"license": "MIT","engines": {"node": ">= 14"@@ -367,11 +396,22 @@"node": ">=6"}},+ "node_modules/ansi-regex": {+ "version": "6.2.2",+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz",+ "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-regex?sponsor=1"+ }+ },"node_modules/ansi-styles": {"version": "4.3.0","resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz","integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",- "dev": true,"license": "MIT","dependencies": {"color-convert": "^2.0.1"@@ -441,6 +481,32 @@"dev": true,"license": "MIT"},+ "node_modules/balanced-match": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",+ "license": "MIT"+ },+ "node_modules/base64-js": {+ "version": "1.5.1",+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT"+ },"node_modules/basic-ftp": {"version": "5.2.0","resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-5.2.0.tgz",@@ -451,6 +517,15 @@"node": ">=10.0.0"}},+ "node_modules/bignumber.js": {+ "version": "9.3.1",+ "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.1.tgz",+ "integrity": "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==",+ "license": "MIT",+ "engines": {+ "node": "*"+ }+ },"node_modules/binary-extensions": {"version": "2.3.0","resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",@@ -471,6 +546,15 @@"dev": true,"license": "MIT"},+ "node_modules/brace-expansion": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",+ "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",+ "license": "MIT",+ "dependencies": {+ "balanced-match": "^1.0.0"+ }+ },"node_modules/braces": {"version": "3.0.3","resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",@@ -484,6 +568,12 @@"node": ">=8"}},+ "node_modules/buffer-equal-constant-time": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",+ "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",+ "license": "BSD-3-Clause"+ },"node_modules/buffer-from": {"version": "1.1.2","resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",@@ -491,6 +581,35 @@"dev": true,"license": "MIT"},+ "node_modules/call-bind-apply-helpers": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/call-bound": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",+ "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "get-intrinsic": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/chalk": {"version": "3.0.0","resolved": "https://registry.npmjs.org/chalk/-/chalk-3.0.0.tgz",@@ -553,7 +672,6 @@"version": "2.0.1","resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz","integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",- "dev": true,"license": "MIT","dependencies": {"color-name": "~1.1.4"@@ -566,7 +684,6 @@"version": "1.1.4","resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz","integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",- "dev": true,"license": "MIT"},"node_modules/commander": {@@ -583,6 +700,20 @@"dev": true,"license": "MIT"},+ "node_modules/cross-spawn": {+ "version": "7.0.6",+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",+ "license": "MIT",+ "dependencies": {+ "path-key": "^3.1.0",+ "shebang-command": "^2.0.0",+ "which": "^2.0.1"+ },+ "engines": {+ "node": ">= 8"+ }+ },"node_modules/culvert": {"version": "0.1.2","resolved": "https://registry.npmjs.org/culvert/-/culvert-0.1.2.tgz",@@ -611,7 +742,6 @@"version": "4.4.3","resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz","integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",- "dev": true,"license": "MIT","dependencies": {"ms": "^2.1.3"@@ -640,6 +770,41 @@"node": ">= 14"}},+ "node_modules/dunder-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.1",+ "es-errors": "^1.3.0",+ "gopd": "^1.2.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/eastasianwidth": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz",+ "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==",+ "license": "MIT"+ },+ "node_modules/ecdsa-sig-formatter": {+ "version": "1.0.11",+ "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",+ "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "safe-buffer": "^5.0.1"+ }+ },+ "node_modules/emoji-regex": {+ "version": "9.2.2",+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",+ "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==",+ "license": "MIT"+ },"node_modules/enquirer": {"version": "2.3.6","resolved": "https://registry.npmjs.org/enquirer/-/enquirer-2.3.6.tgz",@@ -653,6 +818,36 @@"node": ">=8.6"}},+ "node_modules/es-define-property": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-errors": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-object-atoms": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",+ "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },"node_modules/escape-string-regexp": {"version": "4.0.0","resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",@@ -729,6 +924,12 @@"dev": true,"license": "MIT"},+ "node_modules/extend": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",+ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",+ "license": "MIT"+ },"node_modules/extrareqp2": {"version": "1.0.0","resolved": "https://registry.npmjs.org/extrareqp2/-/extrareqp2-1.0.0.tgz",@@ -753,6 +954,29 @@"dev": true,"license": "MIT"},+ "node_modules/fetch-blob": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz",+ "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/jimmywarting"+ },+ {+ "type": "paypal",+ "url": "https://paypal.me/jimmywarting"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "node-domexception": "^1.0.0",+ "web-streams-polyfill": "^3.0.3"+ },+ "engines": {+ "node": "^12.20 || >= 14.13"+ }+ },"node_modules/fill-range": {"version": "7.1.1","resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",@@ -787,6 +1011,46 @@}}},+ "node_modules/foreground-child": {+ "version": "3.3.1",+ "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz",+ "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==",+ "license": "ISC",+ "dependencies": {+ "cross-spawn": "^7.0.6",+ "signal-exit": "^4.0.1"+ },+ "engines": {+ "node": ">=14"+ },+ "funding": {+ "url": "https://github.com/sponsors/isaacs"+ }+ },+ "node_modules/foreground-child/node_modules/signal-exit": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",+ "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==",+ "license": "ISC",+ "engines": {+ "node": ">=14"+ },+ "funding": {+ "url": "https://github.com/sponsors/isaacs"+ }+ },+ "node_modules/formdata-polyfill": {+ "version": "4.0.10",+ "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz",+ "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==",+ "license": "MIT",+ "dependencies": {+ "fetch-blob": "^3.1.2"+ },+ "engines": {+ "node": ">=12.20.0"+ }+ },"node_modules/fsevents": {"version": "2.3.3","resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",@@ -806,12 +1070,77 @@"version": "1.1.2","resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz","integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",- "dev": true,"license": "MIT","funding": {"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/gaxios": {+ "version": "7.1.3",+ "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-7.1.3.tgz",+ "integrity": "sha512-YGGyuEdVIjqxkxVH1pUTMY/XtmmsApXrCVv5EU25iX6inEPbV+VakJfLealkBtJN69AQmh1eGOdCl9Sm1UP6XQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "extend": "^3.0.2",+ "https-proxy-agent": "^7.0.1",+ "node-fetch": "^3.3.2",+ "rimraf": "^5.0.1"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/gcp-metadata": {+ "version": "8.1.2",+ "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-8.1.2.tgz",+ "integrity": "sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg==",+ "license": "Apache-2.0",+ "dependencies": {+ "gaxios": "^7.0.0",+ "google-logging-utils": "^1.0.0",+ "json-bigint": "^1.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/get-intrinsic": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "es-define-property": "^1.0.1",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.1.1",+ "function-bind": "^1.1.2",+ "get-proto": "^1.0.1",+ "gopd": "^1.2.0",+ "has-symbols": "^1.1.0",+ "hasown": "^2.0.2",+ "math-intrinsics": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",+ "license": "MIT",+ "dependencies": {+ "dunder-proto": "^1.0.1",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },"node_modules/get-uri": {"version": "6.0.5","resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.5.tgz",@@ -841,6 +1170,27 @@"dev": true,"license": "MIT"},+ "node_modules/glob": {+ "version": "10.5.0",+ "resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz",+ "integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==",+ "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]",+ "license": "ISC",+ "dependencies": {+ "foreground-child": "^3.1.0",+ "jackspeak": "^3.1.2",+ "minimatch": "^9.0.4",+ "minipass": "^7.1.2",+ "package-json-from-dist": "^1.0.0",+ "path-scurry": "^1.11.1"+ },+ "bin": {+ "glob": "dist/esm/bin.mjs"+ },+ "funding": {+ "url": "https://github.com/sponsors/isaacs"+ }+ },"node_modules/glob-parent": {"version": "5.1.2","resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",@@ -854,6 +1204,73 @@"node": ">= 6"}},+ "node_modules/google-auth-library": {+ "version": "10.6.1",+ "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-10.6.1.tgz",+ "integrity": "sha512-5awwuLrzNol+pFDmKJd0dKtZ0fPLAtoA5p7YO4ODsDu6ONJUVqbYwvv8y2ZBO5MBNp9TJXigB19710kYpBPdtA==",+ "license": "Apache-2.0",+ "dependencies": {+ "base64-js": "^1.3.0",+ "ecdsa-sig-formatter": "^1.0.11",+ "gaxios": "7.1.3",+ "gcp-metadata": "8.1.2",+ "google-logging-utils": "1.1.3",+ "jws": "^4.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/google-logging-utils": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-1.1.3.tgz",+ "integrity": "sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/googleapis": {+ "version": "171.4.0",+ "resolved": "https://registry.npmjs.org/googleapis/-/googleapis-171.4.0.tgz",+ "integrity": "sha512-xybFL2SmmUgIifgsbsRQYRdNrSAYwxWZDmkZTGjUIaRnX5jPqR8el/cEvo6rCqh7iaZx6MfEPS/lrDgZ0bymkg==",+ "license": "Apache-2.0",+ "dependencies": {+ "google-auth-library": "^10.2.0",+ "googleapis-common": "^8.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/googleapis-common": {+ "version": "8.0.1",+ "resolved": "https://registry.npmjs.org/googleapis-common/-/googleapis-common-8.0.1.tgz",+ "integrity": "sha512-eCzNACUXPb1PW5l0ULTzMHaL/ltPRADoPgjBlT8jWsTbxkCp6siv+qKJ/1ldaybCthGwsYFYallF7u9AkU4L+A==",+ "license": "Apache-2.0",+ "dependencies": {+ "extend": "^3.0.2",+ "gaxios": "^7.0.0-rc.4",+ "google-auth-library": "^10.1.0",+ "qs": "^6.7.0",+ "url-template": "^2.0.8"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/gopd": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/has-flag": {"version": "4.0.0","resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",@@ -864,11 +1281,22 @@"node": ">=8"}},+ "node_modules/has-symbols": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/hasown": {"version": "2.0.2","resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz","integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",- "dev": true,"license": "MIT","dependencies": {"function-bind": "^1.1.2"@@ -895,7 +1323,6 @@"version": "7.0.6","resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz","integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",- "dev": true,"license": "MIT","dependencies": {"agent-base": "^7.1.2",@@ -961,6 +1388,15 @@"node": ">=0.10.0"}},+ "node_modules/is-fullwidth-code-point": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },"node_modules/is-glob": {"version": "4.0.3","resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",@@ -984,6 +1420,27 @@"node": ">=0.12.0"}},+ "node_modules/isexe": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",+ "license": "ISC"+ },+ "node_modules/jackspeak": {+ "version": "3.4.3",+ "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz",+ "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==",+ "license": "BlueOak-1.0.0",+ "dependencies": {+ "@isaacs/cliui": "^8.0.2"+ },+ "funding": {+ "url": "https://github.com/sponsors/isaacs"+ },+ "optionalDependencies": {+ "@pkgjs/parseargs": "^0.11.0"+ }+ },"node_modules/js-git": {"version": "0.7.8","resolved": "https://registry.npmjs.org/js-git/-/js-git-0.7.8.tgz",@@ -1010,6 +1467,15 @@"js-yaml": "bin/js-yaml.js"}},+ "node_modules/json-bigint": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz",+ "integrity": "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==",+ "license": "MIT",+ "dependencies": {+ "bignumber.js": "^9.0.0"+ }+ },"node_modules/json-stringify-safe": {"version": "5.0.1","resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz",@@ -1018,7 +1484,28 @@"license": "ISC","optional": true},- "node_modules/lodash": {+ "node_modules/jwa": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",+ "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",+ "license": "MIT",+ "dependencies": {+ "buffer-equal-constant-time": "^1.0.1",+ "ecdsa-sig-formatter": "1.0.11",+ "safe-buffer": "^5.0.1"+ }+ },+ "node_modules/jws": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz",+ "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",+ "license": "MIT",+ "dependencies": {+ "jwa": "^2.0.1",+ "safe-buffer": "^5.0.1"+ }+ },+ "node_modules/lodash": {"version": "4.17.23","resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.23.tgz","integrity": "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==",@@ -1035,6 +1522,39 @@"node": ">=12"}},+ "node_modules/math-intrinsics": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/minimatch": {+ "version": "9.0.9",+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz",+ "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==",+ "license": "ISC",+ "dependencies": {+ "brace-expansion": "^2.0.2"+ },+ "engines": {+ "node": ">=16 || 14 >=14.17"+ },+ "funding": {+ "url": "https://github.com/sponsors/isaacs"+ }+ },+ "node_modules/minipass": {+ "version": "7.1.3",+ "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",+ "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==",+ "license": "BlueOak-1.0.0",+ "engines": {+ "node": ">=16 || 14 >=14.17"+ }+ },"node_modules/mkdirp": {"version": "1.0.4","resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz",@@ -1059,7 +1579,6 @@"version": "2.1.3","resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz","integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",- "dev": true,"license": "MIT"},"node_modules/mute-stream": {@@ -1120,6 +1639,53 @@"node": ">= 0.4.0"}},+ "node_modules/node-domexception": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",+ "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==",+ "deprecated": "Use your platform's native DOMException instead",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/jimmywarting"+ },+ {+ "type": "github",+ "url": "https://paypal.me/jimmywarting"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=10.5.0"+ }+ },+ "node_modules/node-fetch": {+ "version": "3.3.2",+ "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz",+ "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==",+ "license": "MIT",+ "dependencies": {+ "data-uri-to-buffer": "^4.0.0",+ "fetch-blob": "^3.1.4",+ "formdata-polyfill": "^4.0.10"+ },+ "engines": {+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/node-fetch"+ }+ },+ "node_modules/node-fetch/node_modules/data-uri-to-buffer": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz",+ "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==",+ "license": "MIT",+ "engines": {+ "node": ">= 12"+ }+ },"node_modules/normalize-path": {"version": "3.0.0","resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",@@ -1130,6 +1696,18 @@"node": ">=0.10.0"}},+ "node_modules/object-inspect": {+ "version": "1.13.4",+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",+ "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/pac-proxy-agent": {"version": "7.2.0","resolved": "https://registry.npmjs.org/pac-proxy-agent/-/pac-proxy-agent-7.2.0.tgz",@@ -1164,6 +1742,12 @@"node": ">= 14"}},+ "node_modules/package-json-from-dist": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz",+ "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==",+ "license": "BlueOak-1.0.0"+ },"node_modules/pako": {"version": "0.2.9","resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz",@@ -1171,6 +1755,15 @@"dev": true,"license": "MIT"},+ "node_modules/path-key": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },"node_modules/path-parse": {"version": "1.0.7","resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",@@ -1178,6 +1771,28 @@"dev": true,"license": "MIT"},+ "node_modules/path-scurry": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz",+ "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==",+ "license": "BlueOak-1.0.0",+ "dependencies": {+ "lru-cache": "^10.2.0",+ "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0"+ },+ "engines": {+ "node": ">=16 || 14 >=14.18"+ },+ "funding": {+ "url": "https://github.com/sponsors/isaacs"+ }+ },+ "node_modules/path-scurry/node_modules/lru-cache": {+ "version": "10.4.3",+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",+ "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",+ "license": "ISC"+ },"node_modules/picomatch": {"version": "2.3.1","resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",@@ -1386,6 +2001,21 @@"dev": true,"license": "MIT"},+ "node_modules/qs": {+ "version": "6.15.0",+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.0.tgz",+ "integrity": "sha512-mAZTtNCeetKMH+pSjrb76NAM8V9a05I9aBZOHztWy/UqcJdQYNsf59vrRKWnojAT9Y+GbIvoTBC++CPHqpDBhQ==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "side-channel": "^1.1.0"+ },+ "engines": {+ "node": ">=0.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/read": {"version": "1.0.7","resolved": "https://registry.npmjs.org/read/-/read-1.0.7.tgz",@@ -1448,6 +2078,21 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/rimraf": {+ "version": "5.0.10",+ "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-5.0.10.tgz",+ "integrity": "sha512-l0OE8wL34P4nJH/H2ffoaniAokM2qSmrtXHmlpvYr5AVVX8msAyW0l8NVJFDxlSK4u3Uh/f41cQheDVdnYijwQ==",+ "license": "ISC",+ "dependencies": {+ "glob": "^10.3.7"+ },+ "bin": {+ "rimraf": "dist/esm/bin.mjs"+ },+ "funding": {+ "url": "https://github.com/sponsors/isaacs"+ }+ },"node_modules/run-series": {"version": "1.1.9","resolved": "https://registry.npmjs.org/run-series/-/run-series-1.1.9.tgz",@@ -1473,7 +2118,6 @@"version": "5.2.1","resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz","integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",- "dev": true,"funding": [{"type": "github",@@ -1507,6 +2151,27 @@"node": ">=11.0.0"}},+ "node_modules/shebang-command": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",+ "license": "MIT",+ "dependencies": {+ "shebang-regex": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/shebang-regex": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },"node_modules/shimmer": {"version": "1.2.1","resolved": "https://registry.npmjs.org/shimmer/-/shimmer-1.2.1.tgz",@@ -1514,6 +2179,78 @@"dev": true,"license": "BSD-2-Clause"},+ "node_modules/side-channel": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",+ "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.3",+ "side-channel-list": "^1.0.0",+ "side-channel-map": "^1.0.1",+ "side-channel-weakmap": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-list": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz",+ "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-map": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",+ "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-weakmap": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",+ "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3",+ "side-channel-map": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/signal-exit": {"version": "3.0.7","resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",@@ -1590,6 +2327,102 @@"dev": true,"license": "BSD-3-Clause"},+ "node_modules/string-width": {+ "version": "5.1.2",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz",+ "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==",+ "license": "MIT",+ "dependencies": {+ "eastasianwidth": "^0.2.0",+ "emoji-regex": "^9.2.2",+ "strip-ansi": "^7.0.1"+ },+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/string-width-cjs": {+ "name": "string-width",+ "version": "4.2.3",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^8.0.0",+ "is-fullwidth-code-point": "^3.0.0",+ "strip-ansi": "^6.0.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/string-width-cjs/node_modules/ansi-regex": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/string-width-cjs/node_modules/emoji-regex": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",+ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",+ "license": "MIT"+ },+ "node_modules/string-width-cjs/node_modules/strip-ansi": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",+ "license": "MIT",+ "dependencies": {+ "ansi-regex": "^5.0.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/strip-ansi": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz",+ "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==",+ "license": "MIT",+ "dependencies": {+ "ansi-regex": "^6.2.2"+ },+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/strip-ansi?sponsor=1"+ }+ },+ "node_modules/strip-ansi-cjs": {+ "name": "strip-ansi",+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",+ "license": "MIT",+ "dependencies": {+ "ansi-regex": "^5.0.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/strip-ansi-cjs/node_modules/ansi-regex": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },"node_modules/supports-color": {"version": "7.2.0","resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",@@ -1694,6 +2527,12 @@"json-stringify-safe": "^5.0.1"}},+ "node_modules/url-template": {+ "version": "2.0.8",+ "resolved": "https://registry.npmjs.org/url-template/-/url-template-2.0.8.tgz",+ "integrity": "sha512-XdVKMF4SJ0nP/O7XIPB0JwAEuT9lDIYnNsK8yGVe43y0AWoKeJNdv3ZNWh7ksJ6KqQFjOO6ox/VEitLnaVNufw==",+ "license": "BSD"+ },"node_modules/vizion": {"version": "2.2.1","resolved": "https://registry.npmjs.org/vizion/-/vizion-2.2.1.tgz",@@ -1720,6 +2559,118 @@"lodash": "^4.17.14"}},+ "node_modules/web-streams-polyfill": {+ "version": "3.3.3",+ "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz",+ "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==",+ "license": "MIT",+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/which": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",+ "license": "ISC",+ "dependencies": {+ "isexe": "^2.0.0"+ },+ "bin": {+ "node-which": "bin/node-which"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/wrap-ansi": {+ "version": "8.1.0",+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz",+ "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==",+ "license": "MIT",+ "dependencies": {+ "ansi-styles": "^6.1.0",+ "string-width": "^5.0.1",+ "strip-ansi": "^7.0.1"+ },+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"+ }+ },+ "node_modules/wrap-ansi-cjs": {+ "name": "wrap-ansi",+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",+ "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",+ "license": "MIT",+ "dependencies": {+ "ansi-styles": "^4.0.0",+ "string-width": "^4.1.0",+ "strip-ansi": "^6.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"+ }+ },+ "node_modules/wrap-ansi-cjs/node_modules/ansi-regex": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/wrap-ansi-cjs/node_modules/emoji-regex": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",+ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",+ "license": "MIT"+ },+ "node_modules/wrap-ansi-cjs/node_modules/string-width": {+ "version": "4.2.3",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^8.0.0",+ "is-fullwidth-code-point": "^3.0.0",+ "strip-ansi": "^6.0.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/wrap-ansi-cjs/node_modules/strip-ansi": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",+ "license": "MIT",+ "dependencies": {+ "ansi-regex": "^5.0.1"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/wrap-ansi/node_modules/ansi-styles": {+ "version": "6.2.3",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",+ "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"+ }+ },"node_modules/yallist": {"version": "4.0.0","resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",diff --git a/package.json b/package.jsonindex 6652e7f08e..9128cd0fa6 100644--- a/package.json+++ b/package.json@@ -30,5 +30,8 @@},"devDependencies": {"pm2": "^6.0.14"+ },+ "dependencies": {+ "googleapis": "^171.4.0"}}diff --git a/server/lib/identityValidation.js b/server/lib/identityValidation.jsindex 886189932c..dc0458ccb0 100644--- a/server/lib/identityValidation.js+++ b/server/lib/identityValidation.js@@ -87,3 +87,11 @@ export const linkActivityInputSchema = z.object({requiredFrequency: z.number().positive().optional(),note: z.string().max(500).optional().default('')});++// --- Goal-Calendar Link Schemas ---++export const linkCalendarInputSchema = z.object({+ subcalendarId: z.string().min(1),+ subcalendarName: z.string().min(1),+ matchPattern: z.string().max(200).optional().default('')+});diff --git a/server/routes/calendar.js b/server/routes/calendar.jsindex 3a0ba065af..acead3474d 100644--- a/server/routes/calendar.js+++ b/server/routes/calendar.js@@ -4,6 +4,10 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import * as calendarAccounts from '../services/calendarAccounts.js';import * as calendarSync from '../services/calendarSync.js';+import * as calendarGoogleSync from '../services/calendarGoogleSync.js';+import * as dailyReview from '../services/dailyReview.js';+import * as googleAuth from '../services/googleAuth.js';+import * as calendarGoogleApiSync from '../services/calendarGoogleApiSync.js';import { getToken, getTokenStatus, clearTokenCache } from '../services/messageTokenExtractor.js';const router = express.Router();@@ -11,7 +15,7 @@ const router = express.Router();// === Validation Schemas ===const createAccountSchema = z.object({name: z.string().min(1),- type: z.enum(['outlook-calendar']),+ type: z.enum(['outlook-calendar', 'google-calendar']),email: z.union([z.string().email(), z.literal('')]).optional().default(''),syncConfig: z.object({maxAge: z.string().optional(),@@ -28,7 +32,51 @@ const updateAccountSchema = z.object({maxAge: z.string().optional(),syncInterval: z.number().int().positive().optional(),calendarIds: z.array(z.string()).optional()- }).optional()+ }).optional(),+ syncMethod: z.enum(['claude-mcp', 'google-api']).optional()+});++const subcalendarSchema = z.object({+ calendarId: z.string().min(1),+ name: z.string().min(1),+ color: z.string().optional().default(''),+ enabled: z.boolean().optional().default(true),+ dormant: z.boolean().optional().default(false),+ goalIds: z.array(z.string()).optional().default([]),+ addedAt: z.string().optional()+});++const updateSubcalendarsSchema = z.object({+ subcalendars: z.array(subcalendarSchema)+});++const pushSyncSchema = z.object({+ calendarId: z.string().min(1),+ calendarName: z.string().min(1),+ events: z.array(z.object({+ id: z.string().optional(),+ summary: z.string().optional().default(''),+ start: z.object({+ dateTime: z.string().optional(),+ date: z.string().optional()+ }).optional(),+ end: z.object({+ dateTime: z.string().optional(),+ date: z.string().optional()+ }).optional(),+ location: z.string().optional().default(''),+ description: z.string().optional().default(''),+ status: z.string().optional().default('confirmed'),+ htmlLink: z.string().optional()+ }))+});++const confirmEventSchema = z.object({+ eventId: z.string().min(1),+ happened: z.boolean(),+ goalId: z.string().optional(),+ durationMinutes: z.number().int().min(1).max(1440).optional(),+ note: z.string().max(1000).optional()});// === Account Routes ===@@ -117,6 +165,145 @@ router.get('/events/:accountId/:eventId', asyncHandler(async (req, res) => {res.json(event);}));+// === Subcalendar Routes ===+router.get('/accounts/:id/subcalendars', asyncHandler(async (req, res) => {+ if (!z.string().uuid().safeParse(req.params.id).success) {+ throw new ServerError('Invalid account ID format', { status: 400, code: 'VALIDATION_ERROR' });+ }+ const account = await calendarAccounts.getAccount(req.params.id);+ if (!account) throw new ServerError('Account not found', { status: 404, code: 'NOT_FOUND' });+ res.json(account.subcalendars || []);+}));++router.put('/accounts/:id/subcalendars', asyncHandler(async (req, res) => {+ if (!z.string().uuid().safeParse(req.params.id).success) {+ throw new ServerError('Invalid account ID format', { status: 400, code: 'VALIDATION_ERROR' });+ }+ const { subcalendars } = validateRequest(updateSubcalendarsSchema, req.body);+ const account = await calendarAccounts.updateSubcalendars(req.params.id, subcalendars);+ if (!account) throw new ServerError('Account not found', { status: 404, code: 'NOT_FOUND' });+ req.app.get('io')?.emit('calendar:changed', {});+ res.json(account);+}));++// === Push Sync Route ===+router.post('/sync/:accountId/push', asyncHandler(async (req, res) => {+ if (!z.string().uuid().safeParse(req.params.accountId).success) {+ throw new ServerError('Invalid account ID format', { status: 400, code: 'VALIDATION_ERROR' });+ }+ const data = validateRequest(pushSyncSchema, req.body);+ const io = req.app.get('io');+ const result = await calendarGoogleSync.pushSyncEvents(req.params.accountId, data.calendarId, data.calendarName, data.events, io);+ res.json(result);+}));++// === MCP Discover Calendars Route ===+router.post('/sync/:accountId/discover', asyncHandler(async (req, res) => {+ if (!z.string().uuid().safeParse(req.params.accountId).success) {+ throw new ServerError('Invalid account ID format', { status: 400, code: 'VALIDATION_ERROR' });+ }+ const io = req.app.get('io');+ const result = await calendarGoogleSync.mcpDiscoverCalendars(req.params.accountId, io);+ if (result.error) return res.status(result.status || 500).json({ error: result.error });+ req.app.get('io')?.emit('calendar:changed', {});+ res.json(result);+}));++// === MCP Sync Route ===+router.post('/sync/:accountId/google', asyncHandler(async (req, res) => {+ if (!z.string().uuid().safeParse(req.params.accountId).success) {+ throw new ServerError('Invalid account ID format', { status: 400, code: 'VALIDATION_ERROR' });+ }+ const io = req.app.get('io');+ const result = await calendarGoogleSync.mcpSyncAccount(req.params.accountId, io);+ if (result.error) return res.status(result.status || 500).json({ error: result.error });+ res.json(result);+}));++// === Google OAuth Routes ===+router.get('/google/auth/status', asyncHandler(async (req, res) => {+ const status = await googleAuth.getAuthStatus();+ res.json(status);+}));++router.post('/google/auth/credentials', asyncHandler(async (req, res) => {+ const schema = z.object({+ clientId: z.string().min(1),+ clientSecret: z.string().min(1)+ });+ const data = validateRequest(schema, req.body);+ const result = await googleAuth.saveCredentials(data);+ res.json(result);+}));++router.get('/google/auth/url', asyncHandler(async (req, res) => {+ const result = await googleAuth.getAuthUrl();+ if (result.error) return res.status(400).json({ error: result.error });+ res.json(result);+}));++router.get('/google/oauth/callback', asyncHandler(async (req, res) => {+ const code = req.query.code;+ if (!code) return res.status(400).send('Missing authorization code');+ const result = await googleAuth.handleCallback(code);+ if (result.error) return res.status(500).send(result.error);+ // Redirect to calendar config page after successful auth+ res.redirect('/calendar/config');+}));++router.post('/google/auth/clear', asyncHandler(async (req, res) => {+ await googleAuth.clearAuth();+ res.json({ cleared: true });+}));++// === Google API Sync Routes ===+router.post('/sync/:accountId/api', asyncHandler(async (req, res) => {+ if (!z.string().uuid().safeParse(req.params.accountId).success) {+ throw new ServerError('Invalid account ID format', { status: 400, code: 'VALIDATION_ERROR' });+ }+ const io = req.app.get('io');+ const result = await calendarGoogleApiSync.apiSyncAccount(req.params.accountId, io);+ if (result.error) return res.status(result.status || 500).json({ error: result.error });+ res.json(result);+}));++router.post('/sync/:accountId/discover-api', asyncHandler(async (req, res) => {+ if (!z.string().uuid().safeParse(req.params.accountId).success) {+ throw new ServerError('Invalid account ID format', { status: 400, code: 'VALIDATION_ERROR' });+ }+ const result = await calendarGoogleApiSync.apiDiscoverCalendars(req.params.accountId);+ if (result.error) return res.status(result.status || 500).json({ error: result.error });+ req.app.get('io')?.emit('calendar:changed', {});+ res.json(result);+}));++// === Daily Review Routes ===+// NOTE: /review/history must come before /review/:date so Express doesn't match "history" as a date param+router.get('/review/history', asyncHandler(async (req, res) => {+ const { startDate, endDate } = req.query;+ const history = await dailyReview.getDailyReviewHistory(startDate, endDate);+ res.json(history);+}));++router.get('/review/:date', asyncHandler(async (req, res) => {+ const dateStr = req.params.date;+ if (!/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {+ throw new ServerError('Invalid date format, use YYYY-MM-DD', { status: 400, code: 'VALIDATION_ERROR' });+ }+ const review = await dailyReview.getDailyReview(dateStr);+ res.json(review);+}));++router.post('/review/:date/confirm', asyncHandler(async (req, res) => {+ const dateStr = req.params.date;+ if (!/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {+ throw new ServerError('Invalid date format, use YYYY-MM-DD', { status: 400, code: 'VALIDATION_ERROR' });+ }+ const data = validateRequest(confirmEventSchema, req.body);+ const result = await dailyReview.confirmEvent(dateStr, data);+ res.json(result);+}));+// === Debug: Token Status (reuse message token extractor) ===router.get('/debug/token-status', asyncHandler(async (req, res) => {const statuses = ['outlook'].map(p => getTokenStatus(p));diff --git a/server/routes/identity.js b/server/routes/identity.jsindex bb07483961..c8786ed4c2 100644--- a/server/routes/identity.js+++ b/server/routes/identity.js@@ -9,7 +9,8 @@ import {updateGoalInputSchema,addMilestoneInputSchema,addProgressEntrySchema,- linkActivityInputSchema+ linkActivityInputSchema,+ linkCalendarInputSchema} from '../lib/identityValidation.js';const router = Router();@@ -169,4 +170,30 @@ router.delete('/goals/:id/activities/:activityName', asyncHandler(async (req, reres.json(goal);}));+// POST /api/digital-twin/identity/goals/:id/calendars — Link calendar to goal+router.post('/goals/:id/calendars', asyncHandler(async (req, res) => {+ const data = validateRequest(linkCalendarInputSchema, req.body);+ const goal = await identityService.linkCalendarToGoal(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/calendars/:subcalendarId — Unlink calendar from goal+router.delete('/goals/:id/calendars/:subcalendarId', asyncHandler(async (req, res) => {+ const goal = await identityService.unlinkCalendarFromGoal(req.params.id, decodeURIComponent(req.params.subcalendarId));+ if (!goal) {+ throw new ServerError('Goal not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(goal);+}));++// GET /api/digital-twin/identity/goals/:id/calendar-events — Get matching events+router.get('/goals/:id/calendar-events', asyncHandler(async (req, res) => {+ const { startDate, endDate } = req.query;+ const events = await identityService.getGoalCalendarEvents(req.params.id, startDate, endDate);+ res.json(events);+}));+export default router;diff --git a/server/services/calendarAccounts.js b/server/services/calendarAccounts.jsindex 027df336e7..994880eaa9 100644--- a/server/services/calendarAccounts.js+++ b/server/services/calendarAccounts.js@@ -44,6 +44,19 @@ export async function createAccount(data) {lastSyncStatus: null,createdAt: new Date().toISOString()};+ // For google-calendar, initialize subcalendars+ if (data.type === 'google-calendar') {+ accounts[id].subcalendars = (data.subcalendars || []).map(sc => ({+ calendarId: sc.calendarId,+ name: sc.name,+ color: sc.color || '',+ enabled: sc.enabled !== false,+ dormant: sc.dormant || false,+ goalIds: sc.goalIds || [],+ addedAt: sc.addedAt || new Date().toISOString()+ }));+ accounts[id].syncMethod = 'claude-mcp'; // default, user can switch to 'google-api'+ }await saveAccounts(accounts);console.log(`📅 Calendar account created: ${data.name} (${data.type})`);return accounts[id];@@ -57,6 +70,7 @@ export async function updateAccount(id, updates) {if (email !== undefined) accounts[id].email = email;if (enabled !== undefined) accounts[id].enabled = enabled;if (syncConfig) accounts[id].syncConfig = { ...accounts[id].syncConfig, ...syncConfig };+ if (updates.syncMethod !== undefined) accounts[id].syncMethod = updates.syncMethod;accounts[id].updatedAt = new Date().toISOString();await saveAccounts(accounts);return accounts[id];@@ -71,6 +85,24 @@ export async function deleteAccount(id) {return true;}+export async function updateSubcalendars(id, subcalendars) {+ const accounts = await loadAccounts();+ if (!accounts[id]) return null;+ accounts[id].subcalendars = subcalendars.map(sc => ({+ calendarId: sc.calendarId,+ name: sc.name,+ color: sc.color || '',+ enabled: sc.enabled !== false,+ dormant: sc.dormant || false,+ goalIds: sc.goalIds || [],+ addedAt: sc.addedAt || new Date().toISOString()+ }));+ accounts[id].updatedAt = new Date().toISOString();+ await saveAccounts(accounts);+ console.log(`📅 Updated subcalendars for account ${accounts[id].name}: ${subcalendars.length} calendars`);+ return accounts[id];+}+export async function updateSyncStatus(id, status) {const accounts = await loadAccounts();if (!accounts[id]) return null;diff --git a/server/services/calendarGoogleApiSync.js b/server/services/calendarGoogleApiSync.jsnew file mode 100644index 0000000000..b0a49ba409--- /dev/null+++ b/server/services/calendarGoogleApiSync.js@@ -0,0 +1,112 @@+import { google } from 'googleapis';+import { getAuthenticatedClient } from './googleAuth.js';+import { getAccount } from './calendarAccounts.js';+import { pushSyncEvents } from './calendarGoogleSync.js';++export async function apiSyncAccount(accountId, io) {+ const account = await getAccount(accountId);+ if (!account) return { error: 'Account not found', status: 404 };+ if (account.type !== 'google-calendar') return { error: 'Not a Google Calendar account', status: 400 };++ const auth = await getAuthenticatedClient();+ if (!auth) return { error: 'Google OAuth not configured. Set up credentials in Config tab.', status: 401 };++ const enabledCalendars = (account.subcalendars || []).filter(sc => sc.enabled && !sc.dormant);+ if (enabledCalendars.length === 0) return { error: 'No enabled subcalendars', status: 400 };++ io?.emit('calendar:sync:started', { accountId, method: 'api' });+ console.log(`📅 Starting Google API sync for ${account.name} (${enabledCalendars.length} calendars)`);++ const calendar = google.calendar({ version: 'v3', auth });+ const now = new Date();+ const pastDate = new Date(now);+ pastDate.setDate(pastDate.getDate() - 7);+ const futureDate = new Date(now);+ futureDate.setDate(futureDate.getDate() + 30);++ let totalNew = 0;+ let totalUpdated = 0;+ let totalPruned = 0;+ const results = [];++ for (const sc of enabledCalendars) {+ io?.emit('calendar:sync:progress', { accountId, message: `Fetching ${sc.name}...` });++ const allEvents = [];+ let pageToken;++ do {+ const response = await calendar.events.list({+ calendarId: sc.calendarId,+ timeMin: pastDate.toISOString(),+ timeMax: futureDate.toISOString(),+ maxResults: 250,+ singleEvents: true,+ orderBy: 'startTime',+ pageToken+ });+ const items = response.data.items || [];+ allEvents.push(...items.map(item => ({+ id: item.id,+ summary: item.summary || '',+ start: item.start,+ end: item.end,+ location: item.location || '',+ description: item.description || '',+ status: item.status || 'confirmed'+ })));+ pageToken = response.data.nextPageToken;+ } while (pageToken);++ const syncResult = await pushSyncEvents(accountId, sc.calendarId, sc.name, allEvents, null);+ totalNew += syncResult.newEvents;+ totalUpdated += syncResult.updated;+ totalPruned += syncResult.pruned;+ results.push({ calendarId: sc.calendarId, calendarName: sc.name, events: allEvents.length, ...syncResult });+ console.log(`📅 Google API: ${sc.name} → ${allEvents.length} events`);+ }++ io?.emit('calendar:sync:completed', { accountId, newEvents: totalNew, updated: totalUpdated, pruned: totalPruned, status: 'success', method: 'api' });+ console.log(`📅 Google API sync complete for ${account.name}: ${totalNew} new, ${totalUpdated} updated, ${totalPruned} pruned`);++ return { newEvents: totalNew, updated: totalUpdated, pruned: totalPruned, calendars: results, status: 'success' };+}++export async function apiDiscoverCalendars(accountId) {+ const account = await getAccount(accountId);+ if (!account) return { error: 'Account not found', status: 404 };++ const auth = await getAuthenticatedClient();+ if (!auth) return { error: 'Google OAuth not configured', status: 401 };++ const calendar = google.calendar({ version: 'v3', auth });+ const allCalendars = [];+ let pageToken;++ do {+ const response = await calendar.calendarList.list({ pageToken });+ allCalendars.push(...(response.data.items || []));+ pageToken = response.data.nextPageToken;+ } while (pageToken);++ // Merge with existing subcalendars+ const existingMap = new Map((account.subcalendars || []).map(sc => [sc.calendarId, sc]));+ const merged = allCalendars.map(cal => {+ const existing = existingMap.get(cal.id);+ return {+ calendarId: cal.id,+ name: cal.summaryOverride || cal.summary || cal.id,+ color: cal.backgroundColor || existing?.color || '',+ enabled: existing?.enabled ?? false,+ dormant: existing?.dormant ?? false,+ goalIds: existing?.goalIds || [],+ addedAt: existing?.addedAt || new Date().toISOString()+ };+ });++ const { updateSubcalendars } = await import('./calendarAccounts.js');+ await updateSubcalendars(accountId, merged);++ console.log(`📅 Discovered ${allCalendars.length} calendars via Google API for ${account.name}`);+ return { calendars: merged, status: 'success' };+}diff --git a/server/services/calendarGoogleSync.js b/server/services/calendarGoogleSync.jsnew file mode 100644index 0000000000..5d11bdd24b--- /dev/null+++ b/server/services/calendarGoogleSync.js@@ -0,0 +1,315 @@+import { v4 as uuidv4 } from 'uuid';+import { createHash } from 'crypto';+import { spawn } from 'child_process';+import { getAccount, updateSyncStatus } from './calendarAccounts.js';+import { writeFile } from 'fs/promises';+import { join } from 'path';+import { ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';++const CACHE_DIR = join(PATHS.calendar, 'cache');++function md5(str) {+ return createHash('md5').update(str).digest('hex').slice(0, 12);+}++export function normalizeGoogleEvent(event, subcalendarId, subcalendarName) {+ const startDateTime = event.start?.dateTime;+ const startDate = event.start?.date;+ const endDateTime = event.end?.dateTime;+ const endDate = event.end?.date;+ const isAllDay = !startDateTime && !!startDate;++ return {+ id: uuidv4(),+ externalId: `gcal-${md5(event.id || uuidv4())}`,+ apiId: event.id || '',+ title: event.summary || '(No title)',+ description: event.description || '',+ location: event.location || '',+ startTime: startDateTime || (startDate ? `${startDate}T00:00:00` : null),+ endTime: endDateTime || (endDate ? `${endDate}T00:00:00` : null),+ isAllDay,+ isCancelled: event.status === 'cancelled',+ subcalendarId,+ subcalendarName,+ source: 'google-calendar',+ syncMethod: 'push',+ syncedAt: new Date().toISOString()+ };+}++async function loadCache(accountId) {+ await ensureDir(CACHE_DIR);+ const parsed = await readJSONFile(join(CACHE_DIR, `${accountId}.json`), { syncCursor: null, events: [] });+ if (!parsed || !Array.isArray(parsed.events)) return { syncCursor: null, events: [] };+ return parsed;+}++async function saveCache(accountId, cache) {+ await ensureDir(CACHE_DIR);+ await writeFile(join(CACHE_DIR, `${accountId}.json`), JSON.stringify(cache, null, 2));+}++export async function pushSyncEvents(accountId, calendarId, calendarName, rawEvents, io) {+ const account = await getAccount(accountId);+ if (!account) throw new Error('Account not found');++ const cache = await loadCache(accountId);+ const normalized = rawEvents.map(e => normalizeGoogleEvent(e, calendarId, calendarName));++ // Build map of existing events for this subcalendar+ const existingMap = new Map(+ cache.events+ .filter(e => e.externalId && e.subcalendarId === calendarId)+ .map(e => [e.externalId, e])+ );++ let newCount = 0;+ let updatedCount = 0;+ const incomingIds = new Set();++ for (const event of normalized) {+ incomingIds.add(event.externalId);+ if (existingMap.has(event.externalId)) {+ // Update mutable fields+ const existing = existingMap.get(event.externalId);+ existing.title = event.title;+ existing.description = event.description;+ existing.location = event.location;+ existing.startTime = event.startTime;+ existing.endTime = event.endTime;+ existing.isAllDay = event.isAllDay;+ existing.isCancelled = event.isCancelled;+ existing.syncedAt = event.syncedAt;+ updatedCount++;+ } else {+ cache.events.push(event);+ newCount++;+ }+ }++ // Prune events for this subcalendar that are no longer present+ const before = cache.events.length;+ cache.events = cache.events.filter(e =>+ e.subcalendarId !== calendarId || incomingIds.has(e.externalId)+ );+ const pruned = before - cache.events.length;++ await saveCache(accountId, cache);+ await updateSyncStatus(accountId, 'success');++ io?.emit('calendar:sync:completed', {+ accountId,+ calendarId,+ calendarName,+ newEvents: newCount,+ updated: updatedCount,+ pruned,+ status: 'success'+ });++ console.log(`📅 Google push sync for ${calendarName}: ${newCount} new, ${updatedCount} updated, ${pruned} pruned`);+ return { newEvents: newCount, updated: updatedCount, pruned, total: cache.events.length, status: 'success' };+}++const mcpSyncLock = new Map();++export async function mcpSyncAccount(accountId, io) {+ if (mcpSyncLock.has(accountId)) return { error: 'MCP sync already in progress', status: 409 };++ const account = await getAccount(accountId);+ if (!account) return { error: 'Account not found', status: 404 };+ if (account.type !== 'google-calendar') return { error: 'Not a Google Calendar account', status: 400 };++ const enabledCalendars = (account.subcalendars || []).filter(sc => sc.enabled && !sc.dormant);+ if (enabledCalendars.length === 0) return { error: 'No enabled subcalendars', status: 400 };++ mcpSyncLock.set(accountId, true);+ io?.emit('calendar:sync:started', { accountId, method: 'mcp' });+ console.log(`📅 Starting MCP sync for ${account.name} (${enabledCalendars.length} calendars)`);++ const now = new Date();+ const pastDate = new Date(now);+ pastDate.setDate(pastDate.getDate() - 7);+ const futureDate = new Date(now);+ futureDate.setDate(futureDate.getDate() + 30);+ const timeMin = pastDate.toISOString().slice(0, 19);+ const timeMax = futureDate.toISOString().slice(0, 19);++ const calendarList = enabledCalendars.map(sc => `- Calendar: "${sc.name}", ID: "${sc.calendarId}"`).join('\n');++ const prompt = `You have access to Google Calendar MCP tools. Fetch events from the following calendars for the date range ${timeMin} to ${timeMax}.++${calendarList}++For EACH calendar, call gcal_list_events with the calendarId, timeMin, and timeMax. Use maxResults=250.++After fetching ALL calendars, output ONLY a single JSON object (no markdown fences, no explanation) with this exact structure:+{"calendars":[{"calendarId":"...","calendarName":"...","events":[...raw events from gcal_list_events response...]}]}++Include the full events arrays as returned by gcal_list_events. Output NOTHING else — just the JSON.`;++ const result = await runClaudeMcp(prompt, io, accountId).catch(err => {+ console.error(`❌ MCP sync failed for ${account.name}: ${err.message}`);+ return { error: err.message };+ });++ mcpSyncLock.delete(accountId);++ if (result.error) {+ io?.emit('calendar:sync:failed', { accountId, error: result.error, method: 'mcp' });+ await updateSyncStatus(accountId, 'error');+ return { error: result.error, status: 502 };+ }++ // Parse Claude's output and push events+ const parsed = parseCalendarJson(result.output);+ if (!parsed) {+ const errMsg = 'Failed to parse calendar data from Claude response';+ io?.emit('calendar:sync:failed', { accountId, error: errMsg, method: 'mcp' });+ await updateSyncStatus(accountId, 'error');+ console.error(`❌ ${errMsg}`);+ return { error: errMsg, status: 502 };+ }++ let totalNew = 0;+ let totalUpdated = 0;+ let totalPruned = 0;+ const results = [];++ for (const cal of parsed.calendars) {+ if (!cal.calendarId || !Array.isArray(cal.events)) continue;+ const syncResult = await pushSyncEvents(accountId, cal.calendarId, cal.calendarName || cal.calendarId, cal.events, null);+ totalNew += syncResult.newEvents;+ totalUpdated += syncResult.updated;+ totalPruned += syncResult.pruned;+ results.push({ calendarId: cal.calendarId, calendarName: cal.calendarName, ...syncResult });+ }++ await updateSyncStatus(accountId, 'success');+ io?.emit('calendar:sync:completed', { accountId, newEvents: totalNew, updated: totalUpdated, pruned: totalPruned, status: 'success', method: 'mcp' });+ console.log(`📅 MCP sync complete for ${account.name}: ${totalNew} new, ${totalUpdated} updated, ${totalPruned} pruned across ${results.length} calendars`);++ return { newEvents: totalNew, updated: totalUpdated, pruned: totalPruned, calendars: results, status: 'success' };+}++function parseCalendarJson(output) {+ // Try to extract JSON from Claude's response+ // Look for {"calendars":...} pattern+ const jsonMatch = output.match(/\{[\s\S]*"calendars"\s*:\s*\[[\s\S]*\]\s*\}/);+ if (jsonMatch) {+ const parsed = JSON.parse(jsonMatch[0]);+ if (parsed?.calendars) return parsed;+ }+ // Try parsing the entire output as JSON+ const parsed = JSON.parse(output);+ if (parsed?.calendars) return parsed;+ return null;+}++export async function mcpDiscoverCalendars(accountId, io) {+ const account = await getAccount(accountId);+ if (!account) return { error: 'Account not found', status: 404 };+ if (account.type !== 'google-calendar') return { error: 'Not a Google Calendar account', status: 400 };++ console.log(`📅 Discovering Google calendars for ${account.name} via MCP`);+ io?.emit('calendar:sync:progress', { accountId, message: 'Discovering calendars via Claude...' });++ const prompt = `You have access to Google Calendar MCP tools. Call gcal_list_calendars to list all available calendars. If there are more pages (nextPageToken), fetch all pages.++Output ONLY a JSON array (no markdown fences, no explanation) of calendar objects with this structure:+[{"id":"...","name":"...","color":"..."}]++For each calendar, use:+- id: the calendar id field+- name: summaryOverride or summary+- color: backgroundColor++Output NOTHING else — just the JSON array.`;++ const result = await runClaudeMcp(prompt, io, accountId).catch(err => {+ console.error(`❌ Calendar discovery failed: ${err.message}`);+ return { error: err.message };+ });++ if (result.error) {+ return { error: result.error, status: 502 };+ }++ // Parse the calendar list from Claude's output+ const match = result.output.match(/\[[\s\S]*\]/);+ if (!match) return { error: 'Failed to parse calendar list from Claude response', status: 502 };++ const calendars = JSON.parse(match[0]);+ if (!Array.isArray(calendars)) return { error: 'Invalid calendar list format', status: 502 };++ // Merge with existing subcalendars (preserve enabled/dormant state)+ const existingMap = new Map((account.subcalendars || []).map(sc => [sc.calendarId, sc]));+ const merged = calendars.map(cal => {+ const existing = existingMap.get(cal.id);+ return {+ calendarId: cal.id,+ name: cal.name || cal.id,+ color: cal.color || existing?.color || '',+ enabled: existing?.enabled ?? false,+ dormant: existing?.dormant ?? false,+ goalIds: existing?.goalIds || [],+ addedAt: existing?.addedAt || new Date().toISOString()+ };+ });++ // Save merged subcalendars+ const { updateSubcalendars } = await import('./calendarAccounts.js');+ await updateSubcalendars(accountId, merged);++ console.log(`📅 Discovered ${calendars.length} calendars for ${account.name}`);+ return { calendars: merged, status: 'success' };+}++function runClaudeMcp(prompt, io, accountId) {+ return new Promise((resolve, reject) => {+ const args = ['-p', '-', '--allowedTools', 'mcp__claude_ai_Google_Calendar__*'];+ const claudeProcess = spawn(process.env.CLAUDE_PATH || 'claude', args, {+ cwd: process.cwd(),+ shell: false,+ env: (() => { const e = { ...process.env }; delete e.CLAUDECODE; return e; })()+ });++ let output = '';+ let stderr = '';+ const timeout = setTimeout(() => {+ claudeProcess.kill('SIGTERM');+ reject(new Error('MCP sync timed out after 5 minutes'));+ }, 300000);++ claudeProcess.stdin.write(prompt);+ claudeProcess.stdin.end();++ claudeProcess.stdout?.on('data', (data) => {+ output += data.toString();+ });++ claudeProcess.stderr?.on('data', (data) => {+ const text = data.toString();+ stderr += text;+ // Emit progress for UI feedback+ if (text.includes('gcal_list_events')) {+ io?.emit('calendar:sync:progress', { accountId, message: 'Fetching calendar events...' });+ }+ });++ claudeProcess.on('close', (code) => {+ clearTimeout(timeout);+ if (code !== 0 && !output) {+ reject(new Error(stderr.slice(0, 500) || `Claude exited with code ${code}`));+ } else {+ resolve({ output: output.trim(), exitCode: code });+ }+ });++ claudeProcess.on('error', (err) => {+ clearTimeout(timeout);+ reject(new Error(`Failed to spawn Claude CLI: ${err.message}`));+ });+ });+}diff --git a/server/services/calendarSync.js b/server/services/calendarSync.jsindex 4490871fb2..df2e4827c8 100644--- a/server/services/calendarSync.js+++ b/server/services/calendarSync.js@@ -125,6 +125,9 @@ export async function syncAccount(accountId, io, options = {}) {if (account.type === 'outlook-calendar') {const { syncOutlookCalendarApi } = await import('./calendarApiSync.js');providerResult = await syncOutlookCalendarApi(account, cache, io, options);+ } else if (account.type === 'google-calendar') {+ // Google Calendar uses push sync — syncAccount is a no-op+ return { newEvents: 0, pruned: 0, total: cache.events.length, status: 'push-only' };} else {throw new Error(`Unsupported calendar account type: ${account.type}`);}diff --git a/server/services/dailyReview.js b/server/services/dailyReview.jsnew file mode 100644index 0000000000..8abac4c305--- /dev/null+++ b/server/services/dailyReview.js@@ -0,0 +1,158 @@+import { writeFile } from 'fs/promises';+import { join } from 'path';+import { v4 as uuidv4 } from 'uuid';+import { ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';+import * as calendarSync from './calendarSync.js';+import * as calendarAccounts from './calendarAccounts.js';+import { addProgressEntry, getGoals } from './identity.js';++const REVIEW_DIR = join(PATHS.calendar, 'daily-reviews');++async function loadReview(date) {+ await ensureDir(REVIEW_DIR);+ return readJSONFile(join(REVIEW_DIR, `${date}.json`), null);+}++async function saveReview(date, data) {+ await ensureDir(REVIEW_DIR);+ await writeFile(join(REVIEW_DIR, `${date}.json`), JSON.stringify(data, null, 2));+}++export async function getDailyReview(date) {+ // Get all events for this date across all accounts+ const startDate = `${date}T00:00:00`;+ const endDate = `${date}T23:59:59`;+ const { events } = await calendarSync.getEvents({ startDate, endDate, limit: 200 });++ // Load existing review data for this date+ const existing = await loadReview(date) || { confirmations: {}, updatedAt: null };++ // Get accounts for subcalendar info+ const accounts = await calendarAccounts.listAccounts();+ const subcalendarMap = {};+ for (const account of accounts) {+ for (const sc of (account.subcalendars || [])) {+ subcalendarMap[sc.calendarId] = { ...sc, accountName: account.name };+ }+ }++ // Get goals for linking info+ const goalsData = await getGoals();+ const goalMap = {};+ for (const goal of goalsData.goals) {+ goalMap[goal.id] = goal;+ // Build reverse map: subcalendarId -> goalIds+ for (const lc of (goal.linkedCalendars || [])) {+ if (!subcalendarMap[lc.subcalendarId]) continue;+ if (!subcalendarMap[lc.subcalendarId].linkedGoals) subcalendarMap[lc.subcalendarId].linkedGoals = [];+ subcalendarMap[lc.subcalendarId].linkedGoals.push({ goalId: goal.id, goalTitle: goal.title, matchPattern: lc.matchPattern });+ }+ }++ // Enrich events with confirmation status and goal matches+ const enrichedEvents = events.map(event => {+ const confirmation = existing.confirmations[event.id || event.externalId];+ const subcalInfo = subcalendarMap[event.subcalendarId];+ const matchingGoals = (subcalInfo?.linkedGoals || []).filter(lg => {+ if (!lg.matchPattern) return true;+ return event.title?.toLowerCase().includes(lg.matchPattern.toLowerCase());+ });++ return {+ ...event,+ subcalendarColor: subcalInfo?.color,+ subcalendarName: event.subcalendarName || subcalInfo?.name,+ confirmation: confirmation || null,+ matchingGoals+ };+ });++ // Get progress entries for this date+ const progressEntries = [];+ for (const goal of goalsData.goals) {+ for (const entry of (goal.progressLog || [])) {+ if (entry.date === date) {+ progressEntries.push({ ...entry, goalId: goal.id, goalTitle: goal.title });+ }+ }+ }++ // Find last sync time+ let lastSyncAt = null;+ for (const account of accounts) {+ if (account.lastSyncAt && (!lastSyncAt || account.lastSyncAt > lastSyncAt)) {+ lastSyncAt = account.lastSyncAt;+ }+ }++ return {+ date,+ events: enrichedEvents,+ confirmations: existing.confirmations,+ progressEntries,+ lastSyncAt,+ summary: {+ totalEvents: enrichedEvents.length,+ confirmed: Object.values(existing.confirmations).filter(c => c.happened).length,+ skipped: Object.values(existing.confirmations).filter(c => c.happened === false).length,+ unreviewed: enrichedEvents.length - Object.keys(existing.confirmations).length+ },+ updatedAt: existing.updatedAt+ };+}++export async function confirmEvent(date, { eventId, happened, goalId, durationMinutes, note }) {+ const existing = await loadReview(date) || { confirmations: {}, updatedAt: null };++ existing.confirmations[eventId] = {+ happened,+ goalId: goalId || null,+ durationMinutes: durationMinutes || null,+ note: note || '',+ confirmedAt: new Date().toISOString()+ };+ existing.updatedAt = new Date().toISOString();++ await saveReview(date, existing);++ // If event happened and linked to a goal, auto-create progress entry+ let progressEntry = null;+ if (happened && goalId) {+ const entryNote = note || 'Calendar event confirmed';+ progressEntry = await addProgressEntry(goalId, {+ date,+ note: entryNote,+ ...(durationMinutes ? { durationMinutes } : {})+ });+ console.log(`📅 Auto-logged progress for goal ${goalId} from daily review`);+ }++ console.log(`📅 Event ${eventId} ${happened ? 'confirmed' : 'skipped'} for ${date}`);+ return { confirmation: existing.confirmations[eventId], progressEntry };+}++export async function getDailyReviewHistory(startDate, endDate) {+ await ensureDir(REVIEW_DIR);+ const { readdir } = await import('fs/promises');+ const files = await readdir(REVIEW_DIR).catch(() => []);++ const reviews = [];+ for (const file of files) {+ if (!file.endsWith('.json')) continue;+ const reviewDate = file.replace('.json', '');+ if (startDate && reviewDate < startDate) continue;+ if (endDate && reviewDate > endDate) continue;+ const data = await readJSONFile(join(REVIEW_DIR, file), null);+ if (!data) continue;+ const confirmations = Object.values(data.confirmations || {});+ reviews.push({+ date: reviewDate,+ confirmed: confirmations.filter(c => c.happened).length,+ skipped: confirmations.filter(c => c.happened === false).length,+ total: confirmations.length,+ updatedAt: data.updatedAt+ });+ }++ return reviews.sort((a, b) => b.date.localeCompare(a.date));+}diff --git a/server/services/googleAuth.js b/server/services/googleAuth.jsnew file mode 100644index 0000000000..91ad830faf--- /dev/null+++ b/server/services/googleAuth.js@@ -0,0 +1,117 @@+import { google } from 'googleapis';+import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';+import { ensureDir, PATHS } from '../lib/fileUtils.js';++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'];++let oAuth2Client = null;++async function ensureAuthDir() {+ await ensureDir(AUTH_DIR);+}++export async function getCredentials() {+ await ensureAuthDir();+ const raw = await readFile(CREDENTIALS_FILE, 'utf-8').catch(() => null);+ if (!raw) return null;+ return JSON.parse(raw);+}++export async function saveCredentials({ clientId, clientSecret }) {+ await ensureAuthDir();+ const credentials = { clientId, clientSecret, redirectUri: 'http://localhost:5555/api/calendar/google/oauth/callback' };+ await writeFile(CREDENTIALS_FILE, JSON.stringify(credentials, null, 2));+ oAuth2Client = null; // Reset client+ console.log('📅 Google OAuth credentials saved');+ return credentials;+}++export async function getTokens() {+ await ensureAuthDir();+ const raw = await readFile(TOKENS_FILE, 'utf-8').catch(() => null);+ if (!raw) return null;+ return JSON.parse(raw);+}++async function saveTokens(tokens) {+ await ensureAuthDir();+ await writeFile(TOKENS_FILE, JSON.stringify(tokens, null, 2));+ console.log('📅 Google OAuth tokens saved');+}++export async function clearAuth() {+ await ensureAuthDir();+ await writeFile(TOKENS_FILE, '{}').catch(() => {});+ oAuth2Client = null;+ console.log('📅 Google OAuth tokens cleared');+}++function createOAuth2Client(credentials) {+ return new google.auth.OAuth2(+ credentials.clientId,+ credentials.clientSecret,+ credentials.redirectUri || 'http://localhost:5555/api/calendar/google/oauth/callback'+ );+}++export async function getAuthUrl() {+ const credentials = await getCredentials();+ if (!credentials) return { error: 'No Google OAuth credentials configured' };++ const client = createOAuth2Client(credentials);+ const url = client.generateAuthUrl({+ access_type: 'offline',+ prompt: 'consent',+ scope: SCOPES+ });+ return { url };+}++export async function handleCallback(code) {+ const credentials = await getCredentials();+ if (!credentials) return { error: 'No credentials configured' };++ const client = createOAuth2Client(credentials);+ const { tokens } = await client.getToken(code);+ await saveTokens(tokens);+ oAuth2Client = client;+ oAuth2Client.setCredentials(tokens);+ console.log('📅 Google OAuth callback processed, tokens stored');+ return { success: true };+}++export async function getAuthenticatedClient() {+ const credentials = await getCredentials();+ if (!credentials?.clientId) return null;++ const tokens = await getTokens();+ if (!tokens?.access_token) return null;++ if (!oAuth2Client) {+ oAuth2Client = createOAuth2Client(credentials);+ oAuth2Client.setCredentials(tokens);++ // Listen for token refresh+ oAuth2Client.on('tokens', async (newTokens) => {+ const existing = await getTokens();+ await saveTokens({ ...existing, ...newTokens });+ console.log('📅 Google OAuth tokens refreshed');+ });+ }++ return oAuth2Client;+}++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+ };+}diff --git a/server/services/identity.js b/server/services/identity.jsindex 49003b4cf7..e88f5f646f 100644--- a/server/services/identity.js+++ b/server/services/identity.js@@ -696,6 +696,7 @@ export async function getGoals() {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 (!Array.isArray(goal.linkedCalendars)) { goal.linkedCalendars = []; needsSave = true; }}if (needsSave) await saveJSON(GOALS_FILE, data);return data;@@ -999,3 +1000,70 @@ export async function completeMilestone(goalId, milestoneId) {await saveJSON(GOALS_FILE, goals);return milestone;}++export async function linkCalendarToGoal(goalId, { subcalendarId, subcalendarName, matchPattern }) {+ const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);+ const goal = goals.goals.find(g => g.id === goalId);+ if (!goal) return null;++ if (!goal.linkedCalendars) goal.linkedCalendars = [];++ // Prevent duplicates+ const existing = goal.linkedCalendars.find(lc => lc.subcalendarId === subcalendarId);+ if (existing) {+ existing.subcalendarName = subcalendarName;+ existing.matchPattern = matchPattern || '';+ } else {+ goal.linkedCalendars.push({+ subcalendarId,+ subcalendarName,+ matchPattern: matchPattern || '',+ linkedAt: new Date().toISOString()+ });+ }++ goal.updatedAt = new Date().toISOString();+ goals.updatedAt = new Date().toISOString();+ await saveJSON(GOALS_FILE, goals);+ console.log(`📅 Calendar "${subcalendarName}" linked to goal "${goal.title}"`);+ return goal;+}++export async function unlinkCalendarFromGoal(goalId, subcalendarId) {+ const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);+ const goal = goals.goals.find(g => g.id === goalId);+ if (!goal) return null;++ if (!goal.linkedCalendars) return goal;+ const idx = goal.linkedCalendars.findIndex(lc => lc.subcalendarId === subcalendarId);+ if (idx === -1) return goal;++ goal.linkedCalendars.splice(idx, 1);+ goal.updatedAt = new Date().toISOString();+ goals.updatedAt = new Date().toISOString();+ await saveJSON(GOALS_FILE, goals);+ console.log(`📅 Calendar unlinked from goal "${goal.title}"`);+ return goal;+}++export async function getGoalCalendarEvents(goalId, startDate, endDate) {+ const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);+ const goal = goals.goals.find(g => g.id === goalId);+ if (!goal || !goal.linkedCalendars?.length) return [];++ const { getEvents } = await import('./calendarSync.js');+ const { events } = await getEvents({ startDate, endDate, limit: 200 });++ const linkedIds = new Set(goal.linkedCalendars.map(lc => lc.subcalendarId));+ const patternMap = {};+ for (const lc of goal.linkedCalendars) {+ patternMap[lc.subcalendarId] = lc.matchPattern;+ }++ return events.filter(e => {+ if (!linkedIds.has(e.subcalendarId)) return false;+ const pattern = patternMap[e.subcalendarId];+ if (!pattern) return true;+ return e.title?.toLowerCase().includes(pattern.toLowerCase());+ });+}