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

remove the CoS Productivity page and re-source the activity heatmap from live agent history

[._.]/ Adam Eivyc12286395063
diff --git a/README.md b/README.md
index 4a5761e869..97671d6ad3 100644
--- a/README.md
+++ b/README.md
@@ -91,7 +91,7 @@ An autonomous AI agent orchestrator that manages your development workflow. Subm
- **Scheduled Automation** — Cron-based self-improvement and app-improvement jobs with per-app interval overrides
- **Error Recovery** — 6 strategies (retry, escalate, fallback, decompose, defer, investigate) for automatic diagnosis and retry ([CoS Enhancement docs](./docs/features/cos-enhancement.md))
- **Hybrid Memory Search** — BM25 + vector search with Reciprocal Rank Fusion for semantic retrieval across agent history
-- **Productivity Analytics** — Hourly/daily work patterns, task milestones, and AI-generated weekly digests
+- **Activity & Digests** — A runs-per-day activity heatmap on the dashboard, plus AI-generated weekly digests
- **Decision Transparency** — Every skip, switch, and routing decision is logged with reasons, surfaced on the dashboard
- **Briefing + Health** — A daily briefing of what CoS did and what needs you, plus a health view of queue depth, failure storms, and circuit-breaker state
- **Schedule Timeline** — Launch-order visualization of every scheduled task with an inline schedule editor, so overlapping cron runs are visible before they collide. Per-app cron overrides get their own markers, so a task left on-demand globally still shows when it runs for the apps that schedule it
diff --git a/client/src/components/CosDashboardWidget.jsx b/client/src/components/CosDashboardWidget.jsx
index 1e4a66a0e7..9c7b19ea07 100644
--- a/client/src/components/CosDashboardWidget.jsx
+++ b/client/src/components/CosDashboardWidget.jsx
@@ -15,7 +15,7 @@ import {
import * as api from '../services/api';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
import { useTimeTick } from '../hooks/useTimeTick';
-import { timeAgo, formatWeekdayDate } from '../utils/formatters';
+import { timeAgo, formatWeekdayDate, formatCount } from '../utils/formatters';
/**
* CosDashboardWidget - Compact CoS status widget for the main Dashboard
@@ -51,10 +51,10 @@ const CosDashboardWidget = memo(function CosDashboardWidget() {
// `task.completedRelative` string is intentionally ignored — it ships in
// the payload but would freeze across deduped polls if we used it.
//
- // Heatmap comparison walks every cell's (date, tasks, successRate) tuple
- // plus summary totals — per-day tasks/successRate distribution can shift
- // without changing top-level totals (e.g. a task moving from one day to
- // another in late-arriving telemetry).
+ // Heatmap comparison walks every cell's (date, tasks, isToday) tuple plus
+ // summary totals — the per-day distribution can shift without changing
+ // top-level totals (e.g. a run moving from one day to another in
+ // late-arriving telemetry).
compare: (prev, next) => {
const prevTasks = prev.recentTasks?.tasks;
const nextTasks = next.recentTasks?.tasks;
@@ -78,10 +78,10 @@ const CosDashboardWidget = memo(function CosDashboardWidget() {
|| a?.completedAt !== b?.completedAt
) return false;
}
- // Heatmap weeks: array of arrays of {date, tasks, successRate, isToday,
- // isFuture}. Compare every cell — single boundary-cross (isToday rolls
- // from one date to the next) flips the comparator naturally because
- // (date, isToday) on the prior+next today differ.
+ // Heatmap weeks: array of arrays of {date, tasks, isToday, isFuture}.
+ // Compare every cell — a single boundary-cross (isToday rolls from one
+ // date to the next) flips the comparator naturally because (date,
+ // isToday) on the prior+next today differ.
const prevWeeks = prev.activityCalendar?.weeks;
const nextWeeks = next.activityCalendar?.weeks;
const prevWeeksLen = prevWeeks?.length ?? 0;
@@ -97,7 +97,6 @@ const CosDashboardWidget = memo(function CosDashboardWidget() {
if (
pd?.date !== nd?.date
|| pd?.tasks !== nd?.tasks
- || pd?.successRate !== nd?.successRate
|| pd?.isToday !== nd?.isToday
) return false;
}
@@ -119,7 +118,6 @@ const CosDashboardWidget = memo(function CosDashboardWidget() {
&& prev.recentTasks?.summary?.total === next.recentTasks?.summary?.total
&& prev.recentTasks?.summary?.succeeded === next.recentTasks?.summary?.succeeded
&& prev.activityCalendar?.summary?.totalTasks === next.activityCalendar?.summary?.totalTasks
- && prev.activityCalendar?.summary?.successRate === next.activityCalendar?.summary?.successRate
&& prev.activityCalendar?.summary?.activeDays === next.activityCalendar?.summary?.activeDays
&& prev.activityCalendar?.maxTasks === next.activityCalendar?.maxTasks
);
@@ -336,9 +334,13 @@ const CosDashboardWidget = memo(function CosDashboardWidget() {
);
});
+// Intensity 0 is never rendered through this table — an empty or future day
+// short-circuits to the neutral square before the lookup.
+const HEATMAP_SHADES = ['', 'bg-emerald-900/50', 'bg-emerald-700/60', 'bg-emerald-500/70', 'bg-emerald-400'];
+
/**
* ActivityCalendar - Compact GitHub-style activity heatmap
- * Shows daily task completion as colored squares
+ * Shows daily run volume as colored squares
*/
function ActivityCalendar({ data }) {
// Calculate intensity level (0-4) based on tasks completed
@@ -353,23 +355,10 @@ function ActivityCalendar({ data }) {
return 1;
};
- // Get color class based on intensity and success rate
- const getColorClass = (day) => {
- if (day.tasks === 0 || day.isFuture) return 'bg-port-border/20';
- const intensity = getIntensityLevel(day.tasks);
-
- // Color based on success rate
- if (day.successRate >= 80) {
- const shades = ['', 'bg-emerald-900/50', 'bg-emerald-700/60', 'bg-emerald-500/70', 'bg-emerald-400'];
- return shades[intensity];
- } else if (day.successRate >= 50) {
- const shades = ['', 'bg-amber-900/50', 'bg-amber-700/60', 'bg-amber-500/70', 'bg-amber-400'];
- return shades[intensity];
- } else {
- const shades = ['', 'bg-red-900/50', 'bg-red-700/60', 'bg-red-500/70', 'bg-red-400'];
- return shades[intensity];
- }
- };
+ // Color by volume alone, GitHub-contribution style. Outcome is not in this
+ // payload — the Today and Learning tiles above report it live.
+ const getColorClass = (day) =>
+ (day.tasks === 0 || day.isFuture) ? 'bg-port-border/20' : HEATMAP_SHADES[getIntensityLevel(day.tasks)];
return (
<div className="mt-4 pt-4 border-t border-port-border">
@@ -379,7 +368,7 @@ function ActivityCalendar({ data }) {
<span className="text-sm font-medium text-gray-300">Activity</span>
</div>
<Link
- to="/cos/productivity"
+ to="/cos/agents"
className="flex items-center gap-1 text-xs text-gray-500 hover:text-port-accent transition-colors"
>
{data.summary.activeDays} active days
@@ -402,7 +391,7 @@ function ActivityCalendar({ data }) {
${day.isToday ? 'ring-1 ring-port-accent' : ''}
${day.isFuture ? 'opacity-30' : ''}
`}
- title={day.isFuture ? '' : `${formatWeekdayDate(day.date, { weekday: 'short' })}: ${day.tasks} task${day.tasks !== 1 ? 's' : ''} (${day.successRate}% success)`}
+ title={day.isFuture ? '' : `${formatWeekdayDate(day.date, { weekday: 'short' })}: ${day.tasks} run${day.tasks !== 1 ? 's' : ''}`}
/>
))}
</div>
@@ -413,11 +402,8 @@ function ActivityCalendar({ data }) {
{/* Summary Row */}
<div className="flex items-center justify-between mt-2 text-xs text-gray-500">
<span>
- <span className="text-white font-medium">{data.summary.totalTasks}</span> tasks,{' '}
- <span className={`font-medium ${
- data.summary.successRate >= 80 ? 'text-port-success' :
- data.summary.successRate >= 50 ? 'text-port-warning' : 'text-port-error'
- }`}>{data.summary.successRate}%</span> success
+ <span className="text-white font-medium">{formatCount(data.summary.totalTasks)}</span> runs,{' '}
+ <span className="text-white font-medium">{data.summary.avgTasksPerActiveDay}</span>/active day
</span>
{/* Mini Legend */}
<div className="flex items-center gap-0.5">
diff --git a/client/src/components/cos/ActionableInsightsBanner.jsx b/client/src/components/cos/ActionableInsightsBanner.jsx
index 9cfa226117..edc1b1192a 100644
--- a/client/src/components/cos/ActionableInsightsBanner.jsx
+++ b/client/src/components/cos/ActionableInsightsBanner.jsx
@@ -34,10 +34,9 @@ export const formatBranchSummary = ({ leftoverCount, states }) => [
// health surfaces do — but the honesty distinction the feature exists to enforce
// means the level must match how each insight was actually derived. Most insight
// types are direct counts read off records (N tasks awaiting approval, N blocked,
-// N health issues) → data-backed. Only the two that lean on success-rate
-// statistics — auto-skipped task types and the peak-productivity-hour suggestion
-// — are genuinely modeled → inferred.
-const INFERRED_INSIGHT_TYPES = new Set(['learning', 'peak-time']);
+// N health issues) → data-backed. Only auto-skipped task types lean on
+// success-rate statistics → inferred.
+const INFERRED_INSIGHT_TYPES = new Set(['learning']);
const DATA_BACKED_PROVENANCE = {
level: 'data-backed',
@@ -50,7 +49,7 @@ const DATA_BACKED_PROVENANCE = {
const INFERRED_PROVENANCE = {
level: 'inferred',
explainer:
- 'Surfaced by your Chief of Staff from statistical patterns in your task history — success rates by task type and time of day — not a value you set or a direct count.',
+ 'Surfaced by your Chief of Staff from statistical patterns in your task history — success rates by task type — not a value you set or a direct count.',
whatWouldChange:
'As more task runs accumulate and those success rates shift, this recommendation is recomputed or drops away.',
};
@@ -65,8 +64,7 @@ const ICON_MAP = {
Brain,
Newspaper,
ListTodo,
- MessageSquare,
- Zap
+ MessageSquare
};
const PRIORITY_STYLES = {
diff --git a/client/src/components/cos/ActionableInsightsBanner.test.jsx b/client/src/components/cos/ActionableInsightsBanner.test.jsx
index 20bb1771df..3d20be35c3 100644
--- a/client/src/components/cos/ActionableInsightsBanner.test.jsx
+++ b/client/src/components/cos/ActionableInsightsBanner.test.jsx
@@ -16,10 +16,8 @@ describe('ActionableInsightsBanner insightProvenance', () => {
}
});
- it('marks success-rate-modeled insight types as inferred', () => {
- for (const type of ['learning', 'peak-time']) {
- expect(insightProvenance(type).level).toBe('inferred');
- }
+ it('marks the success-rate-modeled insight type as inferred', () => {
+ expect(insightProvenance('learning').level).toBe('inferred');
});
it('defaults an unknown insight type to data-backed (a count, not a model)', () => {
diff --git a/client/src/components/cos/DailyTrendsChart.jsx b/client/src/components/cos/DailyTrendsChart.jsx
deleted file mode 100644
index 74cfec48c5..0000000000
--- a/client/src/components/cos/DailyTrendsChart.jsx
+++ /dev/null
@@ -1,220 +0,0 @@
-import { useState, useEffect, useCallback, useMemo } from 'react';
-import {TrendingUp, TrendingDown, Minus, Activity, ChevronDown, ChevronRight} from 'lucide-react';
-import * as api from '../../services/api';
-import BrailleSpinner from '../BrailleSpinner';
-
-/**
- * DailyTrendsChart - Visualizes daily task completion trends
- * Shows a bar chart of tasks completed per day with success rate overlay
- */
-export default function DailyTrendsChart({ days = 30, initialExpanded = true }) {
- const [data, setData] = useState(null);
- const [loading, setLoading] = useState(true);
- const [expanded, setExpanded] = useState(initialExpanded);
-
- const loadData = useCallback(async () => {
- setLoading(true);
- const result = await api.getCosProductivityTrends(days).catch(() => null);
- setData(result);
- setLoading(false);
- }, [days]);
-
- useEffect(() => {
- loadData();
- }, [loadData]);
-
- // Find max tasks for scaling
- const maxTasks = useMemo(() => {
- if (!data?.data) return 1;
- return Math.max(...data.data.map(d => d.tasks), 1);
- }, [data]);
-
- const getSuccessRateColor = (rate) => {
- if (rate >= 80) return 'bg-port-success';
- if (rate >= 60) return 'bg-port-warning';
- if (rate > 0) return 'bg-port-error';
- return 'bg-port-border';
- };
-
- const getTrendIcon = (trend) => {
- if (trend === 'increasing' || trend === 'improving') {
- return <TrendingUp size={14} className="text-port-success" />;
- }
- if (trend === 'decreasing' || trend === 'declining') {
- return <TrendingDown size={14} className="text-port-error" />;
- }
- return <Minus size={14} className="text-gray-500" />;
- };
-
- const getTrendLabel = (trend) => {
- if (trend === 'increasing') return 'Volume trending up';
- if (trend === 'decreasing') return 'Volume trending down';
- if (trend === 'improving') return 'Success rate improving';
- if (trend === 'declining') return 'Success rate declining';
- return 'Stable';
- };
-
- if (loading) {
- return (
- <div className="bg-port-card border border-port-border rounded-lg p-4">
- <div className="flex items-center justify-center py-8">
- <BrailleSpinner text="Loading" />
- </div>
- </div>
- );
- }
-
- if (!data?.data?.length) {
- return (
- <div className="bg-port-card border border-port-border rounded-lg p-4">
- <div className="flex items-center gap-2 mb-3">
- <Activity size={16} className="text-port-accent" />
- <span className="font-medium text-white">Daily Task Trends</span>
- </div>
- <p className="text-sm text-gray-500">No task history available. Complete tasks to see trends.</p>
- </div>
- );
- }
-
- const { summary } = data;
-
- return (
- <div className="bg-port-card border border-port-border rounded-lg overflow-hidden">
- {/* Header */}
- <button
- onClick={() => setExpanded(!expanded)}
- className="w-full flex items-center justify-between p-4 hover:bg-port-bg/50 transition-colors"
- >
- <div className="flex items-center gap-2">
- {expanded ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
- <Activity size={16} className="text-port-accent" />
- <span className="font-medium text-white">Daily Task Trends</span>
- <span className="text-xs text-gray-500">({summary.days} days)</span>
- </div>
- <div className="flex items-center gap-3">
- {/* Trend indicators */}
- <div className="flex items-center gap-1">
- {getTrendIcon(summary.volumeTrend)}
- <span className="text-xs text-gray-400">{getTrendLabel(summary.volumeTrend)}</span>
- </div>
- </div>
- </button>
-
- {expanded && (
- <div className="p-4 pt-0">
- {/* Summary Stats */}
- <div className="grid grid-cols-2 gap-2 sm:grid-cols-4 mb-4">
- <div className="text-center">
- <div className="text-lg font-bold text-white">{summary.totalTasks}</div>
- <div className="text-xs text-gray-500">Total Tasks</div>
- </div>
- <div className="text-center">
- <div className="text-lg font-bold text-port-accent">{summary.activeDays}</div>
- <div className="text-xs text-gray-500">Active Days</div>
- </div>
- <div className="text-center">
- <div className="text-lg font-bold text-port-accent">{summary.avgTasksPerActiveDay}</div>
- <div className="text-xs text-gray-500">Avg/Day</div>
- </div>
- <div className="text-center">
- <div className={`text-lg font-bold ${summary.avgSuccessRate >= 70 ? 'text-port-success' : summary.avgSuccessRate >= 50 ? 'text-port-warning' : 'text-port-error'}`}>
- {summary.avgSuccessRate}%
- </div>
- <div className="text-xs text-gray-500">Success</div>
- </div>
- </div>
-
- {/* Bar Chart */}
- <div className="relative">
- {/* Y-axis labels */}
- <div className="absolute left-0 top-0 bottom-6 w-8 flex flex-col justify-between text-xs text-gray-600">
- <span>{maxTasks}</span>
- <span>{Math.round(maxTasks / 2)}</span>
- <span>0</span>
- </div>
-
- {/* Chart area */}
- <div className="ml-10 overflow-x-auto">
- <div className="flex items-end gap-0.5 h-32" style={{ minWidth: `${data.data.length * 12}px` }}>
- {data.data.map((day, idx) => {
- const barHeight = (day.tasks / maxTasks) * 100;
- const isToday = idx === data.data.length - 1;
-
- return (
- <div
- key={day.date}
- className="flex-1 flex flex-col items-center group relative"
- style={{ minWidth: '10px', maxWidth: '24px' }}
- >
- {/* Bar */}
- <div
- className={`w-full rounded-t transition-all ${day.tasks > 0 ? getSuccessRateColor(day.successRate) : 'bg-port-border/30'} ${isToday ? 'ring-1 ring-port-accent' : ''}`}
- style={{ height: `${Math.max(barHeight, day.tasks > 0 ? 8 : 2)}%` }}
- />
-
- {/* Tooltip */}
- <div className="absolute bottom-full mb-2 left-1/2 -translate-x-1/2 hidden group-hover:block z-10">
- <div className="bg-port-bg border border-port-border rounded px-2 py-1 text-xs whitespace-nowrap shadow-lg">
- <div className="text-white font-medium">{day.date}</div>
- {day.tasks > 0 ? (
- <>
- <div className="text-gray-400">{day.tasks} task{day.tasks !== 1 ? 's' : ''}</div>
- <div className={day.successRate >= 70 ? 'text-port-success' : day.successRate >= 50 ? 'text-port-warning' : 'text-port-error'}>
- {day.successes}/{day.tasks} passed ({day.successRate}%)
- </div>
- </>
- ) : (
- <div className="text-gray-500">No tasks</div>
- )}
- </div>
- </div>
- </div>
- );
- })}
- </div>
-
- {/* X-axis labels - show every 7th day */}
- <div className="flex gap-0.5 mt-1" style={{ minWidth: `${data.data.length * 12}px` }}>
- {data.data.map((day, idx) => (
- <div
- key={day.date}
- className="flex-1 text-center"
- style={{ minWidth: '10px', maxWidth: '24px' }}
- >
- {idx % 7 === 0 && (
- <span className="text-xs text-gray-600">{day.dateShort}</span>
- )}
- </div>
- ))}
- </div>
- </div>
- </div>
-
- {/* Legend */}
- <div className="flex items-center justify-center gap-4 mt-4 text-xs">
- <div className="flex items-center gap-1">
- <div className="w-3 h-3 rounded bg-port-success" />
- <span className="text-gray-500">80%+</span>
- </div>
- <div className="flex items-center gap-1">
- <div className="w-3 h-3 rounded bg-port-warning" />
- <span className="text-gray-500">60-79%</span>
- </div>
- <div className="flex items-center gap-1">
- <div className="w-3 h-3 rounded bg-port-error" />
- <span className="text-gray-500">&lt;60%</span>
- </div>
- </div>
-
- {/* Success trend indicator */}
- {summary.successTrend !== 'stable' && (
- <div className={`mt-3 p-2 rounded text-xs text-center ${summary.successTrend === 'improving' ? 'bg-port-success/10 text-port-success' : 'bg-port-error/10 text-port-error'}`}>
- {getTrendIcon(summary.successTrend)}
- <span className="ml-1">{getTrendLabel(summary.successTrend)}</span>
- </div>
- )}
- </div>
- )}
- </div>
- );
-}
diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.js
index 38e994ddf1..59a5b1e41a 100644
--- a/client/src/components/cos/constants.js
+++ b/client/src/components/cos/constants.js
@@ -9,7 +9,6 @@ import {
Compass,
GraduationCap,
Bot,
- BarChart2,
Newspaper,
ChartGantt,
Play,
@@ -35,7 +34,6 @@ const TAB_PRESENTATION = {
workflow: { icon: ChartGantt },
digest: { icon: Calendar },
gsd: { icon: Compass },
- productivity: { icon: BarChart2 },
learning: { icon: GraduationCap },
memory: { icon: Brain },
mind: { icon: MessageCircle },
diff --git a/client/src/components/cos/constants.test.js b/client/src/components/cos/constants.test.js
index 1ea3418f64..57352e69ca 100644
--- a/client/src/components/cos/constants.test.js
+++ b/client/src/components/cos/constants.test.js
@@ -387,7 +387,7 @@ describe('CoS TABS ↔ nav manifest', () => {
expectPageNavTabs(TABS, [
'briefing:Briefing', 'tasks:Tasks', 'agents:Agents', 'jobs:System Tasks',
'runs:Runs', 'run-events:Run Events', 'schedule:Schedule', 'workflow:Timeline',
- 'digest:Digest', 'gsd:GSD', 'productivity:Productivity', 'learning:Learning',
+ 'digest:Digest', 'gsd:GSD', 'learning:Learning',
'memory:Memory', 'mind:Mind', 'health:Health', 'config:Config',
]);
});
diff --git a/client/src/components/cos/index.js b/client/src/components/cos/index.js
index e874c06cf9..e7481da59c 100644
--- a/client/src/components/cos/index.js
+++ b/client/src/components/cos/index.js
@@ -16,7 +16,6 @@ export { default as StatCard } from './StatCard';
export { default as StatusBubble } from './StatusBubble';
export { default as EventLog } from './EventLog';
export { default as ActionableInsightsBanner } from './ActionableInsightsBanner';
-export { default as DailyTrendsChart } from './DailyTrendsChart';
// Tab Components
export { default as TasksTab } from './tabs/TasksTab';
@@ -30,5 +29,4 @@ export { default as HealthTab } from './tabs/HealthTab';
export { default as ConfigTab } from './tabs/ConfigTab';
export { default as DigestTab } from './tabs/DigestTab';
export { default as GsdTab } from './tabs/GsdTab';
-export { default as ProductivityTab } from './tabs/ProductivityTab';
export { default as BriefingTab } from './tabs/BriefingTab';
diff --git a/client/src/components/cos/tabs/ProductivityTab.jsx b/client/src/components/cos/tabs/ProductivityTab.jsx
deleted file mode 100644
index d955ea7c8d..0000000000
--- a/client/src/components/cos/tabs/ProductivityTab.jsx
+++ /dev/null
@@ -1,354 +0,0 @@
-import { useState, useEffect, useCallback, useMemo } from 'react';
-import {
- BarChart2,
- RefreshCw,
- TrendingUp,
- Clock,
- Calendar,
- Trophy,
- Target,
- Zap,
- CheckCircle,
- AlertTriangle,
- ChevronDown,
- ChevronRight,
- Award
-} from 'lucide-react';
-import BrailleSpinner from '../../BrailleSpinner';
-import { formatDateTime, formatDateNumeric, formatHourOfDay } from '../../../utils/formatters';
-import * as api from '../../../services/api';
-import DailyTrendsChart from '../DailyTrendsChart';
-
-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({
- patterns: true,
- insights: true,
- milestones: false,
- });
-
- const loadData = useCallback(async (autoRecalculate = false) => {
- setLoading(true);
- const productivity = await api.getCosProductivity().catch(() => null);
- if (!productivity?.totals?.totalTasks && autoRecalculate) {
- // No productivity.json yet — build it from agent history
- await api.recalculateCosProductivity().catch(() => null);
- const refreshed = await api.getCosProductivity().catch(() => null);
- setData(refreshed);
- } else {
- setData(productivity);
- }
- setLoading(false);
- }, []);
-
- useEffect(() => {
- loadData(true);
- }, [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 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, 10), ...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, 10), dayName: DAY_NAMES[parseInt(day, 10)], ...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">
- <BrailleSpinner text="Loading" />
- </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">
- <BarChart2 className="w-5 h-5 text-port-accent" />
- <h3 className="text-lg font-semibold text-white">Productivity</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">
- <BarChart2 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.
- </p>
- </div>
- ) : (
- <>
- {/* Daily Task Trends Chart */}
- <DailyTrendsChart days={30} initialExpanded={true} />
-
- {/* 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-port-success/10 border-port-success/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-port-success 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-port-accent-2" />
- <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-port-accent" />
- 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">{formatHourOfDay(p.hour, { style: 'compact' })}</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-port-accent-2" />
- 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-port-accent-2/10 to-port-accent/10 border border-port-accent-2/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-port-accent">
- {formatHourOfDay(data.bestHour.hour, { style: 'compact' })}
- </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-port-accent-2">
- {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">
- {formatDateNumeric(m.achievedAt)}
- </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: {formatDateTime(data.lastUpdated)}
- </div>
- )}
- </>
- )}
- </div>
- );
-}
diff --git a/client/src/lib/eidoverseFrame.js b/client/src/lib/eidoverseFrame.js
index c54102002f..0ca85bb4a3 100644
--- a/client/src/lib/eidoverseFrame.js
+++ b/client/src/lib/eidoverseFrame.js
@@ -5,8 +5,8 @@ export const EIDOVERSE_FRAME_VERSION = 1;
export const EIDOVERSE_LABEL_PREFERENCES = ['nearby', 'all-nearby', 'off'];
export const EIDOVERSE_SOURCE_ROUTES = Object.freeze({
apps: '/apps', agents: '/cos/agents', tasks: '/cos/tasks', features: '/settings/features',
- peers: '/instances', health: '/cos/health', productivity: '/cos/productivity',
- activity: '/cos/productivity', goals: '/goals/list', memory: '/brain/memory',
+ peers: '/instances', health: '/cos/health', productivity: '/cos/agents',
+ activity: '/cos/agents', goals: '/goals/list', memory: '/brain/memory',
storage: '/settings/database', jira: '/goals/list', operations: '/cos/health',
});
const ROUTES = new Set([...Object.values(EIDOVERSE_SOURCE_ROUTES), '/eidoverse']);
diff --git a/client/src/lib/navPresentation.js b/client/src/lib/navPresentation.js
index b22b412977..2caf969bd2 100644
--- a/client/src/lib/navPresentation.js
+++ b/client/src/lib/navPresentation.js
@@ -44,7 +44,6 @@ import {
Ticket,
Network,
Flame,
- BarChart2,
Cigarette,
HeartPulse,
ClipboardList,
@@ -151,7 +150,6 @@ export const NAV_PRESENTATION = {
'/cos/runs': { icon: Play },
'/cos/schedule': { icon: Clock },
'/agents': { icon: Users },
- '/cos/productivity': { icon: BarChart2 },
'/cos/jobs': { icon: Bot },
'/cos/tasks': { icon: FileText },
'/cos/workflow': { icon: ChartGantt },
diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsx
index 00f91f611e..d8d4f2185d 100644
--- a/client/src/pages/ChiefOfStaff.jsx
+++ b/client/src/pages/ChiefOfStaff.jsx
@@ -55,7 +55,6 @@ const ScheduleTab = lazy(() => import('../components/cos/tabs/ScheduleTab'));
const WorkflowTab = lazy(() => import('../components/cos/tabs/WorkflowTab'));
const DigestTab = lazy(() => import('../components/cos/tabs/DigestTab'));
const GsdTab = lazy(() => import('../components/cos/tabs/GsdTab'));
-const ProductivityTab = lazy(() => import('../components/cos/tabs/ProductivityTab'));
const LearningTab = lazy(() => import('../components/cos/tabs/LearningTab'));
const MemoryTab = lazy(() => import('../components/cos/tabs/MemoryTab'));
const HealthTab = lazy(() => import('../components/cos/tabs/HealthTab'));
@@ -1243,13 +1242,6 @@ export default function ChiefOfStaff() {
</Suspense>
</div>
)}
- {activeTab === 'productivity' && (
- <div role="tabpanel" id="tabpanel-productivity" aria-labelledby="tab-productivity">
- <Suspense fallback={<TabLoadFallback label="productivity" />}>
- <ProductivityTab />
- </Suspense>
- </div>
- )}
{activeTab === 'learning' && (
<div role="tabpanel" id="tabpanel-learning" aria-labelledby="tab-learning">
<Suspense fallback={<TabLoadFallback label="learning" />}>
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index 013cb50d82..b568cbf1eb 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -329,11 +329,8 @@ export const generateCosDigest = (weekId = null) => request('/cos/digest/generat
body: JSON.stringify({ weekId })
});
-// Productivity
-export const getCosProductivity = () => request('/cos/productivity');
-export const recalculateCosProductivity = () => request('/cos/productivity/recalculate', { method: 'POST' });
-export const getCosProductivityTrends = (days = 30) => request(`/cos/productivity/trends?days=${days}`);
-export const getCosActivityCalendar = (weeks = 12, options) => request(`/cos/productivity/calendar?weeks=${weeks}`, options);
+// Activity
+export const getCosActivityCalendar = (weeks = 12, options) => request(`/cos/activity-calendar?weeks=${weeks}`, options);
export const getCosQuickSummary = (options) => request('/cos/quick-summary', options);
export const getCosRecentTasks = (limit = 10, options) => request(`/cos/recent-tasks?limit=${limit}`, options);
export const getCosActionableInsights = (options) => request('/cos/actionable-insights', options);
diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.md
index eab7028dc4..08190c9120 100644
--- a/docs/features/product-surfaces.md
+++ b/docs/features/product-surfaces.md
@@ -63,7 +63,7 @@ Submit tasks, manage durable autonomous agents, schedule recurring automations,
| **Schedule Timeline & Workflows** | `/cos/workflow`, `/cos/schedule` | Visual Gantt-style schedule editor showing launch order, task dependencies, concurrency limits, and cron schedules. | [Chief of Staff](./chief-of-staff.md) |
| **Operational Briefings & Digest** | `/cos/briefing`, `/cos/digest` | Morning briefings of operational signals, system alerts, pending approvals, and end-of-day accomplishment rollups. | [GOALS_OPERATIONAL.md](../GOALS_OPERATIONAL.md) |
| **CoS Health & Diagnostics** | `/cos/health`, `/cos/jobs` | Agent runner daemon health, PM2 worker telemetry, background maintenance jobs, and queue diagnostics. | [Agent Runner](./cos-agent-runner.md) |
-| **Learning & Productivity** | `/cos/learning`, `/cos/productivity` | Task duration models, success rate metrics, category learning curves, and operational work patterns. | — |
+| **Learning** | `/cos/learning` | Task duration models, success rate metrics, and category learning curves. | — |
| **Persistent Mind** | `/cos/mind` | Resident long-term conversational AI agent with persistent context memory, annotation support, and continuous system oversight. | [Agent Tools (MCP)](./agent-context.md), [Memory System](./memory-system.md) |
| **Mind Tools Governance** | `/cos/mind?panel=tools` | Fine-grained tool permission controls, MCP context disclosure settings (metadata-only vs redacted summaries), and semantic action grants. | [Agent Tools (MCP)](./agent-context.md), [Agent Skills](./agent-skills.md) |
| **Feature Agents** | `/feature-agents` | Durable, specialized agents assigned to specific feature domains or managed codebases. | — |
diff --git a/scripts/migrations/393-remove-retired-productivity-store.js b/scripts/migrations/393-remove-retired-productivity-store.js
new file mode 100644
index 0000000000..0a0c1f9814
--- /dev/null
+++ b/scripts/migrations/393-remove-retired-productivity-store.js
@@ -0,0 +1,31 @@
+/**
+ * Remove the retired `data/cos/productivity.json` aggregate (#7599).
+ *
+ * The store backed the CoS Productivity page and the dashboard heatmap, but it
+ * had no automatic writer — nothing in the server called its incremental
+ * updater, so the file only changed when a human opened that page and pressed
+ * Refresh. Both surfaces now read agent history directly
+ * (`server/services/cosActivityCalendar.js`), so the file is orphaned.
+ *
+ * Safe to delete: every field in it was DERIVED from the agent records in
+ * `data/cos/agents/`, which this migration does not touch. Nothing reads the
+ * file after this release, so leaving it would only strand a stale copy of
+ * counts the live stores already hold.
+ */
+
+import { unlink } from 'fs/promises';
+import { join } from 'path';
+
+export default {
+ async up({ rootDir }) {
+ const file = join(rootDir, 'data', 'cos', 'productivity.json');
+ const removed = await unlink(file).then(() => true, (error) => {
+ if (error.code === 'ENOENT') return false;
+ throw error;
+ });
+
+ if (!removed) return { updated: 0, reason: 'no-productivity-store' };
+ console.log('🧹 migration 393: removed the retired data/cos/productivity.json aggregate');
+ return { updated: 1 };
+ },
+};
diff --git a/scripts/migrations/393-remove-retired-productivity-store.test.js b/scripts/migrations/393-remove-retired-productivity-store.test.js
new file mode 100644
index 0000000000..259d85a066
--- /dev/null
+++ b/scripts/migrations/393-remove-retired-productivity-store.test.js
@@ -0,0 +1,40 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import migration from './393-remove-retired-productivity-store.js';
+
+describe('migration 393 — remove the retired productivity store', () => {
+ let rootDir;
+ let cosDir;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-393-productivity-'));
+ cosDir = join(rootDir, 'data', 'cos');
+ mkdirSync(cosDir, { recursive: true });
+ });
+
+ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));
+
+ it('removes the orphaned aggregate and leaves the agent history it was derived from', async () => {
+ const productivity = join(cosDir, 'productivity.json');
+ // The real index the calendar now reads instead — data/cos/agents/index.json.
+ const agentsIndex = join(cosDir, 'agents', 'index.json');
+ mkdirSync(join(cosDir, 'agents'), { recursive: true });
+ writeFileSync(productivity, JSON.stringify({ dailyHistory: { '2026-01-02': { tasks: 3 } } }));
+ writeFileSync(agentsIndex, JSON.stringify({ 'agent-1': '2026-01-02' }));
+
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 1 });
+
+ expect(existsSync(productivity)).toBe(false);
+ expect(JSON.parse(readFileSync(agentsIndex, 'utf8'))).toEqual({ 'agent-1': '2026-01-02' });
+ });
+
+ it('no-ops on an install that never wrote the store, and on a re-run', async () => {
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'no-productivity-store' });
+
+ writeFileSync(join(cosDir, 'productivity.json'), '{}');
+ await migration.up({ rootDir });
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'no-productivity-store' });
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 8df2ba32a7..6e44754451 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -597,7 +597,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `errorHandler.js` | `ServerError` + `asyncHandler` middleware, plus `sendErrorResponse`/`buildErrorEnvelope` for the standard `{ error, code, timestamp }` body outside a handler's catch. |
| `extensionErrors.js` | `isExtensionError(payload)` — true when a client error report came from a browser extension's injected content script (extension URL scheme in `source`/`stack`/`message`, or a short list of vendor/runtime message signatures) rather than from PortOS. Consumed by `services/clientErrors.js` to keep un-actionable extension noise out of the Review Hub *and* out of the 1/sec throttle slot, where it would displace real errors. Re-exported by `client/src/lib/extensionErrors.js`, so both sides classify identically. |
| `fetchErrorChain.js` | `describeFetchError(err)` flattens a fetch rejection's whole `cause` chain (depth-bounded, cycle-guarded) into one searchable `code: message` string — undici reports every network failure as the same opaque `TypeError: fetch failed` with the real reason nested inside, so a classifier reading only `err.message` misjudges every one of them. `isReplayableConnectionError(err)` is the narrow predicate over that string for connection-REUSE artifacts (HTTP/2 GOAWAY, reset, hang-up) that are safe to replay once via `fetchWithTimeout`'s `shouldRetry`; it deliberately EXCLUDES timeouts, which broader classifiers like `ollamaManager`'s `isTransientPullError` include. |
-| `isoWeek.js` | ISO-8601 week identity — the single source of the `YYYY-Www` week id. `getWeekId(date)` keys on the ISO week-numbering **year** (the calendar year of that week's Thursday), not `date.getFullYear()`, so one ISO week is never split across two ids and two weeks never collide on one (#3465). Also `isoWeekParts`, `getIsoWeekNumber`, `getIsoWeekYear`, `parseWeekId` (null on garbage), `weekStartFromWeekId` (local-midnight Monday of that id; null on garbage), and `isoWeeksInYear(year)` (52, or 53 in a leap-week year). Shared by productivity week aggregates and weekly digest filenames. |
+| `isoWeek.js` | ISO-8601 week identity — the single source of the `YYYY-Www` week id. `getWeekId(date)` keys on the ISO week-numbering **year** (the calendar year of that week's Thursday), not `date.getFullYear()`, so one ISO week is never split across two ids and two weeks never collide on one (#3465). Also `isoWeekParts`, `getIsoWeekNumber`, `getIsoWeekYear`, `parseWeekId` (null on garbage), `weekStartFromWeekId` (local-midnight Monday of that id; null on garbage), and `isoWeeksInYear(year)` (52, or 53 in a leap-week year). Shared by weekly digest filenames. |
| `snapshotChecksum.js` | The two snapshot-checksum flavours a sync category can want. `snapshotChecksum(data)` hashes `JSON.stringify` — insertion-order SENSITIVE, correct only where the getter already canonicalizes its own ordering (`dataSync.js`, `digital-twin-sync.js`). `canonicalSnapshotChecksum(data)` hashes `canonicalStringify`, so two converged machines hash identically regardless of the order they learned the data (`peerUsage.js`, whose payload is a map keyed by wire-supplied instance ids). Picking the wrong one is not a crash — it is two synced peers whose checksums never match, which the sync UI reads as "behind" forever. |
| `lwwTimestamp.js` | Last-writer-wins timestamp comparison for cross-instance sync merges. `parseTsMs(s)` (Date.parse → epoch ms or null), `compareNewerWins(candidate, incumbent)` (true iff candidate strictly newer; unparseable-loses, tie → incumbent — used to decide remote-overwrites-local), `compareEarlierWins(a, b)` (−1/0/1 earliest-wins tiebreak; unparseable-loses). Single source of the LWW polarity shared by `mergeMediaCollectionsFromSync` / `mergeAuthorsFromSync` etc. |
| `syncManifest.js` | Wire contract for the snapshot-sync MANIFEST leg — the fix for a category that is always dirty AND a map of per-instance slots (`usage`), where one instance advancing dragged every other instance's digest across the wire. `isManifestEnvelope(value)` validates a `{ data: { instances }, checksum }` response (a legacy peer that 404s the endpoint fails it, and the puller falls back to the whole snapshot); `diffManifestSlots(remoteInstances, localInstances)` returns the sorted slot ids whose REMOTE LWW stamp is strictly newer than ours — exactly the slots worth fetching. Comparison goes through `lwwTimestamp.js`, so a tie breaks to what we already hold. Consumed by `syncOrchestrator.syncDataCategoryFromPeer`; served by `dataSync.getManifest`. |
diff --git a/server/lib/agentOutcome.js b/server/lib/agentOutcome.js
index f331bffac8..7202f29487 100644
--- a/server/lib/agentOutcome.js
+++ b/server/lib/agentOutcome.js
@@ -58,7 +58,7 @@ export function isAgentHandoff(agent) {
* this way until the next scheduled tick).
*
* Consumers that only ask "was this a genuine success/failure" (reports,
- * productivity stats, task learning) should keep using `isAgentHandoff` — a
+ * the activity calendar, task learning) should keep using `isAgentHandoff` — a
* stranded retirement isn't a genuine outcome either, so folding it in there
* is correct.
*/
diff --git a/server/lib/eidoverseWorldSignals.js b/server/lib/eidoverseWorldSignals.js
index 5990e8c126..bd896be395 100644
--- a/server/lib/eidoverseWorldSignals.js
+++ b/server/lib/eidoverseWorldSignals.js
@@ -106,8 +106,8 @@ function projectedApps(apps) {
}));
}
-function projectedProductivity(todayActivity, velocity, taskState) {
- if (!todayActivity && !velocity) return null;
+function projectedProductivity(todayActivity, taskState) {
+ if (!todayActivity) return null;
const stats = todayActivity?.stats || {};
const queue = {
pendingApprovals: Array.isArray(taskState?.awaitingApproval) ? taskState.awaitingApproval.length : null,
@@ -121,13 +121,10 @@ function projectedProductivity(todayActivity, velocity, taskState) {
return [{
id: 'summary',
label: 'Productivity',
- completedToday: nonNegativeOrNull(stats.completed ?? velocity?.today),
- succeededToday: nonNegativeOrNull(stats.succeeded ?? velocity?.todaySuccesses),
- failedToday: nonNegativeOrNull(stats.failed ?? velocity?.todayFailures),
+ completedToday: nonNegativeOrNull(stats.completed),
+ succeededToday: nonNegativeOrNull(stats.succeeded),
+ failedToday: nonNegativeOrNull(stats.failed),
successRate: percentageOrNull(stats.successRate),
- velocity: finiteOrNull(velocity?.velocity),
- averagePerDay: nonNegativeOrNull(velocity?.avgPerDay),
- historicalDays: nonNegativeOrNull(velocity?.historicalDays),
queue,
running: todayActivity?.isRunning === true,
paused: todayActivity?.isPaused === true,
@@ -153,8 +150,6 @@ function projectedActivity(calendar) {
weeks: calendar.weeks.length,
activeDays: nonNegativeOrNull(summary.activeDays),
totalTasks: nonNegativeOrNull(summary.totalTasks),
- totalSuccesses: nonNegativeOrNull(summary.totalSuccesses),
- successRate: percentageOrNull(summary.successRate),
maxTasks: nonNegativeOrNull(calendar.maxTasks),
todayTasks: nonNegativeOrNull(today?.tasks),
},
@@ -162,9 +157,6 @@ function projectedActivity(calendar) {
id: opaqueId('activity-day', day.date, `day-${index}`),
label: 'Activity day',
tasks: nonNegativeOrNull(day.tasks) ?? 0,
- successes: nonNegativeOrNull(day.successes) ?? 0,
- failures: nonNegativeOrNull(day.failures) ?? 0,
- successRate: percentageOrNull(day.successRate),
isToday: day.isToday === true,
})),
];
@@ -382,7 +374,7 @@ function healthSnapshot({ apps, cosStatus, review, backupState, notifications, c
export function buildEidoverseWorldSignals({
apps, agents, taskState, cosStatus, review, featuresState, peers,
backupState, notifications, character, voiceConfig, memory, diskPercent,
- todayActivity, velocity, activityCalendar, goalsData, memoryGraph,
+ todayActivity, activityCalendar, goalsData, memoryGraph,
inboxCounts, introspection, jira, destinations,
}) {
const projectedAgents = Array.isArray(agents)
@@ -421,7 +413,7 @@ export function buildEidoverseWorldSignals({
features: projectedFeatures,
peers: projectedPeers,
health,
- productivity: projectedProductivity(todayActivity, velocity, taskState),
+ productivity: projectedProductivity(todayActivity, taskState),
activity: projectedActivity(activityCalendar),
goals: projectedGoals(goalsData),
memory: projectedMemory(memoryGraph),
diff --git a/server/lib/isoWeek.js b/server/lib/isoWeek.js
index c00b8806c6..2ede714911 100644
--- a/server/lib/isoWeek.js
+++ b/server/lib/isoWeek.js
@@ -1,13 +1,13 @@
/**
* ISO-8601 week identity (pure).
*
- * The one place PortOS turns a date into a `YYYY-Www` week id. Both the CoS
- * productivity week aggregates (`services/productivity.js`) and the weekly digest
- * (`services/weeklyDigest.js`) used to carry their own copy, and both paired
- * the ISO week NUMBER with the CALENDAR year (#3465). Those two disagree at
- * either end of the year, which split one ISO week across two ids (breaking
- * week aggregates and week-over-week lookups) and collided two different weeks onto a
- * single id (a late-December digest overwriting the early-January one).
+ * The one place PortOS turns a date into a `YYYY-Www` week id. The weekly
+ * digest (`services/weeklyDigest.js`) and the since-retired CoS productivity
+ * aggregate each used to carry their own copy, and both paired the ISO week
+ * NUMBER with the CALENDAR year (#3465). Those two disagree at either end of
+ * the year, which split one ISO week across two ids (breaking week aggregates
+ * and week-over-week lookups) and collided two different weeks onto a single
+ * id (a late-December digest overwriting the early-January one).
*
* The year here is the ISO week-numbering year — the calendar year of that
* week's Thursday — so every day of an ISO week shares one id and no id is
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 0f600a2f3b..169bf20b53 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -134,7 +134,6 @@ const RAW_NAV_COMMANDS = [
{ id: 'nav.cos.workflow', path: '/cos/workflow', label: 'Timeline', section: 'Chief of Staff', tabGroup: 'cos', tabId: 'workflow', aliases: ['workflow', 'cos-workflow', 'cos-timeline', 'schedule-timeline'], keywords: ['timeline', 'schedule', 'launch order', 'run order', 'gantt', 'upcoming runs', 'overlap', 'dependencies'] },
{ id: 'nav.cos.digest', path: '/cos/digest', label: 'Digest', section: 'Chief of Staff', tabGroup: 'cos', tabId: 'digest', aliases: ['cos-digest'] },
{ id: 'nav.cos.gsd', path: '/cos/gsd', label: 'GSD', section: 'Chief of Staff', tabGroup: 'cos', tabId: 'gsd', feature: 'gsd', aliases: ['gsd', 'cos-gsd'] },
- { id: 'nav.cos.productivity', path: '/cos/productivity', label: 'Productivity', section: 'Chief of Staff', tabGroup: 'cos', tabId: 'productivity', aliases: ['cos-productivity', 'work-patterns', 'streaks'] },
{ id: 'nav.cos.learning', path: '/cos/learning', label: 'Learning', section: 'Chief of Staff', tabGroup: 'cos', tabId: 'learning', aliases: ['cos-learning'] },
{ id: 'nav.cos.memory', path: '/cos/memory', label: 'Memory', section: 'Chief of Staff', tabGroup: 'cos', tabId: 'memory', aliases: ['cos-memory'] },
{ id: 'nav.cos.mind', path: '/cos/mind', label: 'Mind', section: 'Chief of Staff', tabGroup: 'cos', tabId: 'mind', aliases: ['cos-mind', 'persistent-mind', 'mind-chat'], keywords: ['persistent mind', 'chat', 'annotation', 'resident mind', 'conversation'] },
diff --git a/server/routes/cosInsightRoutes.js b/server/routes/cosInsightRoutes.js
index ddc623a912..b8dc66e634 100644
--- a/server/routes/cosInsightRoutes.js
+++ b/server/routes/cosInsightRoutes.js
@@ -1,11 +1,11 @@
/**
- * CoS Productivity, Insights, Goal Progress, and Decision Log Routes
+ * CoS Activity, Insights, Goal Progress, and Decision Log Routes
*/
import { Router } from 'express';
import * as cos from '../services/cos.js';
import * as taskLearning from '../services/taskLearning.js';
-import * as productivity from '../services/productivity.js';
+import { getActivityCalendar } from '../services/cosActivityCalendar.js';
import * as goalProgress from '../services/goalProgress.js';
import * as decisionLog from '../services/decisionLog.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
@@ -14,47 +14,20 @@ import { detectIdleLeftoverBranches } from '../services/userActionDetectors.js';
const router = Router();
-// GET /api/cos/productivity - Get productivity insights and work patterns
-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 });
-}));
-
-// GET /api/cos/productivity/trends - Get daily task completion trends for charting
-router.get('/productivity/trends', asyncHandler(async (req, res) => {
- const days = parseInt(req.query.days, 10) || 30;
- const trends = await productivity.getDailyTrends(days);
- res.json(trends);
-}));
-
-// GET /api/cos/productivity/calendar - Get activity calendar for GitHub-style heatmap
-router.get('/productivity/calendar', asyncHandler(async (req, res) => {
+// GET /api/cos/activity-calendar - Runs-per-day heatmap for the dashboard widget
+router.get('/activity-calendar', asyncHandler(async (req, res) => {
const weeks = parseInt(req.query.weeks, 10) || 12;
- const calendar = await productivity.getActivityCalendar(weeks);
- res.json(calendar);
+ res.json(await getActivityCalendar(weeks));
}));
// GET /api/cos/actionable-insights - Get prioritized action items requiring user attention
// Surfaces the most important things to address right now across all CoS subsystems
router.get('/actionable-insights', asyncHandler(async (req, res) => {
- const [tasksData, learningSummary, healthCheck, notificationsModule, optimalTimeInfo, pendingFeedbackCount, leftoverFindings] = await Promise.all([
+ const [tasksData, learningSummary, healthCheck, notificationsModule, pendingFeedbackCount, leftoverFindings] = await Promise.all([
cos.getAllTasks().catch(err => { console.error(`❌ Failed to load tasks: ${err.message}`); return { user: null, cos: null }; }),
taskLearning.getLearningInsights().catch(err => { console.error(`❌ Failed to load learning insights: ${err.message}`); return null; }),
cos.runHealthCheck().catch(err => { console.error(`❌ Failed to run health check: ${err.message}`); return { issues: [] }; }),
import('../services/notifications.js').catch(err => { console.error(`❌ Failed to load notifications: ${err.message}`); return null; }),
- productivity.getOptimalTimeInfo().catch(() => ({ hasData: false })),
cos.getPendingAgentFeedbackCount().catch(err => { console.error(`❌ Failed to load pending agent feedback: ${err.message}`); return 0; }),
detectIdleLeftoverBranches().catch(err => { console.error(`❌ Failed to detect leftover branches: ${err.message}`); return []; })
]);
@@ -212,20 +185,6 @@ router.get('/actionable-insights', asyncHandler(async (req, res) => {
});
}
- // 8. Peak productivity time (proactive suggestion)
- // Show when it's a peak hour AND there are pending tasks to work on
- const totalPendingTasks = pendingUserTasks.length + (tasksData.cos?.grouped?.pending?.length || 0);
- if (optimalTimeInfo?.hasData && optimalTimeInfo.isOptimal && totalPendingTasks > 0 && insights.length < 5) {
- insights.push({
- type: 'peak-time',
- priority: 'low',
- icon: 'Zap',
- title: 'Peak productivity hour',
- description: `This hour has a ${optimalTimeInfo.currentSuccessRate || optimalTimeInfo.peakSuccessRate}% success rate — good time to tackle tasks`,
- action: { label: 'Start Task', route: '/cos/tasks' }
- });
- }
-
// Sort by priority. `??`, not `||` — `critical` ranks 0, and `0 || 5` demoted
// it below every other priority, so the single most urgent insight sorted LAST
// and fell off the `slice(0, 5)` below once six insights were open.
@@ -247,12 +206,11 @@ router.get('/recent-tasks', asyncHandler(async (req, res) => {
}));
// GET /api/cos/quick-summary - Get at-a-glance dashboard summary
-// Combines today's activity, queue counts, and velocity into one efficient call.
+// Combines today's activity and queue counts into one efficient call.
router.get('/quick-summary', asyncHandler(async (req, res) => {
- const [todayActivity, tasksData, velocityData] = await Promise.all([
+ const [todayActivity, tasksData] = await Promise.all([
cos.getTodayActivity(),
- cos.getAllTasks(),
- productivity.getVelocityMetrics()
+ cos.getAllTasks()
]);
// Count pending approvals from system tasks
@@ -270,12 +228,6 @@ router.get('/quick-summary', asyncHandler(async (req, res) => {
successRate: todayActivity.stats.successRate,
timeWorked: todayActivity.time.combined
},
- velocity: {
- percentage: velocityData.velocity,
- label: velocityData.velocityLabel,
- avgPerDay: velocityData.avgPerDay,
- historicalDays: velocityData.historicalDays
- },
queue: {
pendingApprovals,
pendingUserTasks,
diff --git a/server/routes/cosInsightRoutes.test.js b/server/routes/cosInsightRoutes.test.js
index ad189c717d..c20d282e24 100644
--- a/server/routes/cosInsightRoutes.test.js
+++ b/server/routes/cosInsightRoutes.test.js
@@ -15,14 +15,8 @@ vi.mock('../services/taskLearning.js', () => ({
getLearningInsights: vi.fn()
}));
-vi.mock('../services/productivity.js', () => ({
- getProductivityInsights: vi.fn(),
- getProductivitySummary: vi.fn(),
- recalculateProductivity: vi.fn(),
- getDailyTrends: vi.fn(),
- getActivityCalendar: vi.fn(),
- getOptimalTimeInfo: vi.fn(),
- getVelocityMetrics: vi.fn()
+vi.mock('../services/cosActivityCalendar.js', () => ({
+ getActivityCalendar: vi.fn()
}));
vi.mock('../services/goalProgress.js', () => ({
@@ -45,7 +39,7 @@ vi.mock('../services/notifications.js', () => ({
import * as cos from '../services/cos.js';
import * as taskLearning from '../services/taskLearning.js';
-import * as productivity from '../services/productivity.js';
+import { getActivityCalendar } from '../services/cosActivityCalendar.js';
import * as goalProgress from '../services/goalProgress.js';
import * as decisionLog from '../services/decisionLog.js';
import * as notifications from '../services/notifications.js';
@@ -64,67 +58,23 @@ describe('CoS Insight Routes', () => {
notifications.getNotifications.mockResolvedValue([]);
});
- describe('GET /api/cos/productivity', () => {
- it('should return productivity insights', async () => {
- productivity.getProductivityInsights.mockResolvedValue({ dailyPatterns: {}, efficiency: 0.8 });
+ describe('GET /api/cos/activity-calendar', () => {
+ it('defaults to 12 weeks', async () => {
+ getActivityCalendar.mockResolvedValue({ weeks: [], maxTasks: 1, summary: {} });
- const response = await request(app).get('/api/cos/productivity');
+ const response = await request(app).get('/api/cos/activity-calendar');
expect(response.status).toBe(200);
- expect(response.body).toHaveProperty('efficiency');
+ expect(getActivityCalendar).toHaveBeenCalledWith(12);
});
- });
-
- describe('GET /api/cos/productivity/summary', () => {
- it('should return productivity summary', async () => {
- productivity.getProductivitySummary.mockResolvedValue({ totalDays: 5 });
-
- const response = await request(app).get('/api/cos/productivity/summary');
-
- expect(response.status).toBe(200);
- expect(response.body.totalDays).toBe(5);
- });
- });
-
- describe('POST /api/cos/productivity/recalculate', () => {
- it('should recalculate productivity', async () => {
- productivity.recalculateProductivity.mockResolvedValue({ recalculated: true });
-
- const response = await request(app).post('/api/cos/productivity/recalculate');
-
- expect(response.status).toBe(200);
- expect(response.body.success).toBe(true);
- });
- });
- describe('GET /api/cos/productivity/trends', () => {
- it('should return daily trends with default days', async () => {
- productivity.getDailyTrends.mockResolvedValue([{ date: '2026-04-01', completed: 3 }]);
+ it('respects a custom week count', async () => {
+ getActivityCalendar.mockResolvedValue({ weeks: [], maxTasks: 1, summary: {} });
- const response = await request(app).get('/api/cos/productivity/trends');
+ const response = await request(app).get('/api/cos/activity-calendar?weeks=4');
expect(response.status).toBe(200);
- expect(productivity.getDailyTrends).toHaveBeenCalledWith(30);
- });
-
- it('should respect custom days', async () => {
- productivity.getDailyTrends.mockResolvedValue([]);
-
- const response = await request(app).get('/api/cos/productivity/trends?days=7');
-
- expect(response.status).toBe(200);
- expect(productivity.getDailyTrends).toHaveBeenCalledWith(7);
- });
- });
-
- describe('GET /api/cos/productivity/calendar', () => {
- it('should return activity calendar with default weeks', async () => {
- productivity.getActivityCalendar.mockResolvedValue({ weeks: [] });
-
- const response = await request(app).get('/api/cos/productivity/calendar');
-
- expect(response.status).toBe(200);
- expect(productivity.getActivityCalendar).toHaveBeenCalledWith(12);
+ expect(getActivityCalendar).toHaveBeenCalledWith(4);
});
});
@@ -137,7 +87,6 @@ describe('CoS Insight Routes', () => {
taskLearning.getLearningInsights.mockResolvedValue({ skippedTypes: [] });
cos.runHealthCheck.mockResolvedValue({ issues: [] });
cos.getPendingAgentFeedbackCount.mockResolvedValue(2);
- productivity.getOptimalTimeInfo.mockResolvedValue({ hasData: false });
const response = await request(app).get('/api/cos/actionable-insights');
@@ -164,7 +113,6 @@ describe('CoS Insight Routes', () => {
taskLearning.getLearningInsights.mockResolvedValue({ skippedTypes: [] });
cos.runHealthCheck.mockResolvedValue({ issues: [] });
cos.getPendingAgentFeedbackCount.mockResolvedValue(0);
- productivity.getOptimalTimeInfo.mockResolvedValue({ hasData: false });
detectIdleLeftoverBranches.mockResolvedValueOnce([{
appId: 'app-acme', appName: 'Acme', leftoverCount: 3, states: { NEEDS_PR: 3 },
branches: ['claim/one'], lastUserReconcileAt: null, agentsIdle: true,
@@ -199,7 +147,6 @@ describe('CoS Insight Routes', () => {
taskLearning.getLearningInsights.mockResolvedValue({ skippedTypes: [] });
cos.runHealthCheck.mockResolvedValue({ issues: [] });
cos.getPendingAgentFeedbackCount.mockResolvedValue(0);
- productivity.getOptimalTimeInfo.mockResolvedValue({ hasData: false });
detectIdleLeftoverBranches.mockResolvedValueOnce([
{ appId: 'app-acme', appName: 'Acme', leftoverCount: 4, states: { NEEDS_PR: 4 }, branches: [], lastUserReconcileAt: null, agentsIdle: true },
{ appId: 'app-beta', appName: 'Beta', leftoverCount: 1, states: { WIP: 1 }, branches: [], lastUserReconcileAt: '2026-08-28T10:00:00.000Z', agentsIdle: true },
@@ -220,7 +167,6 @@ describe('CoS Insight Routes', () => {
cos.getAllTasks.mockResolvedValue({ user: null, cos: null });
taskLearning.getLearningInsights.mockResolvedValue({ skippedTypes: [] });
cos.getPendingAgentFeedbackCount.mockResolvedValue(0);
- productivity.getOptimalTimeInfo.mockResolvedValue({ hasData: false });
cos.runHealthCheck.mockResolvedValue({
issues: [
{ type: 'warning', category: 'memory', message: 'High memory usage in: example-app (900MB)' },
@@ -245,7 +191,6 @@ describe('CoS Insight Routes', () => {
cos.getAllTasks.mockResolvedValue({ user: null, cos: null });
taskLearning.getLearningInsights.mockResolvedValue({ skippedTypes: [] });
cos.getPendingAgentFeedbackCount.mockResolvedValue(0);
- productivity.getOptimalTimeInfo.mockResolvedValue({ hasData: false });
cos.runHealthCheck.mockResolvedValue({
issues: [{ type: 'warning', category: 'memory', message: 'High memory usage in: example-app (900MB)' }]
});
@@ -272,7 +217,6 @@ describe('CoS Insight Routes', () => {
});
taskLearning.getLearningInsights.mockResolvedValue({ skippedTypes: [{ type: 'flaky' }] });
cos.getPendingAgentFeedbackCount.mockResolvedValue(2);
- productivity.getOptimalTimeInfo.mockResolvedValue({ hasData: false });
notifications.getNotifications.mockResolvedValue([{ type: 'briefing_ready' }]);
cos.runHealthCheck.mockResolvedValue({
issues: [{ type: 'error', category: 'processes', message: 'example-app failed to auto-restart' }]
@@ -291,7 +235,6 @@ describe('CoS Insight Routes', () => {
cos.getAllTasks.mockRejectedValue(new Error('fail'));
taskLearning.getLearningInsights.mockRejectedValue(new Error('fail'));
cos.runHealthCheck.mockRejectedValue(new Error('fail'));
- productivity.getOptimalTimeInfo.mockRejectedValue(new Error('fail'));
const response = await request(app).get('/api/cos/actionable-insights');
@@ -334,10 +277,6 @@ describe('CoS Insight Routes', () => {
user: { grouped: { pending: [] } },
cos: { awaitingApproval: [], grouped: { pending: [] } }
});
- productivity.getVelocityMetrics.mockResolvedValue({
- velocity: 120, velocityLabel: 'Above average', avgPerDay: 3, historicalDays: 30
- });
-
const response = await request(app).get('/api/cos/quick-summary');
expect(response.status).toBe(200);
@@ -348,7 +287,7 @@ describe('CoS Insight Routes', () => {
expect(response.body).not.toHaveProperty('optimalTime');
expect(response.body.today).not.toHaveProperty('accomplishments');
expect(response.body.queue).not.toHaveProperty('estimate');
- expect(response.body.velocity.percentage).toBe(120);
+ expect(response.body).not.toHaveProperty('velocity');
});
});
diff --git a/server/services/cosActivityCalendar.js b/server/services/cosActivityCalendar.js
new file mode 100644
index 0000000000..94ab4b8b3f
--- /dev/null
+++ b/server/services/cosActivityCalendar.js
@@ -0,0 +1,147 @@
+/**
+ * CoS Activity Calendar
+ *
+ * The GitHub-style "runs per day" heatmap behind the dashboard widget and the
+ * Eidoverse activity district.
+ *
+ * Derived on every read from the two stores that agent history actually lives
+ * in — the id→date-bucket index (`data/cos/agents/index.json`, maintained by
+ * `archiveStaleAgents`) plus the completed agents still resident in
+ * `state.agents` — so it is correct the moment a run finishes. Both are
+ * process-cached (`loadAgentIndex` memoizes, `loadState` holds `stateCache`),
+ * so the widget's 30-second poll costs no disk I/O.
+ *
+ * It replaces the `data/cos/productivity.json` aggregate this used to read
+ * (#7599). That file had no automatic writer: nothing in the server called the
+ * incremental updater, so it only changed when a human opened the retired
+ * Productivity page and pressed Refresh. On this repo's own install it had gone
+ * four months without a write, which made every heatmap cell read zero.
+ *
+ * ## What a cell counts
+ *
+ * Every completed agent record, with no outcome filtering of any kind: not
+ * success vs failure, and not the `isAgentHandoff` continuation rule that the
+ * daily report and weekly digest apply.
+ *
+ * That is deliberate, and it is the only self-consistent choice available here.
+ * The index stores a date per agent id and nothing else, so an outcome rule
+ * could only ever be evaluated against the records still in `state.agents` —
+ * roughly the last 24 hours, per `completedAgentRetentionMs`. Applying it there
+ * and not to the archive would drop a provider swap from today's cell while
+ * counting it in all ~90 older ones, so the grid would disagree with itself
+ * along a moving 24-hour line. Answering properly for the archive means opening
+ * every record's `metadata.json` — hundreds of files on a 30-second poll.
+ *
+ * So this is a VOLUME signal — how much ran on each day — and it is honest
+ * about being one. Outcome is reported live and exactly by the Today and
+ * Learning tiles beside the heatmap, which read `getTodayActivity` and task
+ * learning rather than this grid.
+ */
+
+import { loadState } from './cosState.js';
+import { loadAgentIndex } from './cosAgentIndex.js';
+
+/**
+ * Day key for an instant, in UTC.
+ *
+ * UTC, not server-local, because that is what every other CoS agent-history day
+ * key already is: `archiveStaleAgents` buckets a record under
+ * `completedAt.slice(0, 10)`, and `getTodayActivity` / `generateReport` ask for
+ * a day with `toISOString().split('T')[0]`. Keying the grid locally instead
+ * would file a run in one cell and look for it in another on any install not
+ * running `TZ=UTC`.
+ */
+const dayKey = (date) => date.toISOString().slice(0, 10);
+
+const MS_PER_DAY = 86400000;
+
+/**
+ * Completed runs per day, from `sinceStr` forward, across both stores.
+ *
+ * Live state is walked FIRST so its ids can be collected into a set the index
+ * pass skips. That direction matters: a record caught mid-archive is in both
+ * stores at once (`archiveStaleAgents` indexes it before evicting it from
+ * state), and deduping the other way round would mean copying the whole index —
+ * thousands of entries on an aged install — to overwrite a few dozen keys.
+ *
+ * Days before `sinceStr` are dropped as they are read rather than counted and
+ * discarded later; the index spans an install's entire history while the grid
+ * only ever asks for the last few weeks of it.
+ *
+ * `getAgentDates()` tallies the same index, but cannot be used here: it returns
+ * `{date, count}` with the ids discarded, and the ids are exactly what the
+ * live-state dedupe needs.
+ */
+async function countRunsByDate(sinceStr) {
+ const [index, state] = await Promise.all([loadAgentIndex(), loadState()]);
+ const counts = new Map();
+ const liveIds = new Set();
+
+ const count = (date) => {
+ if (date >= sinceStr) counts.set(date, (counts.get(date) || 0) + 1);
+ };
+
+ for (const agent of Object.values(state.agents || {})) {
+ if (agent.status !== 'completed' || !agent.completedAt) continue;
+ liveIds.add(agent.id);
+ count(agent.completedAt.slice(0, 10));
+ }
+
+ for (const [agentId, date] of index) {
+ if (liveIds.has(agentId)) continue;
+ count(date);
+ }
+
+ return counts;
+}
+
+/**
+ * Activity calendar for the last N weeks, as a Sunday-aligned grid of exactly N
+ * whole weeks ending with the current one.
+ *
+ * @param {number} weeks - How many weeks of history to include (default 12)
+ */
+export async function getActivityCalendar(weeks = 12) {
+ const today = new Date();
+ const todayStr = dayKey(today);
+
+ // Sunday of the current week, then back N-1 whole weeks — so the grid is
+ // exactly `weeks` columns wide whatever weekday it is read on.
+ const start = new Date(today);
+ start.setUTCDate(today.getUTCDate() - today.getUTCDay() - (weeks - 1) * 7);
+ start.setUTCHours(0, 0, 0, 0);
+
+ const counts = await countRunsByDate(dayKey(start));
+
+ const days = [];
+ let maxTasks = 1;
+ let activeDays = 0;
+ let totalTasks = 0;
+
+ for (let i = 0; i < weeks * 7; i++) {
+ const date = dayKey(new Date(start.getTime() + i * MS_PER_DAY));
+ const isFuture = date > todayStr;
+ const tasks = isFuture ? 0 : (counts.get(date) || 0);
+
+ if (tasks > 0) {
+ activeDays++;
+ totalTasks += tasks;
+ if (tasks > maxTasks) maxTasks = tasks;
+ }
+
+ days.push({ date, dayOfWeek: i % 7, tasks, isToday: date === todayStr, isFuture });
+ }
+
+ const calendar = [];
+ for (let i = 0; i < days.length; i += 7) calendar.push(days.slice(i, i + 7));
+
+ return {
+ weeks: calendar,
+ maxTasks,
+ summary: {
+ activeDays,
+ totalTasks,
+ avgTasksPerActiveDay: activeDays > 0 ? Math.round((totalTasks / activeDays) * 10) / 10 : 0
+ }
+ };
+}
diff --git a/server/services/cosActivityCalendar.test.js b/server/services/cosActivityCalendar.test.js
new file mode 100644
index 0000000000..86ae26950a
--- /dev/null
+++ b/server/services/cosActivityCalendar.test.js
@@ -0,0 +1,142 @@
+/**
+ * The activity calendar is the one surface that turns raw agent history into
+ * the dashboard heatmap and the Eidoverse activity district, so its contract is
+ * the grid shape and the counting rules — not the arithmetic of any one helper.
+ *
+ * Both stores are stubbed at their module boundary: the archive index
+ * (`cosAgentIndex.js`) and live state (`cosState.js`). Fixture dates are UTC,
+ * matching the day key the archive buckets and the daily report already use, so
+ * the expectations hold whatever timezone the runner is in.
+ */
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+const mock = vi.hoisted(() => ({
+ index: new Map(), // agentId → YYYY-MM-DD bucket
+ agents: {}, // state.agents
+}));
+
+vi.mock('./cosAgentIndex.js', () => ({
+ loadAgentIndex: vi.fn(async () => mock.index),
+}));
+
+vi.mock('./cosState.js', () => ({
+ loadState: vi.fn(async () => ({ agents: mock.agents })),
+}));
+
+const { getActivityCalendar } = await import('./cosActivityCalendar.js');
+
+// YYYY-MM-DD for N days before today, in UTC — the day key every CoS
+// agent-history store uses.
+const daysAgo = (n) => {
+ const d = new Date();
+ d.setUTCDate(d.getUTCDate() - n);
+ return d.toISOString().slice(0, 10);
+};
+
+const completedAgent = (id, date) => ({ id, status: 'completed', completedAt: `${date}T12:00:00.000Z` });
+
+beforeEach(() => {
+ mock.index = new Map();
+ mock.agents = {};
+});
+
+describe('getActivityCalendar', () => {
+ it('returns Sunday-aligned whole weeks with today marked and later days flagged future', async () => {
+ const { weeks } = await getActivityCalendar(4);
+
+ expect(weeks).toHaveLength(4);
+ expect(weeks.every(week => week.length === 7)).toBe(true);
+ expect(weeks[0][0].dayOfWeek).toBe(0);
+ expect(weeks.flat().find(day => day.isToday).date).toBe(new Date().toISOString().slice(0, 10));
+ expect(weeks.flat().filter(day => day.isToday)).toHaveLength(1);
+
+ const todayIdx = weeks.flat().findIndex(day => day.isToday);
+ const after = weeks.flat().slice(todayIdx + 1);
+ expect(after.every(day => day.isFuture === true)).toBe(true);
+ expect(weeks.flat().slice(0, todayIdx + 1).some(day => day.isFuture)).toBe(false);
+ });
+
+ it('counts archived runs from the index and live completed runs from state', async () => {
+ const yesterday = daysAgo(1);
+ mock.index.set('agent-archived-a', yesterday);
+ mock.index.set('agent-archived-b', yesterday);
+ mock.agents = { 'agent-live': completedAgent('agent-live', daysAgo(0)) };
+
+ const { weeks, summary, maxTasks } = await getActivityCalendar(4);
+ const byDate = Object.fromEntries(weeks.flat().map(day => [day.date, day.tasks]));
+
+ expect(byDate[yesterday]).toBe(2);
+ expect(byDate[daysAgo(0)]).toBe(1);
+ expect(summary).toMatchObject({ activeDays: 2, totalTasks: 3, avgTasksPerActiveDay: 1.5 });
+ expect(maxTasks).toBe(2);
+ });
+
+ it('counts a record caught mid-archive once, not twice', async () => {
+ // archiveStaleAgents indexes the record before evicting it from state, so
+ // a read landing between those two writes sees the same run in both stores.
+ const yesterday = daysAgo(1);
+ mock.index.set('agent-both', yesterday);
+ mock.agents = { 'agent-both': completedAgent('agent-both', yesterday) };
+
+ const { summary } = await getActivityCalendar(4);
+
+ expect(summary.totalTasks).toBe(1);
+ });
+
+ it('ignores live runs that are still in flight', async () => {
+ mock.agents = {
+ 'agent-running': { id: 'agent-running', status: 'running', completedAt: null },
+ 'agent-paused': { id: 'agent-paused', status: 'paused', completedAt: null },
+ };
+
+ const { summary } = await getActivityCalendar(4);
+
+ expect(summary).toMatchObject({ activeDays: 0, totalTasks: 0, avgTasksPerActiveDay: 0 });
+ });
+
+ it('counts a live handoff, because the archive it shares a grid with cannot recognize one', async () => {
+ // The index stores only id -> date, so applying isAgentHandoff to live
+ // records alone would drop a provider swap from today's cell while counting
+ // it in every older one. Volume is counted uniformly instead.
+ const today = daysAgo(0);
+ mock.agents = {
+ 'agent-real': completedAgent('agent-real', today),
+ 'agent-swap': { ...completedAgent('agent-swap', today), result: { success: false, resumed: true } },
+ };
+
+ const { summary } = await getActivityCalendar(4);
+
+ expect(summary.totalTasks).toBe(2);
+ });
+
+ it('counts a failed run — the grid is volume, not outcome', async () => {
+ mock.agents = {
+ 'agent-failed': { ...completedAgent('agent-failed', daysAgo(0)), result: { success: false } },
+ };
+
+ const { summary } = await getActivityCalendar(4);
+
+ expect(summary.totalTasks).toBe(1);
+ });
+
+ it('drops history older than the requested window', async () => {
+ mock.index.set('agent-old', daysAgo(200));
+ mock.index.set('agent-recent', daysAgo(2));
+
+ const { summary } = await getActivityCalendar(4);
+
+ expect(summary.totalTasks).toBe(1);
+ });
+
+ it('reports an empty install as zeroes rather than omitting the grid', async () => {
+ const { weeks, maxTasks, summary } = await getActivityCalendar(2);
+
+ expect(weeks.length).toBeGreaterThan(0);
+ expect(weeks.flat().every(day => day.tasks === 0)).toBe(true);
+ // maxTasks floors at 1 so the client's `tasks / maxTasks` intensity ratio
+ // never divides by zero on a fresh install.
+ expect(maxTasks).toBe(1);
+ expect(summary).toMatchObject({ activeDays: 0, totalTasks: 0 });
+ });
+});
diff --git a/server/services/eidoverseWorldProjection.js b/server/services/eidoverseWorldProjection.js
index 163a674cf6..e6b009fcdf 100644
--- a/server/services/eidoverseWorldProjection.js
+++ b/server/services/eidoverseWorldProjection.js
@@ -39,8 +39,8 @@ const COMPONENT_RESOURCE_BY_KIND = Object.freeze({
});
export const COMPONENT_ROUTE_BY_KIND = Object.freeze({
app: '/apps', agent: '/cos/agents', task: '/cos/tasks', feature: '/settings/features',
- peer: '/instances', health: '/cos/health', productivity: '/cos/productivity',
- activity: '/cos/productivity', goal: '/goals/list', memory: '/brain/memory',
+ peer: '/instances', health: '/cos/health', productivity: '/cos/agents',
+ activity: '/cos/agents', goal: '/goals/list', memory: '/brain/memory',
storage: '/settings/database', jira: '/goals/list', operations: '/cos/health',
});
const COMPONENT_LABEL_BY_KIND = Object.freeze({
diff --git a/server/services/eidoverseWorldSources.js b/server/services/eidoverseWorldSources.js
index 9df38921f6..dd7a516129 100644
--- a/server/services/eidoverseWorldSources.js
+++ b/server/services/eidoverseWorldSources.js
@@ -19,7 +19,7 @@ import { getCharacter } from './character.js';
import { getVoiceConfig } from './voice/config.js';
import { getMemoryStats } from '../lib/memoryStats.js';
import { getGoals } from './identity.js';
-import { getActivityCalendar, getVelocityMetrics } from './productivity.js';
+import { getActivityCalendar } from './cosActivityCalendar.js';
import { getBrainGraphOverview } from './brainGraph.js';
import { getInboxLogCounts } from './brainStorage.js';
import { getDataIntrospection } from './dataIntrospection.js';
@@ -101,14 +101,13 @@ export async function collectEidoverseWorldSources({ signal } = {}) {
getMemoryStats().catch(() => null),
getDiskUsagePercent(),
getTodayActivity().catch(() => null),
- getVelocityMetrics().catch(() => null),
getActivityCalendar(12).catch(() => null),
getGoals().catch(() => null),
getBrainGraphOverview({ limit: 100 }).catch(() => null),
getInboxLogCounts().catch(() => null),
getDataIntrospection().catch(() => null),
]), signal);
- const [apps, appConfig, agents, taskState, cosStatus, review, featuresState, peers, backupState, notifications, character, voiceConfig, memory, diskPercent, todayActivity, velocity, activityCalendar, goalsData, memoryGraph, inboxCounts, introspection] = reads;
+ const [apps, appConfig, agents, taskState, cosStatus, review, featuresState, peers, backupState, notifications, character, voiceConfig, memory, diskPercent, todayActivity, activityCalendar, goalsData, memoryGraph, inboxCounts, introspection] = reads;
const travel = await import('./eidoverseTravel.js').then((service) => service.listEidoverseDestinations()).catch(() => ({ destinations: [] }));
const destinations = new Set(travel.destinations.map((entry) => entry.peerId));
@@ -117,7 +116,7 @@ export async function collectEidoverseWorldSources({ signal } = {}) {
return buildEidoverseWorldSignals({
apps, agents, taskState, cosStatus, review, featuresState, peers,
backupState, notifications, character, voiceConfig, memory, diskPercent,
- todayActivity, velocity, activityCalendar, goalsData, memoryGraph,
+ todayActivity, activityCalendar, goalsData, memoryGraph,
inboxCounts, introspection, jira, destinations,
});
}
diff --git a/server/services/eidoverseWorldSources.test.js b/server/services/eidoverseWorldSources.test.js
index fa2768026b..97c50602d7 100644
--- a/server/services/eidoverseWorldSources.test.js
+++ b/server/services/eidoverseWorldSources.test.js
@@ -36,9 +36,8 @@ vi.mock('../lib/memoryStats.js', () => ({
getMemoryStats: vi.fn(async () => sources.memory),
}));
vi.mock('./identity.js', () => ({ getGoals: vi.fn(async () => sources.goalsData) }));
-vi.mock('./productivity.js', () => ({
+vi.mock('./cosActivityCalendar.js', () => ({
getActivityCalendar: vi.fn(async () => sources.activityCalendar),
- getVelocityMetrics: vi.fn(async () => sources.velocity),
}));
vi.mock('./brainGraph.js', () => ({
getBrainGraphOverview: vi.fn(async () => sources.memoryGraph),
@@ -72,7 +71,6 @@ beforeEach(() => {
memory: { total: 100, used: 10 },
diskPercent: 10,
todayActivity: null,
- velocity: null,
activityCalendar: { weeks: [] },
goalsData: { goals: [] },
memoryGraph: { nodes: [], edges: [], hasEmbeddings: false },
@@ -161,11 +159,11 @@ describe('Eidoverse world source aggregation', () => {
it('orders recent active days first after the activity summary', async () => {
sources.activityCalendar = {
weeks: [[
- { date: '2026-01-01', tasks: 1, successes: 1 },
- { date: '2026-01-02', tasks: 0, successes: 0 },
- { date: '2026-01-03', tasks: 3, successes: 2, isToday: true },
+ { date: '2026-01-01', tasks: 1 },
+ { date: '2026-01-02', tasks: 0 },
+ { date: '2026-01-03', tasks: 3, isToday: true },
]],
- summary: { activeDays: 2, totalTasks: 4, totalSuccesses: 3 },
+ summary: { activeDays: 2, totalTasks: 4 },
maxTasks: 3,
};
@@ -181,7 +179,6 @@ describe('Eidoverse world source aggregation', () => {
isRunning: true,
isPaused: false,
};
- sources.velocity = { velocity: 1.5, avgPerDay: 2, historicalDays: 7 };
sources.taskState = {
tasks: [
{ id: 'task-one', title: 'Example private task', status: 'pending' },
diff --git a/server/services/personalStoreReadSafety.test.js b/server/services/personalStoreReadSafety.test.js
index 704c10cf9b..9b6fa1ac33 100644
--- a/server/services/personalStoreReadSafety.test.js
+++ b/server/services/personalStoreReadSafety.test.js
@@ -67,7 +67,6 @@ let { listJournals, _clearObsidianLocationsCacheForTest } = {};
let { updatePostConfig } = {};
let { createMemoryItem } = {};
let { applySessionToReviewSchedule } = {};
-let { onTaskCompleted } = {};
let { recordUserAction } = {};
let { getDigitalTwinSnapshot, applyDigitalTwinRemote } = {};
@@ -90,7 +89,6 @@ beforeAll(async () => {
({ updatePostConfig } = await import('./meatspacePost.js'));
({ createMemoryItem } = await import('./meatspacePostMemory.js'));
({ applySessionToReviewSchedule } = await import('./meatspacePostReview.js'));
- ({ onTaskCompleted } = await import('./productivity.js'));
({ recordUserAction } = await import('./userActions.js'));
({ getDigitalTwinSnapshot, applyDigitalTwinRemote } = await import('./digital-twin-sync.js'));
});
@@ -104,7 +102,6 @@ const cases = [
['POST config', () => join(PATHS.meatspace, 'post-config.json'), () => updatePostConfig({ enabled: true })],
['memory items', () => join(PATHS.meatspace, 'post-memory-items.json'), () => createMemoryItem({ title: 'Example', lines: ['Example line'] })],
['review schedule', () => join(PATHS.meatspace, 'post-review-schedule.json'), () => applySessionToReviewSchedule({ masteredSkills: [{ skillId: 'example' }] })],
- ['productivity', () => join(PATHS.cos, 'productivity.json'), () => onTaskCompleted({ completedAt: '2026-01-02T00:00:00Z', result: { success: true } })],
['user actions', () => join(PATHS.data, 'user-action-events.json'), () => recordUserAction({ type: 'cos.task.create', dedupeKey: 'example', actor: 'user' })],
['health day', () => join(PATHS.health, '2026-01-02.json'), () => mergeIntoDay('2026-01-02', 'steps', [{ date: '2026-01-02T12:00:00Z', qty: 1 }])],
['autobiography stories', () => join(PATHS.digitalTwin, 'autobiography/stories.json'), () => saveStory({ promptId: 'childhood-0', content: 'Example memory' })],
diff --git a/server/services/productivity.js b/server/services/productivity.js
deleted file mode 100644
index c7477108ba..0000000000
--- a/server/services/productivity.js
+++ /dev/null
@@ -1,613 +0,0 @@
-/**
- * Productivity Service
- *
- * Tracks agent work patterns and generates insights about optimal working times.
- */
-
-import { join } from 'path';
-import { cosEvents } from './cosEvents.js';
-import { getAgents } from './cosAgentLifecycle.js';
-import { ensureDir, getDateString, PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js';
-import { getWeekId } from '../lib/isoWeek.js';
-import { isAgentHandoff } from '../lib/agentOutcome.js';
-
-const DATA_DIR = PATHS.cos;
-const PRODUCTIVITY_FILE = join(DATA_DIR, 'productivity.json');
-
-/**
- * Default productivity data structure
- */
-const DEFAULT_PRODUCTIVITY = {
- hourlyPatterns: {
- // Aggregated by hour: { tasks, successes, failures, avgDuration }
- },
- dailyPatterns: {
- // Aggregated by day of week (0-6): { tasks, successes, failures, avgDuration }
- },
- dailyHistory: {
- // Indexed by YYYY-MM-DD: { tasks, successes, failures, successRate }
- },
- milestones: [
- // { type, value, achievedAt, description }
- ],
- lastUpdated: null
-};
-
-/**
- * Load productivity data
- */
-export async function loadProductivity() {
- await ensureDir(DATA_DIR);
- const data = await readJSONFile(PRODUCTIVITY_FILE, null, { strict: true });
- // Clone the defaults on every read: callers (onTaskCompleted) mutate the
- // nested pattern maps in place, so handing back the module-level constant
- // would leak one call's counters into the next "no file yet" read.
- const defaults = structuredClone(DEFAULT_PRODUCTIVITY);
- if (!data) return defaults;
- // Ignore the retired streak field when reading older installs. The next
- // normal write removes it from disk without needing a destructive migration.
- const currentData = { ...data };
- delete currentData.streaks;
- if (Array.isArray(currentData.milestones)) {
- currentData.milestones = currentData.milestones.filter((milestone) => milestone?.type !== 'streak');
- }
- // Merge with defaults to ensure all current fields exist.
- return {
- ...defaults,
- ...currentData,
- };
-}
-
-/**
- * Save productivity data
- */
-async function saveProductivity(data) {
- await ensureDir(DATA_DIR);
- data.lastUpdated = new Date().toISOString();
- await atomicWrite(PRODUCTIVITY_FILE, data);
- return data;
-}
-
-/**
- * Recalculate all productivity metrics from agent history
- */
-export async function recalculateProductivity() {
- console.log('📊 Productivity: Recalculating from agent history');
-
- const agents = await getAgents();
- // A relaunch retires its record with `success: false` and requeues the same
- // task, so counting it would score one failure per provider swap against the
- // hour and weekday the user happened to press the button — and then score the
- // continuation on top. The continuation is the run that did the work.
- const completedAgents = agents.filter(a => a.completedAt && a.status === 'completed' && !isAgentHandoff(a));
-
- // Sort by completion date
- completedAgents.sort((a, b) => new Date(a.completedAt) - new Date(b.completedAt));
-
- // Initialize patterns
- const hourlyPatterns = {};
- const dailyPatterns = {};
- const dailyHistory = {};
-
- // Track distinct active dates and weeks for aggregate totals.
- 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 (by day of week)
- 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;
-
- // Daily history (by date)
- if (!dailyHistory[dateStr]) {
- dailyHistory[dateStr] = { tasks: 0, successes: 0, failures: 0 };
- }
- dailyHistory[dateStr].tasks++;
- if (success) dailyHistory[dateStr].successes++;
- else dailyHistory[dateStr].failures++;
- }
-
- // Calculate success rates for daily history
- for (const date of Object.keys(dailyHistory)) {
- const h = dailyHistory[date];
- h.successRate = h.tasks > 0 ? Math.round((h.successes / h.tasks) * 100) : 0;
- }
-
- // 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;
- }
-
- const sortedDates = Array.from(activeDates).sort();
- const sortedWeeks = Array.from(activeWeeks).sort();
-
- // 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 productivity = {
- hourlyPatterns,
- dailyPatterns,
- dailyHistory,
- 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, 10), ...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, 10), dayName: dayNames[parseInt(day, 10)], ...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'
- });
- }
-
- 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 incrementally on task completion.
- * Only processes the single newly completed agent instead of rescanning all agents.
- */
-export async function onTaskCompleted(agent) {
- if (!agent?.completedAt) return;
- // Same exclusion as the full recalculation — kept in step so an incremental
- // update can never bank a run the rebuild would drop.
- if (isAgentHandoff(agent)) return;
-
- const data = await loadProductivity();
- const completedAt = new Date(agent.completedAt);
- const dateStr = getDateString(completedAt);
- const hour = completedAt.getHours();
- const dayOfWeek = completedAt.getDay();
- const success = agent.result?.success === true;
- const duration = agent.result?.duration || 0;
-
- // Update hourly patterns
- if (!data.hourlyPatterns[hour]) {
- data.hourlyPatterns[hour] = { tasks: 0, successes: 0, failures: 0, totalDuration: 0 };
- }
- data.hourlyPatterns[hour].tasks++;
- if (success) data.hourlyPatterns[hour].successes++;
- else data.hourlyPatterns[hour].failures++;
- data.hourlyPatterns[hour].totalDuration += duration;
- data.hourlyPatterns[hour].avgDuration = Math.round(data.hourlyPatterns[hour].totalDuration / data.hourlyPatterns[hour].tasks);
- data.hourlyPatterns[hour].successRate = Math.round((data.hourlyPatterns[hour].successes / data.hourlyPatterns[hour].tasks) * 100);
-
- // Update daily patterns (by day of week)
- if (!data.dailyPatterns[dayOfWeek]) {
- data.dailyPatterns[dayOfWeek] = { tasks: 0, successes: 0, failures: 0, totalDuration: 0 };
- }
- data.dailyPatterns[dayOfWeek].tasks++;
- if (success) data.dailyPatterns[dayOfWeek].successes++;
- else data.dailyPatterns[dayOfWeek].failures++;
- data.dailyPatterns[dayOfWeek].totalDuration += duration;
- data.dailyPatterns[dayOfWeek].avgDuration = Math.round(data.dailyPatterns[dayOfWeek].totalDuration / data.dailyPatterns[dayOfWeek].tasks);
- data.dailyPatterns[dayOfWeek].successRate = Math.round((data.dailyPatterns[dayOfWeek].successes / data.dailyPatterns[dayOfWeek].tasks) * 100);
-
- // Update daily history
- if (!data.dailyHistory[dateStr]) {
- data.dailyHistory[dateStr] = { tasks: 0, successes: 0, failures: 0 };
- }
- data.dailyHistory[dateStr].tasks++;
- if (success) data.dailyHistory[dateStr].successes++;
- else data.dailyHistory[dateStr].failures++;
- data.dailyHistory[dateStr].successRate = Math.round((data.dailyHistory[dateStr].successes / data.dailyHistory[dateStr].tasks) * 100);
-
- // Prune dailyHistory older than 90 days
- const cutoff = new Date();
- cutoff.setDate(cutoff.getDate() - 90);
- const cutoffStr = getDateString(cutoff);
- for (const date of Object.keys(data.dailyHistory)) {
- if (date < cutoffStr) delete data.dailyHistory[date];
- }
-
- await saveProductivity(data);
- cosEvents.emit('productivity:updated');
-}
-
-/**
- * Get summary for the dashboard
- */
-export async function getProductivitySummary() {
- const data = await loadProductivity();
-
- return {
- totalDays: data.totals?.activeDays || 0,
- recentMilestone: data.milestones?.[data.milestones.length - 1] || null
- };
-}
-
-/**
- * Get velocity metrics - how today compares to historical average
- * @returns {Object} Velocity data including today's count, average, and relative performance
- */
-export async function getVelocityMetrics() {
- const data = await loadProductivity();
- const dailyHistory = data.dailyHistory || {};
- const today = getDateString();
-
- // Get today's stats
- const todayStats = dailyHistory[today] || { tasks: 0, successes: 0, failures: 0 };
-
- // Calculate historical daily average (excluding today)
- const historicalDays = Object.entries(dailyHistory)
- .filter(([date]) => date !== today)
- .map(([, stats]) => stats);
-
- // Only count days with at least 1 task for average (active days)
- const activeDays = historicalDays.filter(d => d.tasks > 0);
- const avgTasksPerDay = activeDays.length > 0
- ? activeDays.reduce((sum, d) => sum + d.tasks, 0) / activeDays.length
- : 0;
-
- // Calculate velocity: how today compares to average
- // null if no history, percentage otherwise
- let velocity = null;
- let velocityLabel = null;
-
- if (avgTasksPerDay > 0 && todayStats.tasks > 0) {
- velocity = Math.round((todayStats.tasks / avgTasksPerDay) * 100);
- if (velocity >= 150) velocityLabel = 'exceptional';
- else if (velocity >= 120) velocityLabel = 'above-average';
- else if (velocity >= 80) velocityLabel = 'on-track';
- else if (velocity >= 50) velocityLabel = 'slow';
- else velocityLabel = 'light';
- } else if (todayStats.tasks > 0 && avgTasksPerDay === 0) {
- // First active day ever
- velocity = 100;
- velocityLabel = 'first-day';
- }
-
- return {
- today: todayStats.tasks,
- todaySuccesses: todayStats.successes,
- todayFailures: todayStats.failures,
- avgPerDay: Math.round(avgTasksPerDay * 10) / 10,
- historicalDays: activeDays.length,
- velocity,
- velocityLabel
- };
-}
-
-/**
- * Get daily task trends for visualization
- * Returns last N days of task completion data with trend analysis
- */
-export async function getDailyTrends(days = 30) {
- const data = await loadProductivity();
- const dailyHistory = data.dailyHistory || {};
-
- // Generate date range for last N days
- const today = new Date();
- const dateRange = [];
- for (let i = days - 1; i >= 0; i--) {
- const d = new Date(today);
- d.setDate(d.getDate() - i);
- dateRange.push(getDateString(d));
- }
-
- // Build trend data for each day
- const trendData = dateRange.map(date => {
- const dayData = dailyHistory[date] || { tasks: 0, successes: 0, failures: 0, successRate: 0 };
- return {
- date,
- dateShort: date.slice(5), // MM-DD
- ...dayData
- };
- });
-
- // Calculate rolling averages and trends
- const windowSize = 7;
- const withAverages = trendData.map((day, idx) => {
- const window = trendData.slice(Math.max(0, idx - windowSize + 1), idx + 1);
- const avgTasks = window.reduce((sum, d) => sum + d.tasks, 0) / window.length;
- const avgSuccessRate = window.reduce((sum, d) => sum + d.successRate, 0) / window.length;
- return {
- ...day,
- rollingAvgTasks: Math.round(avgTasks * 10) / 10,
- rollingAvgSuccessRate: Math.round(avgSuccessRate)
- };
- });
-
- // Calculate overall trend direction
- const recentDays = withAverages.slice(-7);
- const olderDays = withAverages.slice(-14, -7);
-
- const recentTotal = recentDays.reduce((sum, d) => sum + d.tasks, 0);
- const olderTotal = olderDays.reduce((sum, d) => sum + d.tasks, 0);
- const recentAvgRate = recentDays.reduce((sum, d) => sum + d.successRate, 0) / (recentDays.length || 1);
- const olderAvgRate = olderDays.reduce((sum, d) => sum + d.successRate, 0) / (olderDays.length || 1);
-
- let volumeTrend = 'stable';
- if (recentTotal > olderTotal * 1.2) volumeTrend = 'increasing';
- else if (recentTotal < olderTotal * 0.8) volumeTrend = 'decreasing';
-
- let successTrend = 'stable';
- if (recentAvgRate > olderAvgRate + 10) successTrend = 'improving';
- else if (recentAvgRate < olderAvgRate - 10) successTrend = 'declining';
-
- // Summary stats
- const activeDaysInRange = trendData.filter(d => d.tasks > 0).length;
- const totalTasksInRange = trendData.reduce((sum, d) => sum + d.tasks, 0);
- const avgTasksPerActiveDay = activeDaysInRange > 0
- ? Math.round(totalTasksInRange / activeDaysInRange * 10) / 10
- : 0;
-
- return {
- data: withAverages,
- summary: {
- days,
- activeDays: activeDaysInRange,
- totalTasks: totalTasksInRange,
- avgTasksPerActiveDay,
- avgSuccessRate: Math.round(
- trendData.filter(d => d.tasks > 0).reduce((sum, d) => sum + d.successRate, 0) /
- (activeDaysInRange || 1)
- ),
- volumeTrend,
- successTrend
- }
- };
-}
-
-/**
- * Get activity calendar data for GitHub-style heatmap
- * Returns last N weeks of daily activity in a format optimized for calendar display
- * @param {number} weeks - Number of weeks to include (default: 12)
- * @returns {Object} Calendar data with days organized by week
- */
-export async function getActivityCalendar(weeks = 12) {
- const data = await loadProductivity();
- const dailyHistory = data.dailyHistory || {};
-
- // Calculate date range: from start of week N weeks ago to today
- const today = new Date();
- const todayStr = getDateString(today);
-
- // Find the start of the range (weeks ago, aligned to Sunday)
- const startDate = new Date(today);
- startDate.setDate(startDate.getDate() - (weeks * 7) + 1);
- // Align to Sunday
- const startDayOfWeek = startDate.getDay();
- startDate.setDate(startDate.getDate() - startDayOfWeek);
-
- // Build calendar grid: array of weeks, each containing 7 days
- const calendar = [];
- let currentDate = new Date(startDate);
- let currentWeek = [];
- let maxTasks = 1;
-
- // Build calendar up through end of today's week (Saturday) for a complete grid
- const endOfWeek = new Date(today);
- endOfWeek.setDate(endOfWeek.getDate() + (6 - endOfWeek.getDay()));
-
- while (currentDate <= endOfWeek) {
- const dateStr = getDateString(currentDate);
- const isFuture = currentDate > today;
- const dayData = isFuture ? { tasks: 0, successes: 0, failures: 0, successRate: 0 } :
- (dailyHistory[dateStr] || { tasks: 0, successes: 0, failures: 0, successRate: 0 });
-
- if (dayData.tasks > maxTasks) {
- maxTasks = dayData.tasks;
- }
-
- currentWeek.push({
- date: dateStr,
- dayOfWeek: currentDate.getDay(),
- tasks: dayData.tasks,
- successes: dayData.successes,
- failures: dayData.failures,
- successRate: dayData.successRate,
- isToday: dateStr === todayStr,
- isFuture
- });
-
- // Start new week on Sunday
- if (currentDate.getDay() === 6) {
- calendar.push(currentWeek);
- currentWeek = [];
- }
-
- currentDate.setDate(currentDate.getDate() + 1);
- }
-
- // Add remaining days if any
- if (currentWeek.length > 0) {
- calendar.push(currentWeek);
- }
-
- // Calculate summary stats
- const allDays = calendar.flat();
- const activeDays = allDays.filter(d => d.tasks > 0);
- const totalTasks = activeDays.reduce((sum, d) => sum + d.tasks, 0);
- const totalSuccesses = activeDays.reduce((sum, d) => sum + d.successes, 0);
-
- return {
- weeks: calendar,
- maxTasks,
- summary: {
- totalDays: allDays.length,
- activeDays: activeDays.length,
- totalTasks,
- totalSuccesses,
- successRate: totalTasks > 0 ? Math.round((totalSuccesses / totalTasks) * 100) : 0,
- avgTasksPerActiveDay: activeDays.length > 0
- ? Math.round((totalTasks / activeDays.length) * 10) / 10
- : 0
- }
- };
-}
-
-/**
- * Get optimal time indicator for current hour
- * Compares current hour's success rate to find peak windows
- * @returns {Object} Optimal time data
- */
-export async function getOptimalTimeInfo() {
- const data = await loadProductivity();
- const hourlyPatterns = data.hourlyPatterns || {};
- const currentHour = new Date().getHours();
-
- // Need minimum data to make meaningful recommendations
- const minTasksForReliable = 3;
-
- // Get hours with enough data, sorted by success rate
- const rankedHours = Object.entries(hourlyPatterns)
- .filter(([, p]) => p.tasks >= minTasksForReliable)
- .map(([hour, p]) => ({
- hour: parseInt(hour, 10),
- tasks: p.tasks,
- successRate: p.successRate
- }))
- .sort((a, b) => b.successRate - a.successRate);
-
- // Not enough data
- if (rankedHours.length < 3) {
- return { hasData: false };
- }
-
- // Find current hour's data
- const currentHourData = hourlyPatterns[currentHour];
- const currentSuccessRate = currentHourData?.successRate ?? null;
- const currentTasks = currentHourData?.tasks ?? 0;
-
- // Calculate average success rate
- const avgSuccessRate = rankedHours.reduce((sum, h) => sum + h.successRate, 0) / rankedHours.length;
-
- // Determine if current hour is optimal (top 25%), good (above avg), or suboptimal
- const topThreshold = Math.ceil(rankedHours.length * 0.25);
- const topHours = rankedHours.slice(0, topThreshold).map(h => h.hour);
- const isOptimal = topHours.includes(currentHour);
- const isAboveAverage = currentSuccessRate !== null && currentSuccessRate >= avgSuccessRate;
-
- // Find next optimal hour if current isn't optimal
- let nextOptimalHour = null;
- if (!isOptimal) {
- // Find nearest future top hour
- for (let offset = 1; offset < 24; offset++) {
- const checkHour = (currentHour + offset) % 24;
- if (topHours.includes(checkHour)) {
- nextOptimalHour = checkHour;
- break;
- }
- }
- }
-
- // Format hour for display
- const formatHour = (h) => {
- if (h === 0) return '12AM';
- if (h === 12) return '12PM';
- return h < 12 ? `${h}AM` : `${h - 12}PM`;
- };
-
- return {
- hasData: true,
- currentHour,
- currentSuccessRate,
- currentTasks,
- isOptimal,
- isAboveAverage,
- topHours,
- nextOptimalHour,
- nextOptimalFormatted: nextOptimalHour !== null ? formatHour(nextOptimalHour) : null,
- avgSuccessRate: Math.round(avgSuccessRate),
- peakSuccessRate: rankedHours[0]?.successRate ?? 0
- };
-}
diff --git a/server/services/productivity.test.js b/server/services/productivity.test.js
deleted file mode 100644
index f1f34a50d8..0000000000
--- a/server/services/productivity.test.js
+++ /dev/null
@@ -1,553 +0,0 @@
-/**
- * Direct tests for the productivity service's computation paths (issue #3448).
- *
- * Before this suite the module existed only as a `vi.mock()` target in
- * `routes/cosInsightRoutes.test.js` — referenced by a test, executed by none.
- * Here the real module runs: only the file-I/O boundary is redirected
- * (`PATHS.cos` → a temp dir) and the agent history source (`cosAgentLifecycle.js` / `cosAgentIndex.js`) is
- * stubbed, so activity aggregation and insight derivation are exercised for real.
- *
- * Dates are built from LOCAL components (`new Date(y, m, d, h)`) because the
- * service reads local getters (`getDateString`, `getHours`, `getDay`) — that
- * keeps every expected value stable regardless of the runner's timezone.
- */
-
-import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';
-import { EventEmitter } from 'events';
-import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync } from 'fs';
-import { tmpdir } from 'os';
-import { join } from 'path';
-import { makePathsProxy } from '../lib/mockPathsDataRoot.js';
-
-const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'productivity-test-'));
-const COS_DIR = join(TEST_DATA_ROOT, 'cos');
-const PRODUCTIVITY_FILE = join(COS_DIR, 'productivity.json');
-
-// productivity.js anchors its store at PATHS.cos — re-rooted into the temp tree
-// along with every other data/-rooted PATHS member by makePathsProxy.
-vi.mock('../lib/fileUtils.js', async (importOriginal) =>
- makePathsProxy(await importOriginal(), { dataRoot: TEST_DATA_ROOT }));
-
-const mock = vi.hoisted(() => ({ agents: [] }));
-
-vi.mock('./cosAgentLifecycle.js', () => ({
- getAgents: vi.fn(async () => mock.agents),
-}));
-
-vi.mock('./cosEvents.js', () => ({
- cosEvents: new EventEmitter(),
- emitLog: vi.fn(),
-}));
-
-const productivity = await import('./productivity.js');
-const { cosEvents } = await import('./cosEvents.js');
-
-afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
-
-// Wednesday 2026-03-18 12:00 local. Week of Mon 2026-03-16 (ISO 2026-W12);
-// the containing Sunday-start week begins 2026-03-15.
-const NOW = new Date(2026, 2, 18, 12, 0, 0);
-
-/** Completed-agent fixture with a local-time completion stamp. */
-const agentOn = (id, { month = 3, day, hour = 10, minute = 0, success = true, duration = 60000, status = 'completed', completedAt } = {}) => ({
- id,
- taskId: `task-${id}`,
- status,
- completedAt: completedAt === undefined
- ? new Date(2026, month - 1, day, hour, minute, 0).toISOString()
- : completedAt,
- result: { success, duration },
-});
-
-// What Relaunch leaves behind: `success: false` with `resumed: true`, requeued on
-// a new provider. It reached no verdict, so it must not score a failure against
-// the hour and weekday the user happened to press the button.
-const handoffOn = (id, opts) => {
- const base = agentOn(id, { ...opts, success: false });
- return { ...base, result: { ...base.result, resumed: true, resumedTaskId: `task-${id}`, error: 'Relaunched by user on codex' } };
-};
-
-const seed = (data) => {
- mkdirSync(COS_DIR, { recursive: true });
- writeFileSync(PRODUCTIVITY_FILE, JSON.stringify(data));
-};
-
-const readStore = () => JSON.parse(readFileSync(PRODUCTIVITY_FILE, 'utf-8'));
-
-beforeEach(() => {
- vi.useFakeTimers({ toFake: ['Date'], now: NOW });
- mock.agents = [];
- rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
- mkdirSync(COS_DIR, { recursive: true });
-});
-
-afterEach(() => {
- vi.useRealTimers();
- vi.clearAllMocks();
- // The mocked bus is shared across cases — drop listeners here so a failing
- // assertion can't strand one and have a later case observe it.
- cosEvents.removeAllListeners();
-});
-
-describe('recalculateProductivity — activity totals', () => {
- it('returns empty totals for an empty history', async () => {
- const result = await productivity.recalculateProductivity();
- expect(result).not.toHaveProperty('streaks');
- expect(result.totals).toEqual({
- totalTasks: 0,
- successfulTasks: 0,
- successRate: 0,
- activeDays: 0,
- activeWeeks: 0,
- });
- });
-
- it('counts distinct active days and weeks without deriving streaks', async () => {
- mock.agents = [
- agentOn('a', { day: 16 }),
- agentOn('b', { day: 17 }),
- agentOn('c', { day: 18 }),
- ];
-
- const result = await productivity.recalculateProductivity();
-
- expect(result).not.toHaveProperty('streaks');
- expect(result.totals).toMatchObject({ totalTasks: 3, activeDays: 3, activeWeeks: 1 });
- });
-
- it('ignores a relaunched run, which reached no verdict', async () => {
- mock.agents = [
- agentOn('good', { day: 18, hour: 9 }),
- handoffOn('swapped', { day: 18, hour: 9 }),
- ];
-
- const result = await productivity.recalculateProductivity();
-
- expect(result.totals).toMatchObject({ totalTasks: 1, successfulTasks: 1, successRate: 100 });
- expect(result.hourlyPatterns[9]).toMatchObject({ tasks: 1, successes: 1, failures: 0 });
- });
-
- it('ignores agents that are not completed or carry no completion stamp', async () => {
- mock.agents = [
- agentOn('good', { day: 18 }),
- { ...agentOn('running', { day: 18 }), status: 'running' },
- { ...agentOn('unstamped', { day: 18 }), completedAt: null },
- ];
-
- const result = await productivity.recalculateProductivity();
-
- expect(result.totals.totalTasks).toBe(1);
- expect(result.dailyHistory['2026-03-18'].tasks).toBe(1);
- });
-});
-describe('recalculateProductivity — aggregates and milestones', () => {
- it('computes exact hourly, day-of-week and per-date aggregates', async () => {
- mock.agents = [
- agentOn('a1', { day: 18, hour: 9, success: true, duration: 1000 }),
- agentOn('a2', { day: 18, hour: 9, success: true, duration: 2000 }),
- agentOn('a3', { day: 18, hour: 9, success: false, duration: 3000 }),
- ];
-
- const result = await productivity.recalculateProductivity();
-
- expect(result.hourlyPatterns[9]).toEqual({
- tasks: 3,
- successes: 2,
- failures: 1,
- totalDuration: 6000,
- avgDuration: 2000,
- successRate: 67,
- });
- // 2026-03-18 is a Wednesday → day-of-week index 3.
- expect(result.dailyPatterns[3]).toMatchObject({ tasks: 3, successes: 2, failures: 1, avgDuration: 2000 });
- expect(result.dailyHistory['2026-03-18']).toEqual({
- tasks: 3,
- successes: 2,
- failures: 1,
- successRate: 67,
- });
- expect(result.totals).toMatchObject({ totalTasks: 3, successfulTasks: 2, successRate: 67 });
- });
-
- it('awards task-count milestones without streak milestones', async () => {
- mock.agents = [
- ...Array.from({ length: 4 }, (_, i) => agentOn(`d16-${i}`, { day: 16 })),
- ...Array.from({ length: 3 }, (_, i) => agentOn(`d17-${i}`, { day: 17 })),
- ...Array.from({ length: 3 }, (_, i) => agentOn(`d18-${i}`, { day: 18 })),
- ];
-
- const { milestones } = await productivity.recalculateProductivity();
-
- expect(milestones).toContainEqual({
- type: 'tasks',
- value: 10,
- achievedAt: expect.any(String),
- description: 'Completed 10 tasks',
- });
- expect(milestones.some(m => m.type === 'streak')).toBe(false);
- // The 25-task milestone is not reached yet.
- expect(milestones.filter(m => m.value === 25)).toEqual([]);
- });
-
- it('persists the recalculated snapshot with a lastUpdated stamp', async () => {
- mock.agents = [agentOn('a1', { day: 18 })];
-
- await productivity.recalculateProductivity();
-
- const stored = readStore();
- expect(stored).not.toHaveProperty('streaks');
- expect(stored.lastUpdated).toBe(NOW.toISOString());
- });
-});
-
-describe('onTaskCompleted — incremental productivity updates', () => {
- it('records the completed task, drops a retired streak field, and emits the update event', async () => {
- seed({
- streaks: { currentDaily: 9, longestDaily: 12 },
- hourlyPatterns: {}, dailyPatterns: {}, dailyHistory: {}, milestones: [],
- });
- const emitted = [];
- const listener = () => emitted.push('productivity:updated');
- cosEvents.on('productivity:updated', listener);
-
- await productivity.onTaskCompleted(agentOn('a1', { day: 18, hour: 9, duration: 4000 }));
-
- const stored = readStore();
- expect(stored).not.toHaveProperty('streaks');
- expect(stored.dailyHistory['2026-03-18']).toMatchObject({ tasks: 1, successes: 1, failures: 0 });
- expect(stored.hourlyPatterns[9]).toMatchObject({ tasks: 1, successes: 1, avgDuration: 4000 });
- expect(emitted).toEqual(['productivity:updated']);
- cosEvents.off('productivity:updated', listener);
- });
-
- it('banks nothing for a relaunched run, keeping the incremental path in step with the rebuild', async () => {
- // The two paths must agree: if the rebuild drops handoffs but the
- // incremental update banks them, the store drifts until the next recalc
- // silently "loses" tasks the user watched it count.
- seed({ hourlyPatterns: {}, dailyPatterns: {}, dailyHistory: {}, milestones: [] });
-
- await productivity.onTaskCompleted(handoffOn('swapped', { day: 18, hour: 9 }));
-
- const stored = readStore();
- expect(stored.dailyHistory['2026-03-18']).toBeUndefined();
- expect(stored.hourlyPatterns[9]).toBeUndefined();
- });
-
- it('prunes daily history older than 90 days', async () => {
- seed({
- hourlyPatterns: {}, dailyPatterns: {},
- dailyHistory: {
- '2025-01-01': { tasks: 1, successes: 1, failures: 0, successRate: 100 },
- '2026-03-18': { tasks: 1, successes: 1, failures: 0, successRate: 100 },
- },
- milestones: [],
- });
-
- await productivity.onTaskCompleted(agentOn('a1', { day: 18 }));
-
- const stored = readStore();
- expect(stored.dailyHistory['2025-01-01']).toBeUndefined();
- expect(stored.dailyHistory['2026-03-18'].tasks).toBe(2);
- });
-
- it('is a no-op for an agent with no completion stamp', async () => {
- await productivity.onTaskCompleted({ id: 'a1', result: { success: true } });
- expect(existsSync(PRODUCTIVITY_FILE)).toBe(false);
- });
-
- it('does not leak one incremental update into the next empty-store read', async () => {
- await productivity.onTaskCompleted(agentOn('a1', { day: 18 }));
- rmSync(PRODUCTIVITY_FILE);
-
- const fresh = await productivity.loadProductivity();
-
- expect(fresh.dailyHistory).toEqual({});
- expect(fresh.hourlyPatterns).toEqual({});
- });
-});
-describe('getProductivityInsights', () => {
- const insightsFixture = {
- hourlyPatterns: {
- 9: { tasks: 10, successes: 8, failures: 2, totalDuration: 10000, avgDuration: 1000, successRate: 80 },
- 13: { tasks: 6, successes: 3, failures: 3, totalDuration: 6000, avgDuration: 1000, successRate: 50 },
- // Below the 5-task reliability floor — must be filtered out entirely.
- 2: { tasks: 4, successes: 4, failures: 0, totalDuration: 4000, avgDuration: 1000, successRate: 100 },
- },
- dailyPatterns: {
- 3: { tasks: 8, successes: 7, failures: 1, totalDuration: 8000, avgDuration: 1000, successRate: 88 },
- 5: { tasks: 4, successes: 1, failures: 3, totalDuration: 4000, avgDuration: 1000, successRate: 25 },
- // Below the 3-task floor for days.
- 0: { tasks: 2, successes: 2, failures: 0, totalDuration: 2000, avgDuration: 1000, successRate: 100 },
- },
- dailyHistory: {},
- milestones: [],
- };
-
- it('derives peak-hour and best-day insights with concrete copy', async () => {
- seed(insightsFixture);
-
- const result = await productivity.getProductivityInsights();
-
- expect(result.bestHour).toMatchObject({ hour: 9, successRate: 80 });
- expect(result.worstHour).toMatchObject({ hour: 13, successRate: 50 });
- expect(result.bestDay).toMatchObject({ day: 3, dayName: 'Wednesday', successRate: 88 });
- expect(result.worstDay).toMatchObject({ day: 5, dayName: 'Friday', successRate: 25 });
-
- expect(result.insights).toEqual([
- {
- type: 'optimization',
- title: 'Peak Performance Hour',
- message: 'Tasks completed around 9AM have a 80% success rate',
- icon: 'clock',
- },
- {
- type: 'info',
- title: 'Most Productive Day',
- message: 'Wednesdays show 88% success rate with 8 tasks completed',
- icon: 'calendar',
- },
- ]);
- });
-
- it('labels midnight and afternoon peak hours in 12-hour form', async () => {
- seed({
- ...insightsFixture,
- hourlyPatterns: { 0: { tasks: 5, successes: 5, failures: 0, avgDuration: 100, successRate: 100 } },
- });
- expect((await productivity.getProductivityInsights()).insights[0].message)
- .toBe('Tasks completed around 12AM have a 100% success rate');
-
- seed({
- ...insightsFixture,
- hourlyPatterns: { 15: { tasks: 5, successes: 3, failures: 2, avgDuration: 100, successRate: 60 } },
- });
- expect((await productivity.getProductivityInsights()).insights[0].message)
- .toBe('Tasks completed around 3PM have a 60% success rate');
- });
-
- it('returns no insights and null extremes for a store with no history', async () => {
- const result = await productivity.getProductivityInsights();
-
- expect(result.insights).toEqual([]);
- expect(result.bestHour).toBeNull();
- expect(result.worstHour).toBeNull();
- expect(result.bestDay).toBeNull();
- expect(result.worstDay).toBeNull();
- });
-});
-
-describe('getProductivitySummary', () => {
- it('projects the dashboard fields from the stored snapshot', async () => {
- seed({
- streaks: { currentDaily: 3, longestDaily: 9 },
- hourlyPatterns: {}, dailyPatterns: {}, dailyHistory: {},
- totals: { totalTasks: 20, successfulTasks: 18, successRate: 90, activeDays: 11, activeWeeks: 3 },
- milestones: [
- { type: 'streak', value: 30, description: '30-day work streak' },
- { type: 'tasks', value: 10, description: 'Completed 10 tasks' },
- { type: 'tasks', value: 25, description: 'Completed 25 tasks' },
- ],
- });
-
- expect(await productivity.getProductivitySummary()).toEqual({
- totalDays: 11,
- recentMilestone: { type: 'tasks', value: 25, description: 'Completed 25 tasks' },
- });
- });
-
- it('falls back to zeros and nulls for an empty store', async () => {
- expect(await productivity.getProductivitySummary()).toEqual({
- totalDays: 0,
- recentMilestone: null,
- });
- });
-});
-
-describe('getVelocityMetrics', () => {
- it('scores today against the historical active-day average', async () => {
- seed({
- streaks: {}, hourlyPatterns: {}, dailyPatterns: {}, milestones: [],
- dailyHistory: {
- '2026-03-18': { tasks: 6, successes: 5, failures: 1, successRate: 83 },
- '2026-03-17': { tasks: 4, successes: 4, failures: 0, successRate: 100 },
- '2026-03-16': { tasks: 2, successes: 1, failures: 1, successRate: 50 },
- // Zero-task days are excluded from the average.
- '2026-03-15': { tasks: 0, successes: 0, failures: 0, successRate: 0 },
- },
- });
-
- expect(await productivity.getVelocityMetrics()).toEqual({
- today: 6,
- todaySuccesses: 5,
- todayFailures: 1,
- avgPerDay: 3,
- historicalDays: 2,
- velocity: 200,
- velocityLabel: 'exceptional',
- });
- });
-
- it('labels the first ever active day', async () => {
- seed({
- streaks: {}, hourlyPatterns: {}, dailyPatterns: {}, milestones: [],
- dailyHistory: { '2026-03-18': { tasks: 2, successes: 2, failures: 0, successRate: 100 } },
- });
-
- expect(await productivity.getVelocityMetrics()).toMatchObject({ velocity: 100, velocityLabel: 'first-day' });
- });
-
- it('leaves velocity null when nothing has been completed today', async () => {
- seed({
- streaks: {}, hourlyPatterns: {}, dailyPatterns: {}, milestones: [],
- dailyHistory: { '2026-03-17': { tasks: 4, successes: 4, failures: 0, successRate: 100 } },
- });
-
- expect(await productivity.getVelocityMetrics()).toMatchObject({
- today: 0,
- avgPerDay: 4,
- historicalDays: 1,
- velocity: null,
- velocityLabel: null,
- });
- });
-});
-
-describe('getOptimalTimeInfo', () => {
- it('needs at least three reliable hours before making a recommendation', async () => {
- seed({
- streaks: {}, dailyPatterns: {}, dailyHistory: {}, milestones: [],
- hourlyPatterns: {
- 9: { tasks: 5, successes: 5, failures: 0, successRate: 100 },
- 10: { tasks: 4, successes: 2, failures: 2, successRate: 50 },
- 11: { tasks: 2, successes: 2, failures: 0, successRate: 100 },
- },
- });
-
- expect(await productivity.getOptimalTimeInfo()).toEqual({ hasData: false });
- });
-
- it('ranks the top quartile and points at the next optimal hour', async () => {
- seed({
- streaks: {}, dailyPatterns: {}, dailyHistory: {}, milestones: [],
- hourlyPatterns: {
- 9: { tasks: 6, successes: 6, failures: 0, successRate: 100 },
- 10: { tasks: 5, successes: 4, failures: 1, successRate: 80 },
- 14: { tasks: 5, successes: 3, failures: 2, successRate: 60 },
- 20: { tasks: 5, successes: 1, failures: 4, successRate: 20 },
- },
- });
-
- // Fake clock sits at 12:00, an hour with no recorded history.
- expect(await productivity.getOptimalTimeInfo()).toEqual({
- hasData: true,
- currentHour: 12,
- currentSuccessRate: null,
- currentTasks: 0,
- isOptimal: false,
- isAboveAverage: false,
- topHours: [9],
- nextOptimalHour: 9,
- nextOptimalFormatted: '9AM',
- avgSuccessRate: 65,
- peakSuccessRate: 100,
- });
- });
-
- it('marks the current hour optimal when it tops the ranking', async () => {
- seed({
- streaks: {}, dailyPatterns: {}, dailyHistory: {}, milestones: [],
- hourlyPatterns: {
- 12: { tasks: 8, successes: 8, failures: 0, successRate: 100 },
- 10: { tasks: 5, successes: 4, failures: 1, successRate: 80 },
- 14: { tasks: 5, successes: 3, failures: 2, successRate: 60 },
- },
- });
-
- expect(await productivity.getOptimalTimeInfo()).toMatchObject({
- isOptimal: true,
- isAboveAverage: true,
- currentSuccessRate: 100,
- currentTasks: 8,
- nextOptimalHour: null,
- nextOptimalFormatted: null,
- avgSuccessRate: 80,
- });
- });
-});
-
-describe('getDailyTrends', () => {
- it('fills missing days with zeros and reports rolling averages over the window', async () => {
- seed({
- streaks: {}, hourlyPatterns: {}, dailyPatterns: {}, milestones: [],
- dailyHistory: {
- '2026-03-18': { tasks: 4, successes: 4, failures: 0, successRate: 100 },
- '2026-03-16': { tasks: 2, successes: 1, failures: 1, successRate: 50 },
- },
- });
-
- const { data, summary } = await productivity.getDailyTrends(7);
-
- expect(data).toHaveLength(7);
- expect(data[0].date).toBe('2026-03-12');
- expect(data[6]).toMatchObject({ date: '2026-03-18', dateShort: '03-18', tasks: 4, rollingAvgTasks: 0.9 });
- expect(data[3]).toMatchObject({ date: '2026-03-15', tasks: 0, successRate: 0 });
- expect(summary).toMatchObject({
- days: 7,
- activeDays: 2,
- totalTasks: 6,
- avgTasksPerActiveDay: 3,
- avgSuccessRate: 75,
- });
- });
-
- it('calls out a falling volume trend against the prior week', async () => {
- const dailyHistory = {};
- // Older week (2026-03-05 … 2026-03-11): 5 tasks a day. Recent week: 1 a day.
- for (let day = 5; day <= 11; day++) {
- dailyHistory[`2026-03-${String(day).padStart(2, '0')}`] = { tasks: 5, successes: 5, failures: 0, successRate: 100 };
- }
- for (let day = 12; day <= 18; day++) {
- dailyHistory[`2026-03-${String(day).padStart(2, '0')}`] = { tasks: 1, successes: 0, failures: 1, successRate: 0 };
- }
- seed({ hourlyPatterns: {}, dailyPatterns: {}, milestones: [], dailyHistory });
-
- const { summary } = await productivity.getDailyTrends(30);
-
- expect(summary.volumeTrend).toBe('decreasing');
- expect(summary.successTrend).toBe('declining');
- });
-});
-
-describe('getActivityCalendar', () => {
- it('builds Sunday-aligned weeks through the end of the current week', async () => {
- seed({
- hourlyPatterns: {}, dailyPatterns: {}, milestones: [],
- dailyHistory: {
- '2026-03-18': { tasks: 7, successes: 6, failures: 1, successRate: 86 },
- '2026-03-10': { tasks: 3, successes: 3, failures: 0, successRate: 100 },
- },
- });
-
- const calendar = await productivity.getActivityCalendar(2);
-
- // 2026-03-01 (Sunday) through 2026-03-21 (Saturday) → three full weeks.
- expect(calendar.weeks).toHaveLength(3);
- expect(calendar.weeks.every(week => week.length === 7)).toBe(true);
- expect(calendar.weeks[0][0].date).toBe('2026-03-01');
- expect(calendar.weeks[2][6]).toMatchObject({ date: '2026-03-21', isFuture: true, tasks: 0 });
-
- const today = calendar.weeks.flat().find(d => d.isToday);
- expect(today).toMatchObject({ date: '2026-03-18', tasks: 7, successRate: 86 });
-
- expect(calendar.maxTasks).toBe(7);
- expect(calendar).not.toHaveProperty('currentStreak');
- expect(calendar.summary).toEqual({
- totalDays: 21,
- activeDays: 2,
- totalTasks: 10,
- totalSuccesses: 9,
- successRate: 90,
- avgTasksPerActiveDay: 5,
- });
- });
-});
diff --git a/server/test/JSON_WRITEBACK.md b/server/test/JSON_WRITEBACK.md
index db952b85a0..3f47765c50 100644
--- a/server/test/JSON_WRITEBACK.md
+++ b/server/test/JSON_WRITEBACK.md
@@ -121,7 +121,6 @@ allowlist of modules. Future service pairs are discovered directly at test time.
| pipeline/reverseOutline.js | <code>outlinePath ( seriesId )</code> | Strict read | [#6983](https://github.com/atomantic/PortOS/pull/6983) |
| postRunStore.js | <code>SESSIONS_FILE</code> | Reviewed exception (see registry) | [#6981](https://github.com/atomantic/PortOS/pull/6981) |
| postRunStore.js | <code>TRAINING_FILE</code> | Reviewed exception (see registry) | [#6981](https://github.com/atomantic/PortOS/pull/6981) |
-| productivity.js | <code>PRODUCTIVITY_FILE</code> | Strict read | [#6981](https://github.com/atomantic/PortOS/pull/6981) |
| projectFileStore.js | <code>file</code> | Strict read | [#6983](https://github.com/atomantic/PortOS/pull/6983) |
| providerQuotaShare.js | <code>PROVIDER_QUOTAS_FILE</code> | Reviewed exception (see registry) | [#6982](https://github.com/atomantic/PortOS/pull/6982) |
| rounds.js | <code>STATE_PATH</code> | Strict read | [#6980](https://github.com/atomantic/PortOS/pull/6980) |