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
fix: finish retired streak cleanup
[._.]/ Adam Eivyc137293b3a6f
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 4b391117f0..e73da22535 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -51,6 +51,7 @@ import {Ticket,Network,Flame,+ BarChart2,Monitor,Cigarette,HeartPulse,@@ -208,7 +209,7 @@ export const NAV_PRESENTATION = {'/cos/runs': { icon: Play },'/cos/schedule': { icon: Clock },'/agents': { icon: Users },- '/cos/productivity': { icon: Flame },+ '/cos/productivity': { icon: BarChart2 },'/cos/jobs': { icon: Bot },'/cos/tasks': { icon: FileText },'/cos/workflow': { icon: ChartGantt },diff --git a/client/src/components/openworld/OpenWorldScene.jsx b/client/src/components/openworld/OpenWorldScene.jsxindex 0640009e65..469709e879 100644--- a/client/src/components/openworld/OpenWorldScene.jsx+++ b/client/src/components/openworld/OpenWorldScene.jsx@@ -168,8 +168,8 @@ function OpenWorldScene({const landmarks = useMemo(() => getResolvedLandmarks(isFeatureEnabled), [isFeatureEnabled]);const collectibles = useMemo(() => getCollectiblesList(isPassiveFeatureEnabled), [isPassiveFeatureEnabled]);const easterEggsList = useMemo(- () => computeEasterEggs({ character, goals, productivityData }),- [character, goals, productivityData]+ () => computeEasterEggs({ character, goals }),+ [character, goals]);useEffect(() => {diff --git a/client/src/utils/openWorldProductivity.test.js b/client/src/utils/openWorldProductivity.test.jsindex 4c496964e2..34b7cdfc34 100644--- a/client/src/utils/openWorldProductivity.test.js+++ b/client/src/utils/openWorldProductivity.test.js@@ -21,6 +21,8 @@ describe('throughputLevel', () => {});});+// @vitest-environment node+describe('velocityTier', () => {it('classifies present pace values and preserves absence', () => {expect(velocityTier(150)?.key).toBe('surging');diff --git a/server/lib/README.md b/server/lib/README.mdindex e8487f1493..6321ca5d01 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 productivity week aggregates and weekly digest filenames. |+| `isoWeek.js` | ISO-8601 week identity — the single source of the `YYYY-Www` week id. `getWeekId(date)` keys on the ISO week-numbering **year** (the calendar year of that week's Thursday), not `date.getFullYear()`, so one ISO week is never split across two ids and two weeks never collide on one (#3465). Also `isoWeekParts`, `getIsoWeekNumber`, `getIsoWeekYear`, `parseWeekId` (null on garbage), and `isoWeeksInYear(year)` (52, or 53 in a leap-week year). 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 b6ec246b6d..0dcbfba541 100644--- a/server/lib/isoWeek.js+++ b/server/lib/isoWeek.js@@ -95,23 +95,3 @@ export function parseWeekId(weekId) {export function isoWeeksInYear(year) {return isoWeekParts(new Date(year, 11, 28)).week;}--/**- * True when `week2` is the ISO week immediately after `week1`.- *- * Across a year rollover, `week1` must be the LAST week of its own numbering- * year — 53 in a leap-week year, 52 otherwise. A bare `week1 >= 52` check would- * wrongly bridge `2026-W52` → `2027-W01` even though `2026-W53` sits between.- *- * @param {string} week1- * @param {string} week2- * @returns {boolean}- */-export function isConsecutiveWeek(week1, week2) {- const a = parseWeekId(week1);- const b = parseWeekId(week2);- if (!a || !b) return false;- if (a.year === b.year) return b.week - a.week === 1;- if (b.year - a.year === 1 && b.week === 1) return a.week === isoWeeksInYear(a.year);- return false;-}diff --git a/server/lib/isoWeek.test.js b/server/lib/isoWeek.test.jsindex 29e59f5623..0a6decf920 100644--- a/server/lib/isoWeek.test.js+++ b/server/lib/isoWeek.test.js@@ -3,7 +3,6 @@ import {getIsoWeekNumber,getIsoWeekYear,getWeekId,- isConsecutiveWeek,isoWeekParts,isoWeeksInYear,parseWeekId,@@ -93,38 +92,3 @@ describe('parseWeekId', () => {}});});--describe('isConsecutiveWeek', () => {- it('accepts adjacent weeks inside a year', () => {- expect(isConsecutiveWeek('2026-W10', '2026-W11')).toBe(true);- });-- it('rejects a gap, a repeat, and a backwards step', () => {- expect(isConsecutiveWeek('2026-W10', '2026-W12')).toBe(false);- expect(isConsecutiveWeek('2026-W10', '2026-W10')).toBe(false);- expect(isConsecutiveWeek('2026-W11', '2026-W10')).toBe(false);- });-- it('still bridges a real year rollover', () => {- expect(isConsecutiveWeek('2025-W52', '2026-W01')).toBe(true);- });-- it('does NOT bridge W52 → W01 across a leap-week year, whose W53 sits between', () => {- expect(isConsecutiveWeek('2026-W52', '2027-W01')).toBe(false);- expect(isConsecutiveWeek('2026-W52', '2026-W53')).toBe(true);- expect(isConsecutiveWeek('2026-W53', '2027-W01')).toBe(true);- });-- it('rejects a multi-year jump and an unparseable id', () => {- expect(isConsecutiveWeek('2024-W52', '2026-W01')).toBe(false);- expect(isConsecutiveWeek(null, '2026-W01')).toBe(false);- expect(isConsecutiveWeek('2026-W01', undefined)).toBe(false);- expect(isConsecutiveWeek('not-a-week', '2026-W01')).toBe(false);- });-- it('chains a whole rollover the way the streak scan walks it', () => {- const weeks = ['2025-W51', '2025-W52', '2026-W01', '2026-W02'];- const chained = weeks.slice(1).every((week, i) => isConsecutiveWeek(weeks[i], week));- expect(chained).toBe(true);- });-});diff --git a/server/routes/cosInsightRoutes.test.js b/server/routes/cosInsightRoutes.test.jsindex 023eb84aba..e39230ccaf 100644--- a/server/routes/cosInsightRoutes.test.js+++ b/server/routes/cosInsightRoutes.test.js@@ -22,8 +22,7 @@ vi.mock('../services/productivity.js', () => ({getDailyTrends: vi.fn(),getActivityCalendar: vi.fn(),getOptimalTimeInfo: vi.fn(),- getVelocityMetrics: vi.fn(),- getWeekComparison: vi.fn()+ getVelocityMetrics: vi.fn()}));vi.mock('../services/goalProgress.js', () => ({diff --git a/server/services/productivity.js b/server/services/productivity.jsindex 8345fdabc2..92f33219cb 100644--- a/server/services/productivity.js+++ b/server/services/productivity.js@@ -306,84 +306,6 @@ export async function getProductivitySummary() {};}-/**- * Get week-over-week comparison metrics- * Compares this week's completed tasks to last week- * @returns {Object} Week comparison data- */-export async function getWeekComparison() {- const data = await loadProductivity();- const dailyHistory = data.dailyHistory || {};-- // Get date ranges for this week and last week- const today = new Date();- const dayOfWeek = today.getDay(); // 0 = Sunday-- // This week: from last Sunday to today- const thisWeekStart = new Date(today);- thisWeekStart.setDate(today.getDate() - dayOfWeek);- thisWeekStart.setHours(0, 0, 0, 0);-- // Last week: 7 days before this week's start, for 7 days- const lastWeekStart = new Date(thisWeekStart);- lastWeekStart.setDate(lastWeekStart.getDate() - 7);-- // Aggregate this week's tasks (up to today)- let thisWeekTasks = 0;- let thisWeekSuccesses = 0;- for (let d = new Date(thisWeekStart); d <= today; d.setDate(d.getDate() + 1)) {- const dateStr = getDateString(d);- const dayData = dailyHistory[dateStr];- if (dayData) {- thisWeekTasks += dayData.tasks || 0;- thisWeekSuccesses += dayData.successes || 0;- }- }-- // Aggregate last week's tasks (same day range as this week for fair comparison)- let lastWeekTasks = 0;- let lastWeekSuccesses = 0;- const lastWeekEnd = new Date(lastWeekStart);- lastWeekEnd.setDate(lastWeekEnd.getDate() + dayOfWeek); // Same relative day as today- for (let d = new Date(lastWeekStart); d <= lastWeekEnd; d.setDate(d.getDate() + 1)) {- const dateStr = getDateString(d);- const dayData = dailyHistory[dateStr];- if (dayData) {- lastWeekTasks += dayData.tasks || 0;- lastWeekSuccesses += dayData.successes || 0;- }- }-- // Calculate change- let changePercent = null;- let trend = 'neutral';- if (lastWeekTasks > 0) {- changePercent = Math.round(((thisWeekTasks - lastWeekTasks) / lastWeekTasks) * 100);- if (changePercent > 10) trend = 'up';- else if (changePercent < -10) trend = 'down';- } else if (thisWeekTasks > 0) {- // No tasks last week but have tasks this week- trend = 'up';- changePercent = 100;- }-- return {- thisWeek: {- tasks: thisWeekTasks,- successes: thisWeekSuccesses,- successRate: thisWeekTasks > 0 ? Math.round((thisWeekSuccesses / thisWeekTasks) * 100) : 0- },- lastWeek: {- tasks: lastWeekTasks,- successes: lastWeekSuccesses,- successRate: lastWeekTasks > 0 ? Math.round((lastWeekSuccesses / lastWeekTasks) * 100) : 0- },- changePercent,- trend,- daysCompared: dayOfWeek + 1 // How many days we're comparing (e.g., if today is Tuesday, comparing 3 days)- };-}-/*** Get velocity metrics - how today compares to historical average* @returns {Object} Velocity data including today's count, average, and relative performancediff --git a/server/services/productivity.test.js b/server/services/productivity.test.jsindex 3cbc785fd2..8d77441b7a 100644--- a/server/services/productivity.test.js+++ b/server/services/productivity.test.js@@ -330,52 +330,6 @@ describe('getProductivitySummary', () => {});});-describe('getWeekComparison', () => {- const withHistory = (dailyHistory) => seed({- streaks: {}, hourlyPatterns: {}, dailyPatterns: {}, dailyHistory, milestones: [],- });-- it('compares matching day ranges of this week and last week', async () => {- // Today is Wednesday 2026-03-18 → this week starts Sunday 2026-03-15 and- // last week's comparable range is Sunday 2026-03-08 through Wed 2026-03-11.- withHistory({- '2026-03-16': { tasks: 4, successes: 4, failures: 0, successRate: 100 },- '2026-03-18': { tasks: 2, successes: 1, failures: 1, successRate: 50 },- '2026-03-09': { tasks: 3, successes: 3, failures: 0, successRate: 100 },- // Outside last week's comparable range (Thursday) — must not be counted.- '2026-03-12': { tasks: 9, successes: 9, failures: 0, successRate: 100 },- });-- expect(await productivity.getWeekComparison()).toEqual({- thisWeek: { tasks: 6, successes: 5, successRate: 83 },- lastWeek: { tasks: 3, successes: 3, successRate: 100 },- changePercent: 100,- trend: 'up',- daysCompared: 4,- });- });-- it('reports a decline when this week trails last week', async () => {- withHistory({- '2026-03-16': { tasks: 2, successes: 2, failures: 0, successRate: 100 },- '2026-03-09': { tasks: 10, successes: 5, failures: 5, successRate: 50 },- });-- const result = await productivity.getWeekComparison();-- expect(result.changePercent).toBe(-80);- expect(result.trend).toBe('down');- });-- it('treats a first active week as a 100% gain and a fully idle pair as neutral', async () => {- withHistory({ '2026-03-16': { tasks: 5, successes: 5, failures: 0, successRate: 100 } });- expect(await productivity.getWeekComparison()).toMatchObject({ changePercent: 100, trend: 'up' });-- withHistory({});- expect(await productivity.getWeekComparison()).toMatchObject({ changePercent: null, trend: 'neutral' });- });-});-describe('getVelocityMetrics', () => {it('scores today against the historical active-day average', async () => {seed({diff --git a/server/services/taskLearning/durations.js b/server/services/taskLearning/durations.jsindex c898e7c91e..6331a2c714 100644--- a/server/services/taskLearning/durations.js+++ b/server/services/taskLearning/durations.js@@ -96,79 +96,3 @@ export async function getAllTaskDurations() {return durations;}--/**- * Estimate queue completion time based on historical duration data- * @param {Array} pendingTasks - List of pending tasks with descriptions- * @param {number} runningCount - Number of currently running agents- * @returns {Object} Estimate with totalMs, formatted string, and confidence- */-export async function estimateQueueCompletion(pendingTasks = [], runningCount = 0) {- const durations = await getAllTaskDurations();- const overallAvg = durations._overall?.avgDurationMs || 300000; // Default 5 min-- let totalEstimateMs = 0;- let tasksWithEstimates = 0;- let tasksWithoutEstimates = 0;-- for (const task of pendingTasks) {- // Try to match task type from description patterns- const desc = (task.description || '').toLowerCase();- let matchedDuration = null;-- // Check for specific task type patterns- for (const [taskType, durationInfo] of Object.entries(durations)) {- if (taskType === '_overall') continue;-- // Match by task type keywords in description- const typeKey = taskType.replace(/^(self-improve:|app-improve:)/, '').toLowerCase();- if (desc.includes(typeKey) || desc.includes(taskType.toLowerCase())) {- matchedDuration = durationInfo.avgDurationMs;- break;- }- }-- if (matchedDuration) {- totalEstimateMs += matchedDuration;- tasksWithEstimates++;- } else {- // Use overall average for unknown tasks- totalEstimateMs += overallAvg;- tasksWithoutEstimates++;- }- }-- // Account for currently running tasks (assume half done on average)- if (runningCount > 0) {- totalEstimateMs += (overallAvg * runningCount * 0.5);- }-- // Format the estimate- const totalMinutes = Math.round(totalEstimateMs / 60000);- let formatted = '';- if (totalMinutes === 0) {- formatted = 'under 1m';- } else if (totalMinutes < 60) {- formatted = `~${totalMinutes}m`;- } else {- const hours = Math.floor(totalMinutes / 60);- const mins = totalMinutes % 60;- formatted = mins > 0 ? `~${hours}h ${mins}m` : `~${hours}h`;- }-- // Calculate confidence based on data quality- const totalTasks = pendingTasks.length + runningCount;- const confidence = totalTasks > 0- ? Math.round((tasksWithEstimates / totalTasks) * 100)- : 0;-- return {- totalMs: totalEstimateMs,- totalMinutes,- formatted,- taskCount: pendingTasks.length,- runningCount,- confidence,- basedOnHistory: tasksWithEstimates > 0- };-}diff --git a/server/services/taskLearning/durations.test.js b/server/services/taskLearning/durations.test.jsindex 233bf740fa..14fb9210bc 100644--- a/server/services/taskLearning/durations.test.js+++ b/server/services/taskLearning/durations.test.js@@ -9,7 +9,7 @@ vi.mock('./store.js', async (importOriginal) => {});import { loadLearningData } from './store.js';-import { getTaskDurationEstimate, getAllTaskDurations, estimateQueueCompletion } from './durations.js';+import { getTaskDurationEstimate, getAllTaskDurations } from './durations.js';const baseData = (overrides = {}) => ({byTaskType: {},@@ -99,47 +99,3 @@ describe('durations.getAllTaskDurations', () => {expect(await getAllTaskDurations()).toEqual({});});});--describe('durations.estimateQueueCompletion', () => {- it('matches tasks by type keyword and formats sub-hour estimates', async () => {- loadLearningData.mockResolvedValue(baseData({- byTaskType: {- 'self-improve:ui': { completed: 4, avgDurationMs: 600000, successRate: 50 }, // 10 min- },- totals: { completed: 4, succeeded: 2, failed: 2, totalDurationMs: 2400000, avgDurationMs: 600000 },- }));- const out = await estimateQueueCompletion([{ description: 'fix ui glitch' }], 0);- expect(out.taskCount).toBe(1);- expect(out.basedOnHistory).toBe(true);- expect(out.formatted).toBe('~10m');- expect(out.confidence).toBe(100);- });-- it('uses the overall average for unmatched tasks and adds half a running task', async () => {- loadLearningData.mockResolvedValue(baseData({- byTaskType: { 'self-improve:ui': { completed: 4, avgDurationMs: 600000, successRate: 50 } },- totals: { completed: 4, succeeded: 2, failed: 2, totalDurationMs: 2400000, avgDurationMs: 600000 },- }));- // unmatched description → overallAvg 600000; runningCount 1 adds 0.5*600000=300000- const out = await estimateQueueCompletion([{ description: 'totally unrelated work' }], 1);- expect(out.totalMs).toBe(900000); // 600000 + 300000- expect(out.basedOnHistory).toBe(false);- expect(out.confidence).toBe(0); // 0 matched of 2 total- });-- it('formats multi-hour estimates with hours and minutes', async () => {- loadLearningData.mockResolvedValue(baseData({- totals: { completed: 4, succeeded: 4, failed: 0, totalDurationMs: 4 * 5400000, avgDurationMs: 5400000 },- }));- // 90 min average; two unmatched tasks → 180 min = 3h 0m- const out = await estimateQueueCompletion([{ description: 'x' }, { description: 'y' }], 0);- expect(out.formatted).toBe('~3h');- });-- it('reports "under 1m" for an empty queue', async () => {- loadLearningData.mockResolvedValue(baseData());- const out = await estimateQueueCompletion([], 0);- expect(out.formatted).toBe('under 1m');- expect(out.confidence).toBe(0);- });-});diff --git a/server/services/taskLearning/index.js b/server/services/taskLearning/index.jsindex 8e6fca6e8c..febec8eb6f 100644--- a/server/services/taskLearning/index.js+++ b/server/services/taskLearning/index.js@@ -82,8 +82,7 @@ export {export {getTaskDurationEstimate,- getAllTaskDurations,- estimateQueueCompletion+ getAllTaskDurations} from './durations.js';export {