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(dashboard): add Decision Log widget for CoS transparency

Adam Eivy005a5ffca633
diff --git a/.changelog/v0.13.20.md b/.changelog/v0.13.20.md
index 6cb168156c..d16e999750 100644
--- a/.changelog/v0.13.20.md
+++ b/.changelog/v0.13.20.md
@@ -253,3 +253,14 @@ This release expands the genome dashboard with comprehensive cancer predispositi
- **Refresh config updates pm2Home** — the `/api/apps/:id/refresh-config` endpoint now auto-populates pm2Home when re-parsing the ecosystem config, so existing apps can pick up custom PM2_HOME settings without re-ingestion
- **Detection uses correct PM2_HOME for status checks** — when detecting a new app with a custom PM2_HOME, the PM2 status check runs against the correct daemon instance instead of the default
- **Fixed template literal parsing** — the regex now correctly handles nested quotes in template literals (e.g., `require("os")`) instead of stopping at the first quote character
+
+### Dashboard — CoS Decision Log Widget
+- **New DecisionLogWidget** on the main dashboard — provides transparency into CoS decision-making by showing why tasks were skipped, switched, or adjusted
+- **Decision types tracked**: task_skipped (poor success rate), task_switched (fallback to alternative), interval_adjusted (learning-based), rehabilitation (retrying skipped tasks), and task_selected (successful selection)
+- **24-hour summary stats** — quick overview of decisions made in the last day with color-coded badges for skipped, switched, selected, and adjusted tasks
+- **Expandable recent decisions list** — click to see detailed reasons for recent impactful decisions, including task type, success rate context, and relative timestamps
+- **Transparency score** — percentage of decisions with recorded explanations, encouraging complete decision logging
+- **New decision log service** (`server/services/decisionLog.js`) — records decisions with rolling 200-entry window, provides summary and pattern analysis APIs
+- **New API endpoints**: `GET /api/cos/decisions`, `GET /api/cos/decisions/summary`, `GET /api/cos/decisions/patterns`
+- **Real-time updates** via Socket.IO `decision` event when new decisions are recorded
+- Addresses user preference for "reason for every no-action decision" visible in dashboards and COS-GOALS.md Goal 4: User Engagement ("Provide status updates and progress reports")
diff --git a/client/src/components/DecisionLogWidget.jsx b/client/src/components/DecisionLogWidget.jsx
new file mode 100644
index 0000000000..9c44fae7cc
--- /dev/null
+++ b/client/src/components/DecisionLogWidget.jsx
@@ -0,0 +1,245 @@
+import { useState, useEffect, memo } from 'react';
+import { Link } from 'react-router-dom';
+import {
+ Eye,
+ ChevronRight,
+ ChevronDown,
+ AlertCircle,
+ CheckCircle,
+ ArrowRight,
+ Clock,
+ RefreshCw,
+ Zap
+} from 'lucide-react';
+import * as api from '../services/api';
+
+/**
+ * DecisionLogWidget - Shows transparency into CoS decision-making
+ * Displays why tasks were skipped, intervals adjusted, or alternatives chosen
+ */
+const DecisionLogWidget = memo(function DecisionLogWidget() {
+ const [summary, setSummary] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [expanded, setExpanded] = useState(false);
+
+ useEffect(() => {
+ const loadData = async () => {
+ const data = await api.getCosDecisionSummary({ silent: true }).catch(() => null);
+ setSummary(data);
+ setLoading(false);
+ };
+
+ loadData();
+ // Refresh every 60 seconds
+ const interval = setInterval(loadData, 60000);
+ return () => clearInterval(interval);
+ }, []);
+
+ // Don't render while loading or if no data
+ if (loading || !summary) {
+ return null;
+ }
+
+ // Only show if there are impactful decisions to display
+ if (!summary.hasImpactfulDecisions && summary.last24Hours.total === 0) {
+ return null;
+ }
+
+ const { last24Hours, impactfulDecisions, transparencyScore } = summary;
+
+ // Get icon and color for decision type
+ const getDecisionStyle = (type) => {
+ switch (type) {
+ case 'task_skipped':
+ return { icon: AlertCircle, color: 'text-port-warning', bg: 'bg-port-warning/10' };
+ case 'task_switched':
+ return { icon: ArrowRight, color: 'text-purple-400', bg: 'bg-purple-400/10' };
+ case 'interval_adjusted':
+ return { icon: Clock, color: 'text-blue-400', bg: 'bg-blue-400/10' };
+ case 'rehabilitation':
+ return { icon: RefreshCw, color: 'text-port-success', bg: 'bg-port-success/10' };
+ case 'task_selected':
+ return { icon: CheckCircle, color: 'text-port-success', bg: 'bg-port-success/10' };
+ default:
+ return { icon: Eye, color: 'text-gray-400', bg: 'bg-gray-400/10' };
+ }
+ };
+
+ // Format decision type for display
+ const formatDecisionType = (type) => {
+ const labels = {
+ task_skipped: 'Skipped',
+ task_switched: 'Switched',
+ interval_adjusted: 'Adjusted',
+ cooldown_active: 'Cooldown',
+ not_due: 'Not Due',
+ queue_full: 'Queue Full',
+ task_selected: 'Selected',
+ rehabilitation: 'Retried'
+ };
+ return labels[type] || type;
+ };
+
+ // Format relative time
+ const formatRelativeTime = (timestamp) => {
+ const now = Date.now();
+ const then = new Date(timestamp).getTime();
+ const diffMs = now - then;
+ const diffMins = Math.floor(diffMs / 60000);
+ const diffHours = Math.floor(diffMs / 3600000);
+
+ if (diffMins < 1) return 'just now';
+ if (diffMins < 60) return `${diffMins}m ago`;
+ if (diffHours < 24) return `${diffHours}h ago`;
+ return 'yesterday';
+ };
+
+ return (
+ <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6">
+ {/* Header */}
+ <div className="flex items-center justify-between mb-4">
+ <div className="flex items-center gap-3">
+ <div className="text-2xl" aria-hidden="true">
+ <Eye className="w-6 h-6 text-purple-400" />
+ </div>
+ <div>
+ <h3 className="text-lg font-semibold text-white">Decision Log</h3>
+ <p className="text-sm text-gray-500">
+ {last24Hours.total > 0
+ ? `${last24Hours.total} decisions in last 24h`
+ : 'No recent decisions'}
+ </p>
+ </div>
+ </div>
+ <Link
+ to="/cos/learning"
+ className="flex items-center gap-1 text-sm text-port-accent hover:text-port-accent/80 transition-colors min-h-[40px] px-2"
+ >
+ <span className="hidden sm:inline">Details</span>
+ <ChevronRight size={16} />
+ </Link>
+ </div>
+
+ {/* Quick Stats Row */}
+ <div className="flex flex-wrap gap-3 mb-4">
+ {last24Hours.skipped > 0 && (
+ <div className="flex items-center gap-1.5 px-2 py-1 rounded bg-port-warning/10 text-port-warning text-xs">
+ <AlertCircle size={12} />
+ <span>{last24Hours.skipped} skipped</span>
+ </div>
+ )}
+ {last24Hours.switched > 0 && (
+ <div className="flex items-center gap-1.5 px-2 py-1 rounded bg-purple-400/10 text-purple-400 text-xs">
+ <ArrowRight size={12} />
+ <span>{last24Hours.switched} switched</span>
+ </div>
+ )}
+ {last24Hours.selected > 0 && (
+ <div className="flex items-center gap-1.5 px-2 py-1 rounded bg-port-success/10 text-port-success text-xs">
+ <CheckCircle size={12} />
+ <span>{last24Hours.selected} selected</span>
+ </div>
+ )}
+ {last24Hours.adjusted > 0 && (
+ <div className="flex items-center gap-1.5 px-2 py-1 rounded bg-blue-400/10 text-blue-400 text-xs">
+ <Clock size={12} />
+ <span>{last24Hours.adjusted} adjusted</span>
+ </div>
+ )}
+ </div>
+
+ {/* Impactful Decisions Section */}
+ {impactfulDecisions.length > 0 && (
+ <div className="border-t border-port-border pt-4">
+ <button
+ onClick={() => setExpanded(!expanded)}
+ className="flex items-center justify-between w-full text-left mb-2 group"
+ >
+ <div className="flex items-center gap-2">
+ <Zap size={14} className="text-purple-400" />
+ <span className="text-sm font-medium text-gray-300">Recent Decisions</span>
+ <span className="text-xs text-gray-500">
+ (why tasks were skipped or changed)
+ </span>
+ </div>
+ <ChevronDown
+ size={16}
+ className={`text-gray-400 transition-transform ${expanded ? 'rotate-180' : ''}`}
+ />
+ </button>
+
+ {expanded && (
+ <div className="space-y-2">
+ {impactfulDecisions.map((decision) => {
+ const style = getDecisionStyle(decision.type);
+ const Icon = style.icon;
+
+ return (
+ <div
+ key={decision.id}
+ className={`flex items-start gap-2 p-2 rounded-lg ${style.bg}`}
+ >
+ <Icon size={14} className={`${style.color} mt-0.5 shrink-0`} />
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2">
+ <span className={`text-xs font-medium ${style.color}`}>
+ {formatDecisionType(decision.type)}
+ </span>
+ {decision.context?.taskType && (
+ <span className="text-xs text-gray-400">
+ {decision.context.taskType}
+ </span>
+ )}
+ </div>
+ <p className="text-sm text-gray-300 truncate" title={decision.reason}>
+ {decision.reason}
+ </p>
+ <div className="text-xs text-gray-500 mt-0.5">
+ {formatRelativeTime(decision.timestamp)}
+ {decision.context?.successRate !== undefined && (
+ <span className="ml-2">
+ Success rate: {decision.context.successRate}%
+ </span>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ {!expanded && (
+ <div className="flex gap-1">
+ {impactfulDecisions.slice(0, 5).map((decision) => {
+ const style = getDecisionStyle(decision.type);
+ return (
+ <div
+ key={decision.id}
+ className={`w-2 h-2 rounded-full ${style.color.replace('text-', 'bg-')}`}
+ title={`${formatDecisionType(decision.type)}: ${decision.reason}`}
+ />
+ );
+ })}
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Transparency Score */}
+ {transparencyScore !== undefined && (
+ <div className="mt-3 pt-3 border-t border-port-border flex items-center justify-between text-xs">
+ <span className="text-gray-500">Transparency score</span>
+ <span className={`font-medium ${
+ transparencyScore >= 90 ? 'text-port-success' :
+ transparencyScore >= 70 ? 'text-port-warning' : 'text-port-error'
+ }`}>
+ {transparencyScore}%
+ </span>
+ </div>
+ )}
+ </div>
+ );
+});
+
+export default DecisionLogWidget;
diff --git a/client/src/pages/Dashboard.jsx b/client/src/pages/Dashboard.jsx
index e22e9c5309..addf9b3eb2 100644
--- a/client/src/pages/Dashboard.jsx
+++ b/client/src/pages/Dashboard.jsx
@@ -5,6 +5,7 @@ import BrailleSpinner from '../components/BrailleSpinner';
import CosDashboardWidget from '../components/CosDashboardWidget';
import GoalProgressWidget from '../components/GoalProgressWidget';
import UpcomingTasksWidget from '../components/UpcomingTasksWidget';
+import DecisionLogWidget from '../components/DecisionLogWidget';
import * as api from '../services/api';
import socket from '../services/socket';
@@ -104,6 +105,11 @@ export default function Dashboard() {
<UpcomingTasksWidget />
</div>
+ {/* Decision Log Widget */}
+ <div className="mb-6">
+ <DecisionLogWidget />
+ </div>
+
{/* App Grid */}
{apps.length === 0 ? (
<div className="bg-port-card border border-port-border rounded-xl p-8 sm:p-12 text-center">
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 0688c1118a..5c47de5f96 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -628,6 +628,15 @@ export const getCosActionableInsights = () => request('/cos/actionable-insights'
export const getCosGoalProgress = () => request('/cos/goal-progress');
export const getCosGoalProgressSummary = (options) => request('/cos/goal-progress/summary', options);
+// Decision Log
+export const getCosDecisions = (limit = 20, type = null) => {
+ const params = new URLSearchParams({ limit: limit.toString() });
+ if (type) params.append('type', type);
+ return request(`/cos/decisions?${params}`);
+};
+export const getCosDecisionSummary = (options) => request('/cos/decisions/summary', options);
+export const getCosDecisionPatterns = () => request('/cos/decisions/patterns');
+
// Task Schedule (Configurable Intervals)
export const getCosUpcomingTasks = (limit = 10) => request(`/cos/upcoming?limit=${limit}`);
export const getCosSchedule = () => request('/cos/schedule');
diff --git a/server/routes/cos.js b/server/routes/cos.js
index f820b1ba61..d214538b77 100644
--- a/server/routes/cos.js
+++ b/server/routes/cos.js
@@ -14,6 +14,7 @@ import * as taskTemplates from '../services/taskTemplates.js';
import { enhanceTaskPrompt } from '../services/taskEnhancer.js';
import * as productivity from '../services/productivity.js';
import * as goalProgress from '../services/goalProgress.js';
+import * as decisionLog from '../services/decisionLog.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
const router = Router();
@@ -1109,4 +1110,28 @@ router.get('/goal-progress/summary', asyncHandler(async (req, res) => {
res.json(summary);
}));
+// ============================================================
+// Decision Log Routes
+// ============================================================
+
+// GET /api/cos/decisions - Get recent decisions
+router.get('/decisions', asyncHandler(async (req, res) => {
+ const limit = parseInt(req.query.limit, 10) || 20;
+ const type = req.query.type || null;
+ const decisions = await decisionLog.getRecentDecisions(limit, type);
+ res.json({ decisions });
+}));
+
+// GET /api/cos/decisions/summary - Get decision summary for dashboard
+router.get('/decisions/summary', asyncHandler(async (req, res) => {
+ const summary = await decisionLog.getDecisionSummary();
+ res.json(summary);
+}));
+
+// GET /api/cos/decisions/patterns - Get decision patterns/insights
+router.get('/decisions/patterns', asyncHandler(async (req, res) => {
+ const patterns = await decisionLog.getDecisionPatterns();
+ res.json(patterns);
+}));
+
export default router;
diff --git a/server/services/cos.js b/server/services/cos.js
index 9665ad5e4a..b81ebb2cbe 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -22,6 +22,7 @@ import { generateProactiveTasks as generateMissionTasks, getStats as getMissionS
import { getDueJobs, generateTaskFromJob, recordJobExecution } from './autonomousJobs.js';
import { formatDuration } from '../lib/fileUtils.js';
import { addNotification, NOTIFICATION_TYPES } from './notifications.js';
+import { recordDecision, DECISION_TYPES } from './decisionLog.js';
// Import and re-export cosEvents from separate module to avoid circular dependencies
import { cosEvents as _cosEvents } from './cosEvents.js';
export const cosEvents = _cosEvents;
@@ -1096,6 +1097,11 @@ async function generateSelfImprovementTask(state) {
if (!nextTypeResult) {
emitLog('info', 'No self-improvement tasks are eligible to run based on schedule');
+ await recordDecision(
+ DECISION_TYPES.NOT_DUE,
+ 'No self-improvement tasks are eligible based on schedule',
+ { category: 'selfImprovement' }
+ );
return null;
}
@@ -1114,13 +1120,28 @@ async function generateSelfImprovementTask(state) {
reason: cooldownInfo.reason
});
+ // Record the skip decision
+ await recordDecision(
+ DECISION_TYPES.TASK_SKIPPED,
+ `Poor success rate (${cooldownInfo.successRate}% after ${cooldownInfo.completed} attempts)`,
+ { taskType: nextType, successRate: cooldownInfo.successRate, attempts: cooldownInfo.completed }
+ );
+
// Try to find another eligible task type
const dueTasks = await taskSchedule.getDueSelfImprovementTasks();
const alternativeTask = dueTasks.find(t => t.taskType !== nextType);
if (alternativeTask) {
+ const originalType = nextType;
nextType = alternativeTask.taskType;
emitLog('info', `Switched to alternative task type: ${nextType}`);
+
+ // Record the switch decision
+ await recordDecision(
+ DECISION_TYPES.TASK_SWITCHED,
+ `Switched from ${originalType} to ${nextType}`,
+ { fromTask: originalType, toTask: nextType, reason: 'poor-success-rate' }
+ );
} else {
// Fall back to the skipped types logic
const skippedTypes = await getSkippedTaskTypes().catch(() => []);
@@ -1129,6 +1150,13 @@ async function generateSelfImprovementTask(state) {
const oldestType = skippedTypes[0].taskType.replace('self-improve:', '');
nextType = oldestType;
emitLog('info', `Retrying ${oldestType} as it hasn't been attempted recently`);
+
+ // Record rehabilitation decision
+ await recordDecision(
+ DECISION_TYPES.REHABILITATION,
+ `Retrying ${oldestType} after period of inactivity`,
+ { taskType: oldestType, reason: 'oldest-skipped-type' }
+ );
} else {
nextType = SELF_IMPROVEMENT_TYPES[0];
}
@@ -1156,6 +1184,18 @@ async function generateSelfImprovementTask(state) {
emitLog('info', `Generating self-improvement task: ${nextType} (${selectionReason})`);
+ // Record task selection decision
+ await recordDecision(
+ DECISION_TYPES.TASK_SELECTED,
+ `Selected ${nextType} for self-improvement`,
+ {
+ taskType: nextType,
+ reason: selectionReason,
+ multiplier: cooldownInfo.multiplier,
+ successRate: cooldownInfo.successRate
+ }
+ );
+
// Get task descriptions from the centralized helper function
const taskDescriptions = getSelfImprovementTaskDescriptions();
diff --git a/server/services/decisionLog.js b/server/services/decisionLog.js
new file mode 100644
index 0000000000..5b887b6f40
--- /dev/null
+++ b/server/services/decisionLog.js
@@ -0,0 +1,243 @@
+/**
+ * Decision Log Service
+ *
+ * Tracks CoS decision-making for transparency.
+ * Records why tasks were skipped, intervals were adjusted, or alternatives were chosen.
+ * This helps users understand CoS behavior and identify patterns.
+ */
+
+import { writeFile, mkdir } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { readJSONFile } from '../lib/fileUtils.js';
+import { cosEvents } from './cosEvents.js';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = dirname(__filename);
+const DATA_DIR = join(__dirname, '../../data/cos');
+const DECISION_FILE = join(DATA_DIR, 'decisions.json');
+
+// In-memory cache for recent decisions (avoid excessive file I/O)
+let decisionCache = null;
+let cacheLoaded = false;
+
+// Decision types
+export const DECISION_TYPES = {
+ TASK_SKIPPED: 'task_skipped', // Task skipped due to poor success rate
+ TASK_SWITCHED: 'task_switched', // Switched to alternative task
+ INTERVAL_ADJUSTED: 'interval_adjusted', // Interval changed by learning system
+ COOLDOWN_ACTIVE: 'cooldown_active', // Task still in cooldown
+ NOT_DUE: 'not_due', // Task not due based on schedule
+ QUEUE_FULL: 'queue_full', // Too many tasks in queue
+ TASK_SELECTED: 'task_selected', // Task was selected to run
+ REHABILITATION: 'rehabilitation' // Skipped task type retried
+};
+
+// Default data structure
+const DEFAULT_DATA = {
+ version: 1,
+ decisions: [],
+ stats: {
+ totalDecisions: 0,
+ byType: {}
+ }
+};
+
+// Maximum decisions to keep
+const MAX_DECISIONS = 200;
+
+/**
+ * Load decision data from file
+ */
+async function loadDecisions() {
+ if (cacheLoaded && decisionCache) {
+ return decisionCache;
+ }
+
+ if (!existsSync(DATA_DIR)) {
+ await mkdir(DATA_DIR, { recursive: true });
+ }
+
+ decisionCache = await readJSONFile(DECISION_FILE, { ...DEFAULT_DATA });
+ cacheLoaded = true;
+ return decisionCache;
+}
+
+/**
+ * Save decision data to file
+ */
+async function saveDecisions(data) {
+ decisionCache = data;
+ await writeFile(DECISION_FILE, JSON.stringify(data, null, 2));
+}
+
+/**
+ * Record a decision
+ * @param {string} type - Decision type from DECISION_TYPES
+ * @param {string} reason - Human-readable reason
+ * @param {Object} context - Additional context (taskType, successRate, etc.)
+ */
+export async function recordDecision(type, reason, context = {}) {
+ const data = await loadDecisions();
+
+ const decision = {
+ id: `dec-${Date.now().toString(36)}-${Math.random().toString(36).substr(2, 4)}`,
+ type,
+ reason,
+ context,
+ timestamp: new Date().toISOString()
+ };
+
+ // Add to beginning (most recent first)
+ data.decisions.unshift(decision);
+
+ // Trim to max size
+ if (data.decisions.length > MAX_DECISIONS) {
+ data.decisions = data.decisions.slice(0, MAX_DECISIONS);
+ }
+
+ // Update stats
+ data.stats.totalDecisions++;
+ data.stats.byType[type] = (data.stats.byType[type] || 0) + 1;
+
+ await saveDecisions(data);
+
+ // Emit event for real-time updates
+ cosEvents.emit('decision', decision);
+
+ return decision;
+}
+
+/**
+ * Get recent decisions
+ * @param {number} limit - Max decisions to return (default 20)
+ * @param {string} type - Optional filter by type
+ */
+export async function getRecentDecisions(limit = 20, type = null) {
+ const data = await loadDecisions();
+
+ let decisions = data.decisions;
+
+ if (type) {
+ decisions = decisions.filter(d => d.type === type);
+ }
+
+ return decisions.slice(0, limit);
+}
+
+/**
+ * Get decision summary for dashboard
+ * Returns counts and recent impactful decisions
+ */
+export async function getDecisionSummary() {
+ const data = await loadDecisions();
+
+ // Get decisions from last 24 hours
+ const oneDayAgo = Date.now() - 24 * 60 * 60 * 1000;
+ const recentDecisions = data.decisions.filter(
+ d => new Date(d.timestamp).getTime() > oneDayAgo
+ );
+
+ // Group by type
+ const byType = {};
+ for (const d of recentDecisions) {
+ byType[d.type] = (byType[d.type] || 0) + 1;
+ }
+
+ // Get impactful decisions (skips, switches, adjustments)
+ const impactfulTypes = [
+ DECISION_TYPES.TASK_SKIPPED,
+ DECISION_TYPES.TASK_SWITCHED,
+ DECISION_TYPES.INTERVAL_ADJUSTED,
+ DECISION_TYPES.REHABILITATION
+ ];
+
+ const impactfulDecisions = recentDecisions
+ .filter(d => impactfulTypes.includes(d.type))
+ .slice(0, 5);
+
+ // Calculate transparency score (how many decisions we can explain)
+ const totalRecent = recentDecisions.length;
+ const explainedCount = recentDecisions.filter(d => d.reason).length;
+ const transparencyScore = totalRecent > 0
+ ? Math.round((explainedCount / totalRecent) * 100)
+ : 100;
+
+ return {
+ last24Hours: {
+ total: recentDecisions.length,
+ byType,
+ skipped: byType[DECISION_TYPES.TASK_SKIPPED] || 0,
+ switched: byType[DECISION_TYPES.TASK_SWITCHED] || 0,
+ adjusted: byType[DECISION_TYPES.INTERVAL_ADJUSTED] || 0,
+ selected: byType[DECISION_TYPES.TASK_SELECTED] || 0
+ },
+ impactfulDecisions,
+ transparencyScore,
+ hasImpactfulDecisions: impactfulDecisions.length > 0
+ };
+}
+
+/**
+ * Get patterns in decisions (for insights)
+ */
+export async function getDecisionPatterns() {
+ const data = await loadDecisions();
+
+ // Analyze task types that are frequently skipped
+ const skippedTasks = {};
+ const switchedFrom = {};
+
+ for (const d of data.decisions) {
+ if (d.type === DECISION_TYPES.TASK_SKIPPED && d.context?.taskType) {
+ skippedTasks[d.context.taskType] = (skippedTasks[d.context.taskType] || 0) + 1;
+ }
+ if (d.type === DECISION_TYPES.TASK_SWITCHED && d.context?.fromTask) {
+ switchedFrom[d.context.fromTask] = (switchedFrom[d.context.fromTask] || 0) + 1;
+ }
+ }
+
+ // Find most skipped tasks
+ const frequentlySkipped = Object.entries(skippedTasks)
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, 3)
+ .map(([taskType, count]) => ({ taskType, count }));
+
+ return {
+ frequentlySkipped,
+ totalSkips: Object.values(skippedTasks).reduce((a, b) => a + b, 0),
+ totalSwitches: Object.values(switchedFrom).reduce((a, b) => a + b, 0),
+ stats: data.stats
+ };
+}
+
+/**
+ * Clear old decisions (keep last N days)
+ */
+export async function cleanupOldDecisions(daysToKeep = 7) {
+ const data = await loadDecisions();
+ const cutoff = Date.now() - daysToKeep * 24 * 60 * 60 * 1000;
+
+ const before = data.decisions.length;
+ data.decisions = data.decisions.filter(
+ d => new Date(d.timestamp).getTime() > cutoff
+ );
+ const removed = before - data.decisions.length;
+
+ if (removed > 0) {
+ await saveDecisions(data);
+ }
+
+ return { removed, remaining: data.decisions.length };
+}
+
+// Export types for easy importing
+export default {
+ recordDecision,
+ getRecentDecisions,
+ getDecisionSummary,
+ getDecisionPatterns,
+ cleanupOldDecisions,
+ DECISION_TYPES
+};