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: rebuild execution-scoped duration buckets during recalc (#8010)
[._.]/ Adam Eivy0545d5579a47
diff --git a/server/services/taskLearning/metrics.js b/server/services/taskLearning/metrics.jsindex 34757ec665..3f22a2e33d 100644--- a/server/services/taskLearning/metrics.js+++ b/server/services/taskLearning/metrics.js@@ -879,6 +879,14 @@ export async function recalculateModelTierMetrics() {* Rebuild success-only duration stats from the agent archive.* Scans all completed agent metadata to recalculate avgDurationMs, maxDurationMs, and p80DurationMs* using only successful agent durations (failed agents often run long in error loops and skew ETAs).+ *+ * Also rebuilds `byTaskTypeExecution` (issue #8001) from the SAME archive pass, so the two+ * dimensions can never disagree about the same runs after a recalc (issue #8010). This REPLACES+ * the map wholesale rather than merging into it — consistent with how this recalc always+ * replaces the derived aggregate it rebuilds — using the shared `executionDurationKey` /+ * `foldDurationOutcome` the live recorder uses, so the rebuilt shape can't drift from the+ * recorded one. `saveLearningData` applies the existing stale-prune + `EXECUTION_BUCKET_CAP`+ * sweep to the replaced map on the way out, same as it does for a live write.*/export async function recalculateDurationStats() {return withLock(async () => {@@ -892,6 +900,8 @@ export async function recalculateDurationStats() {data.totals.successDurationMs = 0;data.totals.successMaxDurationMs = 0;+ const byTaskTypeExecution = {};+let agentCount = 0;let successCount = 0;@@ -947,15 +957,41 @@ export async function recalculateDurationStats() {// bypass, banking its duration into the success-only ETAs.if (isSkipLearningVerdict(vp)) continue;const outcomeSuccess = typeof vp === 'boolean' ? vp : !!meta.result?.success;- if (!outcomeSuccess || duration <= 0) continue;-- successCount++;const taskType = extractTaskType({description: meta.metadata?.taskDescription,metadata: meta.metadata,taskType: meta.metadata?.taskType});+ // Execution-scoped bucket (issue #8001/#8010): folds every non-environmental+ // completion — success OR fail, any duration — mirroring the live+ // `recordExecutionDuration` call, which is NOT gated on success/duration>0 the+ // way the success-only byTaskType recalc below is. Applies the SAME+ // environmental-failure gate (#2618) the live recorder uses so an archived+ // outage never dents this dimension either.+ const errorCategory = meta.result?.errorAnalysis?.category || null;+ const errorOrigin = meta.result?.errorAnalysis?.origin ?? null;+ if (!shouldDivertToEnvironmental(outcomeSuccess, errorCategory, errorOrigin)) {+ const executionKey = executionDurationKey({+ taskType,+ providerId: meta.metadata?.providerId,+ model: meta.metadata?.model,+ effort: meta.metadata?.effort ?? null+ });+ if (executionKey) {+ if (!byTaskTypeExecution[executionKey]) byTaskTypeExecution[executionKey] = emptyDurationBucket();+ foldDurationOutcome(byTaskTypeExecution[executionKey], {+ success: outcomeSuccess,+ duration,+ at: meta.completedAt+ });+ }+ }++ if (!outcomeSuccess || duration <= 0) continue;++ successCount++;+if (data.byTaskType[taskType]) {data.byTaskType[taskType].successDurationMs += duration;data.byTaskType[taskType].successMaxDurationMs = Math.max(@@ -979,6 +1015,8 @@ export async function recalculateDurationStats() {Object.assign(data.totals, calculateDurationETA(data.totals));}+ data.byTaskTypeExecution = byTaskTypeExecution;+await saveLearningData(data);emitLog('info', `📚 Recalculated duration stats from ${agentCount} agents (${successCount} successful)`, {diff --git a/server/services/taskLearning/metricsDurationStats.test.js b/server/services/taskLearning/metricsDurationStats.test.jsindex 536a9cd8c1..0a3313f66e 100644--- a/server/services/taskLearning/metricsDurationStats.test.js+++ b/server/services/taskLearning/metricsDurationStats.test.js@@ -37,7 +37,7 @@ vi.mock('./store.js', async (importActual) => {});import { recalculateDurationStats } from './metrics.js';-import { tryReadFile, loadLearningData, saveLearningData } from './store.js';+import { tryReadFile, loadLearningData, saveLearningData, executionDurationKey } from './store.js';import { SKIP_LEARNING_VERDICT } from '../../lib/learningVerdict.js';import { readdir } from 'fs/promises';import { join } from 'path';@@ -133,3 +133,98 @@ describe('recalculateDurationStats — skip verdict (#4107)', () => {expect(maxActiveReads).toBe(20);});});++describe('recalculateDurationStats — execution-scoped rebuild (#8010)', () => {+ let saved;++ beforeEach(() => {+ vi.clearAllMocks();+ saved = null;+ loadLearningData.mockImplementation(async () => makeData());+ saveLearningData.mockImplementation(async (data) => { saved = data; });+ readdir.mockImplementation(async (path) => (+ path === '/tmp/portos-test-agents'+ ? [{ name: '2026-08-14', isDirectory: () => true }]+ : [+ { name: 'agent-a', isDirectory: () => true },+ { name: 'agent-b', isDirectory: () => true },+ { name: 'agent-c', isDirectory: () => true }+ ]+ ));+ });++ it('rebuilds two execution buckets from two models and skips a run the live path declined to record', async () => {+ tryReadFile.mockImplementation(async (path) => {+ if (path.includes('agent-a')) {+ return JSON.stringify({+ metadata: { taskType: 'internal', taskDescription: 'Study the app', providerId: 'anthropic', model: 'claude-x' },+ result: { success: true, duration: 60000, validationPassed: true },+ completedAt: '2026-08-14T00:00:00.000Z'+ });+ }+ if (path.includes('agent-b')) {+ return JSON.stringify({+ metadata: { taskType: 'internal', taskDescription: 'Study the app', providerId: 'openai', model: 'gpt-y' },+ result: { success: true, duration: 90000, validationPassed: true },+ completedAt: '2026-08-14T00:00:00.000Z'+ });+ }+ // agent-c never reached recordTaskCompletion's aggregates (#4107 skip+ // sentinel) — this rebuild must not resurrect an execution bucket for it.+ return JSON.stringify({+ metadata: { taskType: 'internal', taskDescription: 'Study the app', providerId: 'anthropic', model: 'claude-x' },+ result: { success: true, duration: 30000, validationPassed: SKIP_LEARNING_VERDICT },+ completedAt: '2026-08-14T00:00:00.000Z'+ });+ });++ await recalculateDurationStats();++ expect(Object.keys(saved.byTaskTypeExecution)).toHaveLength(2);++ const anthropicKey = executionDurationKey({ taskType: 'internal-task', providerId: 'anthropic', model: 'claude-x', effort: null });+ const openaiKey = executionDurationKey({ taskType: 'internal-task', providerId: 'openai', model: 'gpt-y', effort: null });++ expect(saved.byTaskTypeExecution[anthropicKey]).toMatchObject({ completed: 1, succeeded: 1, successDurationMs: 60000 });+ expect(saved.byTaskTypeExecution[openaiKey]).toMatchObject({ completed: 1, succeeded: 1, successDurationMs: 90000 });+ });++ it('excludes an environmental failure from the rebuilt execution bucket', async () => {+ tryReadFile.mockImplementation(async (path) => {+ if (path.includes('agent-a')) {+ return JSON.stringify({+ metadata: { taskType: 'internal', taskDescription: 'Study the app', providerId: 'anthropic', model: 'claude-x' },+ result: {+ success: false,+ duration: 5000,+ validationPassed: null,+ errorAnalysis: { category: 'rate-limit', origin: 'provider' }+ },+ completedAt: '2026-08-14T00:00:00.000Z'+ });+ }+ return null;+ });++ await recalculateDurationStats();++ expect(saved.byTaskTypeExecution).toEqual({});+ });++ it('contributes no execution bucket when the archived run is missing its provider/model', async () => {+ tryReadFile.mockImplementation(async (path) => {+ if (path.includes('agent-a')) {+ return JSON.stringify({+ metadata: { taskType: 'internal', taskDescription: 'Study the app' },+ result: { success: true, duration: 60000, validationPassed: true },+ completedAt: '2026-08-14T00:00:00.000Z'+ });+ }+ return null;+ });++ await recalculateDurationStats();++ expect(saved.byTaskTypeExecution).toEqual({});+ });+});