Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: retire agent activity streaks
[._.]/ Adam Eivyb4f58c86b55b
diff --git a/README.md b/README.mdindex beb5600eeb..11a8d3bb9d 100644--- a/README.md+++ b/README.md@@ -83,7 +83,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** — Work streaks, hourly/daily patterns, milestones, and AI-generated weekly digests+- **Productivity Analytics** — Hourly/daily work patterns, task milestones, and 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 collidediff --git a/client/src/components/CosDashboardWidget.jsx b/client/src/components/CosDashboardWidget.jsxindex 21abcdef13..414929f888 100644--- a/client/src/components/CosDashboardWidget.jsx+++ b/client/src/components/CosDashboardWidget.jsx@@ -3,12 +3,10 @@ import { Link } from 'react-router';import {CheckCircle,Clock,- Flame,Brain,AlertCircle,ChevronRight,ChevronDown,- Zap,Bot,XCircle,History,@@ -21,7 +19,7 @@ import { timeAgo, formatWeekdayDate } from '../utils/formatters';/*** CosDashboardWidget - Compact CoS status widget for the main Dashboard- * Shows today's progress, streak status, learning health, CoS running state, and recent tasks+ * Shows today's progress, learning health, CoS running state, and recent tasks*/const CosDashboardWidget = memo(function CosDashboardWidget() {const { data: dashData, loading } = useAutoRefetch(async () => {@@ -40,7 +38,7 @@ const CosDashboardWidget = memo(function CosDashboardWidget() {return { summary, learningSummary, recentTasks, activityCalendar };}, 30000, {// Re-render only when one of the aggregated counts actually moves —- // running agents, completed/failed counts, streak, queue depth, learning+ // running agents, completed/failed counts, queue depth, learning// success rate, every visible recent-task field, every per-day heatmap// cell, and the heatmap summary. The poll fires every 30s; without this// guard each tick re-renders the activity heatmap + recent tasks list@@ -112,7 +110,6 @@ const CosDashboardWidget = memo(function CosDashboardWidget() {&& prev.summary?.today?.running === next.summary?.today?.running&& prev.summary?.today?.completed === next.summary?.today?.completed&& prev.summary?.today?.timeWorked === next.summary?.today?.timeWorked- && prev.summary?.streak?.current === next.summary?.streak?.current&& prev.summary?.queue?.total === next.summary?.queue?.total&& prev.summary?.queue?.pendingApprovals === next.summary?.queue?.pendingApprovals&& prev.learningSummary?.overallSuccessRate === next.learningSummary?.overallSuccessRate@@ -125,7 +122,6 @@ const CosDashboardWidget = memo(function CosDashboardWidget() {&& prev.activityCalendar?.summary?.successRate === next.activityCalendar?.summary?.successRate&& prev.activityCalendar?.summary?.activeDays === next.activityCalendar?.summary?.activeDays&& prev.activityCalendar?.maxTasks === next.activityCalendar?.maxTasks- && prev.activityCalendar?.currentStreak === next.activityCalendar?.currentStreak);},});@@ -145,7 +141,6 @@ const CosDashboardWidget = memo(function CosDashboardWidget() {const hasActivity = summary && (summary.today?.completed > 0 ||summary.today?.running > 0 ||- summary.streak?.current > 0 ||summary.queue?.total > 0 ||summary.status?.running);@@ -157,7 +152,6 @@ const CosDashboardWidget = memo(function CosDashboardWidget() {}const today = summary?.today || {};- const streak = summary?.streak || {};const queue = summary?.queue || {};const status = summary?.status || {};@@ -202,7 +196,7 @@ const CosDashboardWidget = memo(function CosDashboardWidget() {</div>{/* Stats Grid */}- <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">{/* Today's Progress */}<div className="bg-port-bg/50 rounded-lg p-3"><div className="flex items-center gap-2 mb-1">@@ -222,23 +216,6 @@ const CosDashboardWidget = memo(function CosDashboardWidget() {)}</div>- {/* Streak */}- <div className="bg-port-bg/50 rounded-lg p-3">- <div className="flex items-center gap-2 mb-1">- <Flame size={14} className={streak.current >= 3 ? 'text-orange-400' : 'text-gray-400'} />- <span className="text-xs text-gray-500">Streak</span>- </div>- <div className={`text-lg sm:text-xl font-bold ${streak.current >= 3 ? 'text-orange-400' : 'text-white'}`}>- {streak.current || 0}- <span className="text-sm font-normal text-gray-500"> day{streak.current !== 1 ? 's' : ''}</span>- </div>- {streak.current >= 3 && (- <div className="flex items-center gap-1 text-xs text-yellow-400">- <Zap size={10} /> On fire!- </div>- )}- </div>-{/* Pending */}<div className="bg-port-bg/50 rounded-lg p-3"><div className="flex items-center gap-2 mb-1">@@ -400,12 +377,6 @@ function ActivityCalendar({ data }) {<div className="flex items-center gap-2"><Activity size={14} className="text-port-accent" /><span className="text-sm font-medium text-gray-300">Activity</span>- {data.currentStreak > 0 && (- <span className="flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-orange-500/20 text-orange-400">- <Flame size={10} />- {data.currentStreak}d- </span>- )}</div><Linkto="/cos/productivity"diff --git a/client/src/components/cos/QuickSummary.jsx b/client/src/components/cos/QuickSummary.jsxdeleted file mode 100644index 15b70866e7..0000000000--- a/client/src/components/cos/QuickSummary.jsx+++ /dev/null@@ -1,276 +0,0 @@-import { useState } from 'react';-import {- CheckCircle,- Flame,- ListTodo,- Zap,- Timer,- TrendingUp,- TrendingDown,- Minus,- ChevronDown,- ChevronRight,- Award,- Hourglass,- Calendar,- Sun,- Sunset-} from 'lucide-react';-import * as api from '../../services/api';-import { useAutoRefetch } from '../../hooks/useAutoRefetch';-import { timeUntil } from '../../utils/formatters';--/**- * QuickSummary - At-a-glance dashboard widget for CoS status- * Shows today's progress, streak status, next job, and pending work- */-export default function QuickSummary() {- const [showAccomplishments, setShowAccomplishments] = useState(false);- // Let errors throw — `useAutoRefetch` preserves the last-good summary on- // transient failures. `silent: true` keeps the 30s poll quiet on blips.- const { data: summary, loading } = useAutoRefetch(- () => api.getCosQuickSummary({ silent: true }),- 30_000,- );-- if (loading || !summary) {- return null;- }-- const { today, streak, nextJob, queue, velocity, weekComparison, optimalTime } = summary;-- // Only show if there's meaningful data to display- const hasActivity = today.completed > 0 || today.running > 0 || streak.current > 0 || queue.total > 0;- if (!hasActivity && !nextJob) {- return null;- }-- // Velocity indicator helper- const getVelocityDisplay = () => {- if (!velocity?.percentage || velocity.historicalDays < 3) return null;-- const { percentage, label } = velocity;- let icon = Minus;- let color = 'text-gray-400';- let bgColor = 'bg-gray-500/10';-- if (label === 'exceptional') {- icon = TrendingUp;- color = 'text-emerald-400';- bgColor = 'bg-emerald-500/20';- } else if (label === 'above-average') {- icon = TrendingUp;- color = 'text-port-success';- bgColor = 'bg-port-success/15';- } else if (label === 'on-track') {- icon = Minus;- color = 'text-port-accent';- bgColor = 'bg-port-accent/15';- } else if (label === 'slow' || label === 'light') {- icon = TrendingDown;- color = 'text-port-warning';- bgColor = 'bg-port-warning/15';- }-- return { icon, color, bgColor, percentage };- };-- const velocityDisplay = getVelocityDisplay();-- return (- <div className="bg-gradient-to-r from-port-card to-port-bg border border-port-border rounded-lg p-3 mb-4">- <div className="flex flex-wrap items-center gap-x-4 gap-y-2 text-sm">- {/* Today's Stats */}- {(today.completed > 0 || today.running > 0) && (- <div className="flex items-center gap-1.5">- <CheckCircle size={14} className="text-port-success" />- <span className="text-gray-400">Today:</span>- <span className="font-medium text-white">- {today.succeeded}{today.failed > 0 && <span className="text-port-error">/{today.failed}</span>}- </span>- {today.running > 0 && (- <span className="text-port-accent animate-pulse">- +{today.running} running- </span>- )}- {today.timeWorked && today.timeWorked !== '0s' && (- <span className="text-gray-500 text-xs">({today.timeWorked})</span>- )}- </div>- )}-- {/* Streak */}- {streak.current > 0 && (- <div className="flex items-center gap-1.5">- <Flame size={14} className={streak.current >= 3 ? 'text-orange-400' : 'text-gray-400'} />- <span className="text-gray-400">Streak:</span>- <span className={`font-medium ${streak.current >= 3 ? 'text-orange-400' : 'text-white'}`}>- {streak.current} day{streak.current !== 1 ? 's' : ''}- </span>- {streak.current >= 3 && (- <Zap size={12} className="text-yellow-400" />- )}- </div>- )}-- {/* Velocity */}- {velocityDisplay && (- <div className="flex items-center gap-1.5">- <velocityDisplay.icon size={14} className={velocityDisplay.color} />- <span className="text-gray-400">Pace:</span>- <span className={`font-medium ${velocityDisplay.color} px-1.5 py-0.5 rounded ${velocityDisplay.bgColor}`}>- {velocityDisplay.percentage}%- </span>- <span className="text-gray-500 text-xs">vs avg</span>- </div>- )}-- {/* Optimal Time Indicator */}- {optimalTime?.hasData && (- <div- className="flex items-center gap-1.5"- title={optimalTime.isOptimal- ? `This is a peak productivity hour (${optimalTime.currentSuccessRate}% success rate)`- : optimalTime.nextOptimalFormatted- ? `Next peak hour: ${optimalTime.nextOptimalFormatted}`- : 'Current hour performance data'- }- >- {optimalTime.isOptimal ? (- <>- <Sun size={14} className="text-yellow-400" />- <span className="text-gray-400">Time:</span>- <span className="font-medium text-yellow-400 px-1.5 py-0.5 rounded bg-yellow-500/15">- Peak Hour- </span>- </>- ) : optimalTime.isAboveAverage ? (- <>- <Sun size={14} className="text-port-success/70" />- <span className="text-gray-400">Time:</span>- <span className="font-medium text-port-success px-1.5 py-0.5 rounded bg-port-success/10">- Good- </span>- </>- ) : optimalTime.nextOptimalFormatted ? (- <>- <Sunset size={14} className="text-gray-500" />- <span className="text-gray-400">Peak:</span>- <span className="font-medium text-gray-300">- {optimalTime.nextOptimalFormatted}- </span>- </>- ) : null}- </div>- )}-- {/* Week over Week Comparison */}- {weekComparison && weekComparison.lastWeek?.tasks > 0 && (- <div className="flex items-center gap-1.5" title={`This week: ${weekComparison.thisWeek?.tasks || 0} tasks, Last week (same days): ${weekComparison.lastWeek?.tasks} tasks`}>- <Calendar size={14} className={- weekComparison.trend === 'up' ? 'text-port-success' :- weekComparison.trend === 'down' ? 'text-port-warning' :- 'text-gray-400'- } />- <span className="text-gray-400">Week:</span>- <span className={`font-medium flex items-center gap-1 ${- weekComparison.trend === 'up' ? 'text-port-success' :- weekComparison.trend === 'down' ? 'text-port-warning' :- 'text-white'- }`}>- {weekComparison.thisWeek?.tasks || 0}- {weekComparison.changePercent !== null && (- <span className={`text-xs flex items-center ${- weekComparison.trend === 'up' ? 'text-port-success' :- weekComparison.trend === 'down' ? 'text-port-warning' :- 'text-gray-500'- }`}>- {weekComparison.trend === 'up' ? <TrendingUp size={10} /> :- weekComparison.trend === 'down' ? <TrendingDown size={10} /> :- <Minus size={10} />}- {Math.abs(weekComparison.changePercent)}%- </span>- )}- </span>- <span className="text-gray-500 text-xs">vs last</span>- </div>- )}-- {/* Pending Work */}- {queue.total > 0 && (- <div className="flex items-center gap-1.5">- <ListTodo size={14} className="text-port-warning" />- <span className="text-gray-400">Pending:</span>- <span className="font-medium text-white">- {queue.pendingUserTasks > 0 && (- <span>{queue.pendingUserTasks} task{queue.pendingUserTasks !== 1 ? 's' : ''}</span>- )}- {queue.pendingUserTasks > 0 && queue.pendingApprovals > 0 && ', '}- {queue.pendingApprovals > 0 && (- <span className="text-port-warning">{queue.pendingApprovals} approval{queue.pendingApprovals !== 1 ? 's' : ''}</span>- )}- </span>- </div>- )}-- {/* Queue Estimate */}- {queue.estimate?.taskCount > 0 && (- <div className="flex items-center gap-1.5" title={`Based on ${queue.estimate.confidence}% historical data`}>- <Hourglass size={14} className="text-port-accent-2" />- <span className="text-gray-400">ETA:</span>- <span className="font-medium text-port-accent-2">- {queue.estimate.formatted}- </span>- {queue.estimate.runningCount > 0 && (- <span className="text-gray-500 text-xs">- ({queue.estimate.runningCount} active)- </span>- )}- </div>- )}-- {/* Next Job */}- {nextJob && (- <div className="flex items-center gap-1.5">- <Timer size={14} className={nextJob.isDue ? 'text-port-accent animate-pulse' : 'text-gray-400'} />- <span className="text-gray-400">Next:</span>- <span className={`font-medium truncate max-w-[120px] ${nextJob.isDue ? 'text-port-accent' : 'text-white'}`} title={nextJob.jobName}>- {nextJob.jobName?.replace(/^(self-improvement|app-improvement|task)-/, '').replace(/-/g, ' ')}- </span>- <span className="text-gray-500 text-xs">- {nextJob.isDue ? 'due' : timeUntil(nextJob.nextDueAt)}- </span>- </div>- )}- </div>-- {/* Today's Accomplishments - expandable list */}- {today.accomplishments?.length > 0 && (- <div className="mt-2 pt-2 border-t border-port-border/50">- <button- onClick={() => setShowAccomplishments(!showAccomplishments)}- className="flex items-center gap-1.5 text-xs text-gray-400 hover:text-white transition-colors w-full"- aria-expanded={showAccomplishments}- aria-controls="accomplishments-list"- >- {showAccomplishments ? <ChevronDown size={12} /> : <ChevronRight size={12} />}- <Award size={12} className="text-port-success" />- <span>{today.accomplishments.length} task{today.accomplishments.length !== 1 ? 's' : ''} completed today</span>- </button>- {showAccomplishments && (- <ul id="accomplishments-list" className="mt-2 space-y-1 text-xs">- {today.accomplishments.map((item) => (- <li key={item.id} className="flex items-start gap-2 pl-5">- <CheckCircle size={10} className="text-port-success mt-0.5 shrink-0" />- <span className="text-gray-300 line-clamp-1" title={item.description}>- {item.description}- </span>- </li>- ))}- </ul>- )}- </div>- )}- </div>- );-}diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.jsindex a214ef0655..4003cf1272 100644--- a/client/src/components/cos/constants.js+++ b/client/src/components/cos/constants.js@@ -9,7 +9,7 @@ import {Compass,GraduationCap,Bot,- Flame,+ BarChart2,Newspaper,ChartGantt,Play,@@ -30,7 +30,7 @@ export const TABS = [{ id: 'workflow', label: 'Timeline', icon: ChartGantt },{ id: 'digest', label: 'Digest', icon: Calendar },{ id: 'gsd', label: 'GSD', icon: Compass },- { id: 'productivity', label: 'Streaks', icon: Flame },+ { id: 'productivity', label: 'Productivity', icon: BarChart2 },{ id: 'learning', label: 'Learning', icon: GraduationCap },{ id: 'memory', label: 'Memory', icon: Brain },{ id: 'mind', label: 'Mind', icon: MessageCircle },diff --git a/client/src/components/cos/index.js b/client/src/components/cos/index.jsindex 0044a46673..e874c06cf9 100644--- a/client/src/components/cos/index.js+++ b/client/src/components/cos/index.js@@ -15,7 +15,6 @@ export { default as StatusIndicator } from './StatusIndicator';export { default as StatCard } from './StatCard';export { default as StatusBubble } from './StatusBubble';export { default as EventLog } from './EventLog';-export { default as QuickSummary } from './QuickSummary';export { default as ActionableInsightsBanner } from './ActionableInsightsBanner';export { default as DailyTrendsChart } from './DailyTrendsChart';diff --git a/client/src/components/cos/tabs/ProductivityTab.jsx b/client/src/components/cos/tabs/ProductivityTab.jsxindex bbf7ff24e0..86c20d620d 100644--- a/client/src/components/cos/tabs/ProductivityTab.jsx+++ b/client/src/components/cos/tabs/ProductivityTab.jsx@@ -1,6 +1,6 @@import { useState, useEffect, useCallback, useMemo } from 'react';import {- Flame,+ BarChart2,RefreshCw,TrendingUp,Clock,@@ -10,13 +10,12 @@ import {Zap,CheckCircle,AlertTriangle,- BarChart2,ChevronDown,ChevronRight,Award} from 'lucide-react';import BrailleSpinner from '../../BrailleSpinner';-import { formatDateTime, formatDateNumeric } from '../../../utils/formatters';+import { formatDateTime } from '../../../utils/formatters';import * as api from '../../../services/api';import DailyTrendsChart from '../DailyTrendsChart';@@ -28,10 +27,9 @@ export default function ProductivityTab() {const [loading, setLoading] = useState(true);const [recalculating, setRecalculating] = useState(false);const [expandedSections, setExpandedSections] = useState({- streaks: true,patterns: true,insights: true,- milestones: false+ milestones: false,});const loadData = useCallback(async (autoRecalculate = false) => {@@ -113,8 +111,8 @@ export default function ProductivityTab() {{/* Header */}<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4"><div className="flex items-center gap-3">- <Flame className="w-5 h-5 text-orange-400" />- <h3 className="text-lg font-semibold text-white">Productivity & Streaks</h3>+ <BarChart2 className="w-5 h-5 text-port-accent" />+ <h3 className="text-lg font-semibold text-white">Productivity</h3></div><buttononClick={handleRecalculate}@@ -128,85 +126,14 @@ export default function ProductivityTab() {{!hasData ? (<div className="bg-port-card border border-port-border rounded-lg p-8 text-center">- <Flame className="w-12 h-12 text-gray-600 mx-auto mb-3" />+ <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 and building streaks!+ Complete some tasks to start tracking your work patterns.</p></div>) : (<>- {/* Streak Stats */}- <div>- <button- onClick={() => toggleSection('streaks')}- className="flex items-center gap-2 w-full text-left mb-3"- >- {expandedSections.streaks ? <ChevronDown size={16} /> : <ChevronRight size={16} />}- <Flame size={16} className="text-orange-400" />- <span className="font-medium text-white">Work Streaks</span>- </button>- {expandedSections.streaks && (- <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">- {/* Current Daily Streak */}- <div className="bg-gradient-to-br from-orange-500/20 to-red-500/20 border border-orange-500/30 rounded-lg p-4">- <div className="flex items-center gap-2 mb-1">- <Flame size={14} className="text-orange-400" />- <span className="text-xs text-gray-400">Current Streak</span>- </div>- <div className="text-3xl font-bold text-white">- {data.streaks?.currentDaily || 0}- </div>- <div className="text-xs text-gray-500">- {data.streaks?.currentDaily === 1 ? 'day' : 'days'}- </div>- {data.streaks?.currentDaily >= 3 && (- <div className="mt-2 text-xs text-orange-400 flex items-center gap-1">- <Zap size={10} />- On fire!- </div>- )}- </div>-- {/* Longest Daily Streak */}- <div className="bg-port-card border border-port-border rounded-lg p-4">- <div className="flex items-center gap-2 mb-1">- <Trophy size={14} className="text-yellow-400" />- <span className="text-xs text-gray-400">Best Streak</span>- </div>- <div className="text-3xl font-bold text-yellow-400">- {data.streaks?.longestDaily || 0}- </div>- <div className="text-xs text-gray-500">days</div>- </div>-- {/* Weekly Streak */}- <div className="bg-port-card border border-port-border rounded-lg p-4">- <div className="flex items-center gap-2 mb-1">- <Calendar size={14} className="text-port-accent" />- <span className="text-xs text-gray-400">Weekly Streak</span>- </div>- <div className="text-3xl font-bold text-port-accent">- {data.streaks?.currentWeekly || 0}- </div>- <div className="text-xs text-gray-500">weeks</div>- </div>-- {/* Active Days */}- <div className="bg-port-card border border-port-border rounded-lg p-4">- <div className="flex items-center gap-2 mb-1">- <Target size={14} className="text-port-accent" />- <span className="text-xs text-gray-400">Total Active</span>- </div>- <div className="text-3xl font-bold text-white">- {data.totals?.activeDays || 0}- </div>- <div className="text-xs text-gray-500">days worked</div>- </div>- </div>- )}- </div>-{/* Daily Task Trends Chart */}<DailyTrendsChart days={30} initialExpanded={true} />diff --git a/client/src/components/dashboard/builtins/ActivityStreakWidget.jsx b/client/src/components/dashboard/builtins/ActivityStreakWidget.jsxdeleted file mode 100644index 46f6268d3f..0000000000--- a/client/src/components/dashboard/builtins/ActivityStreakWidget.jsx+++ /dev/null@@ -1,45 +0,0 @@-import { streakGlyph } from '../../../lib/streakGlyph.js';--export default function ActivityStreakWidget({ dashboardState }) {- const { usage } = dashboardState;- if (!usage) return null;- return (- <div className="bg-port-card border border-port-border rounded-xl p-4">- <div className="flex items-center gap-3 mb-3">- <div className="text-2xl" aria-hidden="true">- {streakGlyph(usage.currentStreak)}- </div>- <div>- <div className="text-xl font-bold text-white">- {usage.currentStreak} day{usage.currentStreak !== 1 ? 's' : ''}- </div>- <div className="text-xs text-gray-500">Current streak</div>- </div>- {usage.longestStreak > usage.currentStreak && (- <div className="ml-auto text-right">- <div className="text-sm font-semibold text-port-accent">{usage.longestStreak} days</div>- <div className="text-xs text-gray-500">Best</div>- </div>- )}- {usage.currentStreak === usage.longestStreak && usage.currentStreak > 0 && (- <div className="ml-auto px-2 py-1 bg-port-success/20 text-port-success text-xs rounded-full">- Personal best!- </div>- )}- </div>- <div className="flex gap-1">- {usage.last7Days?.map((day) => (- <div- key={day.date}- className={`flex-1 h-2 rounded-full ${day.sessions > 0 ? 'bg-port-success' : 'bg-port-border'}`}- title={`${day.label}: ${day.sessions} sessions`}- />- ))}- </div>- <div className="mt-1 flex justify-between text-xs text-gray-500">- <span>7d ago</span>- <span>Today</span>- </div>- </div>- );-}diff --git a/client/src/components/dashboard/builtins/MeatSpaceStreakWidget.jsx b/client/src/components/dashboard/builtins/MeatSpaceStreakWidget.jsxindex 2c721d5ebf..cb2b587ad5 100644--- a/client/src/components/dashboard/builtins/MeatSpaceStreakWidget.jsx+++ b/client/src/components/dashboard/builtins/MeatSpaceStreakWidget.jsx@@ -4,8 +4,7 @@ import { streakGlyph } from '../../../lib/streakGlyph.js';// Health-logging habit loop. Reads the `meatspaceLogging` slice of// dashboardState (cross-domain streak + this-week counts computed server-side)-// and deep-links into MeatSpace. Mirrors ActivityStreakWidget/DailyPostWidget's-// streak framing. Gated off until at least one health log exists.+// and deep-links into MeatSpace. Gated off until at least one health log exists.export default function MeatSpaceStreakWidget({ dashboardState }) {const stats = dashboardState?.meatspaceLogging;if (!stats) return null;diff --git a/client/src/components/dashboard/widgetRegistry.jsx b/client/src/components/dashboard/widgetRegistry.jsxindex 4bb14463dd..9b7edb8957 100644--- a/client/src/components/dashboard/widgetRegistry.jsx+++ b/client/src/components/dashboard/widgetRegistry.jsx@@ -22,7 +22,6 @@ const ReviewHubCard = lazyWithReload(() => import('../ReviewHubCard'));const WhileAwayWidget = lazyWithReload(() => import('../WhileAwayWidget'));const AppsGridWidget = lazyWithReload(() => import('./builtins/AppsGridWidget'));const QuickStatsWidget = lazyWithReload(() => import('./builtins/QuickStatsWidget'));-const ActivityStreakWidget = lazyWithReload(() => import('./builtins/ActivityStreakWidget'));const HourlyActivityWidget = lazyWithReload(() => import('./builtins/HourlyActivityWidget'));const FeedsWidget = lazyWithReload(() => import('./builtins/FeedsWidget'));const MeatSpaceStreakWidget = lazyWithReload(() => import('./builtins/MeatSpaceStreakWidget'));@@ -69,7 +68,6 @@ export const WIDGETS = [{ id: 'tribe-care', label: 'Tribe Care', Component: TribeCareWidget, width: 'quarter', defaultH: 4, gate: (s) => !!s.tribeCare?.hasPeople },{ id: 'quick-stats', label: 'Quick Stats', Component: QuickStatsWidget, width: 'quarter', defaultH: 3, gate: (s) => s.apps.length > 0 },{ id: 'decision-log', label: 'Decision Log', Component: DecisionLogWidget, width: 'quarter', defaultH: 4 },- { id: 'activity-streak', label: 'Activity Streak', Component: ActivityStreakWidget, width: 'third', defaultH: 3, gate: (s) => s.usage?.currentStreak > 0 || s.usage?.longestStreak > 0 },{ id: 'hourly-activity', label: 'Activity by Hour', Component: HourlyActivityWidget, width: 'full', defaultH: 4, gate: (s) => !!s.usage?.hourlyActivity && s.usage.hourlyActivity.some((v) => v > 0) },{ id: 'feeds', label: 'Feeds Digest', Component: FeedsWidget, width: 'quarter', defaultH: 4, gate: (s) => (s.feeds?.totalFeeds ?? 0) > 0 },{ id: 'meatspace-streak', label: 'Health Logging Streak', Component: MeatSpaceStreakWidget, width: 'third', defaultH: 4, gate: (s) => (s.meatspaceLogging?.totalLogged ?? 0) > 0 },diff --git a/client/src/components/openworld/OpenWorldActivityHeatmap.jsx b/client/src/components/openworld/OpenWorldActivityHeatmap.jsxindex 6241d78097..8c8ba9a290 100644--- a/client/src/components/openworld/OpenWorldActivityHeatmap.jsx+++ b/client/src/components/openworld/OpenWorldActivityHeatmap.jsx@@ -3,7 +3,7 @@ import { useFrame } from '@react-three/fiber';import { computeActivityHeatmap } from '../../utils/openWorldActivityHeatmap';// OpenWorld productivity-district activity heatmap (issue #817): a GitHub-style contribution-// grid laid out as a field of thin ground tiles framing the streak monument. Each tile is one+// grid laid out as a field of thin ground tiles framing the throughput monument. Each tile is one// day; its glow scales with that day's completed-task count relative to the busiest day in the// window. Today's tile reads accent-blue. Active tiles breathe on the highest quality presets;// the static glow keeps the field legible when the pulse is dropped. Data comes from thediff --git a/client/src/components/openworld/OpenWorldArtifacts.jsx b/client/src/components/openworld/OpenWorldArtifacts.jsxindex 2dee9cd972..cbb59e3990 100644--- a/client/src/components/openworld/OpenWorldArtifacts.jsx+++ b/client/src/components/openworld/OpenWorldArtifacts.jsx@@ -6,8 +6,8 @@ import OpenWorldLabel from './OpenWorldLabel';import { computeArtifacts, ARTIFACTS } from '../../utils/openWorldArtifacts';// OpenWorld's earned artifacts (roadmap 3.5): a "Hall of Achievements" cluster of trophies-// that only appear once a milestone is earned (level-ups, completed-goal counts, best CoS-// streak). Each artifact is a dark pedestal topped by a glowing faceted emblem (an octahedron)+// that only appear once a milestone is earned (level-ups and completed-goal counts). Each+// artifact is a dark pedestal topped by a glowing faceted emblem (an octahedron)// — visually distinct from the goal monuments' tower/scaffold so milestones don't read as// goals. The emblems shimmer in unison via a single per-frame ref mutation, gated on the// quality dial. Mirrors OpenWorldGoalMonuments / OpenWorldProductivityDistrict.@@ -42,10 +42,10 @@ function Artifact({ artifact, dayMix = 0 }) {);}-export default function OpenWorldArtifacts({ character, goals, productivityData, settings }) {+export default function OpenWorldArtifacts({ character, goals, settings }) {const hall = useMemo(- () => computeArtifacts({ character, goals, productivityData }),- [character, goals, productivityData],+ () => computeArtifacts({ character, goals }),+ [character, goals],);// Shared shimmer driver: one ref scales emissive intensity for the whole cluster, so thediff --git a/client/src/components/openworld/OpenWorldBillboards.jsx b/client/src/components/openworld/OpenWorldBillboards.jsxindex bb2d7d9b0b..cf5ca4a2ed 100644--- a/client/src/components/openworld/OpenWorldBillboards.jsx+++ b/client/src/components/openworld/OpenWorldBillboards.jsx@@ -274,12 +274,6 @@ export default function OpenWorldBillboards({ positions, apps, cosStatus, reviewtext: `${productivityData.todaySucceeded} TASKS COMPLETED`,});}- if (productivityData.currentDailyStreak > 0) {- activityMessages.push({- label: 'STREAK',- text: `${productivityData.currentDailyStreak} DAY${productivityData.currentDailyStreak > 1 ? 'S' : ''} ACTIVE`,- });- }}const billboards = [];diff --git a/client/src/components/openworld/OpenWorldEasterEggs.jsx b/client/src/components/openworld/OpenWorldEasterEggs.jsxindex 7aa545b40b..1ff706237e 100644--- a/client/src/components/openworld/OpenWorldEasterEggs.jsx+++ b/client/src/components/openworld/OpenWorldEasterEggs.jsx@@ -6,8 +6,8 @@ import OpenWorldLabel from './OpenWorldLabel';import { computeEasterEggs, EGGS } from '../../utils/openWorldEasterEggs';// OpenWorld's easter eggs (roadmap 3.5 follow-up, #824): rare, hidden emblems that only appear-// when a special condition is met (a developer's date, a "leet" level, a palindrome streak, a-// clean-sweep goal board). Tucked in a quiet far corner so they read as a discovery, not a+// when a special condition is met (a developer's date, a "leet" level, or a clean-sweep goal+// board). Tucked in a quiet far corner so they read as a discovery, not a// featured district. Each egg is a small glowing icosahedron with a tiny glyph label; they bob// (each on its own phase offset) gated on the quality dial (mirrors OpenWorldArtifacts).function Egg({ egg, animate, dayMix = 0 }) {@@ -49,14 +49,14 @@ function Egg({ egg, animate, dayMix = 0 }) {);}-export default function OpenWorldEasterEggs({ date, character, goals, productivityData, settings }) {+export default function OpenWorldEasterEggs({ date, character, goals, settings }) {// Re-resolve unlocked eggs as real time advances so calendar eggs (e.g. April 1) turn over at the// day boundary while OpenWorld stays open — an hourly tick is plenty and battery-friendly (shared// singleton timer, paused while hidden). An explicit `date` prop still wins for callers/tests.const tick = useTimeTick(3600000);const cluster = useMemo(- () => computeEasterEggs({ date: date ?? new Date(tick), character, goals, productivityData }),- [date, tick, character, goals, productivityData],+ () => computeEasterEggs({ date: date ?? new Date(tick), character, goals }),+ [date, tick, character, goals],);// Honor the quality dial: drop the bob on the lowest preset, keep the static glow.diff --git a/client/src/components/openworld/OpenWorldProductivityDistrict.jsx b/client/src/components/openworld/OpenWorldProductivityDistrict.jsxindex d33dc45e9c..bcecb2a51a 100644--- a/client/src/components/openworld/OpenWorldProductivityDistrict.jsx+++ b/client/src/components/openworld/OpenWorldProductivityDistrict.jsx@@ -5,25 +5,19 @@ import { useOpenWorldPalette } from './OpenWorldPaletteContext';import OpenWorldLabel from './OpenWorldLabel';import { computeProductivityMonument } from '../../utils/openWorldProductivity';-// OpenWorld's productivity district (roadmap 2.6): a tapered streak monument (an obelisk on-// a stepped plinth) in a southwest district. Its height and glow scale with the user's-// current CoS completion streak; its color tiers by recent velocity (green surging → blue-// steady → amber slowing → red idle). No productivity data reads dim slate ("NO DATA"),-// distinct from a real zero-day streak. The capstone pulses brighter the longer the streak,-// faster while velocity is surging. Mirrors OpenWorldBackupVault / OpenWorldHealthTower.+// OpenWorld's productivity district: a tapered throughput monument whose+// height reflects tasks completed today and whose color reflects recent pace.export default function OpenWorldProductivityDistrict({ productivityData, settings }) {const { tintStructure } = useOpenWorldPalette();const monument = useMemo(() => computeProductivityMonument(productivityData), [productivityData]);const capRef = useRef();- // Honor the quality dial: drop the capstone pulse on the lowest preset, but keep the- // static glow so the streak is still legible.+ // Honor the quality dial: drop the capstone pulse on the lowest preset.const animate = (settings?.particleDensity ?? 1) >= 0.5;const dayMix = openWorldDayMix(settings);useFrame(({ clock }) => {if (!animate || !capRef.current) return;- // A longer streak breathes brighter; a surging velocity beats faster.const speed = monument.surging ? 3.2 : 1.1;const pulse = 0.5 + ((Math.sin(clock.getElapsedTime() * speed) + 1) / 2) * 0.6;capRef.current.material.emissiveIntensity = pulse * (monument.intensity + 0.25);@@ -31,9 +25,7 @@ export default function OpenWorldProductivityDistrict({ productivityData, settinconst { position, baseWidth, height, color } = monument;const shaftTop = height; // top of the tapered shaft (above the plinth, see group offset)- const sublabel = monument.present && monument.longest !== null- ? `${monument.tierLabel} · BEST ${monument.longest}`- : monument.tierLabel;+ const sublabel = monument.tierLabel;return (<group position={position}>@@ -47,7 +39,7 @@ export default function OpenWorldProductivityDistrict({ productivityData, settin<meshStandardMaterial color={tintStructure('#0c121d')} emissive={color} emissiveIntensity={0.12} metalness={0.6} roughness={0.5} /></mesh>- {/* Tapered obelisk shaft — height scales with the streak */}+ {/* Tapered obelisk shaft — height scales with today's throughput. */}<group position={[0, 1.25, 0]}><mesh position={[0, shaftTop / 2, 0]}><cylinderGeometry args={[baseWidth * 0.18, baseWidth * 0.42, shaftTop, 4]} />@@ -60,15 +52,15 @@ export default function OpenWorldProductivityDistrict({ productivityData, settin/></mesh>- {/* Glowing capstone — the live streak indicator that pulses */}+ {/* Glowing capstone — the live pace indicator that pulses. */}<mesh ref={capRef} position={[0, shaftTop + baseWidth * 0.22, 0]} rotation={[0, Math.PI / 4, 0]}><coneGeometry args={[baseWidth * 0.34, baseWidth * 0.55, 4]} /><meshStandardMaterial color={color} emissive={color} emissiveIntensity={monument.intensity} toneMapped={false} /></mesh>- {/* District title + streak above the monument */}+ {/* District title + throughput above the monument. */}<OpenWorldLabel position={[0, shaftTop + 2.6, 0]} fontSize={1.3} color={color} dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={22}>- {monument.streakLabel}+ {monument.throughputLabel}</OpenWorldLabel><OpenWorldLabel position={[0, shaftTop + 1.7, 0]} fontSize={0.8} color="#94a3b8" dayMix={dayMix} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={22}>{sublabel}diff --git a/client/src/components/openworld/OpenWorldScene.jsx b/client/src/components/openworld/OpenWorldScene.jsxindex 10c310e73d..0640009e65 100644--- a/client/src/components/openworld/OpenWorldScene.jsx+++ b/client/src/components/openworld/OpenWorldScene.jsx@@ -403,8 +403,8 @@ function OpenWorldScene({<OpenWorldActivityHeatmap calendarData={activityCalendar} settings={renderSettings} /><OpenWorldTaskFlowRiver cosTasks={cosTasks} productivityData={productivityData} calendarData={activityCalendar} settings={renderSettings} /><OpenWorldGoalMonuments goals={goals} settings={renderSettings} />- <OpenWorldArtifacts character={character} goals={goals} productivityData={productivityData} settings={renderSettings} />- <OpenWorldEasterEggs character={character} goals={goals} productivityData={productivityData} settings={renderSettings} />+ <OpenWorldArtifacts character={character} goals={goals} settings={renderSettings} />+ <OpenWorldEasterEggs character={character} goals={goals} settings={renderSettings} /><OpenWorldVoiceMarker voiceState={voiceState} settings={renderSettings} /><OpenWorldMemoryDistrict memoryGraph={memoryGraph} inboxDepth={inboxDepth} settings={renderSettings} /><OpenWorldDataHarbor introspection={introspection} settings={renderSettings} />diff --git a/client/src/components/openworld/OpenWorldVitalsList.jsx b/client/src/components/openworld/OpenWorldVitalsList.jsxindex bb262f6841..555ce1c4b7 100644--- a/client/src/components/openworld/OpenWorldVitalsList.jsx+++ b/client/src/components/openworld/OpenWorldVitalsList.jsx@@ -2,7 +2,7 @@ import { formatDurationMs, formatMonthDay } from '../../utils/formatters';import { StatButton, metricColor } from './openWorldHudBits';// The System Vitals rows (uptime, health CPU/MEM/DISK, agents, stopped, archived,-// review, nodes, notifs, tasks, streak + the SYS.OK footer). Extracted from the+// review, nodes, notifs, tasks + the SYS.OK footer). Extracted from the// desktop clock-rail so the SAME rows back both the desktop cockpit's vitals panel// AND the compact/phone `vitals` disclosure surface — no divergent copies.export default function OpenWorldVitalsList({@@ -104,16 +104,6 @@ export default function OpenWorldVitalsList({<StatButton label="TASKS" valueClass="text-purple-400" value={`${productivityData.todaySucceeded} TODAY`} onClick={() => onOpenDestination?.('productivity')} title="Teleport to Productivity" />)}- {productivityData?.currentDailyStreak > 0 && (- <StatButton- label="STREAK"- valueClass={productivityData.currentDailyStreak >= 3 ? 'text-orange-400' : 'text-gray-400'}- value={`${productivityData.currentDailyStreak}d`}- onClick={() => onOpenDestination?.('productivity')}- title="Teleport to Productivity"- />- )}-{/* Divider */}<div className="border-t border-cyan-500/15 mt-1.5 pt-1.5"><div className="flex items-center justify-between">diff --git a/client/src/pages/Ambient.jsx b/client/src/pages/Ambient.jsxindex d83239b1cd..04cf934c1c 100644--- a/client/src/pages/Ambient.jsx+++ b/client/src/pages/Ambient.jsx@@ -84,7 +84,6 @@ export default function Ambient() {const cosSummary = data?.cosSummary;const today = useMemo(() => cosSummary?.today || {}, [cosSummary]);- const streak = useMemo(() => cosSummary?.streak || {}, [cosSummary]);const goals = data?.goals;const deathData = data?.deathClock;@@ -204,11 +203,10 @@ export default function Ambient() {</AmbientPanel><AmbientPanel title="Agent Activity">- <div className="grid grid-cols-2 gap-3">+ <div className="grid grid-cols-3 gap-3"><AmbientStat label="Running" value={today.running || 0} color={today.running > 0 ? 'rgb(var(--port-accent))' : null} /><AmbientStat label="Completed" value={today.completed || 0} color={today.completed > 0 ? 'rgb(var(--port-success))' : null} /><AmbientStat label="Failed" value={today.failed || 0} color={today.failed > 0 ? 'rgb(var(--port-error))' : null} />- <AmbientStat label="Streak" value={`${streak.current || 0}d`} color={streak.current >= 7 ? 'rgb(var(--port-warning))' : null} /></div>{cosSummary?.status?.running && (<div className="mt-3 flex items-center gap-2">diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex 84da73198f..d20ab7ea04 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -28,7 +28,6 @@ import StatusIndicator from '../components/cos/StatusIndicator';import StatCard from '../components/cos/StatCard';import StatusBubble from '../components/cos/StatusBubble';import EventLog from '../components/cos/EventLog';-import QuickSummary from '../components/cos/QuickSummary';import ActionableInsightsBanner from '../components/cos/ActionableInsightsBanner';import TasksTab from '../components/cos/tabs/TasksTab';import AgentsTab from '../components/cos/tabs/AgentsTab';@@ -1106,10 +1105,7 @@ export default function ChiefOfStaff() {)}{activeTab === 'tasks' && (<div role="tabpanel" id="tabpanel-tasks" aria-labelledby="tab-tasks">- {/* Tasks-only widgets live under the tab nav so they don't stretch above- tabs that don't surface this data. */}<ActionableInsightsBanner insights={insights} onTaskUnblocked={handleTaskUnblocked} onRefresh={fetchData} />- <QuickSummary /><TasksTab tasks={tasks} agents={agents} onRefresh={fetchData} onTaskAdded={handleUserTaskAdded} providers={providers} apps={apps} /></div>)}diff --git a/client/src/pages/OpenWorld.jsx b/client/src/pages/OpenWorld.jsxindex 3e7b440e42..af1eb644e5 100644--- a/client/src/pages/OpenWorld.jsx+++ b/client/src/pages/OpenWorld.jsx@@ -523,7 +523,6 @@ function OpenWorldInner() {agents: (cosAgents || []).filter(a => a.status === 'running' || a.state === 'coding' || a.state === 'thinking').length,peers: (instances?.peers || []).filter(p => p.status === 'online').length,level: character?.level,- streak: productivityData?.currentStreak ?? productivityData?.streak,};}, [apps, cosAgents, instances, character, productivityData]);diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.jsindex e29b9c4d14..4496fbe496 100644--- a/client/src/services/apiAgents.js+++ b/client/src/services/apiAgents.js@@ -295,7 +295,7 @@ export const generateCosDigest = (weekId = null) => request('/cos/digest/generat});export const compareCosWeeks = (week1, week2) => request(`/cos/digest/compare?week1=${week1}&week2=${week2}`);-// Productivity & Streaks+// Productivityexport const getCosProductivity = () => request('/cos/productivity');export const getCosProductivitySummary = () => request('/cos/productivity/summary');export const recalculateCosProductivity = () => request('/cos/productivity/recalculate', { method: 'POST' });diff --git a/client/src/utils/README.md b/client/src/utils/README.mdindex 8d923b1ab9..aaf0e124eb 100644--- a/client/src/utils/README.md+++ b/client/src/utils/README.md@@ -76,7 +76,7 @@ its tunable constants and placement helpers.| `openWorldAgentMotion` | Agent orbit/trail motion math (`computeAgentOrbit`, `computeAgentTrailPoints`, trail colors). || `openWorldAiCore` | AI-ops core: model tiers, beam thickness, and `computeAiCore` / `computeAiCoreBeams` from live AI status events. || `openWorldAppMetrics` | Per-building live telemetry: aggregate an app's `pm2Status` CPU/memory/uptime/restarts into one snapshot (`computeAppMetrics`, `cpuTone`, `hasPm2Error`, `buildingSignalTone` — façade LED / rooftop stress flags). |-| `openWorldArtifacts` | Earned-artifact milestones (level/goal/streak) → placed artifact descriptors (`computeArtifacts`). |+| `openWorldArtifacts` | Earned-artifact milestones (level/goal) → placed artifact descriptors (`computeArtifacts`). || `openWorldBackupVault` | Backup-vault health/alerting state and color (`computeBackupVault`, `vaultHealth`). || `openWorldChronotype` | Chronotype energy curve by hour → brightness/tempo modifiers (`computeChronotypeEnergy`). || `openWorldCollectibles` | Deterministic Cyber Shards collectible placement, collection overlap math, and progress tracking (`getCollectiblesList`, `checkShardCollection`, `getCollectionStats`, `CYBER_SHARDS`). |@@ -101,7 +101,7 @@ its tunable constants and placement helpers.| `openWorldPlayerRig` | Exploration player-rig math: third-person follow camera, boom collision, damping, facing, avatar state (`thirdPersonCamera`, `resolveBoom`, `dampAngle`, `moveFacing`, `avatarState`). || `openWorldRenderBudget` | Pure Auto-quality render-budget state machine: capability-aware startup tier (`recommendOpenWorldStartTier`), p75 frame-time windows, hysteresis, cooldown, warm-up/gap rejection (`createRenderBudget`, `recordFrame`, `restartWarmup`, `resetRenderBudget`, `getEffectiveTier`, `QUALITY_TIERS`, `DEFAULT_RENDER_BUDGET_CONFIG`). || `openWorldRooftops` | Deterministic rooftop fixture kits (antenna/tank/AC/dish) per app name (`computeRooftopKit`). |-| `openWorldProductivity` | Productivity monument from streak/velocity tiers (`computeProductivityMonument`). |+| `openWorldProductivity` | Productivity monument from same-day throughput and velocity tiers (`computeProductivityMonument`). || `openWorldSoundscape` | Ambient soundscape: mood/energy classification, chord selection (`computeSoundscape`), and the manual mood override (`applyMoodOverride`). || `openWorldSpeedPads` | Luminous road speed boost pads placement and geometric local-coordinate overlap detection (`getSpeedPadsList`, `checkSpeedPadOverlap`, `SPEED_PADS`). || `openWorldTaskFlowRiver` | Task-flow river width/speed from backlog & throughput (`computeTaskFlowRiver`). |diff --git a/client/src/utils/openWorldActivityHeatmap.js b/client/src/utils/openWorldActivityHeatmap.jsindex 34751b092a..e927a41698 100644--- a/client/src/utils/openWorldActivityHeatmap.js+++ b/client/src/utils/openWorldActivityHeatmap.js@@ -1,6 +1,6 @@// Pure, deterministic helpers for OpenWorld's productivity-district activity heatmap// (roadmap 2.6 follow-up, issue #817): a GitHub-style contribution grid rendered as a field-// of ground tiles laid out around the streak monument. Each tile is one day; its glow scales+// of ground tiles laid out around the throughput monument. Each tile is one day; its glow scales// with that day's completed-task count relative to the busiest day in the window. The grid// matches the calendar payload's shape exactly — weeks run left→right (x), day-of-week runs// front→back (z) — so the field reads like the contribution chart on the productivity tab.@@ -42,7 +42,7 @@ export function tileLevel(tasks, maxTasks) {// Full derived view-model for the component. `calendarData` is the `getActivityCalendar`// payload (`{ weeks: [[{ date, dayOfWeek, tasks, isToday, isFuture, ... }]], maxTasks,-// summary, currentStreak }`). A missing/non-object payload, or one with no usable weeks,+// summary }`). A missing/non-object payload, or one with no usable weeks,// yields `present: false` and an empty tile list so the field simply doesn't render rather// than crashing.export function computeActivityHeatmap(calendarData) {diff --git a/client/src/utils/openWorldArtifacts.js b/client/src/utils/openWorldArtifacts.jsindex 4a9dee2176..6f8b33c6eb 100644--- a/client/src/utils/openWorldArtifacts.js+++ b/client/src/utils/openWorldArtifacts.js@@ -3,7 +3,6 @@// earned. Artifacts are DERIVED from data the city already has — no new endpoint:// • level milestones — D&D-style character level crossing a threshold (level-up statues)// • completed-goal milestones — every Nth completed life goal (achievement trophies)-// • streak milestones — best CoS completion streak crossing a threshold (streak trophies)// Nothing earned → empty cluster (no crash). No three.js / React imports so the topology is// unit-testable (mirrors openWorldGoalMonuments.js / openWorldProductivity.js).@@ -46,15 +45,6 @@ export const GOAL_MILESTONES = [{ count: 10, tier: 'gold', label: '10 GOALS' },];-// Best-streak milestones (in days): a trophy when the longest CoS completion streak crosses-// a threshold. Uses the *best* (longest) streak so an earned trophy never disappears when the-// current streak resets.-export const STREAK_MILESTONES = [- { days: 3, tier: 'bronze', label: '3 DAY STREAK' },- { days: 7, tier: 'silver', label: '7 DAY STREAK' },- { days: 30, tier: 'gold', label: '30 DAY STREAK' },-];-// Coerce a value to a finite number or return null (the "absent" sentinel) so an absent field// never collapses into a real 0.function finiteOrNull(value) {@@ -84,20 +74,9 @@ export function completedGoalCount(goals) {return list.filter((g) => g && typeof g === 'object' && g.status === 'completed').length;}-// Best (longest) streak in days from the productivity quick-summary payload-// (`{ streak: { current, longest, ... } }`). Falls back to `current` if `longest` is absent so-// a payload that only carries a current streak still earns trophies. Returns null when absent.-export function bestStreakDays(productivityData) {- const streak = productivityData?.streak;- if (!streak || typeof streak !== 'object') return null;- const longest = finiteOrNull(streak.longest);- if (longest !== null) return longest;- return finiteOrNull(streak.current);-}-// Build the list of EARNED artifact descriptors (kind/label/tier/threshold) from the three// inputs, before placement. Deterministic and side-effect-free.-export function earnedArtifacts({ character, goals, productivityData } = {}) {+export function earnedArtifacts({ character, goals } = {}) {const earned = [];const level = effectiveLevel(character);@@ -116,15 +95,6 @@ export function earnedArtifacts({ character, goals, productivityData } = {}) {}}- const streak = bestStreakDays(productivityData);- if (streak !== null) {- for (const m of STREAK_MILESTONES) {- if (streak >= m.days) {- earned.push({ id: `streak-${m.days}`, kind: 'streak', tier: m.tier, label: m.label, threshold: m.days });- }- }- }-return earned;}@@ -147,10 +117,10 @@ export function placeArtifact(descriptor, index) {// Full derived view-model for the component. Injects all inputs; an all-absent / nothing-earned// state yields an empty cluster (`hasData: false`) rather than a crash. Ordering is stable-// (level → goal → streak, each ascending threshold) so the cluster doesn't reshuffle across+// (level → goal, each ascending threshold) so the cluster doesn't reshuffle across// refetches.-export function computeArtifacts({ character, goals, productivityData } = {}) {- const descriptors = earnedArtifacts({ character, goals, productivityData });+export function computeArtifacts({ character, goals } = {}) {+ const descriptors = earnedArtifacts({ character, goals });const artifacts = descriptors.map((d, i) => placeArtifact(d, i));return {diff --git a/client/src/utils/openWorldArtifacts.test.js b/client/src/utils/openWorldArtifacts.test.jsindex 7cf28c7688..3ab030895d 100644--- a/client/src/utils/openWorldArtifacts.test.js+++ b/client/src/utils/openWorldArtifacts.test.js@@ -3,10 +3,8 @@ import {ARTIFACTS,LEVEL_MILESTONES,GOAL_MILESTONES,- STREAK_MILESTONES,effectiveLevel,completedGoalCount,- bestStreakDays,earnedArtifacts,placeArtifact,computeArtifacts,@@ -67,27 +65,10 @@ describe('completedGoalCount', () => {});});-describe('bestStreakDays', () => {- it('prefers longest over current', () => {- expect(bestStreakDays({ streak: { current: 2, longest: 9 } })).toBe(9);- });-- it('falls back to current when longest absent', () => {- expect(bestStreakDays({ streak: { current: 4 } })).toBe(4);- });-- it('returns null when no streak data', () => {- expect(bestStreakDays(null)).toBeNull();- expect(bestStreakDays({})).toBeNull();- expect(bestStreakDays({ streak: {} })).toBeNull();- expect(bestStreakDays({ streak: 'nope' })).toBeNull();- });-});-describe('earnedArtifacts — thresholds', () => {it('returns nothing when nothing is earned', () => {expect(earnedArtifacts({})).toEqual([]);- expect(earnedArtifacts({ character: { level: 1 }, goals: [], productivityData: { streak: { longest: 0 } } })).toEqual([]);+ expect(earnedArtifacts({ character: { level: 1 }, goals: [] })).toEqual([]);});it('earns level milestones at/above each threshold', () => {@@ -108,21 +89,13 @@ describe('earnedArtifacts — thresholds', () => {expect(ids).not.toContain('goals-10');});- it('earns streak milestones from the best streak', () => {- const ids = earnedArtifacts({ productivityData: { streak: { longest: 7 } } }).map((a) => a.id);- expect(ids).toContain('streak-3');- expect(ids).toContain('streak-7');- expect(ids).not.toContain('streak-30');- });-- it('combines all three sources in stable order (level → goal → streak)', () => {+ it('combines level and goal sources in stable order', () => {const earned = earnedArtifacts({character: { level: 2 },goals: completedGoals(1),- productivityData: { streak: { longest: 3 } },});- expect(earned.map((a) => a.kind)).toEqual(['level', 'goal', 'streak']);- expect(earned.map((a) => a.id)).toEqual(['level-2', 'goals-1', 'streak-3']);+ expect(earned.map((a) => a.kind)).toEqual(['level', 'goal']);+ expect(earned.map((a) => a.id)).toEqual(['level-2', 'goals-1']);});it('attaches a tier + label to each descriptor', () => {@@ -174,9 +147,8 @@ describe('computeArtifacts', () => {const vm = computeArtifacts({character: { level: 10 }, // 3 level milestonesgoals: completedGoals(10), // 3 goal milestones- productivityData: { streak: { longest: 30 } }, // 3 streak milestones});- expect(vm.total).toBe(LEVEL_MILESTONES.length + GOAL_MILESTONES.length + STREAK_MILESTONES.length);+ expect(vm.total).toBe(LEVEL_MILESTONES.length + GOAL_MILESTONES.length);expect(vm.hasData).toBe(true);for (const a of vm.artifacts) {expect(a.position).toHaveLength(3);diff --git a/client/src/utils/openWorldEasterEggs.js b/client/src/utils/openWorldEasterEggs.jsindex 5150e9d344..f0a255656b 100644--- a/client/src/utils/openWorldEasterEggs.js+++ b/client/src/utils/openWorldEasterEggs.js@@ -2,7 +2,7 @@// hidden/rare artifacts that only appear when a special, non-obvious condition is met. Unlike// the earned-artifact trophies (openWorldArtifacts.js), which mark expected milestones, easter eggs// are surprises — a developer's date (Apr 1), a numerically-special level (the "leet" 13/42),-// a palindrome streak, or an exact all-goals-complete state. Each is DERIVED from data the city+// or an exact all-goals-complete state. Each is DERIVED from data the city// already has plus a caller-supplied date — nothing here calls `new Date()` so every condition// is unit-testable on a fixed day. No three.js / React imports (mirrors openWorldArtifacts.js).//@@ -11,7 +11,7 @@// the placement doesn't reshuffle across refetches.import { hashString } from './hashString';-import { effectiveLevel, completedGoalCount, bestStreakDays } from './openWorldArtifacts';+import { effectiveLevel, completedGoalCount } from './openWorldArtifacts';import { PARCELS } from './openWorldPlan';// Placement: a tight cluster at the far -X / +Z corner, deliberately off in a quiet quadrant@@ -23,16 +23,8 @@ export const EGGS = {size: 1.1,};-// A number reads the same forwards and backwards (and is >= 10 so single digits don't trivially-// qualify). Used by the palindrome-streak egg.-function isPalindrome(n) {- if (!Number.isInteger(n) || n < 10) return false;- const s = String(n);- return s === [...s].reverse().join('');-}-// Each egg is { id, label, hint, color, test }. `test` is a pure predicate over the derived-// context { date, level, completedGoals, totalGoals, bestStreak }. Ordered most-special first+// context { date, level, completedGoals, totalGoals }. Ordered most-special first// for stable placement. Colors lean into rare/arcade neon (the city's accent palette).export const EASTER_EGGS = [{@@ -58,13 +50,6 @@ export const EASTER_EGGS = [color: '#3b82f6',test: ({ level }) => level === 42,},- {- id: 'palindrome-streak',- label: '⇄',- hint: 'PALINDROME STREAK',- color: '#a855f7',- test: ({ bestStreak }) => bestStreak !== null && isPalindrome(bestStreak),- },{id: 'clean-sweep',label: '★',@@ -83,15 +68,13 @@ function totalGoalCount(goals) {}// Normalize the raw inputs into the flat predicate context, reusing the openWorldArtifacts derivations-// so the egg conditions stay consistent with the earned-artifact trophies. `level` and `bestStreak`-// are nullable (absent → null, never 0) so an "exact value" egg can't false-fire on missing data.-export function eggContext({ date, character, goals, productivityData } = {}) {+// so the egg conditions stay consistent with the earned-artifact trophies.+export function eggContext({ date, character, goals } = {}) {return {date: date || null,level: effectiveLevel(character), // floored level or null (xp-derived if needed)completedGoals: completedGoalCount(goals),totalGoals: totalGoalCount(goals),- bestStreak: bestStreakDays(productivityData), // longest, else current, else null};}diff --git a/client/src/utils/openWorldEasterEggs.test.js b/client/src/utils/openWorldEasterEggs.test.jsindex 3a670a8f98..b5cf1904e9 100644--- a/client/src/utils/openWorldEasterEggs.test.js+++ b/client/src/utils/openWorldEasterEggs.test.js@@ -28,11 +28,6 @@ describe('eggContext', () => {expect(ctx.totalGoals).toBe(2); // two real objects, junk dropped});- it('prefers longest streak over current, else null (never 0 from absence)', () => {- expect(eggContext({ productivityData: { streak: { current: 2, longest: 11 } } }).bestStreak).toBe(11);- expect(eggContext({ productivityData: { streak: { current: 4 } } }).bestStreak).toBe(4);- expect(eggContext({}).bestStreak).toBeNull();- });});describe('unlockedEggs — conditions', () => {@@ -57,13 +52,6 @@ describe('unlockedEggs — conditions', () => {expect(unlockedEggs({ character: { level: 41 } }).map((e) => e.id)).not.toContain('answer');});- it('unlocks the palindrome-streak egg only for a palindromic best streak >= 10', () => {- expect(unlockedEggs({ productivityData: { streak: { longest: 22 } } }).map((e) => e.id)).toContain('palindrome-streak');- expect(unlockedEggs({ productivityData: { streak: { longest: 121 } } }).map((e) => e.id)).toContain('palindrome-streak');- expect(unlockedEggs({ productivityData: { streak: { longest: 23 } } }).map((e) => e.id)).not.toContain('palindrome-streak');- expect(unlockedEggs({ productivityData: { streak: { longest: 7 } } }).map((e) => e.id)).not.toContain('palindrome-streak'); // single digit- });-it('unlocks the clean-sweep egg only when all (>=1) goals are completed', () => {expect(unlockedEggs({ goals: completedGoals(3) }).map((e) => e.id)).toContain('clean-sweep');const mixed = [...completedGoals(2), { id: 'x', status: 'active' }];diff --git a/client/src/utils/openWorldPhotoMode.js b/client/src/utils/openWorldPhotoMode.jsindex 50683cc784..4d1399ce12 100644--- a/client/src/utils/openWorldPhotoMode.js+++ b/client/src/utils/openWorldPhotoMode.js@@ -103,12 +103,11 @@ export function stepFly(progress, deltaSeconds) {// omitted rather than rendered as "0/undefined", so a sparse install still prints a clean card.export function buildPostcardStats(snapshot = {}) {const lines = [];- const { online, total, agents, peers, level, streak } = snapshot;+ const { online, total, agents, peers, level } = snapshot;if (Number.isFinite(total)) lines.push(`${online ?? 0}/${total} SYSTEMS ONLINE`);if (Number.isFinite(agents) && agents > 0) lines.push(`${agents} AGENT${agents === 1 ? '' : 'S'} ACTIVE`);if (Number.isFinite(peers) && peers > 0) lines.push(`${peers} PEER${peers === 1 ? '' : 'S'} LINKED`);if (Number.isFinite(level)) lines.push(`LEVEL ${level}`);- if (Number.isFinite(streak) && streak > 0) lines.push(`${streak}-DAY STREAK`);return lines;}diff --git a/client/src/utils/openWorldPhotoMode.test.js b/client/src/utils/openWorldPhotoMode.test.jsindex c7aa3e01ab..ff58f25606 100644--- a/client/src/utils/openWorldPhotoMode.test.js+++ b/client/src/utils/openWorldPhotoMode.test.js@@ -93,12 +93,11 @@ describe('stepFly', () => {describe('buildPostcardStats', () => {it('renders the headline lines that have data', () => {- const lines = buildPostcardStats({ online: 3, total: 5, agents: 2, peers: 1, level: 7, streak: 4 });+ const lines = buildPostcardStats({ online: 3, total: 5, agents: 2, peers: 1, level: 7 });expect(lines).toContain('3/5 SYSTEMS ONLINE');expect(lines).toContain('2 AGENTS ACTIVE');expect(lines).toContain('1 PEER LINKED');expect(lines).toContain('LEVEL 7');- expect(lines).toContain('4-DAY STREAK');});it('omits zero/absent fields rather than printing 0', () => {const lines = buildPostcardStats({ online: 0, total: 2, agents: 0, peers: 0 });diff --git a/client/src/utils/openWorldProductivity.js b/client/src/utils/openWorldProductivity.jsindex c3bef34f74..18acc15564 100644--- a/client/src/utils/openWorldProductivity.js+++ b/client/src/utils/openWorldProductivity.js@@ -1,18 +1,15 @@-// Pure, deterministic helpers for OpenWorld's productivity district (roadmap 2.6): a-// streak monument (a glowing obelisk) in a southwest district whose height and glow scale-// with the user's current CoS completion streak, tiered by recent velocity. The monument-// distinguishes "no productivity data yet" (absent → dim, reads "NO DATA") from a real-// zero-day streak (present but unlit beyond the base). No three.js / React imports so the-// topology is unit-testable (mirrors openWorldBackupVault.js / openWorldHealthTower.js).+// Pure, deterministic helpers for OpenWorld's productivity district: a glowing+// obelisk whose height reflects today's completed agent tasks and whose color+// reflects recent velocity. No three.js / React imports.import { PARCELS } from './openWorldPlan';export const MONUMENT = {position: PARCELS.productivity.anchor, // southwest district — anchored by the master plan (openWorldPlan.js)baseWidth: 5, // footprint of the obelisk base- minHeight: 3, // floor height so a 0-streak monument still reads as a stub, not nothing- maxHeight: 26, // height at/above STREAK_CAP days- streakCap: 30, // streak length mapped to full height; longer streaks stay capped (don't overrun the skybox)+ minHeight: 3,+ maxHeight: 26,+ taskCap: 20,};// Velocity tiers drive the monument color so the district speaks recent throughput at a@@ -35,13 +32,12 @@ function finiteOrNull(value) {return typeof value === 'number' && Number.isFinite(value) ? value : null;}-// Map a streak length (in days) to a 0..1 fill against the cap, clamped. Returns null for a-// non-numeric input so an absent streak never collapses into a real 0-day streak.-export function streakLevel(streak, cap = MONUMENT.streakCap) {- const s = finiteOrNull(streak);- if (s === null) return null;+// Map today's completed task count to a 0..1 fill against the cap.+export function throughputLevel(tasks, cap = MONUMENT.taskCap) {+ const count = finiteOrNull(tasks);+ if (count === null) return null;if (typeof cap !== 'number' || !Number.isFinite(cap) || cap <= 0) return null;- return clamp01(s / cap);+ return clamp01(count / cap);}// Classify recent velocity into a color tier. A non-numeric velocity (absent) falls through@@ -53,20 +49,15 @@ export function velocityTier(velocity) {}// Full derived view-model for the component. `productivityData` is the quick-summary payload-// (`{ streak: { current, longest, weekly, lastActive }, today: { completed, ... },-// velocity: { percentage, ... } }`). A missing/non-object payload, or one with no streak-// field, yields an absent monument (dim, floor height) rather than a crash.+// (`{ today: { completed, ... }, velocity: { percentage, ... } }`).export function computeProductivityMonument(productivityData) {const payload = productivityData && typeof productivityData === 'object' ? productivityData : {};- const streakSrc = payload.streak && typeof payload.streak === 'object' ? payload.streak : {};const todaySrc = payload.today && typeof payload.today === 'object' ? payload.today : {};const velocitySrc = payload.velocity && typeof payload.velocity === 'object' ? payload.velocity : {};- const current = finiteOrNull(streakSrc.current);- const longest = finiteOrNull(streakSrc.longest);const completedToday = finiteOrNull(todaySrc.completed);- const level = streakLevel(current) ?? 0; // 0 for both absent and a real 0-streak; `present` disambiguates- const present = current !== null;+ const level = throughputLevel(completedToday) ?? 0;+ const present = completedToday !== null;const tier = velocityTier(velocitySrc.percentage);// Absent productivity data reads slate/dim; a present payload always gets a tier color@@ -76,15 +67,13 @@ export function computeProductivityMonument(productivityData) {const tierLabel = present ? (tier?.label ?? TIERS[TIERS.length - 1].label) : 'NO DATA';const height = MONUMENT.minHeight + level * (MONUMENT.maxHeight - MONUMENT.minHeight);- // Emissive intensity: brighter as the streak grows; a present-but-zero streak still glows- // faintly so it's legible; an absent monument is nearly dark.+ // A present-but-quiet day still glows faintly; absent data is nearly dark.const intensity = present ? 0.3 + level * 0.7 : 0.1;- // Short streak label: "12 DAY STREAK" / "1 DAY STREAK" / "NO STREAK" (real 0) / "NO DATA".- let streakLabel;- if (!present) streakLabel = 'NO DATA';- else if (current === 0) streakLabel = 'NO STREAK';- else streakLabel = `${current} DAY${current === 1 ? '' : 'S'} STREAK`;+ let throughputLabel;+ if (!present) throughputLabel = 'NO DATA';+ else if (completedToday === 0) throughputLabel = 'NO TASKS TODAY';+ else throughputLabel = `${completedToday} TASK${completedToday === 1 ? '' : 'S'} TODAY`;return {position: MONUMENT.position,@@ -92,15 +81,12 @@ export function computeProductivityMonument(productivityData) {height,level,present,- current: present ? current : null,- longest,completedToday,color,intensity,tierKey: present ? (tier?.key ?? TIERS[TIERS.length - 1].key) : 'absent',tierLabel,- streakLabel,- // The monument pulses brighter the higher the streak; surging velocity adds urgency.+ throughputLabel,surging: tier?.key === 'surging',};}diff --git a/client/src/utils/openWorldProductivity.test.js b/client/src/utils/openWorldProductivity.test.jsindex 9ade94a711..4c496964e2 100644--- a/client/src/utils/openWorldProductivity.test.js+++ b/client/src/utils/openWorldProductivity.test.js@@ -1,135 +1,66 @@-import { describe, it, expect } from 'vitest';+import { describe, expect, it } from 'vitest';import {MONUMENT,- streakLevel,- velocityTier,computeProductivityMonument,+ throughputLevel,+ velocityTier,} from './openWorldProductivity';-const full = {- streak: { current: 12, longest: 30, weekly: 3, lastActive: '2026-06-02' },- today: { completed: 8, succeeded: 7, failed: 1 },- velocity: { percentage: 130, label: 'surging' },-};--describe('streakLevel', () => {- it('maps streak/cap into 0..1', () => {- expect(streakLevel(15, 30)).toBe(0.5);- expect(streakLevel(30, 30)).toBe(1);- });-- it('clamps above the cap to 1 and negatives to 0', () => {- expect(streakLevel(999, 30)).toBe(1);- expect(streakLevel(-5, 30)).toBe(0);+describe('throughputLevel', () => {+ it('maps completed tasks into a clamped 0..1 level', () => {+ expect(throughputLevel(10, 20)).toBe(0.5);+ expect(throughputLevel(999, 20)).toBe(1);+ expect(throughputLevel(-5, 20)).toBe(0);+ expect(throughputLevel(0, 20)).toBe(0);});- it('treats a legitimate zero streak as level 0, not absent', () => {- expect(streakLevel(0, 30)).toBe(0);- });-- it('returns null for non-numeric streaks or bad caps', () => {- expect(streakLevel(undefined)).toBeNull();- expect(streakLevel(null)).toBeNull();- expect(streakLevel(NaN)).toBeNull();- expect(streakLevel('12')).toBeNull();- expect(streakLevel(12, 0)).toBeNull();- expect(streakLevel(12, -1)).toBeNull();+ it('returns null for absent values and invalid caps', () => {+ expect(throughputLevel(undefined)).toBeNull();+ expect(throughputLevel('10')).toBeNull();+ expect(throughputLevel(10, 0)).toBeNull();});});describe('velocityTier', () => {- it('classifies into the expected tiers', () => {- expect(velocityTier(130).key).toBe('surging');- expect(velocityTier(100).key).toBe('steady');- expect(velocityTier(60).key).toBe('slowing');- expect(velocityTier(10).key).toBe('idle');- expect(velocityTier(0).key).toBe('idle');- });-- it('returns null for non-numeric velocity', () => {+ it('classifies present pace values and preserves absence', () => {+ expect(velocityTier(150)?.key).toBe('surging');+ expect(velocityTier(100)?.key).toBe('steady');+ expect(velocityTier(50)?.key).toBe('slowing');+ expect(velocityTier(0)?.key).toBe('idle');expect(velocityTier(undefined)).toBeNull();- expect(velocityTier(null)).toBeNull();- expect(velocityTier(NaN)).toBeNull();- expect(velocityTier('100')).toBeNull();});});describe('computeProductivityMonument', () => {- it('carries the fixed position and base width through unchanged', () => {- const vm = computeProductivityMonument(full);- expect(vm.position).toEqual(MONUMENT.position);- expect(vm.baseWidth).toBe(MONUMENT.baseWidth);- });+ it('uses today throughput for height and labeling', () => {+ const vm = computeProductivityMonument({+ today: { completed: 10 },+ velocity: { percentage: 125 },+ });- it('derives a full view-model from complete data', () => {- const vm = computeProductivityMonument(full);expect(vm.present).toBe(true);- expect(vm.current).toBe(12);- expect(vm.longest).toBe(30);- expect(vm.completedToday).toBe(8);- expect(vm.level).toBeCloseTo(0.4);- expect(vm.color).toBe('#22c55e'); // surging tier+ expect(vm.completedToday).toBe(10);+ expect(vm.level).toBe(0.5);+ expect(vm.height).toBe(MONUMENT.minHeight + 0.5 * (MONUMENT.maxHeight - MONUMENT.minHeight));+ expect(vm.throughputLabel).toBe('10 TASKS TODAY');expect(vm.tierKey).toBe('surging');- expect(vm.surging).toBe(true);- expect(vm.streakLabel).toBe('12 DAYS STREAK');- expect(vm.height).toBeGreaterThan(MONUMENT.minHeight);});- it('singularizes a one-day streak label', () => {- const vm = computeProductivityMonument({ ...full, streak: { current: 1 } });- expect(vm.streakLabel).toBe('1 DAY STREAK');- });-- it('distinguishes a real zero-day streak from absent data', () => {- const zero = computeProductivityMonument({ streak: { current: 0 }, velocity: { percentage: 50 } });+ it('distinguishes zero throughput from absent data', () => {+ const zero = computeProductivityMonument({ today: { completed: 0 }, velocity: { percentage: 50 } });expect(zero.present).toBe(true);- expect(zero.current).toBe(0);- expect(zero.level).toBe(0);- expect(zero.streakLabel).toBe('NO STREAK');- expect(zero.color).toBe('#f59e0b'); // slowing tier still colors it, not slate- expect(zero.height).toBeCloseTo(MONUMENT.minHeight);- expect(zero.intensity).toBeGreaterThan(0.1); // faintly lit, above the absent floor+ expect(zero.throughputLabel).toBe('NO TASKS TODAY');+ expect(zero.height).toBe(MONUMENT.minHeight);const absent = computeProductivityMonument({});expect(absent.present).toBe(false);- expect(absent.current).toBeNull();- expect(absent.level).toBe(0);- expect(absent.streakLabel).toBe('NO DATA');- expect(absent.tierLabel).toBe('NO DATA');- expect(absent.color).toBe('#64748b'); // slate- expect(absent.height).toBeCloseTo(MONUMENT.minHeight);- expect(absent.intensity).toBeLessThan(zero.intensity);- });-- it('colors a present-but-velocity-missing payload as idle, never dark', () => {- const vm = computeProductivityMonument({ streak: { current: 5 } });- expect(vm.present).toBe(true);- expect(vm.color).toBe('#ef4444'); // idle tier fallback- expect(vm.tierLabel).toBe('IDLE');- });-- it('clamps a streak above the cap to full height', () => {- const vm = computeProductivityMonument({ streak: { current: 9999 }, velocity: { percentage: 100 } });- expect(vm.level).toBe(1);- expect(vm.height).toBeCloseTo(MONUMENT.maxHeight);- expect(vm.intensity).toBeCloseTo(1);- });-- it('handles null / undefined / non-object input as absent without crashing', () => {- for (const bad of [null, undefined, 'nope', 42, []]) {- const vm = computeProductivityMonument(bad);- expect(vm.present).toBe(false);- expect(vm.level).toBe(0);- expect(vm.streakLabel).toBe('NO DATA');- expect(vm.position).toEqual(MONUMENT.position);- }+ expect(absent.throughputLabel).toBe('NO DATA');+ expect(absent.height).toBe(MONUMENT.minHeight);});- it('tolerates a non-object streak/today/velocity sub-field', () => {- const vm = computeProductivityMonument({ streak: 'oops', today: 5, velocity: null });- expect(vm.present).toBe(false);- expect(vm.completedToday).toBeNull();- expect(vm.longest).toBeNull();+ it('tolerates malformed payloads and clamps unusually high throughput', () => {+ expect(computeProductivityMonument(null).throughputLabel).toBe('NO DATA');+ expect(computeProductivityMonument({ today: 5 }).throughputLabel).toBe('NO DATA');+ expect(computeProductivityMonument({ today: { completed: 9999 } }).level).toBe(1);});});-// @vitest-environment nodediff --git a/client/src/utils/openWorldRegions.js b/client/src/utils/openWorldRegions.jsindex 7a4720faef..d68de6d875 100644--- a/client/src/utils/openWorldRegions.js+++ b/client/src/utils/openWorldRegions.js@@ -32,7 +32,7 @@ export const OPEN_WORLD_REGIONS = [{ id: 'wellness', parcel: 'health', label: 'Wellness Tower', blurb: 'System vitals — CPU, memory, disk.', appPath: '/system-resources/overview', aliases: ['wellness tower', 'health tower', 'vitals tower'] },{ id: 'archive', parcel: 'warehouse', district: 'warehouse', label: 'Archive District', blurb: 'Cold storage for archived apps.', appPath: '/apps', aliases: ['archive district', 'warehouse', 'cold storage'] },{ id: 'quiet-corner', parcel: 'easterEggs', label: 'Quiet Corner', blurb: 'The odd little things the world keeps to itself.', appPath: null, aliases: ['quiet corner', 'easter eggs'] },- { id: 'productivity', parcel: 'productivity', label: 'Productivity Terrace', blurb: 'Streaks, throughput, and the activity heatmap.', appPath: '/insights/overview', aliases: ['productivity terrace', 'productivity', 'streak district'] },+ { id: 'productivity', parcel: 'productivity', label: 'Productivity Terrace', blurb: 'Throughput, pace, and the activity heatmap.', appPath: '/insights/overview', aliases: ['productivity terrace', 'productivity', 'throughput district'] },{ id: 'backup-vault', parcel: 'backupVault', label: 'Backup Vault', blurb: 'The sealed door — last backup and its health.', appPath: '/settings/backup', aliases: ['backup vault', 'the vault'] },{ id: 'memory', parcel: 'memory', label: 'Memory Quarter', blurb: 'Crystal clusters of long-term memory and the inbox well.', appPath: '/brain/inbox', aliases: ['memory quarter', 'memory district', 'knowledge district'] },{ id: 'sprint-yard', parcel: 'jira', label: 'Sprint Yard', blurb: 'The current sprint, laid out as a yard of tickets.', appPath: '/devtools/jira', feature: 'jira', aliases: ['sprint yard', 'jira yard', 'sprint district'] },diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.mdindex 6b151e4e0e..c26a57a186 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 & Streaks** | `/cos/learning`, `/cos/productivity` | Task duration models, success rate metrics, category learning curves, and operational productivity streaks. | — |+| **Learning & Productivity** | `/cos/learning`, `/cos/productivity` | Task duration models, success rate metrics, category learning curves, and operational work patterns. | — || **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. | — |@@ -235,4 +235,3 @@ When performing a **repo-study** task (`server/services/repoIntake.js`) or propo1. **Identify the Core Surface**: Ground every recommendation in PortOS's actual code and surfaces before filing.2. **Clean-Room Reimplementation**: Never copy code, prose, or assets from third-party repositories. Propose clean-room designs that integrate with PortOS's existing architecture.3. **Respect Operational Constraints**: PortOS is a single-user, private-network application. Do not propose multi-tenant SaaS features, rate limiting, or cold-bootstrap LLM calls.-diff --git a/scripts/migrations/309-remove-activity-streak-widget.js b/scripts/migrations/309-remove-activity-streak-widget.jsnew file mode 100644index 0000000000..b0d3c70c5e--- /dev/null+++ b/scripts/migrations/309-remove-activity-streak-widget.js@@ -0,0 +1,38 @@+/**+ * Remove the retired generic activity-streak widget from every persisted+ * dashboard layout. POST and MeatSpace habit widgets remain untouched.+ */++import { readLayoutsDoc, writeLayoutsDoc } from './_lib.js';++const LABEL = 'migration 309';+const WIDGET_ID = 'activity-streak';++function removeFromLayout(layout) {+ if (!layout || !Array.isArray(layout.widgets)) return false;+ const widgets = layout.widgets.filter((id) => id !== WIDGET_ID);+ const existingGrid = Array.isArray(layout.grid) ? layout.grid : [];+ const grid = existingGrid.filter((item) => item?.id !== WIDGET_ID);+ const changed = widgets.length !== layout.widgets.length || grid.length !== existingGrid.length;+ if (!changed) return false;++ layout.widgets = widgets;+ layout.grid = grid.map((item, order) => ({ ...item, order }));+ return true;+}++export default {+ async up({ rootDir }) {+ const result = await readLayoutsDoc({ rootDir, label: LABEL });+ if (!result.ok) return { updated: 0, reason: result.reason };+ const { doc, path } = result;+ let updated = 0;+ for (const layout of doc.layouts) {+ if (removeFromLayout(layout)) updated += 1;+ }+ if (updated === 0) return { updated: 0, reason: 'already-applied' };+ await writeLayoutsDoc(path, doc);+ console.log(`📦 ${LABEL}: removed activity streak widget from ${updated} dashboard layout(s).`);+ return { updated };+ },+};diff --git a/scripts/migrations/309-remove-activity-streak-widget.test.js b/scripts/migrations/309-remove-activity-streak-widget.test.jsnew file mode 100644index 0000000000..cd5e0b3d85--- /dev/null+++ b/scripts/migrations/309-remove-activity-streak-widget.test.js@@ -0,0 +1,52 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import migration from './309-remove-activity-streak-widget.js';++const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);+const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));++describe('migration 309 — remove activity streak dashboard widget', () => {+ let rootDir;+ let layoutsPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-309-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ layoutsPath = join(rootDir, 'data', 'dashboard-layouts.json');+ });++ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));++ it('removes the widget from built-in and custom layouts while preserving other widgets', async () => {+ writeJson(layoutsPath, {+ activeLayoutId: 'default',+ layouts: [+ {+ id: 'default', widgets: ['quick-task', 'activity-streak', 'daily-post'],+ grid: [+ { id: 'quick-task', x: 0, w: 6, order: 0, h: 5 },+ { id: 'activity-streak', x: 6, w: 3, order: 1, h: 3 },+ { id: 'daily-post', x: 9, w: 3, order: 2, h: 3 },+ ],+ },+ { id: 'custom', widgets: ['activity-streak', 'tribe-care'], grid: [] },+ ],+ });++ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 2 });+ const after = readJson(layoutsPath);+ expect(after.layouts[0].widgets).toEqual(['quick-task', 'daily-post']);+ expect(after.layouts[0].grid).toEqual([+ { id: 'quick-task', x: 0, w: 6, order: 0, h: 5 },+ { id: 'daily-post', x: 9, w: 3, order: 1, h: 3 },+ ]);+ expect(after.layouts[1].widgets).toEqual(['tribe-care']);+ });++ it('is safe when no saved layout contains the widget', async () => {+ writeJson(layoutsPath, { layouts: [{ id: 'default', widgets: ['daily-post'], grid: [] }] });+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex ed46a47174..e8487f1493 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -423,7 +423,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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. **Authoritative copy** — mirrored at `client/src/lib/extensionErrors.js`, parity enforced by `extensionErrors.mirror.test.js`. || `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), `isoWeeksInYear(year)` (52, or 53 in a leap-week year), and `isConsecutiveWeek(a, b)` — which bridges a year rollover only when `a` is genuinely its year's last week. Shared by `services/productivity.js` (streaks) and `services/weeklyDigest.js` (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), `isoWeeksInYear(year)` (52, or 53 in a leap-week year), and `isConsecutiveWeek(a, b)` — which bridges a year rollover only when `a` is genuinely its year's last week. Shared by productivity week aggregates and weekly digest filenames. || `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. || `mapWithConcurrency.js` | Generic bounded-concurrency async mapper that preserves input order while capping in-flight work. || `markedSection.js` | Marker-delimited section replacement (pure). `buildMarkers(id)` → `{ start, end }` HTML-comment marker pair; `replaceMarkedSection(content, body, markers)` splices/replaces/removes an auto-generated region without touching surrounding user content (idempotent); `extractMarkedSection` / `hasMarkedSection` read it back. Powers the daily-log activity-digest auto-drafts (#2155) via `brainJournal.upsertAutoSection()`. |diff --git a/server/lib/isoWeek.js b/server/lib/isoWeek.jsindex 3d17c84418..b6ec246b6d 100644--- a/server/lib/isoWeek.js+++ b/server/lib/isoWeek.js@@ -2,11 +2,11 @@* ISO-8601 week identity (pure).** The one place PortOS turns a date into a `YYYY-Www` week id. Both the CoS- * productivity streaks (`services/productivity.js`) and the weekly digest+ * 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- * streaks and week-over-week lookups) and collided two different weeks onto a+ * 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 thatdiff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex a999dd8417..2b72eeb08e 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -35,7 +35,7 @@ const OPEN_WORLD_REGION_COMMANDS = [['wellness', 'Wellness Tower', ['wellness tower', 'health tower', 'vitals tower']],['archive', 'Archive District', ['archive district', 'warehouse', 'cold storage']],['quiet-corner', 'Quiet Corner', ['quiet corner', 'easter eggs']],- ['productivity', 'Productivity Terrace', ['productivity terrace', 'productivity', 'streak district']],+ ['productivity', 'Productivity Terrace', ['productivity terrace', 'productivity', 'throughput district']],['backup-vault', 'Backup Vault', ['backup vault', 'the vault']],['memory', 'Memory Quarter', ['memory quarter', 'memory district', 'knowledge district']],['sprint-yard', 'Sprint Yard', ['sprint yard', 'jira yard', 'sprint district'], 'jira'],@@ -171,7 +171,7 @@ const RAW_NAV_COMMANDS = [// visualization + inline schedule editor). The `workflow` aliases are kept// for muscle memory; the bare `timeline` alias stays with /media/timeline.{ id: 'nav.cos.workflow', path: '/cos/workflow', label: 'Timeline', section: 'Chief of Staff', aliases: ['workflow', 'cos-workflow', 'cos-timeline', 'schedule-timeline'], keywords: ['timeline', 'schedule', 'launch order', 'run order', 'gantt', 'upcoming runs', 'overlap', 'dependencies'] },- { id: 'nav.cos.productivity', path: '/cos/productivity', label: 'Streaks', section: 'Chief of Staff', aliases: ['streaks', 'cos-productivity'] },+ { id: 'nav.cos.productivity', path: '/cos/productivity', label: 'Productivity', section: 'Chief of Staff', aliases: ['cos-productivity', 'work-patterns'] },{ id: 'nav.messages.inbox', path: '/messages/inbox', label: 'Inbox', section: 'Comms', aliases: ['messages', 'comms', 'comms-inbox'], keywords: ['comms', 'email', 'inbox'] },{ id: 'nav.messages.drafts', path: '/messages/drafts', label: 'Drafts', section: 'Comms', aliases: ['drafts', 'comms-drafts'], keywords: ['comms'] },diff --git a/server/routes/cosInsightRoutes.js b/server/routes/cosInsightRoutes.jsindex d67e13adec..ce8c30555a 100644--- a/server/routes/cosInsightRoutes.js+++ b/server/routes/cosInsightRoutes.js@@ -14,7 +14,7 @@ import { parsePagination } from '../lib/validation.js';const router = Router();-// GET /api/cos/productivity - Get productivity insights and streaks+// GET /api/cos/productivity - Get productivity insights and work patternsrouter.get('/productivity', asyncHandler(async (req, res) => {const insights = await productivity.getProductivityInsights();res.json(insights);@@ -210,11 +210,10 @@ router.get('/recent-tasks', asyncHandler(async (req, res) => {}));// GET /api/cos/quick-summary - Get at-a-glance dashboard summary-// Combines today's activity, streak status, next job, and pending approvals into one efficient call+// Combines today's activity, next job, and pending approvals into one efficient callrouter.get('/quick-summary', asyncHandler(async (req, res) => {- const [todayActivity, productivityData, tasksData, jobStats, velocityData, weekData, optimalTime] = await Promise.all([+ const [todayActivity, tasksData, jobStats, velocityData, weekData, optimalTime] = await Promise.all([cos.getTodayActivity(),- productivity.getProductivitySummary(),cos.getAllTasks(),autonomousJobs.getJobStats(),productivity.getVelocityMetrics(),@@ -250,12 +249,6 @@ router.get('/quick-summary', asyncHandler(async (req, res) => {timeWorked: todayActivity.time.combined,accomplishments: todayActivity.accomplishments || []},- streak: {- current: productivityData.currentStreak,- longest: productivityData.longestStreak,- weekly: productivityData.weeklyStreak,- lastActive: productivityData.lastActive- },velocity: {percentage: velocityData.velocity,label: velocityData.velocityLabel,diff --git a/server/routes/cosInsightRoutes.test.js b/server/routes/cosInsightRoutes.test.jsindex 7feaf62122..1a9b18d614 100644--- a/server/routes/cosInsightRoutes.test.js+++ b/server/routes/cosInsightRoutes.test.js@@ -70,7 +70,7 @@ describe('CoS Insight Routes', () => {describe('GET /api/cos/productivity', () => {it('should return productivity insights', async () => {- productivity.getProductivityInsights.mockResolvedValue({ streaks: {}, efficiency: 0.8 });+ productivity.getProductivityInsights.mockResolvedValue({ dailyPatterns: {}, efficiency: 0.8 });const response = await request(app).get('/api/cos/productivity');@@ -81,12 +81,12 @@ describe('CoS Insight Routes', () => {describe('GET /api/cos/productivity/summary', () => {it('should return productivity summary', async () => {- productivity.getProductivitySummary.mockResolvedValue({ currentStreak: 5 });+ productivity.getProductivitySummary.mockResolvedValue({ totalDays: 5 });const response = await request(app).get('/api/cos/productivity/summary');expect(response.status).toBe(200);- expect(response.body.currentStreak).toBe(5);+ expect(response.body.totalDays).toBe(5);});});@@ -277,9 +277,6 @@ describe('CoS Insight Routes', () => {lastEvaluation: Date.now(),accomplishments: ['Fixed bug']});- productivity.getProductivitySummary.mockResolvedValue({- currentStreak: 5, longestStreak: 10, weeklyStreak: 3, lastActive: Date.now()- });cos.getAllTasks.mockResolvedValue({user: { grouped: { pending: [] } },cos: { awaitingApproval: [], grouped: { pending: [] } }@@ -296,7 +293,7 @@ describe('CoS Insight Routes', () => {expect(response.status).toBe(200);expect(response.body.today.completed).toBe(3);- expect(response.body.streak.current).toBe(5);+ expect(response.body).not.toHaveProperty('streak');expect(response.body.velocity.percentage).toBe(120);});});diff --git a/server/services/dashboardLayouts.js b/server/services/dashboardLayouts.jsindex 1e1c1af9f7..790c05785c 100644--- a/server/services/dashboardLayouts.js+++ b/server/services/dashboardLayouts.js@@ -54,16 +54,15 @@ export const INTENT_LAYOUTS = [{id: 'health',name: 'Health',- widgets: ['death-clock', 'goal-progress', 'activity-streak', 'daily-post', 'quick-brain', 'hourly-activity', 'meatspace-streak'],+ widgets: ['death-clock', 'goal-progress', 'daily-post', 'quick-brain', 'hourly-activity', 'meatspace-streak'],grid: [{ id: 'death-clock', x: 0, w: 4, order: 0, h: 3 },{ id: 'goal-progress', x: 4, w: 5, order: 1, h: 5 },- { id: 'activity-streak', x: 9, w: 3, order: 2, h: 3 },- { id: 'quick-brain', x: 0, w: 4, order: 3, h: 2 },- { id: 'daily-post', x: 9, w: 3, order: 4, h: 2 },- { id: 'hourly-activity', x: 0, w: 12, order: 5, h: 4 },+ { id: 'quick-brain', x: 0, w: 4, order: 2, h: 2 },+ { id: 'daily-post', x: 9, w: 3, order: 3, h: 2 },+ { id: 'hourly-activity', x: 0, w: 12, order: 4, h: 4 },// Gated on any health log existing — hidden on installs with no logs.- { id: 'meatspace-streak', x: 0, w: 4, order: 6, h: 4 },+ { id: 'meatspace-streak', x: 0, w: 4, order: 5, h: 4 },],},{@@ -112,7 +111,7 @@ const DEFAULT_LAYOUTS = ['apps','cos', 'goal-progress', 'upcoming-tasks','proactive-alerts', 'review-hub', 'while-away', 'system-health', 'active-processing', 'network-exposure', 'backup', 'death-clock', 'quick-stats', 'decision-log',- 'activity-streak', 'hourly-activity', 'tribe-care', 'feeds',+ 'hourly-activity', 'tribe-care', 'feeds',],// Above-the-fold capture row stretches to h=5 so the Quick Task card// can show its expanded options (worktree/PR/simplify/etc.) without@@ -129,28 +128,27 @@ const DEFAULT_LAYOUTS = [{ id: 'active-processing',x: 5, w: 3, order: 5, h: 5 },{ id: 'proactive-alerts', x: 8, w: 3, order: 6, h: 3 },{ id: 'death-clock', x: 8, w: 4, order: 7, h: 2 },- { id: 'activity-streak', x: 8, w: 4, order: 8, h: 3 },- { id: 'review-hub', x: 5, w: 3, order: 9, h: 2 },+ { id: 'review-hub', x: 5, w: 3, order: 8, h: 2 },// Secondary widgets- { id: 'backup', x: 0, w: 3, order: 10, h: 4 },- { id: 'quick-stats', x: 3, w: 3, order: 11, h: 3 },- { id: 'goal-progress', x: 6, w: 3, order: 12, h: 4 },- { id: 'network-exposure', x: 9, w: 3, order: 13, h: 5 },+ { id: 'backup', x: 0, w: 3, order: 9, h: 4 },+ { id: 'quick-stats', x: 3, w: 3, order: 10, h: 3 },+ { id: 'goal-progress', x: 6, w: 3, order: 11, h: 4 },+ { id: 'network-exposure', x: 9, w: 3, order: 12, h: 5 },// Lower-priority + cos- { id: 'decision-log', x: 0, w: 4, order: 14, h: 2 },- { id: 'cos', x: 4, w: 5, order: 15, h: 4 },- { id: 'while-away', x: 9, w: 3, order: 16, h: 3 },+ { id: 'decision-log', x: 0, w: 4, order: 13, h: 2 },+ { id: 'cos', x: 4, w: 5, order: 14, h: 4 },+ { id: 'while-away', x: 9, w: 3, order: 15, h: 3 },// Full-width visualizations + apps- { id: 'hourly-activity', x: 0, w: 12, order: 17, h: 3 },- { id: 'apps', x: 0, w: 12, order: 18, h: 8 },+ { id: 'hourly-activity', x: 0, w: 12, order: 16, h: 3 },+ { id: 'apps', x: 0, w: 12, order: 17, h: 8 },// Quick-idea (catalog) is sequenced below apps so the seeded layout// doesn't crowd the tightly-packed above-the-fold band.// Reorderable via the Arrange button on the dashboard.- { id: 'quick-idea', x: 0, w: 4, order: 19, h: 4 },+ { id: 'quick-idea', x: 0, w: 4, order: 18, h: 4 },// Gated on the Tribe having people — hidden on installs that don't use it.- { id: 'tribe-care', x: 4, w: 4, order: 20, h: 4 },+ { id: 'tribe-care', x: 4, w: 4, order: 19, h: 4 },// Gated on having subscribed feeds — hidden on installs with none.- { id: 'feeds', x: 8, w: 3, order: 21, h: 4 },+ { id: 'feeds', x: 8, w: 3, order: 20, h: 4 },],},{@@ -161,7 +159,7 @@ const DEFAULT_LAYOUTS = [// All three widgets above the fold. Quick-task is sized to show its// expanded options (matches the Everything layout's h=5 capture row);// upcoming-tasks tall on the right (the focus list); cos below- // quick-task for streak/progress context.+ // quick-task for status/progress context.grid: [{ id: 'quick-task', x: 0, w: 6, order: 0, h: 5 },{ id: 'upcoming-tasks', x: 6, w: 6, order: 1, h: 10 },diff --git a/server/services/productivity.js b/server/services/productivity.jsindex 6ca4227165..fff242d4ea 100644--- a/server/services/productivity.js+++ b/server/services/productivity.js@@ -1,15 +1,14 @@/**- * Productivity & Streaks Service+ * Productivity Service*- * Tracks work patterns, productivity streaks, and generates- * insights about optimal working times.+ * 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, isConsecutiveWeek } from '../lib/isoWeek.js';+import { getWeekId } from '../lib/isoWeek.js';const DATA_DIR = PATHS.cos;const PRODUCTIVITY_FILE = join(DATA_DIR, 'productivity.json');@@ -18,14 +17,6 @@ const PRODUCTIVITY_FILE = join(DATA_DIR, 'productivity.json');* Default productivity data structure*/const DEFAULT_PRODUCTIVITY = {- streaks: {- currentDaily: 0, // Consecutive days with completed tasks- longestDaily: 0, // Best daily streak ever- currentWeekly: 0, // Consecutive weeks with activity- longestWeekly: 0, // Best weekly streak ever- lastActiveDate: null, // Last day with completed tasks- lastActiveWeek: null // Last week with activity- },hourlyPatterns: {// Aggregated by hour: { tasks, successes, failures, avgDuration }},@@ -52,11 +43,14 @@ export async function loadProductivity() {// would leak one call's counters into the next "no file yet" read.const defaults = structuredClone(DEFAULT_PRODUCTIVITY);if (!data) return defaults;- // Merge with defaults to ensure all fields exist+ // 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;+ // Merge with defaults to ensure all current fields exist.return {...defaults,- ...data,- streaks: { ...defaults.streaks, ...data.streaks }+ ...currentData,};}@@ -70,19 +64,6 @@ async function saveProductivity(data) {return data;}-/**- * Check if two dates are consecutive days- */-function isConsecutiveDay(date1, date2) {- if (!date1 || !date2) return false;- const d1 = new Date(date1);- const d2 = new Date(date2);- d1.setHours(0, 0, 0, 0);- d2.setHours(0, 0, 0, 0);- const diffDays = Math.round((d2 - d1) / (1000 * 60 * 60 * 24));- return diffDays === 1;-}-/*** Recalculate all productivity metrics from agent history*/@@ -100,7 +81,7 @@ export async function recalculateProductivity() {const dailyPatterns = {};const dailyHistory = {};- // Track dates with activity for streak calculation+ // Track distinct active dates and weeks for aggregate totals.const activeDates = new Set();const activeWeeks = new Set();@@ -161,70 +142,9 @@ export async function recalculateProductivity() {p.successRate = p.tasks > 0 ? Math.round((p.successes / p.tasks) * 100) : 0;}- // Calculate streaksconst sortedDates = Array.from(activeDates).sort();const sortedWeeks = Array.from(activeWeeks).sort();- const today = getDateString();- const thisWeek = getWeekId();-- // Daily streak calculation- let currentDaily = 0;- let longestDaily = 0;- let tempStreak = 0;-- for (let i = 0; i < sortedDates.length; i++) {- if (i === 0 || isConsecutiveDay(sortedDates[i - 1], sortedDates[i])) {- tempStreak++;- } else {- longestDaily = Math.max(longestDaily, tempStreak);- tempStreak = 1;- }- }- longestDaily = Math.max(longestDaily, tempStreak);-- // Current streak: count backwards from today- const lastDate = sortedDates[sortedDates.length - 1];- if (lastDate === today || isConsecutiveDay(lastDate, today)) {- // Still active or just yesterday- currentDaily = 1;- for (let i = sortedDates.length - 1; i >= 1; i--) {- if (isConsecutiveDay(sortedDates[i - 1], sortedDates[i])) {- currentDaily++;- } else {- break;- }- }- }-- // Weekly streak calculation- let currentWeekly = 0;- let longestWeekly = 0;- let tempWeekStreak = 0;-- for (let i = 0; i < sortedWeeks.length; i++) {- if (i === 0 || isConsecutiveWeek(sortedWeeks[i - 1], sortedWeeks[i])) {- tempWeekStreak++;- } else {- longestWeekly = Math.max(longestWeekly, tempWeekStreak);- tempWeekStreak = 1;- }- }- longestWeekly = Math.max(longestWeekly, tempWeekStreak);-- // Current weekly streak- const lastWeek = sortedWeeks[sortedWeeks.length - 1];- if (lastWeek === thisWeek || isConsecutiveWeek(lastWeek, thisWeek)) {- currentWeekly = 1;- for (let i = sortedWeeks.length - 1; i >= 1; i--) {- if (isConsecutiveWeek(sortedWeeks[i - 1], sortedWeeks[i])) {- currentWeekly++;- } else {- break;- }- }- }-// Check for new milestonesconst milestones = [];const totalTasks = completedAgents.length;@@ -242,26 +162,7 @@ export async function recalculateProductivity() {}}- const streakMilestones = [3, 7, 14, 30, 60, 100];- for (const m of streakMilestones) {- if (longestDaily >= m) {- milestones.push({- type: 'streak',- value: m,- description: `${m}-day work streak`- });- }- }-const productivity = {- streaks: {- currentDaily,- longestDaily,- currentWeekly,- longestWeekly,- lastActiveDate: sortedDates[sortedDates.length - 1] || null,- lastActiveWeek: sortedWeeks[sortedWeeks.length - 1] || null- },hourlyPatterns,dailyPatterns,dailyHistory,@@ -322,34 +223,6 @@ export async function getProductivityInsights() {});}- // Streak encouragement- const { streaks } = data;- if (streaks?.currentDaily >= 3) {- insights.push({- type: 'success',- title: '🔥 Hot Streak!',- message: `${streaks.currentDaily} days of continuous productivity! Keep it up!`,- icon: 'flame'- });- } else if (streaks?.currentDaily === 0 && streaks?.longestDaily > 0) {- insights.push({- type: 'warning',- title: 'Streak Broken',- message: `Your best was ${streaks.longestDaily} days. Start a new streak today!`,- icon: 'refresh'- });- }-- // Weekly consistency- if (streaks?.currentWeekly >= 4) {- insights.push({- type: 'success',- title: 'Weekly Warrior',- message: `${streaks.currentWeekly} consecutive weeks of activity!`,- icon: 'trophy'- });- }-return {...data,insights,@@ -370,7 +243,6 @@ export async function onTaskCompleted(agent) {const data = await loadProductivity();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;@@ -407,27 +279,6 @@ export async function onTaskCompleted(agent) {else data.dailyHistory[dateStr].failures++;data.dailyHistory[dateStr].successRate = Math.round((data.dailyHistory[dateStr].successes / data.dailyHistory[dateStr].tasks) * 100);- // Update streaks using agent's completion date (not "now")- if (data.streaks.lastActiveDate !== dateStr) {- if (isConsecutiveDay(data.streaks.lastActiveDate, dateStr)) {- data.streaks.currentDaily++;- } else {- data.streaks.currentDaily = 1;- }- data.streaks.longestDaily = Math.max(data.streaks.longestDaily, data.streaks.currentDaily);- data.streaks.lastActiveDate = dateStr;- }-- if (data.streaks.lastActiveWeek !== weekId) {- if (isConsecutiveWeek(data.streaks.lastActiveWeek, weekId)) {- data.streaks.currentWeekly++;- } else {- data.streaks.currentWeekly = 1;- }- data.streaks.longestWeekly = Math.max(data.streaks.longestWeekly, data.streaks.currentWeekly);- data.streaks.lastActiveWeek = weekId;- }-// Prune dailyHistory older than 90 daysconst cutoff = new Date();cutoff.setDate(cutoff.getDate() - 90);@@ -447,10 +298,6 @@ export async function getProductivitySummary() {const data = await loadProductivity();return {- currentStreak: data.streaks?.currentDaily || 0,- longestStreak: data.streaks?.longestDaily || 0,- weeklyStreak: data.streaks?.currentWeekly || 0,- lastActive: data.streaks?.lastActiveDate || null,totalDays: data.totals?.activeDays || 0,recentMilestone: data.milestones?.[data.milestones.length - 1] || null};@@ -751,8 +598,7 @@ export async function getActivityCalendar(weeks = 12) {avgTasksPerActiveDay: activeDays.length > 0? Math.round((totalTasks / activeDays.length) * 10) / 10: 0- },- currentStreak: data.streaks?.currentDaily || 0+ }};}diff --git a/server/services/productivity.test.js b/server/services/productivity.test.jsindex 5a47020c33..cb2677dec6 100644--- a/server/services/productivity.test.js+++ b/server/services/productivity.test.js@@ -5,8 +5,7 @@* `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 the streak arithmetic, the day/week boundary handling, and the- * insight derivation are all exercised for real.+ * 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@@ -82,18 +81,10 @@ afterEach(() => {cosEvents.removeAllListeners();});-describe('recalculateProductivity — streaks', () => {- it('returns zeroed streaks and totals for an empty history', async () => {+describe('recalculateProductivity — activity totals', () => {+ it('returns empty totals for an empty history', async () => {const result = await productivity.recalculateProductivity();-- expect(result.streaks).toMatchObject({- currentDaily: 0,- longestDaily: 0,- currentWeekly: 0,- longestWeekly: 0,- lastActiveDate: null,- lastActiveWeek: null,- });+ expect(result).not.toHaveProperty('streaks');expect(result.totals).toEqual({totalTasks: 0,successfulTasks: 0,@@ -101,98 +92,34 @@ describe('recalculateProductivity — streaks', () => {activeDays: 0,activeWeeks: 0,});- expect(result.dailyHistory).toEqual({});- expect(result.milestones).toEqual([]);- });-- it('counts a single active day as a 1-day streak', async () => {- mock.agents = [agentOn('a1', { day: 18 })];-- const { streaks, totals } = await productivity.recalculateProductivity();-- expect(streaks.currentDaily).toBe(1);- expect(streaks.longestDaily).toBe(1);- expect(streaks.lastActiveDate).toBe('2026-03-18');- expect(streaks.lastActiveWeek).toBe('2026-W12');- expect(totals.activeDays).toBe(1);- expect(totals.activeWeeks).toBe(1);- });-- it('counts three consecutive days ending today as a 3-day streak', async () => {- mock.agents = [- agentOn('a1', { day: 16 }),- agentOn('a2', { day: 17 }),- agentOn('a3', { day: 18 }),- ];-- const { streaks } = await productivity.recalculateProductivity();-- expect(streaks.currentDaily).toBe(3);- expect(streaks.longestDaily).toBe(3);- });-- it('breaks the current streak at a gap but keeps the longest run', async () => {- mock.agents = [- agentOn('a1', { day: 10 }),- agentOn('a2', { day: 11 }),- agentOn('a3', { day: 18 }),- ];-- const { streaks, totals } = await productivity.recalculateProductivity();-- expect(streaks.longestDaily).toBe(2);- expect(streaks.currentDaily).toBe(1);- expect(totals.activeDays).toBe(3);- });-- it('keeps the current streak alive when the last activity was yesterday', async () => {- mock.agents = [agentOn('a1', { day: 16 }), agentOn('a2', { day: 17 })];-- const { streaks } = await productivity.recalculateProductivity();-- expect(streaks.currentDaily).toBe(2);- expect(streaks.lastActiveDate).toBe('2026-03-17');});- it('zeroes the current streak once the gap exceeds one day', async () => {- mock.agents = [agentOn('a1', { day: 15 })];-- const { streaks } = await productivity.recalculateProductivity();-- expect(streaks.currentDaily).toBe(0);- expect(streaks.longestDaily).toBe(1);- expect(streaks.lastActiveDate).toBe('2026-03-15');- });-- it('splits activity across the local midnight boundary into two streak days', async () => {+ it('counts distinct active days and weeks without deriving streaks', async () => {mock.agents = [- agentOn('late', { day: 17, hour: 23, minute: 30 }),- agentOn('early', { day: 18, hour: 0, minute: 15 }),+ agentOn('a', { day: 16 }),+ agentOn('b', { day: 17 }),+ agentOn('c', { day: 18 }),];- const { streaks, dailyHistory, hourlyPatterns } = await productivity.recalculateProductivity();+ const result = await productivity.recalculateProductivity();- expect(Object.keys(dailyHistory).sort()).toEqual(['2026-03-17', '2026-03-18']);- expect(hourlyPatterns[23].tasks).toBe(1);- expect(hourlyPatterns[0].tasks).toBe(1);- expect(streaks.currentDaily).toBe(2);- expect(streaks.longestDaily).toBe(2);+ expect(result).not.toHaveProperty('streaks');+ expect(result.totals).toMatchObject({ totalTasks: 3, activeDays: 3, activeWeeks: 1 });});it('ignores agents that are not completed or carry no completion stamp', async () => {mock.agents = [- agentOn('done', { day: 18 }),- agentOn('running', { day: 18, status: 'running' }),- agentOn('no-stamp', { day: 18, completedAt: null }),+ agentOn('good', { day: 18 }),+ { ...agentOn('running', { day: 18 }), status: 'running' },+ { ...agentOn('unstamped', { day: 18 }), completedAt: null },];- const { totals, dailyHistory } = await productivity.recalculateProductivity();+ const result = await productivity.recalculateProductivity();- expect(totals.totalTasks).toBe(1);- expect(dailyHistory['2026-03-18'].tasks).toBe(1);+ 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 = [@@ -222,7 +149,7 @@ describe('recalculateProductivity — aggregates and milestones', () => {expect(result.totals).toMatchObject({ totalTasks: 3, successfulTasks: 2, successRate: 67 });});- it('awards the 10-task and 3-day-streak milestones once earned', async () => {+ 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 })),@@ -237,10 +164,9 @@ describe('recalculateProductivity — aggregates and milestones', () => {achievedAt: expect.any(String),description: 'Completed 10 tasks',});- expect(milestones).toContainEqual({ type: 'streak', value: 3, description: '3-day work streak' });- // 25-task and 7-day milestones are not reached yet.+ 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([]);- expect(milestones.filter(m => m.type === 'streak' && m.value === 7)).toEqual([]);});it('persists the recalculated snapshot with a lastUpdated stamp', async () => {@@ -249,13 +175,17 @@ describe('recalculateProductivity — aggregates and milestones', () => {await productivity.recalculateProductivity();const stored = readStore();- expect(stored.streaks.currentDaily).toBe(1);+ expect(stored).not.toHaveProperty('streaks');expect(stored.lastUpdated).toBe(NOW.toISOString());});});-describe('onTaskCompleted — incremental streak updates', () => {- it('starts a 1-day streak from an empty store and emits the update event', async () => {+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);@@ -263,137 +193,47 @@ describe('onTaskCompleted — incremental streak updates', () => {await productivity.onTaskCompleted(agentOn('a1', { day: 18, hour: 9, duration: 4000 }));const stored = readStore();- expect(stored.streaks).toMatchObject({- currentDaily: 1,- longestDaily: 1,- currentWeekly: 1,- longestWeekly: 1,- lastActiveDate: '2026-03-18',- lastActiveWeek: '2026-W12',- });- expect(stored.hourlyPatterns[9]).toMatchObject({ tasks: 1, successes: 1, avgDuration: 4000, successRate: 100 });- expect(stored.dailyHistory['2026-03-18']).toEqual({ tasks: 1, successes: 1, failures: 0, successRate: 100 });+ 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('extends the streak on a consecutive day and preserves the longest run', async () => {- seed({- streaks: { currentDaily: 2, longestDaily: 5, currentWeekly: 1, longestWeekly: 3, lastActiveDate: '2026-03-17', lastActiveWeek: '2026-W12' },- hourlyPatterns: {}, dailyPatterns: {}, dailyHistory: {}, milestones: [],- });-- await productivity.onTaskCompleted(agentOn('a1', { day: 18 }));-- expect(readStore().streaks).toMatchObject({ currentDaily: 3, longestDaily: 5, lastActiveDate: '2026-03-18' });- });-- it('resets the current streak to 1 after a gap', async () => {- seed({- streaks: { currentDaily: 4, longestDaily: 5, currentWeekly: 1, longestWeekly: 3, lastActiveDate: '2026-03-10', lastActiveWeek: '2026-W11' },- hourlyPatterns: {}, dailyPatterns: {}, dailyHistory: {}, milestones: [],- });-- await productivity.onTaskCompleted(agentOn('a1', { day: 18 }));-- expect(readStore().streaks).toMatchObject({ currentDaily: 1, longestDaily: 5 });- });-- it('leaves the streak untouched for a second task on the same day', async () => {- seed({- streaks: { currentDaily: 4, longestDaily: 5, currentWeekly: 2, longestWeekly: 3, lastActiveDate: '2026-03-18', lastActiveWeek: '2026-W12' },- hourlyPatterns: {}, dailyPatterns: {},- dailyHistory: { '2026-03-18': { tasks: 1, successes: 1, failures: 0, successRate: 100 } },- milestones: [],- });-- await productivity.onTaskCompleted(agentOn('a1', { day: 18, success: false }));-- const stored = readStore();- expect(stored.streaks).toMatchObject({ currentDaily: 4, longestDaily: 5, currentWeekly: 2 });- expect(stored.dailyHistory['2026-03-18']).toEqual({ tasks: 2, successes: 1, failures: 1, successRate: 50 });- });-- it('rolls the weekly streak across a year boundary (W52 → W01)', async () => {- seed({- streaks: { currentDaily: 1, longestDaily: 4, currentWeekly: 3, longestWeekly: 3, lastActiveDate: '2025-12-26', lastActiveWeek: '2025-W52' },- hourlyPatterns: {}, dailyPatterns: {}, dailyHistory: {}, milestones: [],- });-- await productivity.onTaskCompleted(agentOn('a1', { month: 1, day: 1 }));-- expect(readStore().streaks).toMatchObject({- currentWeekly: 4,- longestWeekly: 4,- lastActiveWeek: '2026-W01',- });- });-- it('keeps an ISO week that straddles the new year on a single week id (#3465)', async () => {- // Mon 2025-12-29 and Thu 2026-01-01 are the SAME ISO week. Before #3465 the- // week id paired the ISO week NUMBER with the CALENDAR year, so they stamped- // '2025-W01' and '2026-W01' — splitting the week (and reusing '2025-W01',- // which is also the id of the JANUARY 2025 week). Both are now '2026-W01'.- await productivity.onTaskCompleted(agentOn('dec', { month: 12, day: 29, completedAt: new Date(2025, 11, 29, 10).toISOString() }));- expect(readStore().streaks).toMatchObject({ lastActiveWeek: '2026-W01', currentWeekly: 1 });-- await productivity.onTaskCompleted(agentOn('jan', { month: 1, day: 1 }));-- // Same week, so the id does not move and the week is not counted twice.- expect(readStore().streaks).toMatchObject({- lastActiveWeek: '2026-W01',- currentWeekly: 1,- longestWeekly: 1,- });-- // …and the following week extends the streak instead of resetting it.- await productivity.onTaskCompleted(agentOn('next', { month: 1, day: 5 }));-- expect(readStore().streaks).toMatchObject({- lastActiveWeek: '2026-W02',- currentWeekly: 2,- longestWeekly: 2,- });- });-it('prunes daily history older than 90 days', async () => {seed({- streaks: { currentDaily: 0, longestDaily: 0, currentWeekly: 0, longestWeekly: 0, lastActiveDate: null, lastActiveWeek: null },hourlyPatterns: {}, dailyPatterns: {},dailyHistory: {- '2025-06-01': { tasks: 3, successes: 3, failures: 0, successRate: 100 },- '2026-03-01': { tasks: 1, successes: 1, failures: 0, successRate: 100 },+ '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 }));- expect(Object.keys(readStore().dailyHistory).sort()).toEqual(['2026-03-01', '2026-03-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, hour: 9 }));- rmSync(PRODUCTIVITY_FILE, { force: true });+ await productivity.onTaskCompleted(agentOn('a1', { day: 18 }));+ rmSync(PRODUCTIVITY_FILE);const fresh = await productivity.loadProductivity();- expect(fresh.hourlyPatterns).toEqual({});expect(fresh.dailyHistory).toEqual({});- expect(fresh.streaks.currentDaily).toBe(0);+ expect(fresh.hourlyPatterns).toEqual({});});});-describe('getProductivityInsights', () => {const insightsFixture = {- streaks: { currentDaily: 5, longestDaily: 9, currentWeekly: 4, longestWeekly: 4, lastActiveDate: '2026-03-18', lastActiveWeek: '2026-W12' },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 },@@ -410,7 +250,7 @@ describe('getProductivityInsights', () => {milestones: [],};- it('derives peak-hour, best-day, streak and weekly insights with concrete copy', async () => {+ it('derives peak-hour and best-day insights with concrete copy', async () => {seed(insightsFixture);const result = await productivity.getProductivityInsights();@@ -433,18 +273,6 @@ describe('getProductivityInsights', () => {message: 'Wednesdays show 88% success rate with 8 tasks completed',icon: 'calendar',},- {- type: 'success',- title: '🔥 Hot Streak!',- message: '5 days of continuous productivity! Keep it up!',- icon: 'flame',- },- {- type: 'success',- title: 'Weekly Warrior',- message: '4 consecutive weeks of activity!',- icon: 'trophy',- },]);});@@ -464,24 +292,6 @@ describe('getProductivityInsights', () => {.toBe('Tasks completed around 3PM have a 60% success rate');});- it('flags a broken streak against the previous best', async () => {- seed({- ...insightsFixture,- hourlyPatterns: {},- dailyPatterns: {},- streaks: { currentDaily: 0, longestDaily: 7, currentWeekly: 1, longestWeekly: 4, lastActiveDate: '2026-03-10', lastActiveWeek: '2026-W11' },- });-- const { insights } = await productivity.getProductivityInsights();-- expect(insights).toEqual([{- type: 'warning',- title: 'Streak Broken',- message: 'Your best was 7 days. Start a new streak today!',- icon: 'refresh',- }]);- });-it('returns no insights and null extremes for a store with no history', async () => {const result = await productivity.getProductivityInsights();@@ -496,31 +306,23 @@ describe('getProductivityInsights', () => {describe('getProductivitySummary', () => {it('projects the dashboard fields from the stored snapshot', async () => {seed({- streaks: { currentDaily: 3, longestDaily: 9, currentWeekly: 2, longestWeekly: 4, lastActiveDate: '2026-03-18', lastActiveWeek: '2026-W12' },+ streaks: { currentDaily: 3, longestDaily: 9 },hourlyPatterns: {}, dailyPatterns: {}, dailyHistory: {},totals: { totalTasks: 20, successfulTasks: 18, successRate: 90, activeDays: 11, activeWeeks: 3 },milestones: [{ type: 'tasks', value: 10, description: 'Completed 10 tasks' },- { type: 'streak', value: 3, description: '3-day work streak' },+ { type: 'tasks', value: 25, description: 'Completed 25 tasks' },],});expect(await productivity.getProductivitySummary()).toEqual({- currentStreak: 3,- longestStreak: 9,- weeklyStreak: 2,- lastActive: '2026-03-18',totalDays: 11,- recentMilestone: { type: 'streak', value: 3, description: '3-day work streak' },+ 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({- currentStreak: 0,- longestStreak: 0,- weeklyStreak: 0,- lastActive: null,totalDays: 0,recentMilestone: null,});@@ -719,7 +521,7 @@ describe('getDailyTrends', () => {for (let day = 12; day <= 18; day++) {dailyHistory[`2026-03-${String(day).padStart(2, '0')}`] = { tasks: 1, successes: 0, failures: 1, successRate: 0 };}- seed({ streaks: {}, hourlyPatterns: {}, dailyPatterns: {}, milestones: [], dailyHistory });+ seed({ hourlyPatterns: {}, dailyPatterns: {}, milestones: [], dailyHistory });const { summary } = await productivity.getDailyTrends(30);@@ -731,7 +533,7 @@ describe('getDailyTrends', () => {describe('getActivityCalendar', () => {it('builds Sunday-aligned weeks through the end of the current week', async () => {seed({- streaks: { currentDaily: 3 }, hourlyPatterns: {}, dailyPatterns: {}, milestones: [],+ 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 },@@ -750,7 +552,7 @@ describe('getActivityCalendar', () => {expect(today).toMatchObject({ date: '2026-03-18', tasks: 7, successRate: 86 });expect(calendar.maxTasks).toBe(7);- expect(calendar.currentStreak).toBe(3);+ expect(calendar).not.toHaveProperty('currentStreak');expect(calendar.summary).toEqual({totalDays: 21,activeDays: 2,diff --git a/server/services/usage.js b/server/services/usage.jsindex 883a831721..63df5db013 100644--- a/server/services/usage.js+++ b/server/services/usage.js@@ -635,76 +635,6 @@ export async function recordTokens(inputTokens, outputTokens) {await saveUsage();}-/**- * Calculate current activity streak (consecutive days with sessions)- */-function calculateStreak(dailyActivity) {- const today = new Date();- let streak = 0;- let checkDate = new Date(today);-- // Start from today and work backwards- while (true) {- const dateStr = checkDate.toISOString().split('T')[0];- const dayData = dailyActivity[dateStr];-- if (dayData && dayData.sessions > 0) {- streak++;- checkDate.setDate(checkDate.getDate() - 1);- } else if (streak === 0) {- // If today has no activity, check if yesterday started a streak- checkDate.setDate(checkDate.getDate() - 1);- const yesterdayStr = checkDate.toISOString().split('T')[0];- const yesterdayData = dailyActivity[yesterdayStr];- if (!yesterdayData || yesterdayData.sessions === 0) {- break; // No streak- }- // Continue checking from yesterday- } else {- break; // Streak broken- }- }-- return streak;-}--/**- * Find the longest streak in history- */-function findLongestStreak(dailyActivity) {- const dates = Object.keys(dailyActivity).sort();- if (dates.length === 0) return 0;-- let maxStreak = 0;- let currentStreak = 0;- let prevDate = null;-- for (const dateStr of dates) {- const dayData = dailyActivity[dateStr];- if (!dayData || dayData.sessions === 0) continue;-- if (prevDate) {- const prev = new Date(prevDate);- const curr = new Date(dateStr);- const diffDays = Math.round((curr - prev) / (1000 * 60 * 60 * 24));-- if (diffDays === 1) {- currentStreak++;- } else {- currentStreak = 1;- }- } else {- currentStreak = 1;- }-- maxStreak = Math.max(maxStreak, currentStreak);- prevDate = dateStr;- }-- return maxStreak;-}--/*** Aggregate the per-day per-provider per-model buckets over a date range into* a cost report. `from`/`to` are inclusive `YYYY-MM-DD` strings (null = open@@ -996,8 +926,6 @@ export function getUsageSummary({ from = null, to = null, providers = [] } = {})}return {...empty,- currentStreak: 0,- longestStreak: 0,last7Days,estimatedCost: 0,topProviders: [],@@ -1030,10 +958,6 @@ export function getUsageSummary({ from = null, to = null, providers = [] } = {})last7Days.push({ date: dateStr, label: date.toLocaleDateString('en-US', { weekday: 'short' }), sessions, messages, tokens });}- // Calculate streaks- const currentStreak = calculateStreak(usageData.dailyActivity);- const longestStreak = findLongestStreak(usageData.dailyActivity);-const report = buildUsageReport(usageData.dailyActivity, {from,to,@@ -1058,8 +982,6 @@ export function getUsageSummary({ from = null, to = null, providers = [] } = {})// per-model/fallback-priced report as the headline instead of a second// contradictory blended-rate calculation.estimatedCost: allTimeReport.totals.estimatedCost,- currentStreak,- longestStreak,last7Days,hourlyActivity: usageData.hourlyActivity,topProviders: Object.entries(usageData.byProvider)diff --git a/server/services/usage.test.js b/server/services/usage.test.jsindex 46a12223eb..afe75b2d15 100644--- a/server/services/usage.test.js+++ b/server/services/usage.test.js@@ -1,10 +1,10 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';/**- * Tests for usage.js — streak calculation logic and getUsageSummary shape.+ * Tests for usage.js — getUsageSummary shape and usage persistence.** Strategy: mock fs/promises + fileUtils so usageData is controlled by each test.- * This lets us assert EXACT streak values rather than typeof checks.+ * This lets us assert exact summary values.*/vi.mock('fs/promises', () => ({@@ -59,7 +59,7 @@ function makeUsage(dailyActivity = {}, extras = {}) {// Fixed reference date: noon UTC on a Wednesday to avoid midnight edge cases.const FIXED_DATE = new Date('2025-06-11T12:00:00.000Z');-describe('usage.js — streak calculations', () => {+describe('usage.js — summary', () => {beforeEach(async () => {// Freeze time so daysAgo() and usage.js internal new Date() agree,// preventing flakiness when a test run crosses UTC midnight.@@ -72,110 +72,6 @@ describe('usage.js — streak calculations', () => {vi.useRealTimers();});- describe('currentStreak', () => {- it('returns 0 when dailyActivity is empty', async () => {- readJSONFile.mockResolvedValueOnce(makeUsage({}));- await loadUsage();- const summary = getUsageSummary();- expect(summary.currentStreak).toBe(0);- });-- it('returns 3 for 3 consecutive days ending today', async () => {- const activity = {- [daysAgo(0)]: { sessions: 2, messages: 5, tokens: 100 },- [daysAgo(1)]: { sessions: 1, messages: 3, tokens: 50 },- [daysAgo(2)]: { sessions: 3, messages: 7, tokens: 200 }- };- readJSONFile.mockResolvedValueOnce(makeUsage(activity));- await loadUsage();- const summary = getUsageSummary();- expect(summary.currentStreak).toBe(3);- });-- it('returns 1 when only today has activity', async () => {- const activity = {- [daysAgo(0)]: { sessions: 1, messages: 1, tokens: 10 }- };- readJSONFile.mockResolvedValueOnce(makeUsage(activity));- await loadUsage();- const summary = getUsageSummary();- expect(summary.currentStreak).toBe(1);- });-- it('returns 1 when today has activity but yesterday does not (gap breaks streak)', async () => {- const activity = {- [daysAgo(0)]: { sessions: 1, messages: 1, tokens: 10 },- [daysAgo(2)]: { sessions: 2, messages: 2, tokens: 20 } // gap at day 1- };- readJSONFile.mockResolvedValueOnce(makeUsage(activity));- await loadUsage();- const summary = getUsageSummary();- expect(summary.currentStreak).toBe(1);- });-- it('counts streak from yesterday when today has no activity', async () => {- // Yesterday + day before: streak of 2 from yesterday- const activity = {- [daysAgo(1)]: { sessions: 2, messages: 4, tokens: 80 },- [daysAgo(2)]: { sessions: 1, messages: 2, tokens: 40 }- };- readJSONFile.mockResolvedValueOnce(makeUsage(activity));- await loadUsage();- const summary = getUsageSummary();- expect(summary.currentStreak).toBe(2);- });-- it('returns 0 when there is a day with sessions:0 in the record', async () => {- const activity = {- [daysAgo(0)]: { sessions: 0, messages: 0, tokens: 0 }- };- readJSONFile.mockResolvedValueOnce(makeUsage(activity));- await loadUsage();- const summary = getUsageSummary();- expect(summary.currentStreak).toBe(0);- });- });-- describe('longestStreak', () => {- it('returns 0 for empty data', async () => {- readJSONFile.mockResolvedValueOnce(makeUsage({}));- await loadUsage();- const summary = getUsageSummary();- expect(summary.longestStreak).toBe(0);- });-- it('returns 5 for 5 consecutive days even when current streak is shorter', async () => {- // 5-day run ending 10 days ago, then a new 1-day run today- const activity = {- [daysAgo(14)]: { sessions: 1, messages: 1, tokens: 10 },- [daysAgo(13)]: { sessions: 1, messages: 1, tokens: 10 },- [daysAgo(12)]: { sessions: 1, messages: 1, tokens: 10 },- [daysAgo(11)]: { sessions: 1, messages: 1, tokens: 10 },- [daysAgo(10)]: { sessions: 1, messages: 1, tokens: 10 },- // gap- [daysAgo(0)]: { sessions: 1, messages: 1, tokens: 10 }- };- readJSONFile.mockResolvedValueOnce(makeUsage(activity));- await loadUsage();- const summary = getUsageSummary();- expect(summary.longestStreak).toBe(5);- expect(summary.currentStreak).toBe(1);- });-- it('currentStreak equals longestStreak when all recent days active', async () => {- const activity = {- [daysAgo(0)]: { sessions: 1, messages: 1, tokens: 10 },- [daysAgo(1)]: { sessions: 1, messages: 1, tokens: 10 },- [daysAgo(2)]: { sessions: 1, messages: 1, tokens: 10 }- };- readJSONFile.mockResolvedValueOnce(makeUsage(activity));- await loadUsage();- const summary = getUsageSummary();- expect(summary.currentStreak).toBe(3);- expect(summary.longestStreak).toBe(3);- });- });-describe('summary structure', () => {it('returns all expected fields with correct types', async () => {readJSONFile.mockResolvedValueOnce(makeUsage({}, {