Skip to content

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

feat: Goal Decomposition Engine — auto-decompose goals into milestone task sequences (#898)

Adam Eivy3260bc2b1ac5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ae63a0d6b0..f8c871482f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **[issue-898] Goal Decomposition Engine — auto-decompose a goal into milestones pre-populated with tasks.** Goals already had AI phase-planning, but `Generate Plan` only produced flat milestones with *no* tasks — you then hand-added every todo. A new **Decompose into Tasks** action (Goals → a goal's Plan section) turns a high-level goal into 3–7 ordered milestones, each carrying 2–5 concrete, estimated tasks (priority + minute estimate), in a single LLM pass. The proposal is fully reviewable before accept — reorder milestones, edit titles/descriptions, drop tasks or whole milestones — and only `Accept Tasks` persists it, normalizing each task with its own id and `pending` status (mirrors the existing generate→accept-phases review flow). Accepted tasks render nested under their milestone with check-off, and unlike phase-planning, decomposition works **without** a goal target date (relative ordering only). Server adds `decomposeGoal` / `acceptGoalDecomposition` / `completeMilestoneTask` (file-backed in `goals.json`, mirrored to MortalLoom iCloud — no Postgres migration) with three new validated routes; existing goals lazily gain `milestone.tasks = []` on load with no data loss. (`server/services/identity/goals.js`, `server/lib/identityValidation.js`, `server/routes/identity.js`, `client/src/hooks/useGoalDetail.js`, `client/src/components/goals/{GoalPlanSection,GoalMilestones}.jsx`, #898)
+
- **[issue-1298] Editorial checks flag soft chapter endings and missed POV cut-aways.** Two new pacing checks (Create → Editorial Checks) enforce the serial-fiction rule that *every chapter is an episode*. **Chapter-ending cliffhangers** (LLM) reads your drafted manuscript and flags chapter/issue endings that resolve and settle — "soft landings" that tie everything off mid-story instead of ending on an unresolved beat that pulls the reader forward — escalating severity when a mid-story chapter fully closes the very question that should carry the reader on, while leaving a clearly terminal final chapter alone. It reconciles detected endings against the **authored reader-map cliffhangers** you've logged on the series arc. **Cliffhanger POV switch** (deterministic) reads your reverse-outline POV map: in a multi-POV story, when a chapter ends on an authored cliffhanger the next chapter should cut to a *different* POV character to sustain the tension — so it flags each authored cliffhanger whose following chapter keeps the same viewpoint. It no-ops for single-POV series and when no cliffhangers are authored. One new stage prompt (`pipeline-editorial-endings-cliffhanger`) ships + migrates for existing installs. (#1298)
- **[issue-1295] Editorial check flags point-of-view characters who don't earn their viewpoint.** A new **POV justification** editorial check (Create → Editorial Checks) reads your reverse-outline scene segmentation — which already tags who holds POV in each scene — and surfaces two viewpoint problems. First, a **POV without an arc**: a character we spend scenes inside who has no detected character arc (their arc reads flat, or they don't show up in the story's detected arcs at all) — a viewpoint that exists only to deliver information, with no arc and no stakes, should be cut or folded into another POV. Second, the inverse — a **drive-by POV**: a character who holds the viewpoint in only a single scene, a one-off head-hop that reads as a structural seam. Each finding names the character and anchors to the scene where their viewpoint begins. The drive-by threshold and whether to run the no-arc check are configurable, and the no-arc check **degrades gracefully** — when there's no arc information yet (no analysis has run, or the series is only partially analyzed), it stays silent rather than guessing, while the structural drive-by check keeps working. Requires a generated reverse outline. (#1295)
diff --git a/client/src/components/goals/GoalDetailPanel.jsx b/client/src/components/goals/GoalDetailPanel.jsx
index 0f92d01ccf..50a4c44b28 100644
--- a/client/src/components/goals/GoalDetailPanel.jsx
+++ b/client/src/components/goals/GoalDetailPanel.jsx
@@ -193,6 +193,7 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh })
setNewMilestone={s.setNewMilestone}
handleAddMilestone={s.handleAddMilestone}
handleCompleteMilestone={s.handleCompleteMilestone}
+ handleCompleteMilestoneTask={s.handleCompleteMilestoneTask}
/>
{/* Target Date */}
@@ -213,6 +214,11 @@ export default function GoalDetailPanel({ goal, allGoals, onClose, onRefresh })
proposedPhases={s.proposedPhases}
setProposedPhases={s.setProposedPhases}
handleAcceptPhases={s.handleAcceptPhases}
+ decomposing={s.decomposing}
+ handleDecompose={s.handleDecompose}
+ proposedDecomposition={s.proposedDecomposition}
+ setProposedDecomposition={s.setProposedDecomposition}
+ handleAcceptDecomposition={s.handleAcceptDecomposition}
schedulingBusy={s.schedulingBusy}
handleSchedule={s.handleSchedule}
handleReschedule={s.handleReschedule}
diff --git a/client/src/components/goals/GoalMilestones.jsx b/client/src/components/goals/GoalMilestones.jsx
index 71ac10a11d..42dee74714 100644
--- a/client/src/components/goals/GoalMilestones.jsx
+++ b/client/src/components/goals/GoalMilestones.jsx
@@ -1,7 +1,9 @@
import { Milestone, Check, Calendar } from 'lucide-react';
+import { PRIORITY_BADGE } from './goalConstants';
export default function GoalMilestones({
- goal, newMilestone, setNewMilestone, handleAddMilestone, handleCompleteMilestone
+ goal, newMilestone, setNewMilestone, handleAddMilestone, handleCompleteMilestone,
+ handleCompleteMilestoneTask
}) {
return (
<div>
@@ -14,25 +16,57 @@ export default function GoalMilestones({
{goal.milestones?.length > 0 && (
<div className="space-y-1 mb-2">
{goal.milestones.map(ms => (
- <div key={ms.id} className="flex items-center gap-2 text-sm">
- <button
- onClick={() => !ms.completedAt && handleCompleteMilestone(ms.id)}
- className={`w-4 h-4 rounded border flex items-center justify-center shrink-0 ${
- ms.completedAt
- ? 'bg-green-500/20 border-green-500 text-green-400'
- : 'border-gray-600 hover:border-port-accent'
- }`}
- >
- {ms.completedAt && <Check className="w-3 h-3" />}
- </button>
- <span className={`text-xs ${ms.completedAt ? 'text-gray-500 line-through' : 'text-gray-300'}`}>
- {ms.title}
- </span>
- {ms.targetDate && (
- <span className="text-xs text-gray-600 ml-auto flex items-center gap-1">
- <Calendar className="w-3 h-3" />
- {new Date(ms.targetDate).toLocaleDateString()}
+ <div key={ms.id} className="space-y-1">
+ <div className="flex items-center gap-2 text-sm">
+ <button
+ onClick={() => !ms.completedAt && handleCompleteMilestone(ms.id)}
+ className={`w-4 h-4 rounded border flex items-center justify-center shrink-0 ${
+ ms.completedAt
+ ? 'bg-green-500/20 border-green-500 text-green-400'
+ : 'border-gray-600 hover:border-port-accent'
+ }`}
+ >
+ {ms.completedAt && <Check className="w-3 h-3" />}
+ </button>
+ <span className={`text-xs ${ms.completedAt ? 'text-gray-500 line-through' : 'text-gray-300'}`}>
+ {ms.title}
</span>
+ {ms.targetDate && (
+ <span className="text-xs text-gray-600 ml-auto flex items-center gap-1">
+ <Calendar className="w-3 h-3" />
+ {new Date(ms.targetDate).toLocaleDateString()}
+ </span>
+ )}
+ </div>
+ {ms.tasks?.length > 0 && (
+ <div className="pl-6 space-y-0.5">
+ {ms.tasks.map(task => {
+ const done = task.status === 'done';
+ return (
+ <div key={task.id} className="flex items-center gap-1.5 text-[11px]">
+ <button
+ onClick={() => handleCompleteMilestoneTask?.(ms.id, task.id)}
+ className={`w-3.5 h-3.5 rounded border flex items-center justify-center shrink-0 ${
+ done
+ ? 'bg-green-500/20 border-green-500 text-green-400'
+ : 'border-gray-600 hover:border-port-accent'
+ }`}
+ >
+ {done && <Check className="w-2.5 h-2.5" />}
+ </button>
+ <span className={`flex-1 min-w-0 truncate ${done ? 'text-gray-600 line-through' : 'text-gray-400'}`}>
+ {task.title}
+ </span>
+ {task.estimateMinutes != null && (
+ <span className="text-gray-600 shrink-0">{task.estimateMinutes}m</span>
+ )}
+ <span className={`shrink-0 px-1 rounded ${PRIORITY_BADGE[task.priority] || PRIORITY_BADGE.medium}`}>
+ {task.priority || 'medium'}
+ </span>
+ </div>
+ );
+ })}
+ </div>
)}
</div>
))}
diff --git a/client/src/components/goals/GoalPlanSection.jsx b/client/src/components/goals/GoalPlanSection.jsx
index b1e475b926..ebe737281a 100644
--- a/client/src/components/goals/GoalPlanSection.jsx
+++ b/client/src/components/goals/GoalPlanSection.jsx
@@ -1,11 +1,14 @@
import {
ChevronDown, ChevronRight, Wand2, ArrowUp, ArrowDown, Trash2, Plus,
- CalendarPlus, CalendarX, RefreshCw
+ CalendarPlus, CalendarX, RefreshCw, ListChecks
} from 'lucide-react';
+import { PRIORITY_BADGE } from './goalConstants';
export default function GoalPlanSection({
goal, planOpen, setPlanOpen, generatingPhases, handleGeneratePhases,
proposedPhases, setProposedPhases, handleAcceptPhases,
+ decomposing, handleDecompose, proposedDecomposition, setProposedDecomposition,
+ handleAcceptDecomposition,
schedulingBusy, handleSchedule, handleReschedule, handleRemoveSchedule
}) {
return (
@@ -132,6 +135,123 @@ export default function GoalPlanSection({
</div>
)}
+ {/* Decompose — milestones pre-populated with tasks */}
+ <button
+ onClick={handleDecompose}
+ disabled={decomposing}
+ className="w-full px-3 py-1.5 text-xs rounded bg-purple-500/20 text-purple-300 disabled:opacity-50 flex items-center justify-center gap-1"
+ >
+ <ListChecks className="w-3 h-3" />
+ {decomposing ? 'Decomposing...' : 'Decompose into Tasks'}
+ </button>
+ {proposedDecomposition && (
+ <div className="space-y-1.5">
+ <p className="text-[10px] text-gray-500">{proposedDecomposition.length} milestones proposed</p>
+ {proposedDecomposition.map((ms, idx) => (
+ <div key={idx} className="p-2 rounded bg-port-bg border border-port-border space-y-1.5">
+ <div className="flex items-start gap-2">
+ <div className="flex flex-col gap-0.5 pt-0.5">
+ <button
+ onClick={() => {
+ if (idx === 0) return;
+ const next = [...proposedDecomposition];
+ [next[idx - 1], next[idx]] = [next[idx], next[idx - 1]];
+ next.forEach((m, i) => { m.order = i; });
+ setProposedDecomposition(next);
+ }}
+ disabled={idx === 0}
+ className="text-gray-600 hover:text-white disabled:opacity-30"
+ >
+ <ArrowUp className="w-2.5 h-2.5" />
+ </button>
+ <button
+ onClick={() => {
+ if (idx === proposedDecomposition.length - 1) return;
+ const next = [...proposedDecomposition];
+ [next[idx], next[idx + 1]] = [next[idx + 1], next[idx]];
+ next.forEach((m, i) => { m.order = i; });
+ setProposedDecomposition(next);
+ }}
+ disabled={idx === proposedDecomposition.length - 1}
+ className="text-gray-600 hover:text-white disabled:opacity-30"
+ >
+ <ArrowDown className="w-2.5 h-2.5" />
+ </button>
+ </div>
+ <div className="flex-1 min-w-0">
+ <input
+ type="text"
+ value={ms.title}
+ onChange={e => {
+ const next = [...proposedDecomposition];
+ next[idx] = { ...next[idx], title: e.target.value };
+ setProposedDecomposition(next);
+ }}
+ className="w-full bg-port-card border border-port-border rounded px-2 py-0.5 text-xs text-white"
+ />
+ <input
+ type="text"
+ value={ms.description || ''}
+ onChange={e => {
+ const next = [...proposedDecomposition];
+ next[idx] = { ...next[idx], description: e.target.value };
+ setProposedDecomposition(next);
+ }}
+ placeholder="Description..."
+ className="w-full bg-port-card border border-port-border rounded px-2 py-0.5 text-xs text-gray-400 mt-0.5"
+ />
+ </div>
+ <button
+ onClick={() => setProposedDecomposition(proposedDecomposition.filter((_, i) => i !== idx).map((m, i) => ({ ...m, order: i })))}
+ className="text-gray-600 hover:text-red-400 pt-0.5"
+ >
+ <Trash2 className="w-3 h-3" />
+ </button>
+ </div>
+ {ms.tasks?.length > 0 && (
+ <div className="pl-5 space-y-0.5">
+ {ms.tasks.map((task, tIdx) => (
+ <div key={tIdx} className="flex items-center gap-1.5 text-[11px] text-gray-300">
+ <span className="flex-1 min-w-0 truncate">{task.title}</span>
+ {task.estimateMinutes != null && (
+ <span className="text-gray-600 shrink-0">{task.estimateMinutes}m</span>
+ )}
+ <span className={`shrink-0 px-1 rounded ${PRIORITY_BADGE[task.priority] || PRIORITY_BADGE.medium}`}>
+ {task.priority || 'medium'}
+ </span>
+ <button
+ onClick={() => {
+ const next = [...proposedDecomposition];
+ next[idx] = { ...next[idx], tasks: ms.tasks.filter((_, i) => i !== tIdx) };
+ setProposedDecomposition(next);
+ }}
+ className="text-gray-600 hover:text-red-400 shrink-0"
+ >
+ <Trash2 className="w-2.5 h-2.5" />
+ </button>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ ))}
+ <div className="flex gap-2">
+ <button
+ onClick={handleAcceptDecomposition}
+ className="px-3 py-1.5 text-xs rounded bg-port-accent text-white hover:bg-blue-600"
+ >
+ Accept Tasks
+ </button>
+ <button
+ onClick={() => setProposedDecomposition(null)}
+ className="px-3 py-1.5 text-xs rounded bg-port-border text-gray-300"
+ >
+ Discard
+ </button>
+ </div>
+ </div>
+ )}
+
{/* Schedule Controls */}
{goal.milestones?.length > 0 && goal.timeBlockConfig && (
<div className="pt-2 border-t border-port-border space-y-2">
diff --git a/client/src/components/goals/GoalTodoList.jsx b/client/src/components/goals/GoalTodoList.jsx
index 82ad047162..34ac7964aa 100644
--- a/client/src/components/goals/GoalTodoList.jsx
+++ b/client/src/components/goals/GoalTodoList.jsx
@@ -1,6 +1,7 @@
import { ListTodo, Check, CircleDot, Trash2 } from 'lucide-react';
import InlineConfirmRow from '../ui/InlineConfirmRow';
import { useConfirmDelete } from '../../hooks/useConfirmDelete';
+import { PRIORITY_BADGE } from './goalConstants';
export default function GoalTodoList({
goal, newTodoTitle, setNewTodoTitle, newTodoPriority, setNewTodoPriority,
@@ -37,11 +38,7 @@ export default function GoalTodoList({
{todo.title}
</span>
{/* Not <Pill>: px-1 is tighter than Pill's xs (px-1.5) and would be overridden. */}
- <span className={`shrink-0 px-1 py-0.5 rounded text-[10px] ${
- todo.priority === 'high' ? 'bg-red-500/20 text-red-400' :
- todo.priority === 'low' ? 'bg-gray-700 text-gray-500' :
- 'bg-yellow-500/20 text-yellow-400'
- }`}>
+ <span className={`shrink-0 px-1 py-0.5 rounded text-[10px] ${PRIORITY_BADGE[todo.priority] || PRIORITY_BADGE.medium}`}>
{todo.priority}
</span>
{todo.estimateMinutes && (
diff --git a/client/src/components/goals/goalConstants.js b/client/src/components/goals/goalConstants.js
index 2c5376b2d1..cedb547c12 100644
--- a/client/src/components/goals/goalConstants.js
+++ b/client/src/components/goals/goalConstants.js
@@ -40,3 +40,10 @@ export const CHECK_IN_STATUS_CONFIG = {
};
export const CHECK_IN_DOT_COLORS = { 'on-track': 'bg-green-500', 'behind': 'bg-yellow-500', 'at-risk': 'bg-red-500' };
+
+// Shared priority pill styling for todos and milestone tasks.
+export const PRIORITY_BADGE = {
+ high: 'bg-red-500/20 text-red-400',
+ medium: 'bg-yellow-500/20 text-yellow-400',
+ low: 'bg-gray-700 text-gray-500'
+};
diff --git a/client/src/hooks/useGoalDetail.js b/client/src/hooks/useGoalDetail.js
index 06ca9e091b..0502cafc67 100644
--- a/client/src/hooks/useGoalDetail.js
+++ b/client/src/hooks/useGoalDetail.js
@@ -24,6 +24,8 @@ export function useGoalDetail({ goal, allGoals, onClose, onRefresh }) {
const [planOpen, setPlanOpen] = useState(false);
const [generatingPhases, setGeneratingPhases] = useState(false);
const [proposedPhases, setProposedPhases] = useState(null);
+ const [decomposing, setDecomposing] = useState(false);
+ const [proposedDecomposition, setProposedDecomposition] = useState(null);
const [schedulingBusy, setSchedulingBusy] = useState(false);
const [checkInsOpen, setCheckInsOpen] = useState(false);
const [checkingIn, setCheckingIn] = useState(false);
@@ -86,6 +88,25 @@ export function useGoalDetail({ goal, allGoals, onClose, onRefresh }) {
onRefresh();
};
+ const handleDecompose = async () => {
+ setDecomposing(true);
+ const milestones = await api.decomposeGoal(goal.id).catch(() => null);
+ setDecomposing(false);
+ if (milestones) setProposedDecomposition(milestones);
+ };
+
+ const handleAcceptDecomposition = async () => {
+ if (!proposedDecomposition?.length) return;
+ await api.acceptGoalDecomposition(goal.id, proposedDecomposition);
+ setProposedDecomposition(null);
+ onRefresh();
+ };
+
+ const handleCompleteMilestoneTask = async (milestoneId, taskId) => {
+ await api.completeMilestoneTask(goal.id, milestoneId, taskId);
+ onRefresh();
+ };
+
const handleCheckIn = async () => {
setCheckingIn(true);
await api.checkInGoal(goal.id).catch(() => null);
@@ -269,11 +290,14 @@ export function useGoalDetail({ goal, allGoals, onClose, onRefresh }) {
planOpen, setPlanOpen,
generatingPhases,
proposedPhases, setProposedPhases,
+ decomposing,
+ proposedDecomposition, setProposedDecomposition,
schedulingBusy,
checkInsOpen, setCheckInsOpen,
checkingIn,
startEdit, saveEdit,
handleGeneratePhases, handleAcceptPhases,
+ handleDecompose, handleAcceptDecomposition, handleCompleteMilestoneTask,
handleCheckIn, handleSchedule, handleRemoveSchedule, handleReschedule,
handleDelete, handleComplete,
handleAddMilestone, handleCompleteMilestone,
diff --git a/client/src/services/apiGoals.js b/client/src/services/apiGoals.js
index 1b008d6686..15d7f9e741 100644
--- a/client/src/services/apiGoals.js
+++ b/client/src/services/apiGoals.js
@@ -63,6 +63,9 @@ export const deleteGoalTodo = (goalId, todoId) => request(`/digital-twin/identit
// Goal AI Planning & Scheduling
export const generateGoalPhases = (goalId, options = {}) => request(`/digital-twin/identity/goals/${goalId}/generate-phases`, { method: 'POST', body: JSON.stringify(options) });
export const acceptGoalPhases = (goalId, phases) => request(`/digital-twin/identity/goals/${goalId}/accept-phases`, { method: 'POST', body: JSON.stringify({ phases }) });
+export const decomposeGoal = (goalId, options = {}) => request(`/digital-twin/identity/goals/${goalId}/decompose`, { method: 'POST', body: JSON.stringify(options) });
+export const acceptGoalDecomposition = (goalId, milestones) => request(`/digital-twin/identity/goals/${goalId}/accept-decomposition`, { method: 'POST', body: JSON.stringify({ milestones }) });
+export const completeMilestoneTask = (goalId, milestoneId, taskId) => request(`/digital-twin/identity/goals/${goalId}/milestones/${milestoneId}/tasks/${taskId}/complete`, { method: 'PUT' });
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) });
diff --git a/server/lib/identityValidation.js b/server/lib/identityValidation.js
index d091ab9821..8399601bf7 100644
--- a/server/lib/identityValidation.js
+++ b/server/lib/identityValidation.js
@@ -106,6 +106,28 @@ export const acceptPhasesInputSchema = z.object({
})).min(1).max(20)
});
+// --- Goal Decomposition Schemas (milestones pre-populated with tasks) ---
+
+export const decomposeGoalInputSchema = aiProviderInputSchema;
+
+// Mirrors addTodoInputSchema; estimateMinutes optional (LLM may omit).
+export const decomposedTaskSchema = z.object({
+ title: z.string().min(1).max(200),
+ priority: z.enum(['low', 'medium', 'high']).optional().default('medium'),
+ estimateMinutes: z.number().int().min(1).max(14400).optional()
+});
+
+export const acceptDecompositionInputSchema = z.object({
+ milestones: z.array(z.object({
+ title: z.string().min(1).max(200),
+ description: z.string().max(2000).optional().default(''),
+ // targetDate optional — decomposition works without a goal target date.
+ targetDate: validCalendarDate.optional(),
+ order: z.number().int().min(0),
+ tasks: z.array(decomposedTaskSchema).max(20).optional().default([])
+ })).min(1).max(20)
+});
+
// --- Goal Progress Log Schemas ---
export const addProgressEntrySchema = z.object({
diff --git a/server/routes/identity.js b/server/routes/identity.js
index b3b8286313..e8e2624163 100644
--- a/server/routes/identity.js
+++ b/server/routes/identity.js
@@ -16,6 +16,8 @@ import {
updateProgressSchema,
generatePhasesInputSchema,
acceptPhasesInputSchema,
+ decomposeGoalInputSchema,
+ acceptDecompositionInputSchema,
organizeGoalsInputSchema,
applyOrganizationInputSchema,
checkInGoalInputSchema
@@ -274,6 +276,29 @@ router.post('/goals/:id/accept-phases', asyncHandler(async (req, res) => {
res.json(goal);
}));
+// POST /api/digital-twin/identity/goals/:id/decompose — AI-decompose into milestones + tasks (no persist)
+router.post('/goals/:id/decompose', asyncHandler(async (req, res) => {
+ const data = validateRequest(decomposeGoalInputSchema, req.body);
+ const milestones = await identityService.decomposeGoal(req.params.id, data);
+ res.json(milestones);
+}));
+
+// POST /api/digital-twin/identity/goals/:id/accept-decomposition — Persist milestones + nested tasks
+router.post('/goals/:id/accept-decomposition', asyncHandler(async (req, res) => {
+ const data = validateRequest(acceptDecompositionInputSchema, req.body);
+ const goal = await identityService.acceptGoalDecomposition(req.params.id, data.milestones);
+ res.json(goal);
+}));
+
+// PUT /api/digital-twin/identity/goals/:id/milestones/:milestoneId/tasks/:taskId/complete — Toggle milestone task done
+router.put('/goals/:id/milestones/:milestoneId/tasks/:taskId/complete', asyncHandler(async (req, res) => {
+ const task = await identityService.completeMilestoneTask(req.params.id, req.params.milestoneId, req.params.taskId);
+ if (!task) {
+ throw new ServerError('Goal, milestone, or task not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(task);
+}));
+
// POST /api/digital-twin/identity/goals/organize — AI-organize goals into hierarchy
router.post('/goals/organize', asyncHandler(async (req, res) => {
const data = validateRequest(organizeGoalsInputSchema, req.body);
diff --git a/server/services/identity.js b/server/services/identity.js
index 9a3710316d..218bed6b99 100644
--- a/server/services/identity.js
+++ b/server/services/identity.js
@@ -59,6 +59,9 @@ export {
getGoalCalendarEvents,
generateGoalPhases,
acceptGoalPhases,
+ decomposeGoal,
+ acceptGoalDecomposition,
+ completeMilestoneTask,
organizeGoals,
applyGoalOrganization,
checkInGoal,
diff --git a/server/services/identity/goals.js b/server/services/identity/goals.js
index 8ee7b02454..eefb33c68c 100644
--- a/server/services/identity/goals.js
+++ b/server/services/identity/goals.js
@@ -193,6 +193,7 @@ export async function getGoals() {
for (const ms of (goal.milestones || [])) {
if (ms.description === undefined) { ms.description = ''; needsSave = true; }
if (ms.order === undefined) { ms.order = 0; needsSave = true; }
+ if (!Array.isArray(ms.tasks)) { ms.tasks = []; needsSave = true; }
}
}
if (needsSave) await saveJSON(GOALS_FILE, data);
@@ -432,6 +433,7 @@ export async function addMilestone(goalId, { title, targetDate }) {
title,
targetDate: targetDate || null,
completedAt: null,
+ tasks: [],
createdAt: new Date().toISOString()
};
@@ -625,6 +627,7 @@ export async function acceptGoalPhases(goalId, phases) {
targetDate: phase.targetDate || null,
order: phase.order ?? idx,
completedAt: null,
+ tasks: [],
createdAt: new Date().toISOString()
}));
@@ -635,6 +638,119 @@ export async function acceptGoalPhases(goalId, phases) {
return goal;
}
+// =============================================================================
+// Goal Decomposition (LLM-powered) — milestones pre-populated with tasks
+// =============================================================================
+
+// Builds a single-pass proposal: ordered milestones, each carrying concrete
+// tasks. Unlike generateGoalPhases (flat milestones, no tasks) this closes the
+// "now hand-add every todo" gap. Returns the proposal WITHOUT persisting so the
+// user can review/edit before accept (mirrors generate → accept-phases).
+export async function decomposeGoal(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);
+ // targetDate is optional for decomposition (relative ordering only) — unlike
+ // generateGoalPhases which hard-requires it for date distribution.
+ const dateGuidance = goal.targetDate
+ ? `Distribute milestone target dates chronologically (YYYY-MM-DD) between today (${today}) and the goal's target date (${goal.targetDate}); the last milestone should land on or near the target date.`
+ : `The goal has no target date — order milestones relatively and OMIT the "targetDate" field.`;
+
+ const prompt = `You are a goal decomposition assistant. Break the goal below into an ordered sequence of milestones, each pre-populated with concrete, actionable tasks.
+
+Goal title: ${goal.title}
+Goal description: ${goal.description || 'No description provided'}
+Today's date: ${today}
+${goal.targetDate ? `Target completion date: ${goal.targetDate}` : 'Target completion date: none set'}
+
+Produce 3-7 milestones, each with 2-5 tasks. ${dateGuidance}
+
+Respond with a JSON array only (no markdown fences, no explanation). Each element must have:
+- "title": string (milestone name)
+- "description": string (1-2 sentences)
+${goal.targetDate ? '- "targetDate": string (YYYY-MM-DD format)\n' : ''}- "order": number (0-based index)
+- "tasks": array of { "title": string, "priority": "low"|"medium"|"high", "estimateMinutes": number (whole minutes) }`;
+
+ const result = await callProviderAISimple(provider, selectedModel, prompt, { max_tokens: 4000, temperature: 0.4 });
+ if (result.error) throw new ServerError(`AI decomposition failed: ${result.error}`, { status: 502, code: 'AI_ERROR' });
+
+ let parsed;
+ try {
+ parsed = parseLLMJSON(result.text);
+ } 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 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;
+}
+
+// Persists a reviewed decomposition proposal, normalizing each milestone's
+// tasks into the stored shape (mirrors acceptGoalPhases). Overwrites
+// goal.milestones — the proposal is the new plan.
+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' });
+
+ const now = new Date().toISOString();
+ goal.milestones = milestones.map((ms, idx) => ({
+ id: `ms-${uuidv4()}`,
+ title: ms.title,
+ description: ms.description || '',
+ targetDate: ms.targetDate || null,
+ order: ms.order ?? idx,
+ completedAt: null,
+ tasks: (Array.isArray(ms.tasks) ? ms.tasks : []).map(t => ({
+ id: `ms-task-${uuidv4()}`,
+ title: t.title,
+ priority: t.priority || 'medium',
+ estimateMinutes: t.estimateMinutes ?? null,
+ status: 'pending',
+ completedAt: null,
+ createdAt: now
+ })),
+ createdAt: now
+ }));
+
+ goal.updatedAt = now;
+ goals.updatedAt = now;
+ await saveJSON(GOALS_FILE, goals);
+ const taskCount = goal.milestones.reduce((sum, ms) => sum + ms.tasks.length, 0);
+ console.log(`🧩 Accepted decomposition for "${goal.title}": ${goal.milestones.length} milestones / ${taskCount} tasks`);
+ return goal;
+}
+
+// Toggles a milestone task's done state (mirrors updateTodo's done/pending flip).
+export async function completeMilestoneTask(goalId, milestoneId, taskId) {
+ const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);
+ const goal = goals.goals.find(g => g.id === goalId);
+ if (!goal) return null;
+
+ const milestone = goal.milestones?.find(m => m.id === milestoneId);
+ if (!milestone) return null;
+
+ const task = milestone.tasks?.find(t => t.id === taskId);
+ if (!task) return null;
+
+ const done = task.status === 'done';
+ task.status = done ? 'pending' : 'done';
+ task.completedAt = done ? null : new Date().toISOString();
+ goal.updatedAt = new Date().toISOString();
+ goals.updatedAt = new Date().toISOString();
+ await saveJSON(GOALS_FILE, goals);
+ return task;
+}
+
// =============================================================================
// Goal Hierarchy Organization (LLM-powered)
// =============================================================================
diff --git a/server/services/identity/goals.test.js b/server/services/identity/goals.test.js
index 37502703b2..4a6c193b51 100644
--- a/server/services/identity/goals.test.js
+++ b/server/services/identity/goals.test.js
@@ -1,5 +1,32 @@
-import { describe, it, expect } from 'vitest';
-import { computeGoalVelocity } from './goals.js';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// In-memory store so decompose/accept/migration logic can be exercised without
+// touching disk or a real AI provider.
+const h = vi.hoisted(() => ({ goalsData: null, aiText: '' }));
+
+vi.mock('./store.js', () => ({
+ GOALS_FILE: 'goals.json',
+ LONGEVITY_FILE: 'longevity.json',
+ DEFAULT_GOALS: { goals: [], birthDate: null },
+ DEFAULT_LONGEVITY: {},
+ loadJSON: vi.fn(async (file) => (file === 'goals.json' ? h.goalsData : {})),
+ saveJSON: vi.fn(async (file, data) => { if (file === 'goals.json') h.goalsData = data; })
+}));
+
+vi.mock('../providers.js', () => ({
+ getActiveProvider: vi.fn(async () => ({ id: 'p1', apiType: 'openai', defaultModel: 'm1' })),
+ getProviderById: vi.fn(async () => ({ id: 'p1', apiType: 'openai', defaultModel: 'm1' }))
+}));
+
+vi.mock('../../lib/aiProvider.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, callProviderAISimple: vi.fn(async () => ({ text: h.aiText })) };
+});
+
+const {
+ computeGoalVelocity, getGoals, decomposeGoal,
+ acceptGoalDecomposition, completeMilestoneTask
+} = await import('./goals.js');
describe('computeGoalVelocity', () => {
it('returns null with fewer than two progress entries', () => {
@@ -34,3 +61,88 @@ describe('computeGoalVelocity', () => {
})).toBeNull();
});
});
+
+describe('goal decomposition', () => {
+ 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('decomposeGoal returns ordered milestones with tasks and does NOT persist', async () => {
+ h.aiText = JSON.stringify([
+ { title: 'Outline', description: 'Sketch the arc', targetDate: '2026-09-01', order: 0,
+ tasks: [{ title: 'Beat sheet', priority: 'high', estimateMinutes: 120 }] },
+ { title: 'Draft', description: 'Write it', targetDate: '2026-12-01', order: 1,
+ tasks: [{ title: 'Chapter 1', priority: 'medium', estimateMinutes: 240 }] }
+ ]);
+ const proposal = await decomposeGoal('goal-1', {});
+ expect(Array.isArray(proposal)).toBe(true);
+ expect(proposal).toHaveLength(2);
+ expect(proposal[0].tasks[0].title).toBe('Beat sheet');
+ // Not persisted — the stored goal still has no milestones.
+ expect(h.goalsData.goals[0].milestones).toHaveLength(0);
+ });
+
+ it('decomposeGoal throws AI_PARSE_ERROR when the model returns a non-array', async () => {
+ h.aiText = JSON.stringify({ not: 'an array' });
+ await expect(decomposeGoal('goal-1', {})).rejects.toMatchObject({ code: 'AI_PARSE_ERROR' });
+ });
+
+ it('decomposeGoal throws NOT_FOUND for a missing goal', async () => {
+ await expect(decomposeGoal('nope', {})).rejects.toMatchObject({ status: 404, code: 'NOT_FOUND' });
+ });
+
+ it('acceptGoalDecomposition normalizes tasks (ids, pending status, default priority)', async () => {
+ const goal = await acceptGoalDecomposition('goal-1', [
+ { title: 'Outline', order: 0, tasks: [
+ { title: 'Beat sheet', priority: 'high', estimateMinutes: 120 },
+ { title: 'Research' } // no priority/estimate → defaults
+ ] }
+ ]);
+ expect(goal.milestones).toHaveLength(1);
+ const ms = goal.milestones[0];
+ expect(ms.id).toMatch(/^ms-/);
+ expect(ms.tasks).toHaveLength(2);
+ expect(ms.tasks[0].id).toMatch(/^ms-task-/);
+ expect(ms.tasks[0].status).toBe('pending');
+ expect(ms.tasks[0].completedAt).toBeNull();
+ expect(ms.tasks[1].priority).toBe('medium');
+ expect(ms.tasks[1].estimateMinutes).toBeNull();
+ // Persisted to the store.
+ expect(h.goalsData.goals[0].milestones[0].tasks).toHaveLength(2);
+ });
+
+ it('completeMilestoneTask toggles a task between done and pending', async () => {
+ await acceptGoalDecomposition('goal-1', [
+ { title: 'Outline', order: 0, tasks: [{ title: 'Beat sheet' }] }
+ ]);
+ const msId = h.goalsData.goals[0].milestones[0].id;
+ const taskId = h.goalsData.goals[0].milestones[0].tasks[0].id;
+
+ const done = await completeMilestoneTask('goal-1', msId, taskId);
+ expect(done.status).toBe('done');
+ expect(done.completedAt).not.toBeNull();
+
+ const undone = await completeMilestoneTask('goal-1', msId, taskId);
+ expect(undone.status).toBe('pending');
+ expect(undone.completedAt).toBeNull();
+ });
+
+ it('completeMilestoneTask returns null for an unknown task', async () => {
+ await acceptGoalDecomposition('goal-1', [{ title: 'Outline', order: 0, tasks: [] }]);
+ const msId = h.goalsData.goals[0].milestones[0].id;
+ expect(await completeMilestoneTask('goal-1', msId, 'missing')).toBeNull();
+ });
+
+ it('getGoals lazily backfills milestone.tasks = [] on legacy milestones', async () => {
+ h.goalsData.goals[0].milestones = [{ id: 'ms-legacy', title: 'Old', completedAt: null }];
+ const data = await getGoals();
+ expect(data.goals[0].milestones[0].tasks).toEqual([]);
+ });
+});