Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

address review: fix hierarchy linking, error handling, validation, and add tests

Adam Eivye7aba6ed2553
diff --git a/client/src/components/goals/GoalDetailPanel.jsx b/client/src/components/goals/GoalDetailPanel.jsx
index a2a01d2670..a849cb5206 100644
--- a/client/src/components/goals/GoalDetailPanel.jsx
+++ b/client/src/components/goals/GoalDetailPanel.jsx
@@ -37,7 +37,17 @@ const GOAL_TYPE_OPTIONS = Object.entries(GOAL_TYPE_CONFIG).map(([value, cfg]) =>
const MAX_TAGS = 20;
const MAX_TAG_LENGTH = 50;
-export { CATEGORY_CONFIG, HORIZON_OPTIONS, GOAL_TYPE_CONFIG, GOAL_TYPE_OPTIONS };
+const DEFAULT_NEW_GOAL = { title: '', description: '', horizon: '5-year', category: 'mastery', parentId: null };
+
+const CHECK_IN_STATUS_CONFIG = {
+ 'on-track': { color: 'text-green-400', bg: 'bg-green-500/20', label: 'On Track' },
+ 'behind': { color: 'text-yellow-400', bg: 'bg-yellow-500/20', label: 'Behind' },
+ 'at-risk': { color: 'text-red-400', bg: 'bg-red-500/20', label: 'At Risk' }
+};
+
+const CHECK_IN_DOT_COLORS = { 'on-track': 'bg-green-500', 'behind': 'bg-yellow-500', 'at-risk': 'bg-red-500' };
+
+export { CATEGORY_CONFIG, HORIZON_OPTIONS, GOAL_TYPE_CONFIG, GOAL_TYPE_OPTIONS, DEFAULT_NEW_GOAL };
function ProgressSlider({ goal, onCommit }) {
const [draft, setDraft] = useState(goal.progress ?? 0);
@@ -947,21 +957,15 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh })
{checkInsOpen ? <ChevronDown className="w-3.5 h-3.5" /> : <ChevronRight className="w-3.5 h-3.5" />}
<ClipboardCheck className="w-3.5 h-3.5" />
<span>Check-ins ({goal.checkIns.length})</span>
- {goal.checkIns.length > 0 && (() => {
+ {(() => {
const latest = goal.checkIns[goal.checkIns.length - 1];
- const statusColors = { 'on-track': 'bg-green-500', 'behind': 'bg-yellow-500', 'at-risk': 'bg-red-500' };
- return <span className={`ml-auto w-2 h-2 rounded-full ${statusColors[latest.status] || 'bg-gray-500'}`} />;
+ return <span className={`ml-auto 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 statusConfig = {
- 'on-track': { color: 'text-green-400', bg: 'bg-green-500/20', label: 'On Track' },
- 'behind': { color: 'text-yellow-400', bg: 'bg-yellow-500/20', label: 'Behind' },
- 'at-risk': { color: 'text-red-400', bg: 'bg-red-500/20', label: 'At Risk' }
- };
- const sc = statusConfig[ci.status] || statusConfig['behind'];
+ 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">
diff --git a/client/src/components/goals/GoalsListView.jsx b/client/src/components/goals/GoalsListView.jsx
index 182e02acad..8c024cd48f 100644
--- a/client/src/components/goals/GoalsListView.jsx
+++ b/client/src/components/goals/GoalsListView.jsx
@@ -4,7 +4,7 @@ import {
} from 'lucide-react';
import toast from 'react-hot-toast';
import * as api from '../../services/api';
-import GoalDetailPanel, { CATEGORY_CONFIG, HORIZON_OPTIONS, GOAL_TYPE_CONFIG } from './GoalDetailPanel';
+import GoalDetailPanel, { CATEGORY_CONFIG, HORIZON_OPTIONS, GOAL_TYPE_CONFIG, DEFAULT_NEW_GOAL } from './GoalDetailPanel';
import { applyOrganizationSuggestion } from './applyOrganization';
function urgencyIndicator(urgency) {
@@ -127,7 +127,7 @@ export default function GoalsListView({ data, onRefresh }) {
const [selectedGoal, setSelectedGoal] = useState(null);
const [searchQuery, setSearchQuery] = useState('');
const [showNewGoal, setShowNewGoal] = useState(false);
- const [newGoal, setNewGoal] = useState({ title: '', description: '', horizon: '5-year', category: 'mastery', parentId: null });
+ const [newGoal, setNewGoal] = useState({ ...DEFAULT_NEW_GOAL });
const [organizing, setOrganizing] = useState(false);
const toggleExpand = (id) => {
@@ -158,14 +158,14 @@ export default function GoalsListView({ data, onRefresh }) {
};
const handleAddChild = (parentId) => {
- setNewGoal({ title: '', description: '', horizon: '5-year', category: 'mastery', parentId });
+ setNewGoal({ ...DEFAULT_NEW_GOAL, parentId });
setShowNewGoal(true);
};
const handleCreateGoal = async () => {
if (!newGoal.title.trim()) return;
await api.createGoal(newGoal);
- setNewGoal({ title: '', description: '', horizon: '5-year', category: 'mastery', parentId: null });
+ setNewGoal({ ...DEFAULT_NEW_GOAL });
setShowNewGoal(false);
onRefresh();
};
@@ -197,7 +197,7 @@ export default function GoalsListView({ data, onRefresh }) {
</div>
<button
onClick={() => {
- setNewGoal({ title: '', description: '', horizon: '5-year', category: 'mastery', parentId: null });
+ setNewGoal({ ...DEFAULT_NEW_GOAL });
setShowNewGoal(true);
}}
className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-lg bg-port-accent text-white hover:bg-blue-600"
diff --git a/client/src/components/goals/GoalsTreeView.jsx b/client/src/components/goals/GoalsTreeView.jsx
index 3039728a99..66bba55a27 100644
--- a/client/src/components/goals/GoalsTreeView.jsx
+++ b/client/src/components/goals/GoalsTreeView.jsx
@@ -6,7 +6,7 @@ import { Search, Plus, Wand2, X, Check, Star, Crown } from 'lucide-react';
import toast from 'react-hot-toast';
import * as api from '../../services/api';
import { layoutGoalNodes } from './goalTreeLayout';
-import GoalDetailPanel, { CATEGORY_CONFIG, HORIZON_OPTIONS, GOAL_TYPE_CONFIG } from './GoalDetailPanel';
+import GoalDetailPanel, { CATEGORY_CONFIG, HORIZON_OPTIONS, GOAL_TYPE_CONFIG, DEFAULT_NEW_GOAL } from './GoalDetailPanel';
import { applyOrganizationSuggestion } from './applyOrganization';
const EDGE_COLORS = {
@@ -246,7 +246,7 @@ export default function GoalsTreeView({ data, onRefresh }) {
Object.fromEntries(Object.keys(CATEGORY_CONFIG).map(k => [k, true]))
);
const [showNewGoal, setShowNewGoal] = useState(false);
- const [newGoal, setNewGoal] = useState({ title: '', description: '', horizon: '5-year', category: 'mastery' });
+ const [newGoal, setNewGoal] = useState({ ...DEFAULT_NEW_GOAL });
const [organizing, setOrganizing] = useState(false);
const [orgSuggestion, setOrgSuggestion] = useState(null);
const [applyingOrg, setApplyingOrg] = useState(false);
@@ -305,7 +305,7 @@ export default function GoalsTreeView({ data, onRefresh }) {
const handleCreateGoal = async () => {
if (!newGoal.title.trim()) return;
await api.createGoal(newGoal);
- setNewGoal({ title: '', description: '', horizon: '5-year', category: 'mastery' });
+ setNewGoal({ ...DEFAULT_NEW_GOAL });
setShowNewGoal(false);
onRefresh();
};
diff --git a/client/src/components/goals/applyOrganization.js b/client/src/components/goals/applyOrganization.js
index 9648fe0426..3fb0eff825 100644
--- a/client/src/components/goals/applyOrganization.js
+++ b/client/src/components/goals/applyOrganization.js
@@ -2,6 +2,8 @@ import * as api from '../../services/api';
export async function applyOrganizationSuggestion(suggestion) {
let apexId = null;
+ // Clone organization array to avoid mutating caller's state
+ const organization = suggestion.organization?.map(item => ({ ...item }));
// Create apex goal if suggested as new
if (suggestion.apexGoal?.suggestedTitle && !suggestion.apexGoal?.existingId) {
@@ -11,11 +13,12 @@ export async function applyOrganizationSuggestion(suggestion) {
horizon: 'lifetime',
category: 'legacy',
goalType: 'apex'
- }).catch(() => null);
- apexId = apex?.id;
+ }).then(res => res, () => null);
+ if (!apex?.id) return false;
+ apexId = apex.id;
// Rewrite organization items that should parent under new apex
- if (apexId && suggestion.organization) {
- for (const item of suggestion.organization) {
+ if (organization) {
+ for (const item of organization) {
if (item.suggestedParentId === '__new_apex__' || (!item.suggestedParentId && item.goalType === 'sub-apex')) {
item.suggestedParentId = apexId;
}
@@ -23,21 +26,32 @@ export async function applyOrganizationSuggestion(suggestion) {
}
}
- // Create suggested sub-apex goals in parallel
+ // Resolve apex ID: prefer existing, fall back to newly created
+ if (!apexId && suggestion.apexGoal?.existingId) {
+ apexId = suggestion.apexGoal.existingId;
+ }
+
+ // Create suggested sub-apex goals in parallel, parented under the apex
if (suggestion.suggestedSubApex?.length) {
- await Promise.all(suggestion.suggestedSubApex.map(sg =>
- api.createGoal({
+ const results = await Promise.all(suggestion.suggestedSubApex.map(sg => {
+ const parentId = apexId || (sg.suggestedParentId !== '__new_apex__' ? sg.suggestedParentId : null) || null;
+ return api.createGoal({
title: sg.title,
description: sg.description || '',
horizon: 'lifetime',
category: sg.category || 'legacy',
- goalType: 'sub-apex'
- }).catch(() => null)
- ));
+ goalType: 'sub-apex',
+ ...(parentId ? { parentId } : {})
+ }).then(() => true, () => false);
+ }));
+ if (results.some(r => !r)) return false;
}
// Apply organization to existing goals
- if (suggestion.organization?.length) {
- await api.applyGoalOrganization(suggestion.organization).catch(() => null);
+ if (organization?.length) {
+ const ok = await api.applyGoalOrganization(organization).then(() => true, () => false);
+ if (!ok) return false;
}
+
+ return true;
}
diff --git a/client/src/components/goals/goalTreeLayout.js b/client/src/components/goals/goalTreeLayout.js
index 48a3b34013..b468f7ee9e 100644
--- a/client/src/components/goals/goalTreeLayout.js
+++ b/client/src/components/goals/goalTreeLayout.js
@@ -55,12 +55,11 @@ export function layoutGoalNodes(flatGoals) {
x: (i - (apexGoals.length - 1) / 2) * 2,
y: 0,
z: (rng() - 0.5) * 1.5,
- vx: 0, vy: 0, vz: 0
});
});
// Position sub-apex goals in a tight inner ring around apex
- const subApexRadius = apexGoals.length > 0 ? RING_RADIUS * 0.6 : 0;
+ const subApexRadius = RING_RADIUS * 0.6;
subApexGoals.forEach((goal, i) => {
const rng = seededRandom(goal.id);
const parent = goal.parentId ? positioned.get(goal.parentId) : null;
@@ -72,7 +71,6 @@ export function layoutGoalNodes(flatGoals) {
x: baseX + Math.cos(angle) * subApexRadius,
y: (rng() - 0.5) * Y_SPREAD * 0.5,
z: baseZ + Math.sin(angle) * subApexRadius,
- vx: 0, vy: 0, vz: 0
});
});
@@ -111,8 +109,7 @@ export function layoutGoalNodes(flatGoals) {
positioned.set(goal.id, {
...goal,
- x, y, z,
- vx: 0, vy: 0, vz: 0
+ x, y, z
});
});
}
diff --git a/server/lib/identityValidation.js b/server/lib/identityValidation.js
index 71cef57fa0..b56d98b250 100644
--- a/server/lib/identityValidation.js
+++ b/server/lib/identityValidation.js
@@ -162,7 +162,7 @@ export const applyOrganizationInputSchema = z.object({
organization: z.array(z.object({
id: z.string().min(1),
goalType: goalTypeEnum.optional(),
- suggestedParentId: z.string().nullable().optional(),
+ suggestedParentId: z.string().min(1).nullable().optional(),
reasoning: z.string().optional()
})).min(1)
});
diff --git a/server/services/identity.js b/server/services/identity.js
index f275244843..7dd6a4b307 100644
--- a/server/services/identity.js
+++ b/server/services/identity.js
@@ -1207,9 +1207,12 @@ ${JSON.stringify(goalSummaries, null, 2)}
Respond with JSON only (no markdown fences). The response must be an object with:
- "apexGoal": { "existingId": string|null, "suggestedTitle": string|null, "suggestedDescription": string|null } — if an existing goal IS the apex, set existingId. If no existing goal fits, suggest a new one.
- "organization": array of { "id": string, "goalType": "apex"|"sub-apex"|"standard", "suggestedParentId": string|null, "reasoning": string }
- - For each existing goal, assign its type and suggested parent. Use null parentId for apex and top-level sub-apex goals.
+ - For each existing goal, assign its type and suggested parent.
+ - The apex goal has null parentId.
+ - Sub-apex goals MUST have suggestedParentId set to the apex goal's existingId (if an existing goal is the apex) or "__new_apex__" (if you are suggesting a new apex goal). Sub-apex goals are never root nodes.
+ - Standard goals should have suggestedParentId set to the most appropriate sub-apex goal id, or to the apex goal id if they directly support the apex.
- The reasoning should be 1 sentence explaining why this goal fits where it does.
-- "suggestedSubApex": array of { "title": string, "description": string, "category": string } — suggest 0-3 sub-apex goals if the existing goals don't cover major life pillars well.
+- "suggestedSubApex": array of { "title": string, "description": string, "category": string, "suggestedParentId": string|null } — suggest 0-3 sub-apex goals if the existing goals don't cover major life pillars well. Set suggestedParentId to the apex goal's existingId or "__new_apex__" if suggesting a new apex.
- "analysis": string — 2-3 sentences summarizing the person's core purpose and how their goals connect.`;
const result = await callProviderAISimple(provider, selectedModel, prompt, { max_tokens: 3000, temperature: 0.4 });
diff --git a/server/services/identity.test.js b/server/services/identity.test.js
index ad08034413..d1a8b90361 100644
--- a/server/services/identity.test.js
+++ b/server/services/identity.test.js
@@ -1583,3 +1583,309 @@ describe('Integration: Calendar Linking', () => {
expect(result).toBeNull();
});
});
+
+// =============================================================================
+// Goal Hierarchy Organization
+// =============================================================================
+
+describe('Integration: applyGoalOrganization', () => {
+ let createGoal, getGoals, applyGoalOrganization;
+
+ beforeEach(async () => {
+ vi.resetModules();
+
+ vi.doMock('fs/promises', () => {
+ const store = {};
+ return {
+ readFile: vi.fn(async (path) => {
+ if (store[path]) return store[path];
+ throw new Error('ENOENT');
+ }),
+ writeFile: vi.fn(async (path, data) => {
+ store[path] = data;
+ }),
+ mkdir: vi.fn(async () => {})
+ };
+ });
+
+ vi.doMock('./genome.js', () => ({
+ getGenomeSummary: vi.fn(async () => ({
+ uploaded: false, markerCount: 0, uploadedAt: null, savedMarkers: {}
+ }))
+ }));
+
+ vi.doMock('./taste-questionnaire.js', () => ({
+ getTasteProfile: vi.fn(async () => ({
+ completedCount: 0, totalSections: 5, overallPercentage: 0, lastSessionAt: null
+ }))
+ }));
+
+ const mod = await import('./identity.js');
+ createGoal = mod.createGoal;
+ getGoals = mod.getGoals;
+ applyGoalOrganization = mod.applyGoalOrganization;
+ });
+
+ it('should apply goalType and parentId changes to goals', async () => {
+ const apex = await createGoal({ title: 'Apex Goal' });
+ const sub = await createGoal({ title: 'Sub Apex Goal' });
+ const standard = await createGoal({ title: 'Standard Goal' });
+
+ const result = await applyGoalOrganization([
+ { id: apex.id, goalType: 'apex', suggestedParentId: null },
+ { id: sub.id, goalType: 'sub-apex', suggestedParentId: apex.id },
+ { id: standard.id, goalType: 'standard', suggestedParentId: sub.id }
+ ]);
+
+ expect(result.applied).toBe(3);
+
+ const goals = await getGoals();
+ const updatedApex = goals.goals.find(g => g.id === apex.id);
+ const updatedSub = goals.goals.find(g => g.id === sub.id);
+ const updatedStandard = goals.goals.find(g => g.id === standard.id);
+
+ expect(updatedApex.goalType).toBe('apex');
+ expect(updatedApex.parentId).toBeNull();
+ expect(updatedSub.goalType).toBe('sub-apex');
+ expect(updatedSub.parentId).toBe(apex.id);
+ expect(updatedStandard.goalType).toBe('standard');
+ expect(updatedStandard.parentId).toBe(sub.id);
+ });
+
+ it('should prevent a goal from becoming its own parent', async () => {
+ const goal = await createGoal({ title: 'Self Referencing' });
+
+ await applyGoalOrganization([
+ { id: goal.id, goalType: 'standard', suggestedParentId: goal.id }
+ ]);
+
+ const goals = await getGoals();
+ const updated = goals.goals.find(g => g.id === goal.id);
+
+ // parentId should remain null — self-cycle prevented
+ expect(updated.parentId).toBeNull();
+ });
+
+ it('should prevent ancestor cycles in reparenting', async () => {
+ const a = await createGoal({ title: 'A' });
+ const b = await createGoal({ title: 'B', parentId: a.id });
+ const c = await createGoal({ title: 'C', parentId: b.id });
+
+ // Try to make A a child of C (would create A->B->C->A cycle)
+ await applyGoalOrganization([
+ { id: a.id, suggestedParentId: c.id }
+ ]);
+
+ const goals = await getGoals();
+ const updatedA = goals.goals.find(g => g.id === a.id);
+
+ // parentId should remain null — cycle prevented
+ expect(updatedA.parentId).toBeNull();
+ });
+
+ it('should ignore invalid goalType values', async () => {
+ const goal = await createGoal({ title: 'Test Goal', goalType: 'standard' });
+
+ await applyGoalOrganization([
+ { id: goal.id, goalType: 'bogus' }
+ ]);
+
+ const goals = await getGoals();
+ const updated = goals.goals.find(g => g.id === goal.id);
+
+ // goalType should remain unchanged
+ expect(updated.goalType).toBe('standard');
+ });
+
+ it('should accept all valid goalType values', async () => {
+ const g1 = await createGoal({ title: 'Goal 1' });
+ const g2 = await createGoal({ title: 'Goal 2' });
+ const g3 = await createGoal({ title: 'Goal 3' });
+
+ await applyGoalOrganization([
+ { id: g1.id, goalType: 'apex' },
+ { id: g2.id, goalType: 'sub-apex' },
+ { id: g3.id, goalType: 'standard' }
+ ]);
+
+ const goals = await getGoals();
+ expect(goals.goals.find(g => g.id === g1.id).goalType).toBe('apex');
+ expect(goals.goals.find(g => g.id === g2.id).goalType).toBe('sub-apex');
+ expect(goals.goals.find(g => g.id === g3.id).goalType).toBe('standard');
+ });
+
+ it('should skip non-existent goal IDs without error', async () => {
+ const goal = await createGoal({ title: 'Exists' });
+
+ const result = await applyGoalOrganization([
+ { id: 'nonexistent', goalType: 'apex' },
+ { id: goal.id, goalType: 'sub-apex' }
+ ]);
+
+ // Only the existing goal counts as changed
+ expect(result.applied).toBe(1);
+
+ const goals = await getGoals();
+ expect(goals.goals.find(g => g.id === goal.id).goalType).toBe('sub-apex');
+ });
+
+ it('should skip reparenting to a non-existent parent', async () => {
+ const goal = await createGoal({ title: 'Goal' });
+
+ await applyGoalOrganization([
+ { id: goal.id, suggestedParentId: 'nonexistent-parent' }
+ ]);
+
+ const goals = await getGoals();
+ const updated = goals.goals.find(g => g.id === goal.id);
+
+ // parentId should remain null — target parent doesn't exist
+ expect(updated.parentId).toBeNull();
+ });
+
+ it('should allow clearing parentId by setting it to null', async () => {
+ const parent = await createGoal({ title: 'Parent' });
+ const child = await createGoal({ title: 'Child', parentId: parent.id });
+
+ await applyGoalOrganization([
+ { id: child.id, suggestedParentId: null }
+ ]);
+
+ const goals = await getGoals();
+ const updated = goals.goals.find(g => g.id === child.id);
+ expect(updated.parentId).toBeNull();
+ });
+});
+
+describe('Integration: organizeGoals', () => {
+ let organizeGoals, createGoal;
+
+ beforeEach(async () => {
+ vi.resetModules();
+
+ vi.doMock('fs/promises', () => {
+ const store = {};
+ return {
+ readFile: vi.fn(async (path) => {
+ if (store[path]) return store[path];
+ throw new Error('ENOENT');
+ }),
+ writeFile: vi.fn(async (path, data) => {
+ store[path] = data;
+ }),
+ mkdir: vi.fn(async () => {})
+ };
+ });
+
+ vi.doMock('./genome.js', () => ({
+ getGenomeSummary: vi.fn(async () => ({
+ uploaded: false, markerCount: 0, uploadedAt: null, savedMarkers: {}
+ }))
+ }));
+
+ vi.doMock('./taste-questionnaire.js', () => ({
+ getTasteProfile: vi.fn(async () => ({
+ completedCount: 0, totalSections: 5, overallPercentage: 0, lastSessionAt: null
+ }))
+ }));
+
+ vi.doMock('./providers.js', () => ({
+ getActiveProvider: vi.fn(async () => ({
+ id: 'mock-provider',
+ name: 'Mock AI',
+ defaultModel: 'mock-model'
+ })),
+ getProviderById: vi.fn(async () => ({
+ id: 'mock-provider',
+ name: 'Mock AI',
+ defaultModel: 'mock-model'
+ }))
+ }));
+
+ vi.doMock('../lib/aiProvider.js', () => ({
+ callProviderAISimple: vi.fn(async () => ({
+ text: JSON.stringify({
+ apexGoal: { existingId: null, suggestedTitle: 'Live fully', suggestedDescription: 'The ultimate purpose' },
+ organization: [
+ { id: 'g1', goalType: 'sub-apex', suggestedParentId: null, reasoning: 'Major life pillar' },
+ { id: 'g2', goalType: 'standard', suggestedParentId: 'g1', reasoning: 'Supports pillar' }
+ ],
+ suggestedSubApex: [],
+ analysis: 'Your goals center around personal growth.'
+ })
+ })),
+ parseLLMJSON: vi.fn((text) => JSON.parse(text))
+ }));
+
+ const mod = await import('./identity.js');
+ organizeGoals = mod.organizeGoals;
+ createGoal = mod.createGoal;
+ });
+
+ it('should return LLM organization suggestion', async () => {
+ await createGoal({ title: 'Health & Fitness' });
+ await createGoal({ title: 'Learn Spanish' });
+
+ const result = await organizeGoals();
+
+ expect(result.apexGoal).toBeDefined();
+ expect(result.apexGoal.suggestedTitle).toBe('Live fully');
+ expect(result.organization).toHaveLength(2);
+ expect(result.organization[0].goalType).toBe('sub-apex');
+ expect(result.organization[1].suggestedParentId).toBe('g1');
+ expect(result.analysis).toContain('personal growth');
+ });
+
+ it('should throw when fewer than 2 active goals', async () => {
+ await createGoal({ title: 'Only one' });
+
+ await expect(organizeGoals()).rejects.toMatchObject({ code: 'TOO_FEW_GOALS' });
+ });
+
+ it('should throw when no AI provider is available', async () => {
+ vi.resetModules();
+
+ vi.doMock('fs/promises', () => {
+ const store = {};
+ return {
+ readFile: vi.fn(async (path) => {
+ if (store[path]) return store[path];
+ throw new Error('ENOENT');
+ }),
+ writeFile: vi.fn(async (path, data) => { store[path] = data; }),
+ mkdir: vi.fn(async () => {})
+ };
+ });
+
+ vi.doMock('./genome.js', () => ({
+ getGenomeSummary: vi.fn(async () => ({
+ uploaded: false, markerCount: 0, uploadedAt: null, savedMarkers: {}
+ }))
+ }));
+
+ vi.doMock('./taste-questionnaire.js', () => ({
+ getTasteProfile: vi.fn(async () => ({
+ completedCount: 0, totalSections: 5, overallPercentage: 0, lastSessionAt: null
+ }))
+ }));
+
+ vi.doMock('./providers.js', () => ({
+ getActiveProvider: vi.fn(async () => null),
+ getProviderById: vi.fn(async () => null)
+ }));
+
+ vi.doMock('../lib/aiProvider.js', () => ({
+ callProviderAISimple: vi.fn(),
+ parseLLMJSON: vi.fn()
+ }));
+
+ const mod = await import('./identity.js');
+ const localCreateGoal = mod.createGoal;
+ const localOrganizeGoals = mod.organizeGoals;
+
+ await localCreateGoal({ title: 'Goal A' });
+ await localCreateGoal({ title: 'Goal B' });
+
+ await expect(localOrganizeGoals()).rejects.toMatchObject({ code: 'NO_PROVIDER' });
+ });
+});