Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add productivity & streaks dashboard to CoS
Adam Eivy861bf95052af
diff --git a/.changelog/v0.12.x.md b/.changelog/v0.12.x.mdindex 76d1808215..a20a5e57b8 100644--- a/.changelog/v0.12.x.md+++ b/.changelog/v0.12.x.md@@ -23,6 +23,23 @@ This release adds branch management and automated release workflow capabilities- `client/src/services/api.js` — Added `updateBranches`, `getBranchComparison`, `pushBranch` API functions- `client/src/pages/DevTools.jsx` — Expanded GitPage with Update button, Release Status panel, release confirmation dialog, and CoS task integration+### CoS — Productivity & Streaks Dashboard+- **New Productivity Tab**: Added a "Streaks" tab to the Chief of Staff page that tracks work patterns and productivity metrics+- **Work Streaks**: Tracks consecutive days and weeks with completed tasks, displaying current and best streaks with visual emphasis+- **Hourly & Daily Patterns**: Analyzes which hours and days of the week have the highest success rates for tasks+- **AI Insights**: Generates recommendations like "Peak Performance Hour" and "Most Productive Day" based on historical patterns+- **Milestones**: Tracks achievements like "Completed 100 tasks" or "7-day work streak"+- **Gamification**: Flame icon for active streaks, trophy icons for milestones, encouraging consistent productivity++**Server changes**:+- `server/services/productivity.js` — New service with streak calculation, pattern analysis, and milestone tracking+- `server/routes/cos.js` — Added `/productivity`, `/productivity/summary`, `/productivity/recalculate` endpoints++**Client changes**:+- `client/src/components/cos/tabs/ProductivityTab.jsx` — Full-featured productivity dashboard with collapsible sections+- `client/src/components/cos/constants.js` — Added "Streaks" tab with Flame icon+- `client/src/services/api.js` — Added `getCosProductivity`, `getCosProductivitySummary`, `recalculateCosProductivity` functions+## Fixes### Runner Config Access Crashdiff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.jsindex 6c957be29a..bd67dfb7eb 100644--- a/client/src/components/cos/constants.js+++ b/client/src/components/cos/constants.js@@ -8,7 +8,8 @@ import {Calendar,Clock,GraduationCap,- Bot+ Bot,+ Flame} from 'lucide-react';export const TABS = [@@ -18,6 +19,7 @@ export const TABS = [{ id: 'scripts', label: 'Scripts', icon: Terminal },{ id: 'schedule', label: 'Schedule', icon: Clock },{ id: 'digest', label: 'Digest', icon: Calendar },+ { id: 'productivity', label: 'Streaks', icon: Flame },{ id: 'learning', label: 'Learning', icon: GraduationCap },{ id: 'memory', label: 'Memory', icon: Brain },{ id: 'health', label: 'Health', icon: Activity },diff --git a/client/src/components/cos/index.js b/client/src/components/cos/index.jsindex 0df33a2472..c577c15069 100644--- a/client/src/components/cos/index.js+++ b/client/src/components/cos/index.js@@ -29,3 +29,4 @@ export { default as MemoryTab } from './tabs/MemoryTab';export { default as HealthTab } from './tabs/HealthTab';export { default as ConfigTab } from './tabs/ConfigTab';export { default as DigestTab } from './tabs/DigestTab';+export { default as ProductivityTab } from './tabs/ProductivityTab';diff --git a/client/src/components/cos/tabs/ProductivityTab.jsx b/client/src/components/cos/tabs/ProductivityTab.jsxnew file mode 100644index 0000000000..8ed402dda8--- /dev/null+++ b/client/src/components/cos/tabs/ProductivityTab.jsx@@ -0,0 +1,421 @@+import { useState, useEffect, useCallback, useMemo } from 'react';+import {+ Flame,+ RefreshCw,+ TrendingUp,+ Clock,+ Calendar,+ Trophy,+ Target,+ Zap,+ CheckCircle,+ AlertTriangle,+ BarChart2,+ ChevronDown,+ ChevronRight,+ Award+} from 'lucide-react';+import * as api from '../../../services/api';++const DAY_NAMES = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];+const FULL_DAY_NAMES = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];++export default function ProductivityTab() {+ const [data, setData] = useState(null);+ const [loading, setLoading] = useState(true);+ const [recalculating, setRecalculating] = useState(false);+ const [expandedSections, setExpandedSections] = useState({+ streaks: true,+ patterns: true,+ insights: true,+ milestones: false+ });++ const loadData = useCallback(async () => {+ setLoading(true);+ const productivity = await api.getCosProductivity().catch(() => null);+ setData(productivity);+ setLoading(false);+ }, []);++ useEffect(() => {+ loadData();+ }, [loadData]);++ const handleRecalculate = useCallback(async () => {+ setRecalculating(true);+ await api.recalculateCosProductivity().catch(() => null);+ await loadData();+ setRecalculating(false);+ }, [loadData]);++ const toggleSection = useCallback((section) => {+ setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));+ }, []);++ const formatHour = useCallback((hour) => {+ const h = parseInt(hour);+ if (h === 0) return '12AM';+ if (h === 12) return '12PM';+ return h < 12 ? `${h}AM` : `${h - 12}PM`;+ }, []);++ const getSuccessRateColor = useCallback((rate) => {+ if (rate >= 80) return 'text-port-success';+ if (rate >= 60) return 'text-port-warning';+ return 'text-port-error';+ }, []);++ const getSuccessRateBg = useCallback((rate) => {+ if (rate >= 80) return 'bg-port-success';+ if (rate >= 60) return 'bg-port-warning';+ return 'bg-port-error';+ }, []);++ // Sort hourly patterns by hour+ const sortedHourlyPatterns = useMemo(() => {+ if (!data?.hourlyPatterns) return [];+ return Object.entries(data.hourlyPatterns)+ .map(([hour, p]) => ({ hour: parseInt(hour), ...p }))+ .sort((a, b) => a.hour - b.hour);+ }, [data?.hourlyPatterns]);++ // Sort daily patterns by day+ const sortedDailyPatterns = useMemo(() => {+ if (!data?.dailyPatterns) return [];+ return Object.entries(data.dailyPatterns)+ .map(([day, p]) => ({ day: parseInt(day), dayName: DAY_NAMES[parseInt(day)], ...p }))+ .sort((a, b) => a.day - b.day);+ }, [data?.dailyPatterns]);++ const hasData = data?.totals?.totalTasks > 0;++ if (loading) {+ return (+ <div className="flex items-center justify-center py-12">+ <RefreshCw className="w-6 h-6 animate-spin text-port-accent" />+ </div>+ );+ }++ return (+ <div className="space-y-6">+ {/* Header */}+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">+ <div className="flex items-center gap-3">+ <Flame className="w-5 h-5 text-orange-400" />+ <h3 className="text-lg font-semibold text-white">Productivity & Streaks</h3>+ </div>+ <button+ onClick={handleRecalculate}+ disabled={recalculating}+ className="flex items-center gap-2 px-3 py-1.5 text-sm bg-port-border hover:bg-port-border/80 text-white rounded-lg transition-colors disabled:opacity-50 min-h-[40px]"+ >+ <RefreshCw size={14} className={recalculating ? 'animate-spin' : ''} />+ {recalculating ? 'Calculating...' : 'Refresh'}+ </button>+ </div>++ {!hasData ? (+ <div className="bg-port-card border border-port-border rounded-lg p-8 text-center">+ <Flame className="w-12 h-12 text-gray-600 mx-auto mb-3" />+ <p className="text-gray-400">No productivity data yet.</p>+ <p className="text-gray-500 text-sm mt-1">+ Complete some tasks to start tracking your work patterns and building streaks!+ </p>+ </div>+ ) : (+ <>+ {/* Streak Stats */}+ <div>+ <button+ onClick={() => toggleSection('streaks')}+ className="flex items-center gap-2 w-full text-left mb-3"+ >+ {expandedSections.streaks ? <ChevronDown size={16} /> : <ChevronRight size={16} />}+ <Flame size={16} className="text-orange-400" />+ <span className="font-medium text-white">Work Streaks</span>+ </button>+ {expandedSections.streaks && (+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">+ {/* Current Daily Streak */}+ <div className="bg-gradient-to-br from-orange-500/20 to-red-500/20 border border-orange-500/30 rounded-lg p-4">+ <div className="flex items-center gap-2 mb-1">+ <Flame size={14} className="text-orange-400" />+ <span className="text-xs text-gray-400">Current Streak</span>+ </div>+ <div className="text-3xl font-bold text-white">+ {data.streaks?.currentDaily || 0}+ </div>+ <div className="text-xs text-gray-500">+ {data.streaks?.currentDaily === 1 ? 'day' : 'days'}+ </div>+ {data.streaks?.currentDaily >= 3 && (+ <div className="mt-2 text-xs text-orange-400 flex items-center gap-1">+ <Zap size={10} />+ On fire!+ </div>+ )}+ </div>++ {/* Longest Daily Streak */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center gap-2 mb-1">+ <Trophy size={14} className="text-yellow-400" />+ <span className="text-xs text-gray-400">Best Streak</span>+ </div>+ <div className="text-3xl font-bold text-yellow-400">+ {data.streaks?.longestDaily || 0}+ </div>+ <div className="text-xs text-gray-500">days</div>+ </div>++ {/* Weekly Streak */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center gap-2 mb-1">+ <Calendar size={14} className="text-cyan-400" />+ <span className="text-xs text-gray-400">Weekly Streak</span>+ </div>+ <div className="text-3xl font-bold text-cyan-400">+ {data.streaks?.currentWeekly || 0}+ </div>+ <div className="text-xs text-gray-500">weeks</div>+ </div>++ {/* Active Days */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center gap-2 mb-1">+ <Target size={14} className="text-port-accent" />+ <span className="text-xs text-gray-400">Total Active</span>+ </div>+ <div className="text-3xl font-bold text-white">+ {data.totals?.activeDays || 0}+ </div>+ <div className="text-xs text-gray-500">days worked</div>+ </div>+ </div>+ )}+ </div>++ {/* AI Insights */}+ {data.insights?.length > 0 && (+ <div>+ <button+ onClick={() => toggleSection('insights')}+ className="flex items-center gap-2 w-full text-left mb-3"+ >+ {expandedSections.insights ? <ChevronDown size={16} /> : <ChevronRight size={16} />}+ <Zap size={16} className="text-yellow-400" />+ <span className="font-medium text-white">Insights</span>+ <span className="text-xs text-gray-500">({data.insights.length})</span>+ </button>+ {expandedSections.insights && (+ <div className="space-y-2">+ {data.insights.map((insight, idx) => (+ <div+ key={idx}+ className={`border rounded-lg p-3 ${+ insight.type === 'success' ? 'bg-port-success/10 border-port-success/30' :+ insight.type === 'warning' ? 'bg-port-warning/10 border-port-warning/30' :+ insight.type === 'optimization' ? 'bg-green-500/10 border-green-500/30' :+ 'bg-port-accent/10 border-port-accent/30'+ }`}+ >+ <div className="flex items-start gap-2">+ {insight.type === 'success' && <CheckCircle size={14} className="text-port-success mt-0.5" />}+ {insight.type === 'warning' && <AlertTriangle size={14} className="text-port-warning mt-0.5" />}+ {insight.type === 'optimization' && <TrendingUp size={14} className="text-green-400 mt-0.5" />}+ {insight.type === 'info' && <Target size={14} className="text-port-accent mt-0.5" />}+ <div>+ <div className="font-medium text-sm text-white">{insight.title}</div>+ <div className="text-sm text-gray-400">{insight.message}</div>+ </div>+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ )}++ {/* Patterns */}+ <div>+ <button+ onClick={() => toggleSection('patterns')}+ className="flex items-center gap-2 w-full text-left mb-3"+ >+ {expandedSections.patterns ? <ChevronDown size={16} /> : <ChevronRight size={16} />}+ <BarChart2 size={16} className="text-purple-400" />+ <span className="font-medium text-white">Work Patterns</span>+ </button>+ {expandedSections.patterns && (+ <div className="grid gap-4 lg:grid-cols-2">+ {/* Best Hours */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <h4 className="text-sm font-medium text-gray-400 mb-3 flex items-center gap-2">+ <Clock size={14} className="text-cyan-400" />+ Hourly Performance+ </h4>+ {sortedHourlyPatterns.length > 0 ? (+ <div className="space-y-2 max-h-48 overflow-y-auto">+ {sortedHourlyPatterns.map((p) => (+ <div key={p.hour} className="flex items-center justify-between text-sm">+ <span className="text-gray-400 w-12">{formatHour(p.hour)}</span>+ <div className="flex-1 mx-2">+ <div className="h-2 bg-port-border rounded-full overflow-hidden">+ <div+ className={`h-full ${getSuccessRateBg(p.successRate)}`}+ style={{ width: `${p.successRate}%` }}+ />+ </div>+ </div>+ <span className={`font-mono w-10 text-right ${getSuccessRateColor(p.successRate)}`}>+ {p.successRate}%+ </span>+ <span className="text-gray-500 w-8 text-right text-xs">+ {p.tasks}+ </span>+ </div>+ ))}+ </div>+ ) : (+ <p className="text-sm text-gray-500">No hourly data yet</p>+ )}+ </div>++ {/* Best Days */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <h4 className="text-sm font-medium text-gray-400 mb-3 flex items-center gap-2">+ <Calendar size={14} className="text-purple-400" />+ Daily Performance+ </h4>+ {sortedDailyPatterns.length > 0 ? (+ <div className="space-y-2">+ {sortedDailyPatterns.map((p) => (+ <div key={p.day} className="flex items-center justify-between text-sm">+ <span className="text-gray-400 w-8">{p.dayName}</span>+ <div className="flex-1 mx-2">+ <div className="h-2 bg-port-border rounded-full overflow-hidden">+ <div+ className={`h-full ${getSuccessRateBg(p.successRate)}`}+ style={{ width: `${p.successRate}%` }}+ />+ </div>+ </div>+ <span className={`font-mono w-10 text-right ${getSuccessRateColor(p.successRate)}`}>+ {p.successRate}%+ </span>+ <span className="text-gray-500 w-8 text-right text-xs">+ {p.tasks}+ </span>+ </div>+ ))}+ </div>+ ) : (+ <p className="text-sm text-gray-500">No daily data yet</p>+ )}+ </div>++ {/* Best Hour/Day Highlight */}+ {(data.bestHour || data.bestDay) && (+ <div className="lg:col-span-2 bg-gradient-to-r from-purple-500/10 to-cyan-500/10 border border-purple-500/30 rounded-lg p-4">+ <h4 className="text-sm font-medium text-white mb-3 flex items-center gap-2">+ <Award size={14} className="text-yellow-400" />+ Optimal Work Times+ </h4>+ <div className="grid grid-cols-2 gap-4">+ {data.bestHour && (+ <div>+ <div className="text-xs text-gray-500">Best Hour</div>+ <div className="text-lg font-semibold text-cyan-400">+ {formatHour(data.bestHour.hour)}+ </div>+ <div className="text-xs text-gray-400">+ {data.bestHour.successRate}% success ({data.bestHour.tasks} tasks)+ </div>+ </div>+ )}+ {data.bestDay && (+ <div>+ <div className="text-xs text-gray-500">Best Day</div>+ <div className="text-lg font-semibold text-purple-400">+ {FULL_DAY_NAMES[data.bestDay.day]}+ </div>+ <div className="text-xs text-gray-400">+ {data.bestDay.successRate}% success ({data.bestDay.tasks} tasks)+ </div>+ </div>+ )}+ </div>+ </div>+ )}+ </div>+ )}+ </div>++ {/* Milestones */}+ {data.milestones?.length > 0 && (+ <div>+ <button+ onClick={() => toggleSection('milestones')}+ className="flex items-center gap-2 w-full text-left mb-3"+ >+ {expandedSections.milestones ? <ChevronDown size={16} /> : <ChevronRight size={16} />}+ <Trophy size={16} className="text-yellow-400" />+ <span className="font-medium text-white">Milestones</span>+ <span className="text-xs text-gray-500">({data.milestones.length})</span>+ </button>+ {expandedSections.milestones && (+ <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3">+ {data.milestones.map((m, idx) => (+ <div+ key={idx}+ className="bg-port-card border border-yellow-500/30 rounded-lg p-3 text-center"+ >+ <Trophy size={20} className="text-yellow-400 mx-auto mb-1" />+ <div className="text-sm font-medium text-white">{m.description}</div>+ {m.achievedAt && (+ <div className="text-xs text-gray-500 mt-1">+ {new Date(m.achievedAt).toLocaleDateString()}+ </div>+ )}+ </div>+ ))}+ </div>+ )}+ </div>+ )}++ {/* Summary Stats */}+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">+ <div className="bg-port-card border border-port-border rounded-lg p-3 text-center">+ <div className="text-2xl font-bold text-white">{data.totals?.totalTasks || 0}</div>+ <div className="text-xs text-gray-500">Total Tasks</div>+ </div>+ <div className="bg-port-card border border-port-border rounded-lg p-3 text-center">+ <div className={`text-2xl font-bold ${getSuccessRateColor(data.totals?.successRate || 0)}`}>+ {data.totals?.successRate || 0}%+ </div>+ <div className="text-xs text-gray-500">Success Rate</div>+ </div>+ <div className="bg-port-card border border-port-border rounded-lg p-3 text-center">+ <div className="text-2xl font-bold text-white">{data.totals?.activeDays || 0}</div>+ <div className="text-xs text-gray-500">Active Days</div>+ </div>+ <div className="bg-port-card border border-port-border rounded-lg p-3 text-center">+ <div className="text-2xl font-bold text-white">{data.totals?.activeWeeks || 0}</div>+ <div className="text-xs text-gray-500">Active Weeks</div>+ </div>+ </div>++ {/* Last Updated */}+ {data.lastUpdated && (+ <div className="text-xs text-gray-600 text-center pt-4 border-t border-port-border">+ Last updated: {new Date(data.lastUpdated).toLocaleString()}+ </div>+ )}+ </>+ )}+ </div>+ );+}diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex e550d1064e..b761361bce 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -26,6 +26,7 @@ import {ScriptsTab,ScheduleTab,DigestTab,+ ProductivityTab,LearningTab,MemoryTab,HealthTab,@@ -565,6 +566,11 @@ export default function ChiefOfStaff() {<DigestTab /></div>)}+ {activeTab === 'productivity' && (+ <div role="tabpanel" id="tabpanel-productivity" aria-labelledby="tab-productivity">+ <ProductivityTab />+ </div>+ )}{activeTab === 'learning' && (<div role="tabpanel" id="tabpanel-learning" aria-labelledby="tab-learning"><LearningTab />diff --git a/client/src/services/api.js b/client/src/services/api.jsindex eb4114d288..9203f2def4 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -463,6 +463,11 @@ export const generateCosDigest = (weekId = null) => request('/cos/digest/generat});export const compareCosWeeks = (week1, week2) => request(`/cos/digest/compare?week1=${week1}&week2=${week2}`);+// Productivity & Streaks+export const getCosProductivity = () => request('/cos/productivity');+export const getCosProductivitySummary = () => request('/cos/productivity/summary');+export const recalculateCosProductivity = () => request('/cos/productivity/recalculate', { method: 'POST' });+// Task Schedule (Configurable Intervals)export const getCosSchedule = () => request('/cos/schedule');export const getCosScheduleIntervalTypes = () => request('/cos/schedule/interval-types');diff --git a/server/routes/cos.js b/server/routes/cos.jsindex 89adb0b97a..6fe429e5fd 100644--- a/server/routes/cos.js+++ b/server/routes/cos.js@@ -12,6 +12,7 @@ import * as taskSchedule from '../services/taskSchedule.js';import * as autonomousJobs from '../services/autonomousJobs.js';import * as taskTemplates from '../services/taskTemplates.js';import { enhanceTaskPrompt } from '../services/taskEnhancer.js';+import * as productivity from '../services/productivity.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';const router = Router();@@ -828,4 +829,26 @@ router.delete('/templates/:id', asyncHandler(async (req, res) => {res.json(result);}));+// ============================================================+// Productivity & Streaks Routes+// ============================================================++// GET /api/cos/productivity - Get productivity insights and streaks+router.get('/productivity', asyncHandler(async (req, res) => {+ const insights = await productivity.getProductivityInsights();+ res.json(insights);+}));++// GET /api/cos/productivity/summary - Get quick summary for dashboard+router.get('/productivity/summary', asyncHandler(async (req, res) => {+ const summary = await productivity.getProductivitySummary();+ res.json(summary);+}));++// POST /api/cos/productivity/recalculate - Force recalculation from history+router.post('/productivity/recalculate', asyncHandler(async (req, res) => {+ const data = await productivity.recalculateProductivity();+ res.json({ success: true, data });+}));+export default router;diff --git a/server/services/productivity.js b/server/services/productivity.jsnew file mode 100644index 0000000000..164ddcdb34--- /dev/null+++ b/server/services/productivity.js@@ -0,0 +1,408 @@+/**+ * Productivity & Streaks Service+ *+ * Tracks work patterns, productivity streaks, and generates+ * insights about optimal working times.+ */++import { writeFile, mkdir } from 'fs/promises';+import { existsSync } from 'fs';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import { cosEvents, getAgents } from './cos.js';+import { readJSONFile } from '../lib/fileUtils.js';++const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);+const DATA_DIR = join(__dirname, '../../data/cos');+const PRODUCTIVITY_FILE = join(DATA_DIR, 'productivity.json');++/**+ * Default productivity data structure+ */+const DEFAULT_PRODUCTIVITY = {+ streaks: {+ currentDaily: 0, // Consecutive days with completed tasks+ longestDaily: 0, // Best daily streak ever+ currentWeekly: 0, // Consecutive weeks with activity+ longestWeekly: 0, // Best weekly streak ever+ lastActiveDate: null, // Last day with completed tasks+ lastActiveWeek: null // Last week with activity+ },+ hourlyPatterns: {+ // Aggregated by hour: { tasks, successes, failures, avgDuration }+ },+ dailyPatterns: {+ // Aggregated by day of week (0-6): { tasks, successes, failures, avgDuration }+ },+ milestones: [+ // { type, value, achievedAt, description }+ ],+ lastUpdated: null+};++/**+ * Ensure data directory exists+ */+async function ensureDataDir() {+ if (!existsSync(DATA_DIR)) {+ await mkdir(DATA_DIR, { recursive: true });+ }+}++/**+ * Load productivity data+ */+export async function loadProductivity() {+ await ensureDataDir();+ const data = await readJSONFile(PRODUCTIVITY_FILE, DEFAULT_PRODUCTIVITY);+ // Merge with defaults to ensure all fields exist+ return {+ ...DEFAULT_PRODUCTIVITY,+ ...data,+ streaks: { ...DEFAULT_PRODUCTIVITY.streaks, ...data.streaks }+ };+}++/**+ * Save productivity data+ */+async function saveProductivity(data) {+ await ensureDataDir();+ data.lastUpdated = new Date().toISOString();+ await writeFile(PRODUCTIVITY_FILE, JSON.stringify(data, null, 2));+ return data;+}++/**+ * Get date string (YYYY-MM-DD) for a Date object+ */+function getDateString(date = new Date()) {+ return date.toISOString().split('T')[0];+}++/**+ * Get week identifier (YYYY-WXX format)+ */+function getWeekId(date = new Date()) {+ const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));+ const dayNum = d.getUTCDay() || 7;+ d.setUTCDate(d.getUTCDate() + 4 - dayNum);+ const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));+ const week = Math.ceil((((d - yearStart) / 86400000) + 1) / 7);+ return `${date.getFullYear()}-W${week.toString().padStart(2, '0')}`;+}++/**+ * Check if two dates are consecutive days+ */+function isConsecutiveDay(date1, date2) {+ if (!date1 || !date2) return false;+ const d1 = new Date(date1);+ const d2 = new Date(date2);+ d1.setHours(0, 0, 0, 0);+ d2.setHours(0, 0, 0, 0);+ const diffDays = Math.round((d2 - d1) / (1000 * 60 * 60 * 24));+ return diffDays === 1;+}++/**+ * Check if two weeks are consecutive+ */+function isConsecutiveWeek(week1, week2) {+ if (!week1 || !week2) return false;+ // Parse YYYY-WXX format+ const [y1, w1] = week1.split('-W').map(Number);+ const [y2, w2] = week2.split('-W').map(Number);++ if (y1 === y2) return w2 - w1 === 1;+ if (y2 - y1 === 1 && w1 >= 52 && w2 === 1) return true;+ return false;+}++/**+ * Recalculate all productivity metrics from agent history+ */+export async function recalculateProductivity() {+ console.log('📊 Productivity: Recalculating from agent history');++ const agents = await getAgents();+ const completedAgents = agents.filter(a => a.completedAt && a.status === 'completed');++ // Sort by completion date+ completedAgents.sort((a, b) => new Date(a.completedAt) - new Date(b.completedAt));++ // Initialize patterns+ const hourlyPatterns = {};+ const dailyPatterns = {};++ // Track dates with activity for streak calculation+ const activeDates = new Set();+ const activeWeeks = new Set();++ for (const agent of completedAgents) {+ const completedAt = new Date(agent.completedAt);+ const dateStr = getDateString(completedAt);+ const weekId = getWeekId(completedAt);+ const hour = completedAt.getHours();+ const dayOfWeek = completedAt.getDay();+ const success = agent.result?.success === true;+ const duration = agent.result?.duration || 0;++ activeDates.add(dateStr);+ activeWeeks.add(weekId);++ // Hourly patterns+ if (!hourlyPatterns[hour]) {+ hourlyPatterns[hour] = { tasks: 0, successes: 0, failures: 0, totalDuration: 0 };+ }+ hourlyPatterns[hour].tasks++;+ if (success) hourlyPatterns[hour].successes++;+ else hourlyPatterns[hour].failures++;+ hourlyPatterns[hour].totalDuration += duration;++ // Daily patterns+ if (!dailyPatterns[dayOfWeek]) {+ dailyPatterns[dayOfWeek] = { tasks: 0, successes: 0, failures: 0, totalDuration: 0 };+ }+ dailyPatterns[dayOfWeek].tasks++;+ if (success) dailyPatterns[dayOfWeek].successes++;+ else dailyPatterns[dayOfWeek].failures++;+ dailyPatterns[dayOfWeek].totalDuration += duration;+ }++ // Calculate average durations+ for (const hour of Object.keys(hourlyPatterns)) {+ const p = hourlyPatterns[hour];+ p.avgDuration = p.tasks > 0 ? Math.round(p.totalDuration / p.tasks) : 0;+ p.successRate = p.tasks > 0 ? Math.round((p.successes / p.tasks) * 100) : 0;+ }+ for (const day of Object.keys(dailyPatterns)) {+ const p = dailyPatterns[day];+ p.avgDuration = p.tasks > 0 ? Math.round(p.totalDuration / p.tasks) : 0;+ p.successRate = p.tasks > 0 ? Math.round((p.successes / p.tasks) * 100) : 0;+ }++ // Calculate streaks+ const sortedDates = Array.from(activeDates).sort();+ const sortedWeeks = Array.from(activeWeeks).sort();++ const today = getDateString();+ const thisWeek = getWeekId();++ // Daily streak calculation+ let currentDaily = 0;+ let longestDaily = 0;+ let tempStreak = 0;++ for (let i = 0; i < sortedDates.length; i++) {+ if (i === 0 || isConsecutiveDay(sortedDates[i - 1], sortedDates[i])) {+ tempStreak++;+ } else {+ longestDaily = Math.max(longestDaily, tempStreak);+ tempStreak = 1;+ }+ }+ longestDaily = Math.max(longestDaily, tempStreak);++ // Current streak: count backwards from today+ const lastDate = sortedDates[sortedDates.length - 1];+ if (lastDate === today || isConsecutiveDay(lastDate, today)) {+ // Still active or just yesterday+ currentDaily = 1;+ for (let i = sortedDates.length - 1; i >= 1; i--) {+ if (isConsecutiveDay(sortedDates[i - 1], sortedDates[i])) {+ currentDaily++;+ } else {+ break;+ }+ }+ }++ // Weekly streak calculation+ let currentWeekly = 0;+ let longestWeekly = 0;+ let tempWeekStreak = 0;++ for (let i = 0; i < sortedWeeks.length; i++) {+ if (i === 0 || isConsecutiveWeek(sortedWeeks[i - 1], sortedWeeks[i])) {+ tempWeekStreak++;+ } else {+ longestWeekly = Math.max(longestWeekly, tempWeekStreak);+ tempWeekStreak = 1;+ }+ }+ longestWeekly = Math.max(longestWeekly, tempWeekStreak);++ // Current weekly streak+ const lastWeek = sortedWeeks[sortedWeeks.length - 1];+ if (lastWeek === thisWeek || isConsecutiveWeek(lastWeek, thisWeek)) {+ currentWeekly = 1;+ for (let i = sortedWeeks.length - 1; i >= 1; i--) {+ if (isConsecutiveWeek(sortedWeeks[i - 1], sortedWeeks[i])) {+ currentWeekly++;+ } else {+ break;+ }+ }+ }++ // Check for new milestones+ const milestones = [];+ const totalTasks = completedAgents.length;+ const successfulTasks = completedAgents.filter(a => a.result?.success).length;++ const taskMilestones = [10, 25, 50, 100, 250, 500, 1000];+ for (const m of taskMilestones) {+ if (totalTasks >= m) {+ milestones.push({+ type: 'tasks',+ value: m,+ achievedAt: completedAgents[m - 1]?.completedAt,+ description: `Completed ${m} tasks`+ });+ }+ }++ const streakMilestones = [3, 7, 14, 30, 60, 100];+ for (const m of streakMilestones) {+ if (longestDaily >= m) {+ milestones.push({+ type: 'streak',+ value: m,+ description: `${m}-day work streak`+ });+ }+ }++ const productivity = {+ streaks: {+ currentDaily,+ longestDaily,+ currentWeekly,+ longestWeekly,+ lastActiveDate: sortedDates[sortedDates.length - 1] || null,+ lastActiveWeek: sortedWeeks[sortedWeeks.length - 1] || null+ },+ hourlyPatterns,+ dailyPatterns,+ milestones,+ totals: {+ totalTasks,+ successfulTasks,+ successRate: totalTasks > 0 ? Math.round((successfulTasks / totalTasks) * 100) : 0,+ activeDays: sortedDates.length,+ activeWeeks: sortedWeeks.length+ }+ };++ return await saveProductivity(productivity);+}++/**+ * Get productivity insights+ */+export async function getProductivityInsights() {+ const data = await loadProductivity();++ // Find best hours (highest success rate with at least 5 tasks)+ const hourlyEntries = Object.entries(data.hourlyPatterns || {})+ .filter(([, p]) => p.tasks >= 5)+ .map(([hour, p]) => ({ hour: parseInt(hour), ...p }))+ .sort((a, b) => b.successRate - a.successRate);++ // Find best days+ const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];+ const dailyEntries = Object.entries(data.dailyPatterns || {})+ .filter(([, p]) => p.tasks >= 3)+ .map(([day, p]) => ({ day: parseInt(day), dayName: dayNames[parseInt(day)], ...p }))+ .sort((a, b) => b.successRate - a.successRate);++ const insights = [];++ // Best time insight+ if (hourlyEntries.length >= 1) {+ const best = hourlyEntries[0];+ const timeLabel = best.hour < 12 ? `${best.hour || 12}AM` : `${best.hour === 12 ? 12 : best.hour - 12}PM`;+ insights.push({+ type: 'optimization',+ title: 'Peak Performance Hour',+ message: `Tasks completed around ${timeLabel} have a ${best.successRate}% success rate`,+ icon: 'clock'+ });+ }++ // Best day insight+ if (dailyEntries.length >= 1) {+ const best = dailyEntries[0];+ insights.push({+ type: 'info',+ title: 'Most Productive Day',+ message: `${best.dayName}s show ${best.successRate}% success rate with ${best.tasks} tasks completed`,+ icon: 'calendar'+ });+ }++ // Streak encouragement+ const { streaks } = data;+ if (streaks?.currentDaily >= 3) {+ insights.push({+ type: 'success',+ title: '🔥 Hot Streak!',+ message: `${streaks.currentDaily} days of continuous productivity! Keep it up!`,+ icon: 'flame'+ });+ } else if (streaks?.currentDaily === 0 && streaks?.longestDaily > 0) {+ insights.push({+ type: 'warning',+ title: 'Streak Broken',+ message: `Your best was ${streaks.longestDaily} days. Start a new streak today!`,+ icon: 'refresh'+ });+ }++ // Weekly consistency+ if (streaks?.currentWeekly >= 4) {+ insights.push({+ type: 'success',+ title: 'Weekly Warrior',+ message: `${streaks.currentWeekly} consecutive weeks of activity!`,+ icon: 'trophy'+ });+ }++ return {+ ...data,+ insights,+ bestHour: hourlyEntries[0] || null,+ worstHour: hourlyEntries[hourlyEntries.length - 1] || null,+ bestDay: dailyEntries[0] || null,+ worstDay: dailyEntries[dailyEntries.length - 1] || null+ };+}++/**+ * Update productivity data on task completion+ */+export async function onTaskCompleted(agent) {+ // Debounce recalculation - just trigger it+ // A full recalculation ensures accurate streak counting+ await recalculateProductivity();+ cosEvents.emit('productivity:updated');+}++/**+ * Get summary for the dashboard+ */+export async function getProductivitySummary() {+ const data = await loadProductivity();++ return {+ currentStreak: data.streaks?.currentDaily || 0,+ longestStreak: data.streaks?.longestDaily || 0,+ weeklyStreak: data.streaks?.currentWeekly || 0,+ lastActive: data.streaks?.lastActiveDate || null,+ totalDays: data.totals?.activeDays || 0,+ recentMilestone: data.milestones?.[data.milestones.length - 1] || null+ };+}