Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fold the duration-bucket accumulation into one shared helper

[._.]/ Adam Eivya8f83b5a8197
diff --git a/client/src/components/cos/tabs/AgentRuntimeStatus.jsx b/client/src/components/cos/tabs/AgentRuntimeStatus.jsx
index f510b65ba5..1f36eedf51 100644
--- a/client/src/components/cos/tabs/AgentRuntimeStatus.jsx
+++ b/client/src/components/cos/tabs/AgentRuntimeStatus.jsx
@@ -1,7 +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';
+import { describeEstimateBasis } from '../../../lib/cosDurationEstimate';
const ETA_PRESENTATION = {
inline: {
@@ -66,7 +66,7 @@ export function AgentRuntimeStatus({
{!inactive && durationEstimate ? (
<span
className="flex items-center gap-1.5 text-gray-500 whitespace-nowrap"
- title={`Based on ${durationEstimate.basedOn} completed ${describeEstimateScope(durationEstimate)} (avg: ${formatDurationMs(durationEstimate.avgMs)}, est: ${formatDurationMs(durationEstimate.estimatedMs)})`}
+ title={`${describeEstimateBasis(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.jsx
index 89e1a3a1ef..e08df47a45 100644
--- a/client/src/components/cos/tabs/LearningTab.durations.test.jsx
+++ b/client/src/components/cos/tabs/LearningTab.durations.test.jsx
@@ -9,26 +9,8 @@
* 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() } }));
+import { describe, expect, it } from 'vitest';
+import { taskTypeDurationRows } from './LearningTab';
const row = (avgDurationMs, completed) => ({
avgDurationMs,
@@ -39,38 +21,23 @@ const row = (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),
+describe('taskTypeDurationRows', () => {
+ it('keeps only real task types, slowest first, whatever reserved keys ride along', () => {
+ const rows = taskTypeDurationRows({
'user-task': row(60000, 3),
+ 'self-improve:release-check': row(120000, 6),
_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'));
+ // Both the table and the "(N task types)" count read this list, so its length
+ // is the count — no reserved key can inflate it and none renders a blank row.
+ expect(rows.map(([taskType]) => taskType)).toEqual(['self-improve:release-check', 'user-task']);
+ });
- 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();
- }
+ it('answers an empty list before any history has loaded', () => {
+ expect(taskTypeDurationRows(null)).toEqual([]);
+ expect(taskTypeDurationRows({})).toEqual([]);
});
});
diff --git a/client/src/components/cos/tabs/LearningTab.jsx b/client/src/components/cos/tabs/LearningTab.jsx
index e881ed8f89..cbf37e3a1c 100644
--- a/client/src/components/cos/tabs/LearningTab.jsx
+++ b/client/src/components/cos/tabs/LearningTab.jsx
@@ -45,6 +45,22 @@ export const runsLabel = (item, noun = 'runs') =>
? `${item.windowedCompleted} recent ${noun}`
: `${item?.completed} ${noun}`;
+/**
+ * The real task-type rows in a `/api/cos/learning/durations` payload, slowest
+ * first. `_`-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 the table —
+ * `_byExecution` carries no `avgDurationMs`, so it would render an empty row —
+ * and the count beside the heading is this list's length rather than a magic
+ * `keys.length - 1` offset. Pure; exported for its test.
+ */
+export function taskTypeDurationRows(durations) {
+ if (!durations) return [];
+ return Object.entries(durations)
+ .filter(([key]) => !key.startsWith('_'))
+ .sort((a, b) => b[1].avgDurationMs - a[1].avgDurationMs);
+}
+
export function FeedbackSummary({ feedback }) {
if (!feedback?.total) return null;
@@ -237,17 +253,7 @@ export default function LearningTab() {
}, []);
// Memoize sorted durations to avoid re-sorting on each render
- const 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.startsWith('_'))
- .sort((a, b) => b[1].avgDurationMs - a[1].avgDurationMs);
- }, [durations]);
+ const sortedDurations = useMemo(() => taskTypeDurationRows(durations), [durations]);
const hasData = learning?.totals?.completed > 0;
diff --git a/client/src/components/cos/tabs/TaskItem.jsx b/client/src/components/cos/tabs/TaskItem.jsx
index 2eb6f59e1d..dc5146cea2 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 { estimateCosDuration, describeEstimateScope } from '../../../lib/cosDurationEstimate';
+import { estimateCosDuration, describeEstimateBasis } from '../../../lib/cosDurationEstimate';
import InstancePicker from '../InstancePicker';
import EffortSelect from '../EffortSelect';
import RelaunchAgentModal from './RelaunchAgentModal';
@@ -247,11 +247,7 @@ export default function TaskItem({ task, agent = null, liveOutput, isSystem, spa
});
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)
- };
+ return { ...estimate, estimatedMin: Math.round(estimate.estimatedMs / 60000) };
}, [durations, task, taskSource, taskProvider, taskModel, taskEffort, displayStatus]);
const handleStatusChange = async (newStatus, blockedReasonText = '', successMessage = `Task marked as ${newStatus}`) => {
@@ -462,14 +458,14 @@ export default function TaskItem({ task, agent = null, liveOutput, isSystem, spa
{durationEstimate && (
<span
className="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 ${describeEstimateScope(durationEstimate)}`}
+ title={describeEstimateBasis(durationEstimate)}
>
<Timer size={10} aria-hidden="true" />
{formatDurationMin(durationEstimate.estimatedMin, { approximate: true })}
</span>
)}
{/* Success rate indicator for pending tasks */}
- {durationEstimate && durationEstimate.successRate !== undefined && durationEstimate.isTypeSpecific && (
+ {durationEstimate && durationEstimate.successRate !== undefined && durationEstimate.basis !== 'overall' && (
(() => {
const style = getSuccessRateStyle(durationEstimate.successRate);
return (
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 0f6999d6b4..c27dfad60f 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -144,7 +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`. |
+| `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 `describeEstimateBasis(estimate)` renders the cards' shared "Based on N completed …" tooltip clause naming which rung answered. 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.js
index 4e72029afb..b3b704c054 100644
--- a/client/src/lib/cosDurationEstimate.js
+++ b/client/src/lib/cosDurationEstimate.js
@@ -32,12 +32,25 @@ 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);
+//
+// Rungs 3 and 4 deliberately carry NO threshold here: `getAllTaskDurations`
+// already filters what it publishes, and the cards have always shown whatever
+// task-type row arrived. The server's own reader applies its thresholds against
+// the RAW store, which this payload is a projection of — so the mirror is the key
+// composition, the cascade ORDER, and this execution-rung bar, not every gate.
+const MIN_EXECUTION_SAMPLES = 3;
+
+// A key part must be a non-empty string that cannot itself contain the separator
+// (MIRRORS the server): otherwise `a|p|m|x` is both "model m at effort x" and
+// "model m|x at no effort", and the rollup would match an unrelated identity.
+const nonEmptyKeyPart = (value) => {
+ if (typeof value !== 'string') return null;
+ const trimmed = value.trim();
+ return trimmed && !trimmed.includes(EXECUTION_KEY_SEPARATOR) ? trimmed : null;
+};
/** `taskType|providerId|model`, or null when any part is missing. Pure. */
-export function executionProviderModelKey({ taskType, providerId, model } = {}) {
+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);
@@ -45,7 +58,7 @@ export function executionProviderModelKey({ taskType, providerId, model } = {})
/** `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 });
+ const prefix = executionKeyPrefix({ taskType, providerId, model });
if (prefix === null) return null;
return `${prefix}${EXECUTION_KEY_SEPARATOR}${nonEmptyKeyPart(effort) ?? EXECUTION_EFFORT_NONE}`;
}
@@ -59,27 +72,28 @@ const shape = (row, { taskType, basis }) => ({
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',
});
+// How each rung's history is described in the cards' tooltips. The overall rung
+// names no task type — it is every task type — which is why the phrase, not just
+// the qualifier, lives in this table.
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',
+ overall: 'runs across all tasks',
};
/**
- * 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.
+ * The cards' shared "Based on N completed …" clause: how much history the estimate
+ * rests on, and what narrowed it. One sentence in one place, so the agent card and
+ * the pending-task chip cannot describe the same estimate differently. Pure.
*/
-export function describeEstimateScope(estimate) {
+export function describeEstimateBasis(estimate) {
if (!estimate) return '';
- const scope = BASIS_SCOPE[estimate.basis];
- return scope ? `${estimate.taskType} ${scope}` : 'runs across all tasks';
+ const scope = BASIS_SCOPE[estimate.basis] || BASIS_SCOPE.overall;
+ const subject = estimate.basis === 'overall' ? scope : `${estimate.taskType} ${scope}`;
+ return `Based on ${estimate.basedOn} completed ${subject}`;
}
/**
@@ -90,7 +104,8 @@ export function describeEstimateScope(estimate) {
* @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
+ * taskType:string, basis:'execution'|'provider-model'|'task-type'|'overall'}|null}
+ * null when nothing is learned yet
*/
export function estimateCosDuration({ durations, task, agentMetadata = null } = {}) {
if (!durations) return null;
@@ -113,7 +128,7 @@ export function estimateCosDuration({ durations, task, agentMetadata = null } =
}
// Rung 2 — same provider + model, summed across effort levels by the server.
- const rollupKey = executionProviderModelKey(identity);
+ const rollupKey = executionKeyPrefix(identity);
const rollup = rollupKey ? durations._byExecutionProviderModel?.[rollupKey] : null;
if (hasDuration(rollup) && rollup.completed >= MIN_EXECUTION_SAMPLES) {
return shape(rollup, { taskType, basis: 'provider-model' });
@@ -125,7 +140,7 @@ export function estimateCosDuration({ durations, task, agentMetadata = null } =
// Rung 4 — the overall average.
const overallData = durations._overall;
- if (hasDuration(overallData)) return shape(overallData, { taskType: 'all tasks', basis: 'overall' });
+ if (hasDuration(overallData)) return shape(overallData, { taskType, basis: 'overall' });
return null;
}
diff --git a/server/services/taskLearning/durations.js b/server/services/taskLearning/durations.js
index 7e4f02348e..3413615153 100644
--- a/server/services/taskLearning/durations.js
+++ b/server/services/taskLearning/durations.js
@@ -12,7 +12,7 @@ import {
calculateDurationETA,
executionDurationKey,
executionKeyPrefix,
- executionKeyMatchesPrefix
+ executionKeyPrefixOf
} from './store.js';
// Minimum completions before an execution-scoped bucket (issue #8001) is trusted
@@ -25,17 +25,32 @@ const MIN_OVERALL_SAMPLES = 3;
const confidenceFor = (completed) => (completed >= 10 ? 'high' : completed >= 5 ? 'medium' : 'low');
+/**
+ * Group an execution map by the `taskType|providerId|model` identity its keys
+ * carry, collapsing the effort segment. Pure. The ONE grouping in this module:
+ * the rung-2 lookup and the `_byExecutionProviderModel` payload rollup both read
+ * it, so the estimate the server computes and the one the client looks up cannot
+ * be derived two different ways. A malformed key groups nowhere.
+ */
+function groupExecutionBucketsByProviderModel(executionBuckets, { minCompleted = 1 } = {}) {
+ const groups = new Map();
+ for (const [key, metrics] of Object.entries(executionBuckets)) {
+ if (!metrics || (metrics.completed || 0) < minCompleted) continue;
+ const prefix = executionKeyPrefixOf(key);
+ if (!prefix) continue;
+ if (!groups.has(prefix)) groups.set(prefix, []);
+ groups.get(prefix).push(metrics);
+ }
+ return groups;
+}
+
/**
* 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) {
+function aggregateExecutionBuckets(buckets) {
const list = (buckets || []).filter(Boolean);
if (list.length === 0) return null;
const agg = list.reduce((acc, m) => ({
@@ -114,15 +129,10 @@ export async function getTaskDurationEstimate(taskDescription, { providerId, mod
// 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' });
- }
+ const group = prefix ? groupExecutionBucketsByProviderModel(executionBuckets).get(prefix) : null;
+ const providerModel = group ? aggregateExecutionBuckets(group) : null;
+ 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.
@@ -194,24 +204,18 @@ export async function getAllTaskDurations() {
// 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);
- }
+ const byExecution = Object.fromEntries(
+ Object.entries(executionBuckets)
+ .filter(([, metrics]) => metrics && (metrics.completed || 0) >= 1)
+ .map(([key, metrics]) => [key, toDurationRow(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))])
+ [...groupExecutionBucketsByProviderModel(executionBuckets)]
+ .map(([prefix, buckets]) => [prefix, toDurationRow(aggregateExecutionBuckets(buckets))])
);
}
diff --git a/server/services/taskLearning/executionDurations.test.js b/server/services/taskLearning/executionDurations.test.js
index 7fea0dba07..b6bff5251a 100644
--- a/server/services/taskLearning/executionDurations.test.js
+++ b/server/services/taskLearning/executionDurations.test.js
@@ -23,7 +23,7 @@ vi.mock('./store.js', async (importActual) => {
import { recordTaskCompletion } from './metrics.js';
import { getTaskDurationEstimate, getAllTaskDurations } from './durations.js';
-import { loadLearningData, saveLearningData, executionDurationKey, EXECUTION_EFFORT_NONE } from './store.js';
+import { loadLearningData, saveLearningData, executionDurationKey } from './store.js';
const emptyData = () => ({
version: 2,
@@ -123,9 +123,7 @@ describe('recordTaskCompletion — execution-scoped duration buckets', () => {
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: null })].completed).toBe(1);
expect(data.byTaskTypeExecution[executionDurationKey({ ...base, effort: 'high' })].completed).toBe(1);
});
@@ -154,15 +152,6 @@ describe('getTaskDurationEstimate — cascade', () => {
...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
diff --git a/server/services/taskLearning/metrics.js b/server/services/taskLearning/metrics.js
index 787cf87fe7..34757ec665 100644
--- a/server/services/taskLearning/metrics.js
+++ b/server/services/taskLearning/metrics.js
@@ -54,43 +54,40 @@ export { ENVIRONMENTAL_ERROR_CATEGORIES };
* 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 empty duration bucket every ETA-shaped aggregate starts from. One literal so
+ * `byTaskType` and `byTaskTypeExecution` cannot persist different shapes on their
+ * first write — they already had: the task-type initializer relied on `|| 0` for the
+ * success-only fields while the execution one seeded them.
+ */
+const emptyDurationBucket = () => ({
+ completed: 0,
+ succeeded: 0,
+ failed: 0,
+ totalDurationMs: 0,
+ successDurationMs: 0,
+ successMaxDurationMs: 0,
+ avgDurationMs: 0,
+ maxDurationMs: 0,
+ p80DurationMs: 0,
+ lastCompleted: null,
+ successRate: 0
+});
+
+/**
+ * Fold one completion into an ETA-shaped duration bucket. Pure — mutates and returns
+ * `metrics`. The single place the "success-only durations drive the ETA" rule lives:
+ * a failed agent often loops long in an error path, so only successful runs feed
+ * `calculateDurationETA`. Shared by the `byTaskType` and `byTaskTypeExecution` folds
+ * below so the two dimensions can never disagree about what an ETA is.
*
- * The caller applies the environmental-failure gate (#2618) before reaching here, so
- * an outage teaches this dimension nothing either.
+ * The bounded `recentOutcomes` ring stays at the call site — only `byTaskType` carries
+ * one (it feeds LI's windowed success rate, which the duration-only execution bucket
+ * has no part in).
*/
-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];
+function foldDurationOutcome(metrics, { success, duration = 0, at } = {}) {
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 {
@@ -100,6 +97,23 @@ export function recordExecutionDuration(data, { key, success, duration = 0, at }
Object.assign(metrics, calculateDurationETA(metrics));
metrics.lastCompleted = at || new Date().toISOString();
metrics.successRate = Math.round((metrics.succeeded / metrics.completed) * 100);
+ return metrics;
+}
+
+/**
+ * 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.
+ *
+ * The caller applies the environmental-failure gate (#2618) before reaching here, so
+ * an outage teaches this dimension nothing either.
+ */
+function recordExecutionDuration(data, { key, success, duration = 0, at } = {}) {
+ if (!key) return data;
+ if (!data.byTaskTypeExecution) data.byTaskTypeExecution = {};
+ if (!data.byTaskTypeExecution[key]) data.byTaskTypeExecution[key] = emptyDurationBucket();
+ foldDurationOutcome(data.byTaskTypeExecution[key], { success, duration, at });
return data;
}
@@ -522,15 +536,7 @@ export async function recordTaskCompletion(agent, task) {
// Initialize task type bucket if needed
if (!data.byTaskType[taskType]) {
data.byTaskType[taskType] = {
- completed: 0,
- succeeded: 0,
- failed: 0,
- totalDurationMs: 0,
- avgDurationMs: 0,
- maxDurationMs: 0,
- p80DurationMs: 0,
- lastCompleted: null,
- successRate: 0,
+ ...emptyDurationBucket(),
// Bounded recency ring (issue #2460) — feeds the windowed rate LI reads.
recentOutcomes: []
};
@@ -549,21 +555,7 @@ export async function recordTaskCompletion(agent, task) {
}
// Update task type metrics
- const typeMetrics = data.byTaskType[taskType];
- typeMetrics.completed++;
- if (outcomeSuccess) {
- typeMetrics.succeeded++;
- // Only include successful durations in ETA calculations — failed agents often
- // run long in error loops and skew estimates
- typeMetrics.successDurationMs = (typeMetrics.successDurationMs || 0) + duration;
- typeMetrics.successMaxDurationMs = Math.max(typeMetrics.successMaxDurationMs || 0, duration);
- } else {
- typeMetrics.failed++;
- }
- typeMetrics.totalDurationMs += duration;
- Object.assign(typeMetrics, calculateDurationETA(typeMetrics));
- typeMetrics.lastCompleted = new Date().toISOString();
- typeMetrics.successRate = Math.round((typeMetrics.succeeded / typeMetrics.completed) * 100);
+ const typeMetrics = foldDurationOutcome(data.byTaskType[taskType], { success: outcomeSuccess, duration });
// Append this run to the bounded recency ring (issue #2460). The lifetime
// counters above never decay; the ring lets LI read a recency-windowed rate so
// a since-resolved failure burst ages out of the "is work needed" signal
diff --git a/server/services/taskLearning/store.js b/server/services/taskLearning/store.js
index 899bb38e8a..8b45faf9eb 100644
--- a/server/services/taskLearning/store.js
+++ b/server/services/taskLearning/store.js
@@ -66,7 +66,14 @@ const EXECUTION_KEY_SEPARATOR = '|';
// 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);
+// A key part must be a non-empty string that cannot itself contain the separator:
+// otherwise `a|p|m|x` is both "model m at effort x" and "model m|x at no effort",
+// and the provider+model rollup would sum two unrelated identities together.
+const nonEmptyKeyPart = (value) => {
+ if (typeof value !== 'string') return null;
+ const trimmed = value.trim();
+ return trimmed && !trimmed.includes(EXECUTION_KEY_SEPARATOR) ? trimmed : null;
+};
/**
* Compose the `taskType|providerId|model` prefix shared by every effort level of
@@ -93,14 +100,15 @@ export function executionDurationKey({ taskType, providerId, model, effort } = {
}
/**
- * 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.
+ * The `taskType|providerId|model` identity a stored execution key belongs to — the
+ * parse counterpart of `executionKeyPrefix`, so composition and decomposition live
+ * and change together. Null for anything that is not a well-formed key (a
+ * hand-edited learning.json), which the reader drops rather than mis-grouping. Pure.
*/
-export function executionKeyMatchesPrefix(key, prefix) {
- if (typeof key !== 'string' || typeof prefix !== 'string' || !prefix) return false;
- return key.startsWith(`${prefix}${EXECUTION_KEY_SEPARATOR}`);
+export function executionKeyPrefixOf(key) {
+ if (typeof key !== 'string') return null;
+ const parts = key.split(EXECUTION_KEY_SEPARATOR);
+ return parts.length === 4 ? parts.slice(0, 3).join(EXECUTION_KEY_SEPARATOR) : null;
}
// ---------------------------------------------------------------------------
diff --git a/server/services/taskLearning/store.test.js b/server/services/taskLearning/store.test.js
index ae21c3d86d..b93147881b 100644
--- a/server/services/taskLearning/store.test.js
+++ b/server/services/taskLearning/store.test.js
@@ -43,6 +43,8 @@ import {
loadDismissedRecommendations,
saveDismissedRecommendations,
executionDurationKey,
+ executionKeyPrefix,
+ executionKeyPrefixOf,
EXECUTION_EFFORT_NONE,
EXECUTION_BUCKET_CAP
} from './store.js';
@@ -728,6 +730,23 @@ describe('execution duration keys and bounding (#8001)', () => {
expect(executionDurationKey({ ...identity, taskType: undefined, effort: 'low' })).toBeNull();
});
+ it('refuses a part carrying the separator, which would make the key ambiguous', () => {
+ // `a|p|m|x` must mean exactly one thing. Were a model id allowed to carry the
+ // separator, it would be both "model m at effort x" and "model m|x at no
+ // effort", and the provider+model rollup would sum two unrelated identities.
+ expect(executionDurationKey({ ...identity, model: 'local|coder', effort: 'low' })).toBeNull();
+ expect(executionDurationKey({ ...identity, effort: 'low|high' }))
+ .toBe(`self-improve:release-check|ollama|local-coder|${EXECUTION_EFFORT_NONE}`);
+ });
+
+ it('round-trips a key back to the provider+model identity it belongs to', () => {
+ const key = executionDurationKey({ ...identity, effort: 'high' });
+ expect(executionKeyPrefixOf(key)).toBe(executionKeyPrefix(identity));
+ // A hand-edited learning.json must group nowhere rather than mis-group.
+ expect(executionKeyPrefixOf('not-a-key')).toBeNull();
+ expect(executionKeyPrefixOf(undefined)).toBeNull();
+ });
+
describe('saveLearningData bounding', () => {
const cosDir = () => join(getTempRoot(), 'cos');
const thirtyOneDaysAgo = new Date(Date.now() - 31 * 24 * 60 * 60 * 1000).toISOString();