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
scope CoS agent ETA to the run's provider, model and effort (#8001)
[._.]/ Adam Eivya63e1c2ac045
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsxindex c31b68f2ef..bb7393af32 100644--- a/client/src/components/cos/tabs/AgentCard.jsx+++ b/client/src/components/cos/tabs/AgentCard.jsx@@ -30,7 +30,7 @@ import Modal from '../../ui/Modal';import CollapsibleText from '../../ui/CollapsibleText';import toast from '../../ui/Toast';import { copyToClipboard } from '../../../lib/clipboard';-import { extractCosTaskType } from '../../../lib/cosTaskType';+import { estimateCosDuration } from '../../../lib/cosDurationEstimate';import { isAgentFeedbackUpdateTarget, isSystemAgent as isSystemAgentRecord } from '../../../lib/cosAgentFeedback';import AgentResultLine from '../AgentResultLine';import { DEFAULT_REVIEWER, normalizeReviewers } from '../constants';@@ -471,37 +471,19 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,// Calculate duration estimate for running agents// Uses P80 (80th percentile approximation) for progress bars to prevent premature 100%const durationEstimate = useMemo(() => {- if (inactive || !durations) return null;-- const taskType = extractCosTaskType({- description: agent.metadata?.taskDescription,- taskType: agent.metadata?.taskType,- metadata: agent.metadata+ if (inactive) return null;+ // The shared 4-rung cascade (#8001): this run's provider/model/effort first,+ // falling outward to the plain task-type average. `TaskItem` estimates through+ // the same module, so a pending task and the agent it becomes agree.+ return estimateCosDuration({+ durations,+ task: {+ description: agent.metadata?.taskDescription,+ taskType: agent.metadata?.taskType,+ metadata: agent.metadata+ },+ agentMetadata: agent.metadata});- const typeData = durations[taskType];- const overallData = durations._overall;-- if (typeData && typeData.avgDurationMs) {- return {- estimatedMs: typeData.p80DurationMs || typeData.avgDurationMs,- avgMs: typeData.avgDurationMs,- basedOn: typeData.completed,- taskType,- isTypeSpecific: true- };- }-- if (overallData && overallData.avgDurationMs) {- return {- estimatedMs: overallData.p80DurationMs || overallData.avgDurationMs,- avgMs: overallData.avgDurationMs,- basedOn: overallData.completed,- taskType: 'all tasks',- isTypeSpecific: false- };- }-- return null;}, [inactive, durations, agent.metadata]);// Calculate progress percentage using P80-based estimatediff --git a/client/src/components/cos/tabs/AgentCard.test.jsx b/client/src/components/cos/tabs/AgentCard.test.jsxindex de1ac23cc1..f617e60d34 100644--- a/client/src/components/cos/tabs/AgentCard.test.jsx+++ b/client/src/components/cos/tabs/AgentCard.test.jsx@@ -89,17 +89,31 @@ describe('AgentCard runtime presentation', () => {expect(screen.queryByText(/left$/)).not.toBeInTheDocument();});+ // The run this card is for, and the execution-scoped history that describes it+ // (#8001). Same task type as `durationHistory` above, but four times slower —+ // so a card that fell back to the task-type average would show the wrong ETA.+ const SLOW_RUN = { providerId: 'ollama', model: 'local-coder', effort: 'low' };+ const executionHistory = {+ ...durationHistory,+ _byExecution: { 'user-task|ollama|local-coder|low': { avgDurationMs: 180_000, p80DurationMs: 240_000, completed: 6 } },+ _byExecutionProviderModel: { 'user-task|ollama|local-coder': { avgDurationMs: 180_000, p80DurationMs: 240_000, completed: 6 } },+ };+it.each([- ['type P80', 30_000, durationHistory, '50% complete', /Based on 8 completed user-task tasks \(avg: 45s, est: 1m 0s\)/],- ['type average', 60_000, { 'user-task': { avgDurationMs: 60_000, completed: 3 } }, '99% complete', /Based on 3 completed user-task tasks \(avg: 1m 0s, est: 1m 0s\)/],- ['overall P80', 60_000, { _overall: durationHistory._overall }, '50% complete', /Based on 20 completed all tasks tasks \(avg: 1m 30s, est: 2m 0s\)/],- ])('uses the %s duration fallback', (_label, elapsedMs, durations, progress, title) => {+ ['this provider/model/effort', 120_000, executionHistory, SLOW_RUN, '50% complete', /Based on 6 completed user-task runs on this provider, model and effort \(avg: 3m 0s, est: 4m 0s\)/],+ ['type P80', 30_000, durationHistory, {}, '50% complete', /Based on 8 completed user-task runs across all providers \(avg: 45s, est: 1m 0s\)/],+ ['type average', 60_000, { 'user-task': { avgDurationMs: 60_000, completed: 3 } }, {}, '99% complete', /Based on 3 completed user-task runs across all providers \(avg: 1m 0s, est: 1m 0s\)/],+ // A run whose provider/model IS named still falls back to the task type when+ // the execution history is another model's.+ ['type average for an unlearned model', 30_000, executionHistory, { providerId: 'claude', model: 'opus', effort: 'low' }, '50% complete', /Based on 8 completed user-task runs across all providers \(avg: 45s, est: 1m 0s\)/],+ ['overall P80', 60_000, { _overall: durationHistory._overall }, {}, '50% complete', /Based on 20 completed runs across all tasks \(avg: 1m 30s, est: 2m 0s\)/],+ ])('uses the %s duration bucket', (_label, elapsedMs, durations, metadata, progress, title) => {vi.useFakeTimers();vi.setSystemTime(now);render(<MemoryRouter>- <AgentCard agent={runningAt(elapsedMs)} durations={durations} />+ <AgentCard agent={runningAt(elapsedMs, metadata)} durations={durations} /></MemoryRouter>);diff --git a/client/src/components/cos/tabs/AgentRuntimeStatus.jsx b/client/src/components/cos/tabs/AgentRuntimeStatus.jsxindex fc9c6f3ead..f510b65ba5 100644--- a/client/src/components/cos/tabs/AgentRuntimeStatus.jsx+++ b/client/src/components/cos/tabs/AgentRuntimeStatus.jsx@@ -1,6 +1,7 @@import { Link } from 'react-router';import { Activity, Clock, Hourglass, MessageSquare, Skull, Terminal } from 'lucide-react';import { formatDateTime, formatDurationMs, formatMonthDay, formatTimeOfDay } from '../../../utils/formatters';+import { describeEstimateScope } from '../../../lib/cosDurationEstimate';const ETA_PRESENTATION = {inline: {@@ -65,7 +66,7 @@ export function AgentRuntimeStatus({{!inactive && durationEstimate ? (<spanclassName="flex items-center gap-1.5 text-gray-500 whitespace-nowrap"- title={`Based on ${durationEstimate.basedOn} completed ${durationEstimate.taskType} tasks (avg: ${formatDurationMs(durationEstimate.avgMs)}, est: ${formatDurationMs(durationEstimate.estimatedMs)})`}+ title={`Based on ${durationEstimate.basedOn} completed ${describeEstimateScope(durationEstimate)} (avg: ${formatDurationMs(durationEstimate.avgMs)}, est: ${formatDurationMs(durationEstimate.estimatedMs)})`}><Clock size={12} aria-hidden="true" className="shrink-0" /><span className="font-mono">{formatDurationMs(duration)}</span>diff --git a/client/src/components/cos/tabs/LearningTab.durations.test.jsx b/client/src/components/cos/tabs/LearningTab.durations.test.jsxnew file mode 100644index 0000000000..89e1a3a1ef--- /dev/null+++ b/client/src/components/cos/tabs/LearningTab.durations.test.jsx@@ -0,0 +1,76 @@+/**+ * Reserved-key handling in the duration table (#8001).+ *+ * `/api/cos/learning/durations` keeps real task types top-level and rides its+ * non-task-type aggregates on `_`-prefixed keys. The table used to skip only the+ * literal `_overall` and count rows as `Object.keys(durations).length - 1`, so the+ * execution-scoped maps added for this issue would have rendered as bogus+ * "task type" rows (with an empty duration, since they hold no `avgDurationMs`)+ * and inflated the count beside the heading.+ */++import { beforeEach, describe, expect, it, vi } from 'vitest';+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { MemoryRouter } from 'react-router';+import LearningTab from './LearningTab';++const api = vi.hoisted(() => ({+ getCosLearning: vi.fn(),+ getCosLearningPerformance: vi.fn(),+ getCosLearningSkipped: vi.fn(),+ getCosLearningDurations: vi.fn(),+ getCosLearningRouting: vi.fn(),+ getCosLearningConfidence: vi.fn(),+ getCosFeedbackStats: vi.fn(),+ getDismissedCosRecommendations: vi.fn(),+ resetCosTaskTypeLearning: vi.fn(),+}));++vi.mock('../../../services/api', () => api);+vi.mock('../../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));++const row = (avgDurationMs, completed) => ({+ avgDurationMs,+ avgDurationMin: Math.round(avgDurationMs / 60000),+ p80DurationMs: avgDurationMs,+ maxDurationMs: avgDurationMs,+ completed,+ successRate: 100,+});++describe('LearningTab — duration table reserved keys', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ api.getCosLearning.mockResolvedValue({ totals: { completed: 9, succeeded: 9, avgDurationMs: 60000 }, recommendations: [] });+ api.getCosLearningPerformance.mockResolvedValue({ topPerformers: [], needsAttention: [], skipped: [] });+ api.getCosLearningSkipped.mockResolvedValue({ skippedCount: 0, skippedTypes: [] });+ api.getCosLearningRouting.mockResolvedValue({ byModelTier: {} });+ api.getCosLearningConfidence.mockResolvedValue({+ levels: { high: [], medium: [], low: [], new: [] },+ thresholds: { highThreshold: 80, lowThreshold: 50, minSamples: 5 },+ summary: { high: 0, medium: 0, low: 0, new: 0, total: 0, requireApproval: 0 },+ });+ api.getCosFeedbackStats.mockResolvedValue({ total: 0 });+ api.getDismissedCosRecommendations.mockResolvedValue({ dismissed: [] });+ api.getCosLearningDurations.mockResolvedValue({+ 'self-improve:release-check': row(120000, 6),+ 'user-task': row(60000, 3),+ _overall: row(90000, 9),+ _byExecution: { 'self-improve:release-check|ollama|local-coder|low': row(480000, 4) },+ _byExecutionProviderModel: { 'self-improve:release-check|ollama|local-coder': row(480000, 4) },+ });+ });++ it('counts and lists only real task types, never a reserved aggregate', async () => {+ render(<MemoryRouter><LearningTab /></MemoryRouter>);+ await userEvent.click(await screen.findByText('Duration Estimates'));++ expect(screen.getByText('(2 task types)')).toBeInTheDocument();+ expect(screen.getByText('self-improve:release-check')).toBeInTheDocument();+ expect(screen.getByText('user-task')).toBeInTheDocument();+ for (const reserved of ['_overall', '_byExecution', '_byExecutionProviderModel']) {+ expect(screen.queryByText(reserved), `${reserved} is an aggregate, not a task type`).not.toBeInTheDocument();+ }+ });+});diff --git a/client/src/components/cos/tabs/LearningTab.jsx b/client/src/components/cos/tabs/LearningTab.jsxindex b6d931bd73..e881ed8f89 100644--- a/client/src/components/cos/tabs/LearningTab.jsx+++ b/client/src/components/cos/tabs/LearningTab.jsx@@ -239,8 +239,13 @@ export default function LearningTab() {// Memoize sorted durations to avoid re-sorting on each renderconst sortedDurations = useMemo(() => {if (!durations) return [];+ // `_`-prefixed keys are reserved aggregates, not task types: `_overall`, plus+ // the execution-scoped maps from #8001. Skipping the whole prefix (rather than+ // naming `_overall`) is what keeps a new reserved key out of this table —+ // `_byExecution` has no `avgDurationMs`, so it would render an empty row and+ // inflate the count beside it.return Object.entries(durations)- .filter(([key]) => key !== '_overall')+ .filter(([key]) => !key.startsWith('_')).sort((a, b) => b[1].avgDurationMs - a[1].avgDurationMs);}, [durations]);@@ -720,7 +725,7 @@ export default function LearningTab() {<Timer size={16} className="text-port-accent" /><span className="font-medium text-white">Duration Estimates</span><span className="text-xs text-gray-500">- ({Object.keys(durations).length - 1} task types)+ ({sortedDurations.length} task types)</span></button>{expandedSections.durations && (diff --git a/client/src/components/cos/tabs/TaskItem.jsx b/client/src/components/cos/tabs/TaskItem.jsxindex d74f441d08..2eb6f59e1d 100644--- a/client/src/components/cos/tabs/TaskItem.jsx+++ b/client/src/components/cos/tabs/TaskItem.jsx@@ -30,7 +30,7 @@ import ConfirmButtonPair from '../../ui/ConfirmButtonPair';import { useConfirmDelete } from '../../../hooks/useConfirmDelete';import Modal from '../../ui/Modal';import CollapsibleText from '../../ui/CollapsibleText';-import { extractCosTaskType } from '../../../lib/cosTaskType';+import { estimateCosDuration, describeEstimateScope } from '../../../lib/cosDurationEstimate';import InstancePicker from '../InstancePicker';import EffortSelect from '../EffortSelect';import RelaunchAgentModal from './RelaunchAgentModal';@@ -231,40 +231,28 @@ export default function TaskItem({ task, agent = null, liveOutput, isSystem, spa// Calculate duration estimate for pending tasks// Uses P80 estimate when available for more realistic time predictionsconst durationEstimate = useMemo(() => {- if (!durations || displayStatus !== 'pending') return null;-- // Queue reads return raw parsed tasks without taskType. Supply the queue- // source so this estimate stays in the same bucket the server records.- const taskType = extractCosTaskType({ ...task, taskType: task.taskType || taskSource });- const typeData = durations[taskType];- const overallData = durations._overall;-- if (typeData && typeData.avgDurationMin) {- const p80Min = typeData.p80DurationMs ? Math.round(typeData.p80DurationMs / 60000) : typeData.avgDurationMin;- return {- estimatedMin: p80Min,- avgMin: typeData.avgDurationMin,- basedOn: typeData.completed,- taskType,- successRate: typeData.successRate,- isTypeSpecific: true- };- }-- if (overallData && overallData.avgDurationMin) {- const p80Min = overallData.p80DurationMs ? Math.round(overallData.p80DurationMs / 60000) : overallData.avgDurationMin;- return {- estimatedMin: p80Min,- avgMin: overallData.avgDurationMin,- basedOn: overallData.completed,- taskType: 'all tasks',- successRate: overallData.successRate,- isTypeSpecific: false- };- }-- return null;- }, [durations, task, displayStatus]);+ if (displayStatus !== 'pending') return null;++ // The shared 4-rung cascade (#8001) — the same module `AgentCard` estimates+ // through, so a pending task and the agent it becomes agree. Queue reads+ // return raw parsed tasks without taskType, so supply the queue source to keep+ // this estimate in the same bucket the server records.+ //+ // A pending task already names the provider/model/effort it will run at, so+ // the estimate can be execution-scoped before the agent ever spawns.+ const estimate = estimateCosDuration({+ durations,+ task: { ...task, taskType: task.taskType || taskSource },+ agentMetadata: { providerId: taskProvider, model: taskModel, effort: taskEffort || null }+ });+ if (!estimate) return null;+ // This card renders whole minutes; the shared estimator answers in ms.+ return {+ ...estimate,+ estimatedMin: Math.round(estimate.estimatedMs / 60000),+ avgMin: Math.round(estimate.avgMs / 60000)+ };+ }, [durations, task, taskSource, taskProvider, taskModel, taskEffort, displayStatus]);const handleStatusChange = async (newStatus, blockedReasonText = '', successMessage = `Task marked as ${newStatus}`) => {const updates = { status: newStatus, type: taskSource };@@ -474,7 +462,7 @@ export default function TaskItem({ task, agent = null, liveOutput, isSystem, spa{durationEstimate && (<spanclassName="flex items-center gap-1 px-1.5 py-0.5 text-xs bg-port-accent/10 text-port-accent/80 rounded"- title={`Based on ${durationEstimate.basedOn} completed ${durationEstimate.taskType} tasks`}+ title={`Based on ${durationEstimate.basedOn} completed ${describeEstimateScope(durationEstimate)}`}><Timer size={10} aria-hidden="true" />{formatDurationMin(durationEstimate.estimatedMin, { approximate: true })}diff --git a/client/src/components/cos/tabs/TaskItem.test.jsx b/client/src/components/cos/tabs/TaskItem.test.jsxindex 43e0c83fbb..24e4ae5ba1 100644--- a/client/src/components/cos/tabs/TaskItem.test.jsx+++ b/client/src/components/cos/tabs/TaskItem.test.jsx@@ -39,6 +39,7 @@ describe('TaskItem task source', () => {};const durations = {'self-improve:security': {+ avgDurationMs: 120000,avgDurationMin: 2,p80DurationMs: 120000,completed: 5,@@ -48,10 +49,38 @@ describe('TaskItem task source', () => {render(<TaskItem task={scheduled} isSystem onRefresh={vi.fn()} providers={providers} durations={durations} />);- expect(screen.getByTitle('Based on 5 completed self-improve:security tasks')).toBeInTheDocument();+ expect(screen.getByTitle('Based on 5 completed self-improve:security runs across all providers')).toBeInTheDocument();expect(screen.getByText('~2m')).toBeInTheDocument();});+ // A pending task already names the provider/model/effort it will run at, so its+ // ETA can be execution-scoped before the agent spawns (#8001) — through the SAME+ // shared estimator `AgentCard` uses. Here the task-type average (2m) would be+ // four times too fast for the model this task is actually pinned to.+ it('prefers this task provider/model/effort history over the task-type average', () => {+ const pinned = {+ ...task,+ id: 'sys-security-local',+ description: '[Self-Improvement] security audit: fix exposed configuration',+ taskType: 'internal',+ metadata: { analysisType: 'security', provider: 'ollama', model: 'local-coder', effort: 'low' },+ };+ const durations = {+ 'self-improve:security': { avgDurationMs: 120000, avgDurationMin: 2, p80DurationMs: 120000, completed: 5, successRate: 100 },+ _byExecution: {+ 'self-improve:security|ollama|local-coder|low': { avgDurationMs: 480000, avgDurationMin: 8, p80DurationMs: 480000, completed: 4, successRate: 75 },+ },+ _byExecutionProviderModel: {+ 'self-improve:security|ollama|local-coder': { avgDurationMs: 480000, avgDurationMin: 8, p80DurationMs: 480000, completed: 4, successRate: 75 },+ },+ };++ render(<TaskItem task={pinned} isSystem onRefresh={vi.fn()} providers={providers} durations={durations} />);++ expect(screen.getByTitle('Based on 4 completed self-improve:security runs on this provider, model and effort')).toBeInTheDocument();+ expect(screen.getByText('~8m')).toBeInTheDocument();+ });+it('uses its queue source for an untyped raw task ETA', () => {const rawUserTask = {...task,@@ -59,13 +88,13 @@ describe('TaskItem task source', () => {description: 'Fix the queued task display',};const durations = {- 'user-task': { avgDurationMin: 3, p80DurationMs: 180000, completed: 4, successRate: 100 },- 'auto-fix': { avgDurationMin: 1, p80DurationMs: 60000, completed: 9, successRate: 100 },+ 'user-task': { avgDurationMs: 180000, avgDurationMin: 3, p80DurationMs: 180000, completed: 4, successRate: 100 },+ 'auto-fix': { avgDurationMs: 60000, avgDurationMin: 1, p80DurationMs: 60000, completed: 9, successRate: 100 },};render(<TaskItem task={rawUserTask} onRefresh={vi.fn()} providers={providers} durations={durations} />);- expect(screen.getByTitle('Based on 4 completed user-task tasks')).toBeInTheDocument();+ expect(screen.getByTitle('Based on 4 completed user-task runs across all providers')).toBeInTheDocument();expect(screen.getByText('~3m')).toBeInTheDocument();});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 60549914db..0f6999d6b4 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -144,6 +144,7 @@ grep -i "what you want to do" client/src/lib/README.md| `falVideoHandoff.js` | `buildFalH3MaxPrompt(prompt, negativePrompt)` composes the provider-neutral shot prompt fal's free MiniMax H3 Max tool is driven with; `FAL_H3_MAX_FREE_URL` and `FAL_H3_MAX_FREE_ALLOWANCE_NOTE` carry the tool URL and current vendor allowance copy. The free web allowance is deliberately a handoff, not the separately metered fal API. || `compareHelpers.js` | `equalByKeys(a, b, keys)` / `equalListByKeys(a, b, keys)` — typed key-based equality for `useAutoRefetch`'s `compare`. Keys are property names, dotted paths (`'context.running'`), or `(item) => value` accessors. The typed alternative to `sameJsonShape` when a monotonic timestamp or unrendered field would break stringify-equality dedup. || `consoleFilters.js` | `installConsoleFilters()` — drops a small allow-list of known-noise console strings (THREE.js `Clock` deprecation, expected WebGL `Context Lost.`) from `console.{warn,log,debug}`. Idempotent; auto-installed on import. Imported for its side effect from `main.jsx`. |+| `cosDurationEstimate.js` | Shared CoS ETA estimator for the agent and task cards: `estimateCosDuration({ durations, task, agentMetadata })` walks the `/api/cos/learning/durations` payload from the narrowest bucket outward — this run's provider+model+effort, then provider+model, then task type, then all tasks — and `describeEstimateScope(estimate)` names which rung answered for the tooltip. MIRRORS the key composition in `server/services/taskLearning/store.js`. || `cosSpawnWindow.js` | Re-export of the spawn-window settlement from the pure server leaf `server/lib/cosSpawnWindow.js`. A task keeps `status: 'pending'` for a beat after its agent registers as `running`, so a view rendering both lists must decide which side it belongs to (ACTIVE, until `SPAWN_CLAIM_GRACE_MS`). `GET /api/cos/tasks` already settles its payload, so most surfaces just read `task.spawning`; `cos/tabs/TasksTab.jsx` settles client-side because it also has the socket agent feed, which lands ahead of the next task refetch. || `cosTaskType.js` | CoS task-learning bucket resolver for ETA surfaces: `extractCosTaskType(task)` mirrors the server's metadata-first `extractTaskType` handling for live tasks and archived-agent projections, so `self-improve:*`, `user-task`, and fallback estimates use the same history bucket that recorded the run. || `diffLines.js` | `diffLineBlocks(oldText, newText)` → `{ blocks }` (`{ type: 'same', lines }` / `{ type: 'change', oldLines, newLines }`) — line-level Myers LCS with common prefix/suffix trim and a 4M-cell `LINE_DIFF_CELL_CAP` guard. The structural layer behind `HunkDiff` (collapse same-blocks to context, word-diff each change-block). |diff --git a/client/src/lib/cosDurationEstimate.js b/client/src/lib/cosDurationEstimate.jsnew file mode 100644index 0000000000..4e72029afb--- /dev/null+++ b/client/src/lib/cosDurationEstimate.js@@ -0,0 +1,131 @@+// Shared CoS duration/ETA estimator for the agent and task cards.+//+// MIRROR: keep the key composition aligned with server/services/taskLearning/store.js's+// `executionDurationKey()` / `executionKeyPrefix()`. The server owns the buckets;+// composing the same key here is what attaches a card's ETA to the historical runs+// that produced it — the same discipline `cosTaskType.js` follows for the task type.+//+// The cascade answers from the NARROWEST bucket with enough evidence, mirroring the+// server's `getTaskDurationEstimate` (#8001):+// 1. execution — this task type on THIS provider + model + effort+// 2. provider-model — same provider + model, any effort+// 3. task-type — today's behavior+// 4. overall — today's fallback+//+// The run's provider/model/effort is the largest single driver of wall-clock time, so+// a release check on a slow local model and the same check on a fast cloud model stop+// sharing one average that is wrong for both.+//+// No ETA arithmetic lives here: `/api/cos/learning/durations` publishes the per-effort+// buckets AND the provider+model rollup already summed through the server's own+// `calculateDurationETA`, so every rung below is a pure lookup.++import { extractCosTaskType } from './cosTaskType.js';++// Effort sentinel for a provider with no effort control — MIRRORS the server's+// EXECUTION_EFFORT_NONE. Absent effort is its own bucket, never a key ending in a+// bare separator that both `''` and `undefined` would collapse into.+export const EXECUTION_EFFORT_NONE = 'default';++const EXECUTION_KEY_SEPARATOR = '|';++// Minimum completions before an execution-scoped bucket outranks the broader+// task-type average — MIRRORS the server's MIN_EXECUTION_SAMPLES. One run of a+// specific provider/model/effort says less than a rich task-type history does.+export const MIN_EXECUTION_SAMPLES = 3;++const nonEmptyKeyPart = (value) => (typeof value === 'string' && value.trim() ? value.trim() : null);++/** `taskType|providerId|model`, or null when any part is missing. Pure. */+export function executionProviderModelKey({ taskType, providerId, model } = {}) {+ const parts = [nonEmptyKeyPart(taskType), nonEmptyKeyPart(providerId), nonEmptyKeyPart(model)];+ if (parts.some((part) => part === null)) return null;+ return parts.join(EXECUTION_KEY_SEPARATOR);+}++/** `taskType|providerId|model|effort`, or null when any required part is missing. Pure. */+export function executionDurationKey({ taskType, providerId, model, effort } = {}) {+ const prefix = executionProviderModelKey({ taskType, providerId, model });+ if (prefix === null) return null;+ return `${prefix}${EXECUTION_KEY_SEPARATOR}${nonEmptyKeyPart(effort) ?? EXECUTION_EFFORT_NONE}`;+}++const hasDuration = (row) => !!row && !!row.avgDurationMs;++const shape = (row, { taskType, basis }) => ({+ estimatedMs: row.p80DurationMs || row.avgDurationMs,+ avgMs: row.avgDurationMs,+ basedOn: row.completed,+ successRate: row.successRate,+ taskType,+ basis,+ // Kept for the existing call sites: true for anything sharper than the+ // all-tasks average, which is what the cards gate their per-type chips on.+ isTypeSpecific: basis !== 'overall',+});++const BASIS_SCOPE = {+ execution: 'runs on this provider, model and effort',+ 'provider-model': 'runs on this provider and model',+ 'task-type': 'runs across all providers',+};++/**+ * Human-readable phrase for the history an estimate was drawn from, for the+ * cards' tooltips: which task type, and what NARROWED it. Reads as the object of+ * "Based on N completed …", so the user can tell an execution-specific estimate+ * from one averaged over every provider. Pure.+ */+export function describeEstimateScope(estimate) {+ if (!estimate) return '';+ const scope = BASIS_SCOPE[estimate.basis];+ return scope ? `${estimate.taskType} ${scope}` : 'runs across all tasks';+}++/**+ * Resolve a duration estimate for one task/agent from the `/durations` payload.+ *+ * @param {Object} args+ * @param {Object|null} args.durations - the `/api/cos/learning/durations` payload+ * @param {Object|null} args.task - task-shaped input for `extractCosTaskType`+ * @param {Object|null} [args.agentMetadata] - the run's `metadata` (providerId / model / effort)+ * @returns {{estimatedMs:number, avgMs:number, basedOn:number, successRate:number|undefined,+ * taskType:string, basis:string, isTypeSpecific:boolean}|null} null when nothing is learned yet+ */+export function estimateCosDuration({ durations, task, agentMetadata = null } = {}) {+ if (!durations) return null;++ const taskType = extractCosTaskType(task);+ const identity = {+ taskType,+ providerId: agentMetadata?.providerId,+ model: agentMetadata?.model,+ // `?? null` (not `||`): a provider with no effort control reports a genuinely+ // absent effort, which the key builder maps to its own sentinel.+ effort: agentMetadata?.effort ?? null,+ };++ // Rung 1 — this exact provider/model/effort.+ const exactKey = executionDurationKey(identity);+ const exact = exactKey ? durations._byExecution?.[exactKey] : null;+ if (hasDuration(exact) && exact.completed >= MIN_EXECUTION_SAMPLES) {+ return shape(exact, { taskType, basis: 'execution' });+ }++ // Rung 2 — same provider + model, summed across effort levels by the server.+ const rollupKey = executionProviderModelKey(identity);+ const rollup = rollupKey ? durations._byExecutionProviderModel?.[rollupKey] : null;+ if (hasDuration(rollup) && rollup.completed >= MIN_EXECUTION_SAMPLES) {+ return shape(rollup, { taskType, basis: 'provider-model' });+ }++ // Rung 3 — this task type, whatever it ran on.+ const typeData = durations[taskType];+ if (hasDuration(typeData)) return shape(typeData, { taskType, basis: 'task-type' });++ // Rung 4 — the overall average.+ const overallData = durations._overall;+ if (hasDuration(overallData)) return shape(overallData, { taskType: 'all tasks', basis: 'overall' });++ return null;+}diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 012297bf7c..e0d9d0c7e7 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -111,6 +111,7 @@ export * from './clipboard.js';export * from './effortCostEstimate.js';export * from './compareHelpers.js';export * from './consoleFilters.js';+export * from './cosDurationEstimate.js';export * from './cosSpawnWindow.js';export * from './cosTaskType.js';export * from './diffLines.js';diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 48c50fa42a..58f3c513c7 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -595,6 +595,29 @@ async function runAgentSpawn(task) {// separate condition the provider reports for itself. All we do is raise the// estimate and say so.//+ // Task-level OpenCode/Ollama generation controls override provider defaults+ // for this one run. The child-environment composer turns these into the+ // dynamic `agent.build` config instead of mutating saved provider state.+ const requestedProvider = applyTaskGenerationOverrides(provider, task.metadata);+ // Ollama 400s the whole request when a model that never implements thinking+ // is asked to think, so a non-reasoning local model dispatched at any effort+ // level dies on its first turn with exit 1 and no output. Resolved here,+ // once, on the provider EVERY spawn path shares — so the two carriers of the+ // level (the `--effort` argv and OpenCode's `agent.*.reasoningEffort` config)+ // drop it together. Resolve task-over-provider defaults before recording the+ // run so the registered effort and every launch path use the same value.+ // The argv builders no-op it for providers without an effort control.+ //+ // Resolved BEFORE the duration estimate below (#8001): that lookup keys off+ // the effort this run will actually execute at, and the learning store records+ // the same post-drop `taskEffort` through `buildAgentRegistration`. Reading a+ // pre-drop level here would look up a bucket nothing ever writes.+ const { provider: runProvider, effort: taskEffort } = await dropUnsupportedOllamaThinking(+ requestedProvider,+ selectedModel,+ requestedProvider.effort || null,+ );+// Cloud runs take no async hop at all: `localEndpointOfProvider` answers null// for anything not on this machine, and `planLocalPromptBudget` is skipped.const localEndpoint = localEndpointOfProvider(provider);@@ -602,12 +625,20 @@ async function runAgentSpawn(task) {? planLocalPromptBudget({prompt,endpoint: localEndpoint,- // The learned per-task-type average — the estimate being raised. A+ // The learned average for THIS run's execution identity — task type ×+ // provider × model × effort, falling outward to the plain task-type+ // average when that bucket is still thin (#8001). The identity matters+ // most for exactly this caller: the estimate being raised is a local+ // model's, and a cloud run of the same task type is no guide to it. A// dynamic import for the same reason the workspace snapshot above uses// one: it keeps the task-learning graph out of this hot module's load// path, and a failed read means "nothing learned", not "zero".baseDurationMs: await import('./taskLearning.js')- .then((tl) => tl.getTaskDurationEstimate(task.description))+ .then((tl) => tl.getTaskDurationEstimate(task.description, {+ providerId: provider.id,+ model: selectedModel,+ effort: taskEffort,+ })).then((estimate) => estimate?.estimatedDurationMs ?? null).catch(() => null),})@@ -700,23 +731,6 @@ async function runAgentSpawn(task) {: resolveRepoForgeTarget(workspacePath),sourceWorkspace ? capturePrimaryCheckoutState(sourceWorkspace) : null,]);- // Task-level OpenCode/Ollama generation controls override provider defaults- // for this one run. The child-environment composer turns these into the- // dynamic `agent.build` config instead of mutating saved provider state.- const requestedProvider = applyTaskGenerationOverrides(provider, task.metadata);- // Ollama 400s the whole request when a model that never implements thinking- // is asked to think, so a non-reasoning local model dispatched at any effort- // level dies on its first turn with exit 1 and no output. Resolved here,- // once, on the provider EVERY spawn path shares — so the two carriers of the- // level (the `--effort` argv and OpenCode's `agent.*.reasoningEffort` config)- // drop it together. Resolve task-over-provider defaults before recording the- // run so the registered effort and every launch path use the same value.- // The argv builders no-op it for providers without an effort control.- const { provider: runProvider, effort: taskEffort } = await dropUnsupportedOllamaThinking(- requestedProvider,- selectedModel,- requestedProvider.effort || null,- );await registerAgent(agentId, task.id, buildAgentRegistration({task,provider,diff --git a/server/services/taskLearning/durations.js b/server/services/taskLearning/durations.jsindex 6331a2c714..7e4f02348e 100644--- a/server/services/taskLearning/durations.js+++ b/server/services/taskLearning/durations.js@@ -2,40 +2,137 @@* Task Learning — duration estimation** Read-only duration lookups used for ETA display and queue-completion- * estimates. Derived entirely from the persisted byTaskType / totals- * duration stats produced by the metrics module.+ * estimates. Derived entirely from the persisted byTaskType / byTaskTypeExecution+ * / totals duration stats produced by the metrics module.*/-import { loadLearningData, extractTaskType } from './store.js';+import {+ loadLearningData,+ extractTaskType,+ calculateDurationETA,+ executionDurationKey,+ executionKeyPrefix,+ executionKeyMatchesPrefix+} from './store.js';++// Minimum completions before an execution-scoped bucket (issue #8001) is trusted+// over the broader task-type average. Higher than the task-type bar (2) on+// purpose: this dimension is far more granular, so one or two samples of a+// specific provider/model/effort say less than a rich task-type history does.+const MIN_EXECUTION_SAMPLES = 3;+const MIN_TASK_TYPE_SAMPLES = 2;+const MIN_OVERALL_SAMPLES = 3;++const confidenceFor = (completed) => (completed >= 10 ? 'high' : completed >= 5 ? 'medium' : 'low');++/**+ * Sum a set of execution buckets into one aggregate, re-deriving the ETA stats+ * from the RAW success totals via `calculateDurationETA` rather than averaging+ * already-averaged numbers (which would weight a 1-run bucket like a 50-run one).+ * Pure. Returns null when the set is empty.+ *+ * Shared by the rung-2 lookup below and the `_byExecutionProviderModel` rollup+ * `getAllTaskDurations` publishes, so the server's own reader and the payload the+ * client estimates from cannot drift.+ */+export function aggregateExecutionBuckets(buckets) {+ const list = (buckets || []).filter(Boolean);+ if (list.length === 0) return null;+ const agg = list.reduce((acc, m) => ({+ completed: acc.completed + (m.completed || 0),+ succeeded: acc.succeeded + (m.succeeded || 0),+ failed: acc.failed + (m.failed || 0),+ totalDurationMs: acc.totalDurationMs + (m.totalDurationMs || 0),+ successDurationMs: acc.successDurationMs + (m.successDurationMs || 0),+ successMaxDurationMs: Math.max(acc.successMaxDurationMs, m.successMaxDurationMs || 0)+ }), { completed: 0, succeeded: 0, failed: 0, totalDurationMs: 0, successDurationMs: 0, successMaxDurationMs: 0 });+ Object.assign(agg, calculateDurationETA(agg));+ agg.successRate = agg.completed > 0 ? Math.round((agg.succeeded / agg.completed) * 100) : 0;+ return agg;+}++/** Shape one metrics bucket as a duration estimate. Pure. */+function toEstimate(metrics, { taskType, basis }) {+ return {+ estimatedDurationMs: metrics.avgDurationMs,+ estimatedDurationMin: Math.round(metrics.avgDurationMs / 60000),+ p80DurationMs: metrics.p80DurationMs || metrics.avgDurationMs,+ confidence: confidenceFor(metrics.completed),+ basedOn: metrics.completed,+ taskType,+ basis,+ successRate: metrics.successRate+ };+}++/** The bulk-payload projection of one bucket. Pure. */+function toDurationRow(metrics) {+ return {+ avgDurationMs: metrics.avgDurationMs,+ avgDurationMin: Math.round(metrics.avgDurationMs / 60000),+ p80DurationMs: metrics.p80DurationMs || metrics.avgDurationMs,+ maxDurationMs: metrics.maxDurationMs || metrics.avgDurationMs,+ completed: metrics.completed,+ successRate: metrics.successRate+ };+}/**- * Get estimated duration for a task based on historical averages+ * Get estimated duration for a task based on historical averages.+ *+ * Answers from the NARROWEST bucket that has enough evidence, cascading outward+ * (issue #8001): the exact provider/model/effort this run uses → the same+ * provider+model at any effort → the task type → the overall average. The run's+ * execution identity is the largest single driver of wall-clock time, so a+ * release check on a slow local model and the same check on a fast cloud model+ * stop sharing one meaningless average.+ *+ * `basis` names which rung answered, so the UI can say what it estimated from.+ ** @param {string} taskDescription - The task description to analyze- * @returns {Object} Duration estimate with confidence+ * @param {{ providerId?: string, model?: string, effort?: string|null }} [execution]+ * The run's concrete execution identity. Omitted (a legacy string-only call)+ * skips both execution rungs and behaves exactly as this function always has.+ * @returns {Object} Duration estimate with confidence and basis*/-export async function getTaskDurationEstimate(taskDescription) {+export async function getTaskDurationEstimate(taskDescription, { providerId, model, effort } = {}) {const data = await loadLearningData();// Extract task type from descriptionconst taskType = extractTaskType({ description: taskDescription });+ const executionBuckets = data.byTaskTypeExecution || {};- const metrics = data.byTaskType[taskType];+ // Rung 1 — this exact provider/model/effort.+ const exactKey = executionDurationKey({ taskType, providerId, model, effort });+ const exact = exactKey ? executionBuckets[exactKey] : null;+ if (exact && exact.completed >= MIN_EXECUTION_SAMPLES) {+ return toEstimate(exact, { taskType, basis: 'execution' });+ }- // If we have data for this specific task type- if (metrics && metrics.completed >= 2) {- return {- estimatedDurationMs: metrics.avgDurationMs,- estimatedDurationMin: Math.round(metrics.avgDurationMs / 60000),- p80DurationMs: metrics.p80DurationMs || metrics.avgDurationMs,- confidence: metrics.completed >= 10 ? 'high' : metrics.completed >= 5 ? 'medium' : 'low',- basedOn: metrics.completed,- taskType,- successRate: metrics.successRate- };+ // Rung 2 — same provider+model, summed across every effort level. A model's+ // throughput dominates the estimate; effort refines it. So once effort has too+ // little history of its own, the provider+model history is still far sharper+ // than lumping every provider's runs of this task type together.+ const prefix = executionKeyPrefix({ taskType, providerId, model });+ if (prefix) {+ const providerModel = aggregateExecutionBuckets(+ Object.entries(executionBuckets)+ .filter(([key]) => executionKeyMatchesPrefix(key, prefix))+ .map(([, metrics]) => metrics)+ );+ if (providerModel && providerModel.completed >= MIN_EXECUTION_SAMPLES) {+ return toEstimate(providerModel, { taskType, basis: 'provider-model' });+ }+ }++ // Rung 3 — data for this specific task type, whatever it ran on.+ const metrics = data.byTaskType[taskType];+ if (metrics && metrics.completed >= MIN_TASK_TYPE_SAMPLES) {+ return toEstimate(metrics, { taskType, basis: 'task-type' });}- // Fall back to overall average- if (data.totals.completed >= 3) {+ // Rung 4 — fall back to overall average+ if (data.totals.completed >= MIN_OVERALL_SAMPLES) {return {estimatedDurationMs: data.totals.avgDurationMs,estimatedDurationMin: Math.round(data.totals.avgDurationMs / 60000),@@ -43,6 +140,7 @@ export async function getTaskDurationEstimate(taskDescription) {confidence: 'low',basedOn: data.totals.completed,taskType: 'all',+ basis: 'overall',successRate: Math.round((data.totals.succeeded / data.totals.completed) * 100)};}@@ -54,12 +152,20 @@ export async function getTaskDurationEstimate(taskDescription) {confidence: 'none',basedOn: 0,taskType: null,+ basis: null,successRate: null};}/**- * Get all task type durations for bulk lookup+ * Get all task type durations for bulk lookup.+ *+ * Task types stay TOP-LEVEL entries so the response shape is backward compatible;+ * the aggregates that are not task types ride under reserved `_`-prefixed keys+ * (`_overall`, plus the execution dimension's `_byExecution` /+ * `_byExecutionProviderModel` from issue #8001). Every consumer that enumerates+ * task types must skip reserved keys, not just `_overall`.+ ** @returns {Object} Map of task type to duration info*/export async function getAllTaskDurations() {@@ -69,29 +175,44 @@ export async function getAllTaskDurations() {for (const [taskType, metrics] of Object.entries(data.byTaskType)) {if (metrics.completed >= 1) {- const p80 = metrics.p80DurationMs || metrics.avgDurationMs;- durations[taskType] = {- avgDurationMs: metrics.avgDurationMs,- avgDurationMin: Math.round(metrics.avgDurationMs / 60000),- p80DurationMs: p80,- maxDurationMs: metrics.maxDurationMs || metrics.avgDurationMs,- completed: metrics.completed,- successRate: metrics.successRate- };+ durations[taskType] = toDurationRow(metrics);}}// Add overall averageif (data.totals.completed >= 1) {- const overallP80 = data.totals.p80DurationMs || data.totals.avgDurationMs;- durations._overall = {- avgDurationMs: data.totals.avgDurationMs,- avgDurationMin: Math.round(data.totals.avgDurationMs / 60000),- p80DurationMs: overallP80,+ durations._overall = toDurationRow({+ ...data.totals,maxDurationMs: data.totals.maxDurationMs || data.totals.avgDurationMs,- completed: data.totals.completed,successRate: Math.round((data.totals.succeeded / data.totals.completed) * 100)- };+ });+ }++ // Execution-scoped buckets (issue #8001), keyed by `executionDurationKey`, plus+ // the provider+model rollup across effort levels. The rollup is published rather+ // than left to the client: it is summed from the RAW success totals through the+ // same `calculateDurationETA` the server's own cascade uses, so the client+ // estimator is a pure lookup and cannot re-derive the ETA math differently.+ const executionBuckets = data.byTaskTypeExecution || {};+ const byExecution = {};+ const providerModelGroups = new Map();+ for (const [key, metrics] of Object.entries(executionBuckets)) {+ if (!metrics || (metrics.completed || 0) < 1) continue;+ byExecution[key] = toDurationRow(metrics);+ // The key is `taskType|providerId|model|effort` — everything but the effort+ // segment is the rollup identity.+ const prefix = key.slice(0, key.lastIndexOf('|'));+ if (!prefix) continue;+ if (!providerModelGroups.has(prefix)) providerModelGroups.set(prefix, []);+ providerModelGroups.get(prefix).push(metrics);+ }+ // Published only when there is something in them, the same discipline `_overall`+ // follows — an install with no learned history still answers a bare `{}`.+ if (Object.keys(byExecution).length > 0) {+ durations._byExecution = byExecution;+ durations._byExecutionProviderModel = Object.fromEntries(+ [...providerModelGroups].map(([prefix, buckets]) => [prefix, toDurationRow(aggregateExecutionBuckets(buckets))])+ );}return durations;diff --git a/server/services/taskLearning/durations.test.js b/server/services/taskLearning/durations.test.jsindex 14fb9210bc..ab0f8a4150 100644--- a/server/services/taskLearning/durations.test.js+++ b/server/services/taskLearning/durations.test.js@@ -74,7 +74,7 @@ describe('durations.getTaskDurationEstimate', () => {const est = await getTaskDurationEstimate('something brand new');expect(est).toEqual({estimatedDurationMs: null, estimatedDurationMin: null,- confidence: 'none', basedOn: 0, taskType: null, successRate: null,+ confidence: 'none', basedOn: 0, taskType: null, basis: null, successRate: null,});});});diff --git a/server/services/taskLearning/executionDurations.test.js b/server/services/taskLearning/executionDurations.test.jsnew file mode 100644index 0000000000..7fea0dba07--- /dev/null+++ b/server/services/taskLearning/executionDurations.test.js@@ -0,0 +1,242 @@+/**+ * Execution-scoped duration buckets (issue #8001).+ *+ * The ETA used to average a task type across every provider, model and effort it+ * had ever run on, so a `self-improve:release-check` on a slow local model and the+ * same check on a fast cloud model shared one number that was wrong for both.+ * These tests pin the two halves of the fix at their real boundaries: what+ * `recordTaskCompletion` banks, and what `getTaskDurationEstimate` /+ * `getAllTaskDurations` hand back.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('./store.js', async (importActual) => {+ const actual = await importActual();+ return {+ ...actual,+ loadLearningData: vi.fn(),+ saveLearningData: vi.fn(async () => {}),+ emitLog: vi.fn()+ };+});++import { recordTaskCompletion } from './metrics.js';+import { getTaskDurationEstimate, getAllTaskDurations } from './durations.js';+import { loadLearningData, saveLearningData, executionDurationKey, EXECUTION_EFFORT_NONE } from './store.js';++const emptyData = () => ({+ version: 2,+ byTaskType: {},+ byTaskTypeExecution: {},+ byModelTier: {},+ errorPatterns: {},+ failureSignatures: {},+ routingAccuracy: {},+ environmentalFailures: {},+ correlationWindow: [],+ totals: { completed: 0, succeeded: 0, failed: 0, totalDurationMs: 0, avgDurationMs: 0 }+});++const TASK = { id: 't1', description: '[self-improvement] release-check - verify the release', taskType: 'scheduled' };++const agentOn = ({ providerId = 'ollama', model = 'local-coder', effort = 'low', duration, errorCategory = null } = {}) => ({+ id: 'agent-x',+ startedAt: '2026-09-01T10:00:00.000Z',+ completedAt: '2026-09-01T10:10:00.000Z',+ metadata: {+ providerId,+ model,+ effort,+ modelTier: 'user-specified',+ taskDescription: TASK.description+ },+ result: {+ success: !errorCategory,+ duration,+ ...(errorCategory ? { errorAnalysis: { category: errorCategory, origin: 'provider' } } : {})+ }+});++/** Run N completions through the recorder against one accumulating data object. */+async function record(agents) {+ const data = emptyData();+ loadLearningData.mockResolvedValue(data);+ for (const agent of agents) await recordTaskCompletion(agent, TASK);+ // Every write lands on the same object the loader handed back.+ return saveLearningData.mock.calls.at(-1)?.[0] ?? data;+}++beforeEach(() => {+ vi.clearAllMocks();+});++describe('recordTaskCompletion — execution-scoped duration buckets', () => {+ it('keeps the same task type on two different models in two buckets', async () => {+ const data = await record([+ agentOn({ model: 'local-coder', duration: 600_000 }),+ agentOn({ model: 'local-coder', duration: 600_000 }),+ agentOn({ model: 'local-coder', duration: 600_000 }),+ agentOn({ providerId: 'claude', model: 'opus', duration: 60_000 }),+ agentOn({ providerId: 'claude', model: 'opus', duration: 60_000 }),+ agentOn({ providerId: 'claude', model: 'opus', duration: 60_000 })+ ]);++ const slow = executionDurationKey({ taskType: 'self-improve:release-check', providerId: 'ollama', model: 'local-coder', effort: 'low' });+ const fast = executionDurationKey({ taskType: 'self-improve:release-check', providerId: 'claude', model: 'opus', effort: 'low' });+ expect(Object.keys(data.byTaskTypeExecution)).toEqual([slow, fast]);+ expect(data.byTaskTypeExecution[slow].avgDurationMs).toBe(600_000);+ expect(data.byTaskTypeExecution[fast].avgDurationMs).toBe(60_000);++ // The whole point: two runs of ONE task type, two different estimates —+ // the single `byTaskType` average is 330s, which describes neither.+ expect(data.byTaskType['self-improve:release-check'].avgDurationMs).toBe(330_000);+ loadLearningData.mockResolvedValue(data);+ const onSlow = await getTaskDurationEstimate(TASK.description, { providerId: 'ollama', model: 'local-coder', effort: 'low' });+ const onFast = await getTaskDurationEstimate(TASK.description, { providerId: 'claude', model: 'opus', effort: 'low' });+ expect(onSlow.estimatedDurationMs).toBe(600_000);+ expect(onFast.estimatedDurationMs).toBe(60_000);+ expect(onSlow.basis).toBe('execution');+ });++ it('banks only successful durations, matching the byTaskType ETA rule', async () => {+ const data = await record([+ agentOn({ duration: 60_000 }),+ // A task-level failure: it counts as a completion and dents the rate, but a+ // long error loop must not drag the ETA up.+ { ...agentOn({ duration: 3_600_000 }), result: { success: false, duration: 3_600_000 } }+ ]);+ const key = executionDurationKey({ taskType: 'self-improve:release-check', providerId: 'ollama', model: 'local-coder', effort: 'low' });+ expect(data.byTaskTypeExecution[key]).toMatchObject({ completed: 2, succeeded: 1, failed: 1, avgDurationMs: 60_000 });+ });++ it('records no execution bucket for an environmental failure', async () => {+ const data = await record([agentOn({ duration: 900_000, errorCategory: 'rate-limit' })]);+ expect(data.byTaskTypeExecution, 'an outage must teach the estimator nothing').toEqual({});+ expect(data.byTaskType, 'the existing #2618 gate still holds too').toEqual({});+ expect(data.environmentalFailures['rate-limit'].count).toBe(1);+ });++ it('gives an absent effort its own sentinel bucket, never merged with a real level', async () => {+ const data = await record([+ agentOn({ effort: null, duration: 100_000 }),+ agentOn({ effort: 'high', duration: 900_000 })+ ]);+ const base = { taskType: 'self-improve:release-check', providerId: 'ollama', model: 'local-coder' };+ const none = executionDurationKey({ ...base, effort: null });+ expect(none).toMatch(new RegExp(`\\|${EXECUTION_EFFORT_NONE}$`));+ expect(data.byTaskTypeExecution[none].completed).toBe(1);+ expect(data.byTaskTypeExecution[executionDurationKey({ ...base, effort: 'high' })].completed).toBe(1);+ });++ it('skips the write when the run never recorded a provider or model', async () => {+ const data = await record([+ agentOn({ providerId: null, duration: 60_000 }),+ agentOn({ model: '', duration: 60_000 })+ ]);+ expect(data.byTaskTypeExecution, 'a partial key would merge unlike runs').toEqual({});+ expect(data.byTaskType['self-improve:release-check'].completed, 'the task-type bucket is unaffected').toBe(2);+ });+});++describe('getTaskDurationEstimate — cascade', () => {+ const identity = { providerId: 'ollama', model: 'local-coder', effort: 'low' };+ const bucket = (completed, avgDurationMs) => ({+ completed, succeeded: completed, failed: 0,+ totalDurationMs: avgDurationMs * completed,+ successDurationMs: avgDurationMs * completed,+ successMaxDurationMs: avgDurationMs,+ avgDurationMs, maxDurationMs: avgDurationMs, p80DurationMs: avgDurationMs, successRate: 100+ });+ const key = (effort) => executionDurationKey({ taskType: 'self-improve:release-check', ...identity, effort });++ const data = (byTaskTypeExecution, byTaskType = {}, totals = { completed: 0, succeeded: 0, failed: 0, avgDurationMs: 0 }) => ({+ ...emptyData(), byTaskTypeExecution, byTaskType, totals+ });++ it('answers from the exact provider/model/effort bucket once it has 3 completions', async () => {+ loadLearningData.mockResolvedValue(data(+ { [key('low')]: bucket(3, 500_000) },+ { 'self-improve:release-check': bucket(50, 90_000) }+ ));+ const est = await getTaskDurationEstimate(TASK.description, identity);+ expect(est).toMatchObject({ basis: 'execution', estimatedDurationMs: 500_000, basedOn: 3 });+ });++ it('falls outward to the provider+model rollup when this effort is still thin', async () => {+ // Two efforts, two samples each — neither reaches the bar alone, but the same+ // provider+model has four completions and is still far sharper than the+ // all-providers average.+ loadLearningData.mockResolvedValue(data(+ { [key('low')]: bucket(2, 400_000), [key('high')]: bucket(2, 600_000) },+ { 'self-improve:release-check': bucket(50, 90_000) }+ ));+ const est = await getTaskDurationEstimate(TASK.description, identity);+ expect(est).toMatchObject({ basis: 'provider-model', basedOn: 4 });+ // Re-derived from the RAW success totals, not an average of averages.+ expect(est.estimatedDurationMs).toBe(500_000);+ });++ it('ignores another provider/model at the same task type', async () => {+ loadLearningData.mockResolvedValue(data(+ { [executionDurationKey({ taskType: 'self-improve:release-check', providerId: 'claude', model: 'opus', effort: 'low' })]: bucket(9, 60_000) },+ { 'self-improve:release-check': bucket(50, 90_000) }+ ));+ const est = await getTaskDurationEstimate(TASK.description, identity);+ expect(est).toMatchObject({ basis: 'task-type', estimatedDurationMs: 90_000 });+ });++ it('falls to the task type, then to the overall average', async () => {+ loadLearningData.mockResolvedValue(data({}, { 'self-improve:release-check': bucket(2, 90_000) }));+ expect(await getTaskDurationEstimate(TASK.description, identity)).toMatchObject({ basis: 'task-type' });++ loadLearningData.mockResolvedValue(data(+ { [key('low')]: bucket(2, 400_000) },+ { 'self-improve:release-check': bucket(1, 90_000) },+ { completed: 6, succeeded: 3, failed: 3, avgDurationMs: 200_000 }+ ));+ expect(await getTaskDurationEstimate(TASK.description, identity)).toMatchObject({+ basis: 'overall', taskType: 'all', estimatedDurationMs: 200_000+ });+ });++ it('is unchanged for a legacy string-only call', async () => {+ // A rich execution bucket exists, but a caller that never named its run must+ // not silently start estimating from it.+ loadLearningData.mockResolvedValue(data(+ { [key('low')]: bucket(20, 500_000) },+ { 'self-improve:release-check': bucket(12, 90_000) }+ ));+ expect(await getTaskDurationEstimate(TASK.description)).toMatchObject({+ basis: 'task-type', estimatedDurationMs: 90_000, confidence: 'high', basedOn: 12+ });+ });+});++describe('getAllTaskDurations — reserved keys', () => {+ it('publishes the execution maps under reserved keys, leaving task types top-level', async () => {+ const lowKey = executionDurationKey({ taskType: 'self-improve:release-check', providerId: 'ollama', model: 'local-coder', effort: 'low' });+ const highKey = executionDurationKey({ taskType: 'self-improve:release-check', providerId: 'ollama', model: 'local-coder', effort: 'high' });+ loadLearningData.mockResolvedValue({+ ...emptyData(),+ byTaskType: { 'self-improve:release-check': { completed: 4, avgDurationMs: 90_000, p80DurationMs: 90_000, maxDurationMs: 90_000, successRate: 100 } },+ byTaskTypeExecution: {+ [lowKey]: { completed: 2, succeeded: 2, totalDurationMs: 800_000, successDurationMs: 800_000, successMaxDurationMs: 400_000, avgDurationMs: 400_000, maxDurationMs: 400_000, p80DurationMs: 400_000, successRate: 100 },+ [highKey]: { completed: 2, succeeded: 2, totalDurationMs: 1_200_000, successDurationMs: 1_200_000, successMaxDurationMs: 600_000, avgDurationMs: 600_000, maxDurationMs: 600_000, p80DurationMs: 600_000, successRate: 100 }+ },+ totals: { completed: 4, succeeded: 4, failed: 0, totalDurationMs: 2_000_000, avgDurationMs: 500_000 }+ });++ const out = await getAllTaskDurations();+ expect(Object.keys(out).filter((k) => !k.startsWith('_')), 'only real task types are top-level')+ .toEqual(['self-improve:release-check']);+ expect(out._byExecution[lowKey]).toMatchObject({ avgDurationMs: 400_000, completed: 2 });+ expect(out._byExecutionProviderModel['self-improve:release-check|ollama|local-coder'])+ .toMatchObject({ avgDurationMs: 500_000, completed: 4 });+ });++ it('stays a bare empty payload on an install with no history', async () => {+ loadLearningData.mockResolvedValue(emptyData());+ expect(await getAllTaskDurations()).toEqual({});+ });+});diff --git a/server/services/taskLearning/metrics.js b/server/services/taskLearning/metrics.jsindex 2ffdb16ab1..787cf87fe7 100644--- a/server/services/taskLearning/metrics.js+++ b/server/services/taskLearning/metrics.js@@ -24,6 +24,7 @@ import {recurrenceMilestoneReached,appendRecentOutcome,computeWindowedStats,+ executionDurationKey,DEFAULT_WINDOW_MAX_COUNT,DEFAULT_WINDOW_MAX_AGE_MS,ENVIRONMENTAL_ERROR_CATEGORIES@@ -52,6 +53,56 @@ export { ENVIRONMENTAL_ERROR_CATEGORIES };* the same way. Additive + back-compat: tolerates a learning.json that predates* the `environmentalFailures` key. No-op when the failure carries no category.*/+/**+ * Fold one completion's duration into its execution-scoped bucket (issue #8001).+ * Pure — mutates and returns `data`. A null `key` (the run's provider or model was+ * never recorded) is a no-op: a partial key would merge unlike runs into one+ * estimate, which is exactly the blur this dimension exists to remove.+ *+ * Mirrors the `byTaskType` bucket's duration shape and reuses `calculateDurationETA`,+ * so the two dimensions can never disagree about what an ETA is. Deliberately carries+ * NO `recentOutcomes` ring — this bucket feeds the ETA only; the LI success-rate+ * signal keeps reading `byTaskType`.+ *+ * The caller applies the environmental-failure gate (#2618) before reaching here, so+ * an outage teaches this dimension nothing either.+ */+export function recordExecutionDuration(data, { key, success, duration = 0, at } = {}) {+ if (!key) return data;+ if (!data.byTaskTypeExecution) data.byTaskTypeExecution = {};+ if (!data.byTaskTypeExecution[key]) {+ data.byTaskTypeExecution[key] = {+ completed: 0,+ succeeded: 0,+ failed: 0,+ totalDurationMs: 0,+ successDurationMs: 0,+ successMaxDurationMs: 0,+ avgDurationMs: 0,+ maxDurationMs: 0,+ p80DurationMs: 0,+ lastCompleted: null,+ successRate: 0+ };+ }+ const metrics = data.byTaskTypeExecution[key];+ metrics.completed++;+ if (success) {+ metrics.succeeded++;+ // Success-only durations drive the ETA — a failed agent often loops long in an+ // error path and would skew the estimate (same rule as `byTaskType`).+ metrics.successDurationMs = (metrics.successDurationMs || 0) + duration;+ metrics.successMaxDurationMs = Math.max(metrics.successMaxDurationMs || 0, duration);+ } else {+ metrics.failed++;+ }+ metrics.totalDurationMs += duration;+ Object.assign(metrics, calculateDurationETA(metrics));+ metrics.lastCompleted = at || new Date().toISOString();+ metrics.successRate = Math.round((metrics.succeeded / metrics.completed) * 100);+ return data;+}+export function recordEnvironmentalFailure(data, { category, taskType } = {}) {if (!category) return data;if (!data.environmentalFailures) data.environmentalFailures = {};@@ -529,6 +580,25 @@ export async function recordTaskCompletion(agent, task) {durationMs: Number.isFinite(durationMs) ? durationMs : null});+ // Fold the same duration into the execution-scoped bucket (issue #8001) —+ // task type × the provider/model/effort this run actually executed on, which+ // is what makes a local-Ollama release check and a cloud one two estimates+ // instead of one wrong average. Stamped with the SAME `lastCompleted` the+ // task-type bucket just took so the prune sweep sees one consistent clock.+ // `?? null` (not `||`) on effort: a provider with no effort control is+ // genuinely absent, and the key builder maps that to its own sentinel.+ recordExecutionDuration(data, {+ key: executionDurationKey({+ taskType,+ providerId: agent.metadata?.providerId,+ model: agent.metadata?.model,+ effort: agent.metadata?.effort ?? null+ }),+ success: outcomeSuccess,+ duration,+ at: typeMetrics.lastCompleted+ });+// Update model tier metricsconst tierMetrics = data.byModelTier[modelTier];tierMetrics.completed++;diff --git a/server/services/taskLearning/store.js b/server/services/taskLearning/store.jsindex 95bce95dd6..899bb38e8a 100644--- a/server/services/taskLearning/store.js+++ b/server/services/taskLearning/store.js@@ -39,6 +39,70 @@ export function calculateDurationETA(metrics) {return { avgDurationMs: avg, maxDurationMs: max, p80DurationMs: p80 };}+// ---------------------------------------------------------------------------+// Execution-scoped duration buckets (issue #8001)+//+// `byTaskType` averages every run of a task type together, so the same+// `self-improve:release-check` on a slow local Ollama model and on a fast cloud+// model land in one bucket and the card's "N min remaining" is wrong for both.+// The provider/model/effort a run actually executed on is the largest single+// driver of its wall-clock time, so `byTaskTypeExecution` keys a second,+// duration-only aggregate by that concrete identity. It is a FLAT map under one+// composed key rather than a 4-level nest: cheaper to prune, iterate and cap.+//+// Duration only — no `recentOutcomes` ring. The LI success-rate signal keeps+// reading `byTaskType`; this dimension exists solely to sharpen the ETA.+// ---------------------------------------------------------------------------++// Effort sentinel for a provider with no effort control. The repo's absent-vs-empty+// rule: a run at no effort level must be its own bucket, never a key ending in a+// bare separator that an `''` and an `undefined` would both produce.+export const EXECUTION_EFFORT_NONE = 'default';++const EXECUTION_KEY_SEPARATOR = '|';++// Ceiling on retained execution buckets. This dimension multiplies task types by+// every provider/model/effort the install has ever run, so the <2-completions/30-day+// prune `byTaskType` gets is not enough on its own — see `saveLearningData`.+export const EXECUTION_BUCKET_CAP = 200;++const nonEmptyKeyPart = (value) => (typeof value === 'string' && value.trim() ? value.trim() : null);++/**+ * Compose the `taskType|providerId|model` prefix shared by every effort level of+ * one execution identity. Returns null when any part is missing — a partial key+ * would silently merge unlike runs. Pure.+ */+export function executionKeyPrefix({ taskType, providerId, model } = {}) {+ const parts = [nonEmptyKeyPart(taskType), nonEmptyKeyPart(providerId), nonEmptyKeyPart(model)];+ if (parts.some((part) => part === null)) return null;+ return parts.join(EXECUTION_KEY_SEPARATOR);+}++/**+ * Compose the full `byTaskTypeExecution` key for one run. Returns null when the+ * task type, provider or model is missing, so the recorder can skip the write+ * instead of banking a run under a key that means nothing. A missing/blank+ * effort becomes the explicit `EXECUTION_EFFORT_NONE` sentinel. Pure — the ONE+ * place writer and reader compose this key, so they cannot drift.+ */+export function executionDurationKey({ taskType, providerId, model, effort } = {}) {+ const prefix = executionKeyPrefix({ taskType, providerId, model });+ if (prefix === null) return null;+ return `${prefix}${EXECUTION_KEY_SEPARATOR}${nonEmptyKeyPart(effort) ?? EXECUTION_EFFORT_NONE}`;+}++/**+ * True when `key` is an execution bucket for the given `taskType|providerId|model`+ * identity, at any effort level. Pure — the reader's rung-2 rollup uses this so+ * "same provider+model, different effort" can never be matched by a prefix that+ * merely starts with the same characters.+ */+export function executionKeyMatchesPrefix(key, prefix) {+ if (typeof key !== 'string' || typeof prefix !== 'string' || !prefix) return false;+ return key.startsWith(`${prefix}${EXECUTION_KEY_SEPARATOR}`);+}+// ---------------------------------------------------------------------------// Recent-outcomes ring (issue #2460)//@@ -259,6 +323,14 @@ const DEFAULT_LEARNING_DATA = {// Metrics by self-improvement task typebyTaskType: {},+ // Duration-only metrics by task type × the concrete execution identity the run+ // used (issue #8001) — a flat map keyed by `executionDurationKey`. Additive:+ // older learning.json files predate this key and load fine; the recording path+ // initializes it on first use, exactly as `failureSignatures` /+ // `environmentalFailures` / `correlationWindow` did. Bounded by the prune ++ // EXECUTION_BUCKET_CAP sweep in `saveLearningData`.+ byTaskTypeExecution: {},+// Metrics by model tierbyModelTier: {},@@ -342,10 +414,34 @@ export async function saveLearningData(data) {// Prune task types with fewer than 2 completions and last seen > 30 days agoconst cutoff = Date.now() - 30 * 24 * 60 * 60 * 1000;+ const isStaleThinBucket = (stats) =>+ (stats?.completed || 0) < 2 && stats?.lastCompleted && new Date(stats.lastCompleted).getTime() < cutoff;if (data.byTaskType) {for (const [type, stats] of Object.entries(data.byTaskType)) {- if ((stats.completed || 0) < 2 && stats.lastCompleted && new Date(stats.lastCompleted).getTime() < cutoff) {- delete data.byTaskType[type];+ if (isStaleThinBucket(stats)) delete data.byTaskType[type];+ }+ }++ // Same prune for the execution dimension (issue #8001), plus a hard cap: this+ // map is task types MULTIPLIED by every provider/model/effort the install has+ // run, so the thin/stale sweep alone can't bound it — a long-lived install that+ // keeps switching models would accumulate a bucket per combination forever.+ // Over the cap, the least-recently-completed buckets go first: they are the ones+ // whose estimate is least likely to describe how the install runs today.+ if (data.byTaskTypeExecution) {+ for (const [key, stats] of Object.entries(data.byTaskTypeExecution)) {+ if (isStaleThinBucket(stats)) delete data.byTaskTypeExecution[key];+ }+ const keys = Object.keys(data.byTaskTypeExecution);+ if (keys.length > EXECUTION_BUCKET_CAP) {+ // An undated bucket sorts oldest (0) — it carries no evidence of recency,+ // so it is the first thing to give up when the map is over budget.+ const byRecency = keys.sort((a, b) => (+ (Date.parse(data.byTaskTypeExecution[a]?.lastCompleted) || 0)+ - (Date.parse(data.byTaskTypeExecution[b]?.lastCompleted) || 0)+ ));+ for (const key of byRecency.slice(0, keys.length - EXECUTION_BUCKET_CAP)) {+ delete data.byTaskTypeExecution[key];}}}diff --git a/server/services/taskLearning/store.test.js b/server/services/taskLearning/store.test.jsindex 995427d41a..ae21c3d86d 100644--- a/server/services/taskLearning/store.test.js+++ b/server/services/taskLearning/store.test.js@@ -41,7 +41,10 @@ import {saveLearningData,clearLearningCache,loadDismissedRecommendations,- saveDismissedRecommendations+ saveDismissedRecommendations,+ executionDurationKey,+ EXECUTION_EFFORT_NONE,+ EXECUTION_BUCKET_CAP} from './store.js';afterAll(() => { if (tempRoot) rmSync(tempRoot, { recursive: true, force: true }); });@@ -697,3 +700,71 @@ describe('taskLearning store strict reads (#4115)', () => {expect(await loadDismissedRecommendations()).toHaveProperty('rec-1');});});++/**+ * Execution-bucket key + bounding (issue #8001).+ *+ * `byTaskTypeExecution` is task types MULTIPLIED by every provider/model/effort+ * an install has ever run, so it is the one learning aggregate that can grow+ * without bound. The key builder is the single place writer and reader compose+ * that key, and `saveLearningData` is the only thing standing between the map+ * and unbounded growth.+ */+describe('execution duration keys and bounding (#8001)', () => {+ const identity = { taskType: 'self-improve:release-check', providerId: 'ollama', model: 'local-coder' };++ it('maps an absent effort to the explicit sentinel, never an empty segment', () => {+ for (const effort of [null, undefined, '', ' ']) {+ expect(executionDurationKey({ ...identity, effort }))+ .toBe(`self-improve:release-check|ollama|local-coder|${EXECUTION_EFFORT_NONE}`);+ }+ expect(executionDurationKey({ ...identity, effort: 'high' }))+ .toBe('self-improve:release-check|ollama|local-coder|high');+ });++ it('refuses a partial key rather than merging unlike runs', () => {+ expect(executionDurationKey({ ...identity, providerId: null, effort: 'low' })).toBeNull();+ expect(executionDurationKey({ ...identity, model: '', effort: 'low' })).toBeNull();+ expect(executionDurationKey({ ...identity, taskType: undefined, effort: 'low' })).toBeNull();+ });++ describe('saveLearningData bounding', () => {+ const cosDir = () => join(getTempRoot(), 'cos');+ const thirtyOneDaysAgo = new Date(Date.now() - 31 * 24 * 60 * 60 * 1000).toISOString();+ const bucket = (completed, lastCompleted) => ({ completed, succeeded: completed, failed: 0, lastCompleted });++ beforeEach(() => {+ rmSync(getTempRoot(), { recursive: true, force: true });+ mkdirSync(cosDir(), { recursive: true });+ clearLearningCache();+ });++ it('prunes thin stale execution buckets, keeping thin RECENT and proven stale ones', async () => {+ const data = {+ byTaskType: {},+ byTaskTypeExecution: {+ 'a|p|m|low': bucket(1, thirtyOneDaysAgo), // thin + stale → pruned+ 'b|p|m|low': bucket(1, new Date().toISOString()), // thin but recent → kept+ 'c|p|m|low': bucket(9, thirtyOneDaysAgo) // stale but proven → kept+ }+ };+ await saveLearningData(data);+ expect(Object.keys(data.byTaskTypeExecution).sort()).toEqual(['b|p|m|low', 'c|p|m|low']);+ });++ it('caps the map at EXECUTION_BUCKET_CAP, dropping the least recently completed first', async () => {+ const byTaskTypeExecution = {};+ // Every bucket is proven and recent, so ONLY the cap can bound this map.+ for (let i = 0; i < EXECUTION_BUCKET_CAP + 5; i++) {+ byTaskTypeExecution[`t${i}|p|m|low`] = bucket(5, new Date(Date.UTC(2026, 0, 1) + i * 60_000).toISOString());+ }+ const data = { byTaskType: {}, byTaskTypeExecution };+ await saveLearningData(data);+ const kept = Object.keys(data.byTaskTypeExecution);+ expect(kept).toHaveLength(EXECUTION_BUCKET_CAP);+ expect(kept, 'the five oldest go first').not.toContain('t0|p|m|low');+ expect(kept).not.toContain('t4|p|m|low');+ expect(kept).toContain('t5|p|m|low');+ });+ });+});