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

refactor: keep CoS duration history keys shared across server and cards (#9339)

[._.]/ Adam Eivy1e49a6169797
diff --git a/client/src/lib/cosDurationEstimate.js b/client/src/lib/cosDurationEstimate.js
index b3b704c054..56ae702a60 100644
--- a/client/src/lib/cosDurationEstimate.js
+++ b/client/src/lib/cosDurationEstimate.js
@@ -1,10 +1,5 @@
// 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
@@ -22,46 +17,11 @@
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 = '|';
+import { executionDurationKey, executionKeyPrefix, MIN_EXECUTION_SAMPLES } from '../../../server/lib/executionDurationKey.js';
+export { EXECUTION_EFFORT_NONE, executionDurationKey, executionKeyPrefix, MIN_EXECUTION_SAMPLES } from '../../../server/lib/executionDurationKey.js';
-// 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.
-//
-// 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 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);
-}
-
-/** `taskType|providerId|model|effort`, or null when any required part is missing. Pure. */
-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}`;
-}
+// Rungs 3 and 4 deliberately carry no threshold here: getAllTaskDurations
+// pre-filters the published task-type and overall rows at one completion.
const hasDuration = (row) => !!row && !!row.avgDurationMs;
diff --git a/server/lib/README.md b/server/lib/README.md
index 83ec5bc83e..9b6d45f9ee 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -62,6 +62,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME`, `doneSentinelName(agentId)` → the per-instance filename `.agent-done-<agentId>` (worktree-less agents share one workspace, so a shared name lets concurrent runs clobber — and finalize on — each other's signal), `doneSentinelCandidateNames(agentId)` → the canonical name plus the bounded one-character truncation recovery candidate for generated ids, `doneSentinelPath(workspacePath, agentId)` → the canonical path every producer resolves, `doneSentinelAgentId(filename)` → its inverse (`''` for the bare unscoped name, `null` for a non-sentinel), so the stale-sentinel sweep in `services/agentSentinelSweep.js` matches leftovers to runs the same way the producer named them, + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. `extractSentinelPayloadFromTranscript(transcript, isPayload)` (async) is the third tier for programmatic-I/O types ONLY — scans the ANSI-stripped PTY transcript, newest balanced JSON block first, for a payload the model PRINTED instead of writing, and adopts it only if the owning hook's shape predicate accepts it (#3640). `PROGRAMMATIC_OUTPUT_COMPLETION_HEADING` names the briefing section that prints this run's absolute sentinel path — a task-type hook renders its prompt before spawn, so it points the agent at that section by name rather than at a filename it cannot know. |
| `persistentMind.js` | Pure persistent-CoS-mind runtime state: default-off durable shape, normalization, FIFO-message/self-wake selection, interrupted-wake requeue, accepted-route fingerprints/receipts, image-work rollback guard, bounded exponential backoff, watchdog staleness, and next-wake projection. |
| `persistentMindCapabilities.js` | Default-off persistent-mind action grants plus bounded typed CoS-task, private-Eidoverse, and self-cleanup contracts (app/provider/model/effort, PR completion policy, the optional exact provider/model task allowlist, and mind-owned context scopes). |
+| `executionDurationKey.js` | Shared pure execution-duration key composers/parser, separator and absent-effort sentinel, and minimum execution sample threshold; preserves persisted keys for server writers and browser lookups. |
| `cosAgentListProjection.js` | What a CoS agent LIST response may carry. `toAgentListItem` / `toAgentListItems` drop the transcript and bound `metadata.taskDescription` to `AGENT_LIST_DESCRIPTION_CHARS` (2000, on a clause boundary via `textUtils.clampToCharLimit`), stamping `taskDescriptionTruncated` + the original `taskDescriptionLength` so the UI can hydrate the rest from `GET /api/cos/agents/:id`. That one field was 68% of the Agents tab payload — p50 is 75 characters but a pasted-prompt description runs past 50 KB, and `GET /api/cos/agents` sits on the first-paint critical path of every `/cos/*` tab and re-reads every 30s. Applied at the ROUTE layer only: `getAgents`/`getAgentsByDate` also feed the weekly digest and CoS reports, which need the whole text. |
| `cosSpawnWindow.js` | The one settlement for the window in which a CoS task is BOTH pending and active. `spawnAgentForTask` registers an agent as `running` before it flips that agent's task off `pending`, so a surface counting the task list and the agent list independently reports the same task as queued AND active — "1 pending, 1 active" for a queue of one, clearing only on a later poll. Reversing the two writes would not close it (two stores, and the UI joins the lists from two separate HTTP reads anyway). `runningAgentsByTaskId(agents)` → `Map<taskId, agent>` (keyed by `taskId` or `metadata.taskId`, matching `agentManagement.js`), `isSpawningTask` / `withoutSpawningTasks` / `countSpawningTasks` / `unclaimedTaskIds` (the id-list form) and `settleTaskSourceSpawnWindow(source, …)`, which stamps `spawning` and moves the task from `grouped.pending` to `grouped.in_progress` for a RESPONSE — that is how `GET /api/cos/tasks` spares its consumers from knowing the window exists, while the dispatch readers of `getAllTasks()` keep the raw truth. **Bounded by `SPAWN_CLAIM_GRACE_MS`** (60s, shared with `services/cos.js#forceSpawnTask`): past it a `pending` task under a `running` agent is a zombie, and settling it as active forever would hide the stuck task from every count AND from the list that renders its "Run now" recovery. Pure leaf with no imports, so `client/src/lib/cosSpawnWindow.js` re-exports it. |
| `cosToolContracts.js` | Provider-neutral `portos_tool` catalog/call schema version, request-id and per-turn bounds, catalog query formats, and Persistent Mind tool-call shape. |
diff --git a/server/lib/executionDurationKey.js b/server/lib/executionDurationKey.js
new file mode 100644
index 0000000000..5771e6b460
--- /dev/null
+++ b/server/lib/executionDurationKey.js
@@ -0,0 +1,56 @@
+/** Shared persisted execution-duration key contract for the server and browser. */
+
+// 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';
+
+export const EXECUTION_KEY_SEPARATOR = '|';
+
+// 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.
+export 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
+ * 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}`;
+}
+
+/**
+ * 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 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;
+}
+
+// Execution-scoped estimates require more evidence than the broader task-type bucket.
+export const MIN_EXECUTION_SAMPLES = 3;
diff --git a/server/lib/index.js b/server/lib/index.js
index b6dbfea1f4..969f3a0181 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -39,6 +39,7 @@ export * from './cronFields.js';
export * from './cronValidation.js';
export * from './cosAgentListProjection.js';
export * from './cosSpawnWindow.js';
+export * from './executionDurationKey.js';
export * from './cosToolContracts.js';
export * as creativeCommissionValidation from './creativeCommissionValidation.js';
// The generation-key spec creativeCommissionValidation.js builds its Zod schema
diff --git a/server/services/taskLearning/durations.js b/server/services/taskLearning/durations.js
index 3413615153..d046c50d3e 100644
--- a/server/services/taskLearning/durations.js
+++ b/server/services/taskLearning/durations.js
@@ -15,11 +15,8 @@ import {
executionKeyPrefixOf
} 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;
+import { MIN_EXECUTION_SAMPLES } from '../../lib/executionDurationKey.js';
+
const MIN_TASK_TYPE_SAMPLES = 2;
const MIN_OVERALL_SAMPLES = 3;
diff --git a/server/services/taskLearning/executionDurations.test.js b/server/services/taskLearning/executionDurations.test.js
index b6bff5251a..80812faff1 100644
--- a/server/services/taskLearning/executionDurations.test.js
+++ b/server/services/taskLearning/executionDurations.test.js
@@ -24,6 +24,8 @@ vi.mock('./store.js', async (importActual) => {
import { recordTaskCompletion } from './metrics.js';
import { getTaskDurationEstimate, getAllTaskDurations } from './durations.js';
import { loadLearningData, saveLearningData, executionDurationKey } from './store.js';
+import { executionKeyPrefixOf } from '../../lib/executionDurationKey.js';
+import { executionDurationKey as clientExecutionDurationKey, estimateCosDuration } from '../../../client/src/lib/cosDurationEstimate.js';
const emptyData = () => ({
version: 2,
@@ -71,6 +73,24 @@ beforeEach(() => {
vi.clearAllMocks();
});
+// Pins the persisted wire format through both entrypoints, including old history.
+describe('execution-duration persisted key compatibility', () => {
+ it.each([
+ ['high', 'self-improve:release-check|claude|opus|high'],
+ [undefined, 'self-improve:release-check|claude|opus|default']
+ ])('keeps server and browser keys stable for effort %s', async (effort, expectedKey) => {
+ const identity = { taskType: 'self-improve:release-check', providerId: 'claude', model: 'opus', effort };
+ expect(executionDurationKey(identity)).toBe(expectedKey);
+ expect(clientExecutionDurationKey(identity)).toBe(expectedKey);
+
+ const data = await record(Array.from({ length: 3 }, () => agentOn({ ...identity, effort: effort ?? null, duration: 60_000 })));
+ expect(Object.keys(data.byTaskTypeExecution)).toEqual([expectedKey]);
+ const durations = await getAllTaskDurations();
+ expect(estimateCosDuration({ durations, task: TASK, agentMetadata: identity }))
+ .toMatchObject({ basis: 'execution', estimatedMs: 60_000, basedOn: 3 });
+ });
+});
+
describe('recordTaskCompletion — execution-scoped duration buckets', () => {
it('keeps the same task type on two different models in two buckets', async () => {
const data = await record([
@@ -219,6 +239,8 @@ describe('getAllTaskDurations — reserved keys', () => {
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(executionKeyPrefixOf(lowKey)).toBe('self-improve:release-check|ollama|local-coder');
+ expect(clientExecutionDurationKey({ taskType: 'self-improve:release-check', providerId: 'ollama', model: 'local-coder', effort: 'low' })).toBe(lowKey);
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 });
diff --git a/server/services/taskLearning/store.js b/server/services/taskLearning/store.js
index 7707d6ad8f..02340cff18 100644
--- a/server/services/taskLearning/store.js
+++ b/server/services/taskLearning/store.js
@@ -24,6 +24,7 @@ const DISMISSED_RECS_FILE = join(DATA_DIR, 'dismissed-recommendations.json');
// Re-export the infra that sibling modules consume so they import from one
// place. (ensureDir / readJSONFile / atomicWrite stay internal to this file.)
export { cosEvents, emitLog, tryReadFile };
+export { EXECUTION_EFFORT_NONE, executionKeyPrefix, executionKeyPrefixOf, executionDurationKey } from '../../lib/executionDurationKey.js';
/**
* Calculate ETA-oriented duration stats from success-only metrics with fallback.
@@ -55,63 +56,11 @@ export function calculateDurationETA(metrics) {
// 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;
-// 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
- * 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}`;
-}
-
-/**
- * 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 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;
-}
-
// ---------------------------------------------------------------------------
// Recent-outcomes ring (issue #2460)
//