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(goals): add AI-powered goal check-ins
Adam Eivy1218e3760f1d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 3bbcd2a20a..c7ce0d1e8e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -27,6 +27,7 @@- Legacy Portrait export format — comprehensive human-readable Markdown document consolidating identity docs, traits, chronotype, taste profile, genome, longevity, goals, autobiography, and social presence- Autobiography prompt chains — LLM-generated follow-up questions after saving a story, enabling deeper exploration of life themes with linked story chains- RSS/Atom feed ingestion — subscribe to feeds, fetch/parse articles, read/mark-read from Brain > Feeds tab+- AI-powered goal check-ins — "Run Check-In" button on goal detail panel generates LLM assessment of goal health (on-track/behind/at-risk), actionable recommendations, and motivational encouragement based on progress, velocity, milestones, and activity attendance## Changeddiff --git a/client/src/components/goals/GoalDetailPanel.jsx b/client/src/components/goals/GoalDetailPanel.jsxindex 96bd32b3a5..a4f9455213 100644--- a/client/src/components/goals/GoalDetailPanel.jsx+++ b/client/src/components/goals/GoalDetailPanel.jsx@@ -130,6 +130,7 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh })const [proposedPhases, setProposedPhases] = useState(null);const [schedulingBusy, setSchedulingBusy] = useState(false);const [checkInsOpen, setCheckInsOpen] = useState(false);+ const [checkingIn, setCheckingIn] = useState(false);useEffect(() => {api.getActivities().then(setActivities).catch(() => {});@@ -196,6 +197,14 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh })onRefresh();};+ const handleCheckIn = async () => {+ setCheckingIn(true);+ await api.checkInGoal(goal.id).catch(() => null);+ setCheckingIn(false);+ setCheckInsOpen(true);+ onRefresh();+ };+const handleSchedule = async () => {setSchedulingBusy(true);await api.scheduleGoalTimeBlocks(goal.id);@@ -948,47 +957,60 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh })</div>{/* Check-ins */}- {goal.checkIns?.length > 0 && (- <div>+ <div>+ <div className="flex items-center justify-between mb-2"><buttononClick={() => setCheckInsOpen(!checkInsOpen)}- className="flex items-center gap-1 text-xs font-medium text-gray-400 hover:text-white w-full"+ className="flex items-center gap-1 text-xs font-medium text-gray-400 hover:text-white">{checkInsOpen ? <ChevronDown className="w-3.5 h-3.5" /> : <ChevronRight className="w-3.5 h-3.5" />}<ClipboardCheck className="w-3.5 h-3.5" />- <span>Check-ins ({goal.checkIns.length})</span>- {(() => {+ <span>Check-ins ({goal.checkIns?.length || 0})</span>+ {goal.checkIns?.length > 0 && (() => {const latest = goal.checkIns[goal.checkIns.length - 1];- return <span className={`ml-auto w-2 h-2 rounded-full ${CHECK_IN_DOT_COLORS[latest.status] || 'bg-gray-500'}`} />;+ return <span className={`ml-1 w-2 h-2 rounded-full ${CHECK_IN_DOT_COLORS[latest.status] || 'bg-gray-500'}`} />;})()}</button>- {checkInsOpen && (- <div className="mt-2 space-y-2 max-h-48 overflow-y-auto">- {[...goal.checkIns].reverse().map(ci => {- const sc = CHECK_IN_STATUS_CONFIG[ci.status] || CHECK_IN_STATUS_CONFIG['behind'];- return (- <div key={ci.id} className="p-2 rounded bg-port-bg border border-port-border space-y-1">- <div className="flex items-center justify-between">- <span className="text-[10px] text-gray-500">{new Date(ci.date + 'T00:00:00').toLocaleDateString()}</span>- <span className={`px-1.5 py-0.5 rounded text-[10px] ${sc.bg} ${sc.color}`}>{sc.label}</span>- </div>- <div className="text-[10px] text-gray-500">- Progress: {ci.actualProgress}% / {ci.expectedProgress}% expected- {ci.attendanceRate != null && ` · ${ci.attendanceRate}% activity`}- </div>- {ci.assessment && <p className="text-xs text-gray-300">{ci.assessment}</p>}- {ci.recommendations?.length > 0 && (- <ul className="text-[10px] text-gray-400 list-disc pl-3 space-y-0.5">- {ci.recommendations.map((r, i) => <li key={i}>{r}</li>)}- </ul>- )}- </div>- );- })}- </div>+ {goal.status === 'active' && (+ <button+ onClick={handleCheckIn}+ disabled={checkingIn}+ className="flex items-center gap-1 px-2 py-1 text-[10px] rounded bg-port-accent/20 text-port-accent hover:bg-port-accent/30 disabled:opacity-50"+ >+ <Wand2 className={`w-3 h-3 ${checkingIn ? 'animate-spin' : ''}`} />+ {checkingIn ? 'Checking in...' : 'Run Check-In'}+ </button>)}</div>- )}+ {checkInsOpen && goal.checkIns?.length > 0 && (+ <div className="space-y-2 max-h-48 overflow-y-auto">+ {[...goal.checkIns].reverse().map(ci => {+ const sc = CHECK_IN_STATUS_CONFIG[ci.status] || CHECK_IN_STATUS_CONFIG['behind'];+ return (+ <div key={ci.id} className="p-2 rounded bg-port-bg border border-port-border space-y-1">+ <div className="flex items-center justify-between">+ <span className="text-[10px] text-gray-500">{new Date(ci.date + 'T00:00:00').toLocaleDateString()}</span>+ <span className={`px-1.5 py-0.5 rounded text-[10px] ${sc.bg} ${sc.color}`}>{sc.label}</span>+ </div>+ <div className="text-[10px] text-gray-500">+ Progress: {ci.actualProgress}%{ci.expectedProgress != null && ` / ${ci.expectedProgress}% expected`}+ {ci.attendanceRate != null && ` · ${ci.attendanceRate}% activity`}+ </div>+ {ci.assessment && <p className="text-xs text-gray-300">{ci.assessment}</p>}+ {ci.recommendations?.length > 0 && (+ <ul className="text-[10px] text-gray-400 list-disc pl-3 space-y-0.5">+ {ci.recommendations.map((r, i) => <li key={i}>{r}</li>)}+ </ul>+ )}+ {ci.encouragement && (+ <p className="text-[10px] text-port-accent italic">{ci.encouragement}</p>+ )}+ </div>+ );+ })}+ </div>+ )}+ </div>{/* Progress Log */}<div>diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 6aeab64415..0a220c7209 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -1924,6 +1924,7 @@ export const generateGoalPhases = (goalId, options = {}) => request(`/digital-twexport const acceptGoalPhases = (goalId, phases) => request(`/digital-twin/identity/goals/${goalId}/accept-phases`, { method: 'POST', body: JSON.stringify({ phases }) });export const organizeGoals = (options = {}) => request('/digital-twin/identity/goals/organize', { method: 'POST', body: JSON.stringify(options) });export const applyGoalOrganization = (organization) => request('/digital-twin/identity/goals/organize/apply', { method: 'POST', body: JSON.stringify({ organization }) });+export const checkInGoal = (goalId, options = {}) => request(`/digital-twin/identity/goals/${goalId}/check-in`, { method: 'POST', body: JSON.stringify(options) });export const scheduleGoalTimeBlocks = (goalId) => request(`/digital-twin/identity/goals/${goalId}/schedule`, { method: 'POST' });export const removeGoalSchedule = (goalId) => request(`/digital-twin/identity/goals/${goalId}/schedule`, { method: 'DELETE' });export const rescheduleGoalTimeBlocks = (goalId) => request(`/digital-twin/identity/goals/${goalId}/reschedule`, { method: 'POST' });diff --git a/server/lib/identityValidation.js b/server/lib/identityValidation.jsindex b56d98b250..d091ab9821 100644--- a/server/lib/identityValidation.js+++ b/server/lib/identityValidation.js@@ -158,6 +158,8 @@ export const linkCalendarInputSchema = z.object({export const organizeGoalsInputSchema = aiProviderInputSchema;+export const checkInGoalInputSchema = aiProviderInputSchema;+export const applyOrganizationInputSchema = z.object({organization: z.array(z.object({id: z.string().min(1),diff --git a/server/routes/identity.js b/server/routes/identity.jsindex 7fc6e638b3..1018a2607b 100644--- a/server/routes/identity.js+++ b/server/routes/identity.js@@ -17,7 +17,8 @@ import {generatePhasesInputSchema,acceptPhasesInputSchema,organizeGoalsInputSchema,- applyOrganizationInputSchema+ applyOrganizationInputSchema,+ checkInGoalInputSchema} from '../lib/identityValidation.js';import * as goalCalendarScheduler from '../services/goalCalendarScheduler.js';@@ -281,6 +282,13 @@ router.post('/goals/organize/apply', asyncHandler(async (req, res) => {res.json(result);}));+// POST /api/digital-twin/identity/goals/:id/check-in — AI-powered goal check-in+router.post('/goals/:id/check-in', asyncHandler(async (req, res) => {+ const data = validateRequest(checkInGoalInputSchema, req.body);+ const checkIn = await identityService.checkInGoal(req.params.id, data);+ res.status(201).json(checkIn);+}));+// POST /api/digital-twin/identity/goals/:id/schedule — Create time blocksrouter.post('/goals/:id/schedule', asyncHandler(async (req, res) => {const result = await goalCalendarScheduler.scheduleTimeBlocks(req.params.id);diff --git a/server/services/identity.js b/server/services/identity.jsindex 24921c9415..3f43a195be 100644--- a/server/services/identity.js+++ b/server/services/identity.js@@ -1284,6 +1284,105 @@ export async function applyGoalOrganization(organization) {return { applied: changed };}+// =============================================================================+// Goal AI Check-In+// =============================================================================++export async function checkInGoal(goalId, { providerId, model } = {}) {+ const { getActiveProvider, getProviderById } = await import('./providers.js');+ const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);+ const goal = goals.goals.find(g => g.id === goalId);+ if (!goal) throw new ServerError('Goal not found', { status: 404, code: 'NOT_FOUND' });++ const provider = providerId ? await getProviderById(providerId) : await getActiveProvider();+ if (!provider) throw new ServerError('No AI provider available', { status: 503, code: 'NO_PROVIDER' });+ const selectedModel = model ?? provider.defaultModel;++ const today = new Date().toISOString().slice(0, 10);+ const velocity = computeGoalVelocity(goal);++ // Calculate expected progress based on creation date and target date+ let expectedProgress = null;+ if (goal.targetDate) {+ const created = new Date(goal.createdAt).getTime();+ const target = new Date(goal.targetDate + 'T00:00:00').getTime();+ const now = Date.now();+ const elapsed = now - created;+ const total = target - created;+ expectedProgress = total > 0 ? Math.min(100, Math.round((elapsed / total) * 100)) : 100;+ }++ // Gather activity attendance if linked activities exist+ let attendanceRate = null;+ if (goal.linkedActivities?.length > 0) {+ const totalRequired = goal.linkedActivities.reduce((sum, a) => sum + (a.requiredFrequency || 1), 0);+ const recentEntries = (goal.progressLog || []).filter(e => {+ const daysAgo = (Date.now() - new Date(e.date + 'T00:00:00').getTime()) / (1000 * 60 * 60 * 24);+ return daysAgo <= 30;+ });+ attendanceRate = totalRequired > 0 ? Math.min(100, Math.round((recentEntries.length / (totalRequired * 4)) * 100)) : null;+ }++ const milestoneSummary = (goal.milestones || []).map(m =>+ `- ${m.title}${m.completedAt ? ' (DONE)' : m.targetDate ? ` (due ${m.targetDate})` : ''}`+ ).join('\n');++ const recentProgress = (goal.progressLog || []).slice(-5).map(e =>+ `- ${e.date}: ${e.note}${e.durationMinutes ? ` (${e.durationMinutes}min)` : ''}`+ ).join('\n');++ const prompt = `You are a goal coaching assistant doing a check-in assessment. Analyze the current state of this goal and provide honest, actionable feedback.++Goal: ${goal.title}+Description: ${goal.description || 'No description'}+Category: ${goal.category}+Horizon: ${goal.horizon}+Current progress: ${goal.progress}%${expectedProgress != null ? `\nExpected progress by now: ${expectedProgress}%` : ''}+Target date: ${goal.targetDate || 'None set'}+Created: ${goal.createdAt?.slice(0, 10)}+Today: ${today}${velocity ? `\nVelocity: ${velocity.percentPerMonth}%/month (${velocity.trend})${velocity.projectedCompletion ? `, projected completion: ${velocity.projectedCompletion}` : ''}` : ''}${attendanceRate != null ? `\nActivity attendance (30 days): ${attendanceRate}%` : ''}+${milestoneSummary ? `\nMilestones:\n${milestoneSummary}` : ''}+${recentProgress ? `\nRecent progress entries:\n${recentProgress}` : '\nNo recent progress logged.'}++Respond with JSON only (no markdown fences). The response must be an object with:+- "status": "on-track" | "behind" | "at-risk" — honest assessment of goal health+- "assessment": string — 2-3 sentence assessment of where things stand+- "recommendations": string[] — 2-4 specific, actionable next steps+- "encouragement": string — 1 brief motivational sentence`;++ const result = await callProviderAISimple(provider, selectedModel, prompt, { max_tokens: 1000, temperature: 0.5 });+ if (result.error) throw new ServerError(`AI check-in failed: ${result.error}`, { status: 502, code: 'AI_ERROR' });++ let parsed;+ try {+ parsed = parseLLMJSON(result.text);+ } catch (e) {+ throw new ServerError(`AI returned invalid check-in data: ${e.message}`, { status: 502, code: 'AI_PARSE_ERROR' });+ }++ const validStatuses = ['on-track', 'behind', 'at-risk'];+ const checkIn = {+ id: `ci-${uuidv4()}`,+ date: today,+ status: validStatuses.includes(parsed.status) ? parsed.status : 'behind',+ actualProgress: goal.progress,+ expectedProgress,+ attendanceRate,+ assessment: parsed.assessment || '',+ recommendations: Array.isArray(parsed.recommendations) ? parsed.recommendations.slice(0, 5) : [],+ encouragement: parsed.encouragement || '',+ createdAt: new Date().toISOString()+ };++ goal.checkIns.push(checkIn);+ goal.updatedAt = new Date().toISOString();+ goals.updatedAt = new Date().toISOString();+ await saveJSON(GOALS_FILE, goals);++ console.log(`📋 Check-in for "${goal.title}": ${checkIn.status} (${goal.progress}%${expectedProgress != null ? ` vs ${expectedProgress}% expected` : ''})`);+ return checkIn;+}+// =============================================================================// Goal Progress Percentage// =============================================================================