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
fix([issue-1422]): guard goal re-plan against orphaned scheduledEvents + validate raw LLM proposals
Adam Eivy4478b8fd58f3
diff --git a/server/lib/identityValidation.js b/server/lib/identityValidation.jsindex 64bb434902..4c650fc72f 100644--- a/server/lib/identityValidation.js+++ b/server/lib/identityValidation.js@@ -130,6 +130,34 @@ export const acceptDecompositionInputSchema = z.object({})).min(1).max(20)});+// --- Goal Proposal Schemas (generation-time validation of raw LLM output) ---+//+// generateGoalPhases / decomposeGoal return the LLM proposal to the review UI+// WITHOUT persisting it, so the user can edit before accept. These schemas+// validate/coerce that raw output at generation time and fail fast with a clear+// AI_PARSE_ERROR instead of passing a malformed shape (non-object element,+// missing title, wrong-typed tasks) downstream to only blow up at accept-time.+//+// Intentionally looser than the accept schemas: `targetDate` is a free string+// here (the LLM commonly emits a near-miss date the user fixes in review; the+// strict validCalendarDate check still runs at accept), `order` is optional (the+// service fills it from the array index), and unknown keys are stripped. The+// strictness is on structural shape — title present, tasks well-formed.+export const goalPhaseProposalSchema = z.object({+ title: z.string().min(1).max(500),+ description: z.string().max(5000).optional().default(''),+ targetDate: z.string().max(40).nullable().optional(),+ order: z.number().int().min(0).optional()+});++export const goalPhasesProposalSchema = z.array(goalPhaseProposalSchema).min(1).max(50);++export const goalDecompositionMilestoneProposalSchema = goalPhaseProposalSchema.extend({+ tasks: z.array(decomposedTaskSchema).max(50).optional().default([])+});++export const goalDecompositionProposalSchema = z.array(goalDecompositionMilestoneProposalSchema).min(1).max(50);+// --- Goal Progress Log Schemas ---export const addProgressEntrySchema = z.object({diff --git a/server/services/identity/goals.js b/server/services/identity/goals.jsindex eefb33c68c..2619cbd094 100644--- a/server/services/identity/goals.js+++ b/server/services/identity/goals.js@@ -2,7 +2,11 @@ import { v4 as uuidv4 } from '../../lib/uuid.js';import { ServerError } from '../../lib/errorHandler.js';import { getActivities } from '../meatspaceCalendar.js';import { callProviderAISimple, parseLLMJSON } from '../../lib/aiProvider.js';-import { goalTypeEnum } from '../../lib/identityValidation.js';+import {+ goalTypeEnum,+ goalPhasesProposalSchema,+ goalDecompositionProposalSchema+} from '../../lib/identityValidation.js';import {GOALS_FILE,LONGEVITY_FILE,@@ -569,6 +573,24 @@ export async function getGoalCalendarEvents(goalId, startDate, endDate) {// AI Phase Planning// =============================================================================+// Re-planning (acceptGoalPhases / acceptGoalDecomposition) replaces+// goal.milestones wholesale, which would orphan any goal.scheduledEvents — each+// references an old milestone id AND a live Google Calendar block. Refuse to+// overwrite milestones while scheduled events exist so calendar blocks aren't+// silently stranded; the user unschedules first (removeScheduledEvents /+// rescheduleTimeBlocks). A 409 reject is chosen over auto-deleting here because+// deletion requires live Google OAuth — coupling accept to calendar auth would+// either fail the accept (no token) or silently orphan events if swallowed.+// Applied identically by both accept paths to keep them consistent.+function assertNoScheduledEvents(goal) {+ if (goal.scheduledEvents?.length) {+ throw new ServerError(+ 'Goal has scheduled calendar events tied to the current milestones. Unschedule them before re-planning so the calendar blocks are not orphaned.',+ { status: 409, code: 'GOAL_HAS_SCHEDULED_EVENTS' }+ );+ }+}+export async function generateGoalPhases(goalId, { providerId, model } = {}) {const { getActiveProvider, getProviderById } = await import('../providers.js');const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);@@ -609,16 +631,21 @@ Respond with a JSON array only (no markdown fences, no explanation). Each elemen} catch (e) {throw new ServerError(`AI returned invalid phase data: ${e.message}`, { status: 502, code: 'AI_PARSE_ERROR' });}- if (!Array.isArray(parsed)) throw new ServerError('AI returned invalid phase data', { status: 502, code: 'AI_PARSE_ERROR' });+ const validated = goalPhasesProposalSchema.safeParse(parsed);+ if (!validated.success) {+ const detail = validated.error.issues[0]?.message || 'shape mismatch';+ throw new ServerError(`AI returned invalid phase data: ${detail}`, { status: 502, code: 'AI_PARSE_ERROR' });+ }- console.log(`🎯 Generated ${parsed.length} phases for goal "${goal.title}"`);- return parsed;+ console.log(`🎯 Generated ${validated.data.length} phases for goal "${goal.title}"`);+ return validated.data;}export async function acceptGoalPhases(goalId, phases) {const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);const goal = goals.goals.find(g => g.id === goalId);if (!goal) throw new ServerError('Goal not found', { status: 404, code: 'NOT_FOUND' });+ assertNoScheduledEvents(goal);goal.milestones = phases.map((phase, idx) => ({id: `ms-${uuidv4()}`,@@ -687,11 +714,16 @@ ${goal.targetDate ? '- "targetDate": string (YYYY-MM-DD format)\n' : ''}- "order} catch (e) {throw new ServerError(`AI returned invalid decomposition data: ${e.message}`, { status: 502, code: 'AI_PARSE_ERROR' });}- if (!Array.isArray(parsed)) throw new ServerError('AI returned invalid decomposition data', { status: 502, code: 'AI_PARSE_ERROR' });+ const validated = goalDecompositionProposalSchema.safeParse(parsed);+ if (!validated.success) {+ const detail = validated.error.issues[0]?.message || 'shape mismatch';+ throw new ServerError(`AI returned invalid decomposition data: ${detail}`, { status: 502, code: 'AI_PARSE_ERROR' });+ }- const taskCount = parsed.reduce((sum, ms) => sum + (Array.isArray(ms?.tasks) ? ms.tasks.length : 0), 0);- console.log(`🧩 Decomposed goal "${goal.title}" into ${parsed.length} milestones / ${taskCount} tasks`);- return parsed;+ const milestones = validated.data;+ const taskCount = milestones.reduce((sum, ms) => sum + ms.tasks.length, 0);+ console.log(`🧩 Decomposed goal "${goal.title}" into ${milestones.length} milestones / ${taskCount} tasks`);+ return milestones;}// Persists a reviewed decomposition proposal, normalizing each milestone's@@ -701,6 +733,7 @@ export async function acceptGoalDecomposition(goalId, milestones) {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' });+ assertNoScheduledEvents(goal);const now = new Date().toISOString();goal.milestones = milestones.map((ms, idx) => ({diff --git a/server/services/identity/goals.test.js b/server/services/identity/goals.test.jsindex 66c7aff535..3577f74190 100644--- a/server/services/identity/goals.test.js+++ b/server/services/identity/goals.test.js@@ -24,8 +24,8 @@ vi.mock('../../lib/aiProvider.js', async (importOriginal) => {});const {- computeGoalVelocity, getGoals, decomposeGoal,- acceptGoalDecomposition, completeMilestoneTask+ computeGoalVelocity, getGoals, decomposeGoal, generateGoalPhases,+ acceptGoalPhases, acceptGoalDecomposition, completeMilestoneTask} = await import('./goals.js');describe('computeGoalVelocity', () => {@@ -156,3 +156,92 @@ describe('goal decomposition', () => {expect(data.goals[0].milestones[0].tasks).toEqual([]);});});++describe('proposal validation (raw LLM output)', () => {+ beforeEach(() => {+ h.goalsData = {+ goals: [{+ id: 'goal-1', title: 'Write a novel', description: 'A fantasy epic',+ targetDate: '2027-01-01', milestones: []+ }],+ birthDate: null+ };+ h.aiText = '';+ });++ it('generateGoalPhases coerces/strips and returns a clean proposal', async () => {+ h.aiText = JSON.stringify([+ { title: 'Phase 1', description: 'Start', targetDate: '2026-09-01', order: 0, junk: 'x' }+ ]);+ const phases = await generateGoalPhases('goal-1', {});+ expect(phases).toHaveLength(1);+ expect(phases[0].title).toBe('Phase 1');+ expect(phases[0].junk).toBeUndefined(); // unknown keys stripped+ });++ it('generateGoalPhases throws AI_PARSE_ERROR when an element is missing its title', async () => {+ h.aiText = JSON.stringify([{ description: 'no title', targetDate: '2026-09-01', order: 0 }]);+ await expect(generateGoalPhases('goal-1', {})).rejects.toMatchObject({ status: 502, code: 'AI_PARSE_ERROR' });+ });++ it('generateGoalPhases throws AI_PARSE_ERROR on an empty array', async () => {+ h.aiText = JSON.stringify([]);+ await expect(generateGoalPhases('goal-1', {})).rejects.toMatchObject({ code: 'AI_PARSE_ERROR' });+ });++ it('decomposeGoal coerces task priority default and strips unknown milestone keys', async () => {+ h.aiText = JSON.stringify([+ { title: 'Outline', order: 0, extra: 'drop me', tasks: [{ title: 'Beat sheet' }] }+ ]);+ const proposal = await decomposeGoal('goal-1', {});+ expect(proposal[0].extra).toBeUndefined();+ expect(proposal[0].tasks[0].priority).toBe('medium'); // coerced default+ });++ it('decomposeGoal throws AI_PARSE_ERROR when a task has a non-string title', async () => {+ h.aiText = JSON.stringify([+ { title: 'Outline', order: 0, tasks: [{ title: 42 }] }+ ]);+ await expect(decomposeGoal('goal-1', {})).rejects.toMatchObject({ status: 502, code: 'AI_PARSE_ERROR' });+ });+});++describe('re-plan guard — orphaned scheduledEvents', () => {+ beforeEach(() => {+ h.goalsData = {+ goals: [{+ id: 'goal-1', title: 'Write a novel', description: 'A fantasy epic',+ targetDate: '2027-01-01', milestones: [{ id: 'ms-old', title: 'Old', order: 0, tasks: [] }]+ }],+ birthDate: null+ };+ h.aiText = '';+ });++ it('acceptGoalPhases rejects with 409 GOAL_HAS_SCHEDULED_EVENTS when calendar blocks exist', async () => {+ h.goalsData.goals[0].scheduledEvents = [{ id: 'sched-1', googleEventId: 'g1', milestoneId: 'ms-old' }];+ await expect(acceptGoalPhases('goal-1', [{ title: 'New', targetDate: '2026-09-01', order: 0 }]))+ .rejects.toMatchObject({ status: 409, code: 'GOAL_HAS_SCHEDULED_EVENTS' });+ // Milestones untouched — the wholesale replace never ran.+ expect(h.goalsData.goals[0].milestones[0].id).toBe('ms-old');+ });++ it('acceptGoalDecomposition rejects with 409 GOAL_HAS_SCHEDULED_EVENTS when calendar blocks exist', async () => {+ h.goalsData.goals[0].scheduledEvents = [{ id: 'sched-1', googleEventId: 'g1', milestoneId: 'ms-old' }];+ await expect(acceptGoalDecomposition('goal-1', [{ title: 'New', order: 0, tasks: [] }]))+ .rejects.toMatchObject({ status: 409, code: 'GOAL_HAS_SCHEDULED_EVENTS' });+ expect(h.goalsData.goals[0].milestones[0].id).toBe('ms-old');+ });++ it('accept paths proceed when scheduledEvents is empty or absent', async () => {+ // empty array+ h.goalsData.goals[0].scheduledEvents = [];+ const g1 = await acceptGoalPhases('goal-1', [{ title: 'Fresh', targetDate: '2026-09-01', order: 0 }]);+ expect(g1.milestones[0].title).toBe('Fresh');++ // absent entirely+ delete h.goalsData.goals[0].scheduledEvents;+ const g2 = await acceptGoalDecomposition('goal-1', [{ title: 'Fresh decomp', order: 0, tasks: [] }]);+ expect(g2.milestones[0].title).toBe('Fresh decomp');+ });+});