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
feat: auto-classify untyped task executions for telemetry + routing (#2333)
Adam Eivy6a8e78ed9ec4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 2eb8c95740..c865243eda 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -12,6 +12,7 @@## Added+- **[issue-2333] Untyped task executions are now auto-classified instead of piling up as `unknown`.** Task-learning's `extractTaskType` used to dump every execution it couldn't pattern-match into a single blind `unknown` bucket — those tasks bypassed routing logic, skipped outcome learning, and leaked unstructured failures. It now runs an execution-entry classification hook (`classifyUntypedTask`, pure/idempotent/<50ms) that, before giving up, infers a concrete domain from additional signals — a `selfImprovementType` metadata hint, an explicit `task.taskType` the primary extractor didn't special-case (e.g. `scheduled` → `scheduled-task`), and broader whole-word description keyword signatures (`fix`/`investigate`/`crash` → `auto-fix`, `refactor`/`optimize` → `self-improve:general`, `review`/`audit` → `idle-review`, `unit test`/`coverage` → `test-task`) — and only falls back to a new sandboxed `external/untyped` type when nothing matches. Newly-classified and fallback executions flow through the existing #2329 failure-signature harvesting so their failures are captured in the normalized telemetry schema. The `external/untyped` bucket is explicitly walled off from routing (it never drives a model-tier suggestion and is never globally skipped) so a heterogeneous grab-bag can't create a routing blind spot or loop. (Partial delivery of #2333; the spawn-time key mirror in `agentModelSelection.extractTaskTypeKey` and deeper self-improvement-loop consumption of the harvested `failureSignatures` remain.)- **[issue-2329] Task-learning now records a structured telemetry context for every completed agent.** On each completion the learning system builds a `TaskTelemetryContext` — a failure signature (`{ category, messageSnippet, failurePosition }`, reusing the category `agentErrorAnalysis` already classified), execution context (`provider`, `model`, `modelTier`, `taskType`, `component`, input-size, and the routing decision rationale), and a latency breakdown (`wallMs` spawn→completion vs. `queueMs` wait vs. `executionMs` measured) — using explicit null sentinels for anything not cheaply derivable rather than fabricating values. Failure signatures are aggregated per error category into a new additive `failureSignatures` block in `learning.json` (older files without the key load unchanged), and the enriched context is surfaced on the single-line completion log. (Partial delivery of #2329; routing auto-adjustment that consumes these signals, success-criteria validation flags, the queue/compute split where spawn timestamps are missing, and correlation-quality measurement remain.)## Fixeddiff --git a/server/services/taskLearning/index.js b/server/services/taskLearning/index.jsindex 2d249ba169..0e258c1789 100644--- a/server/services/taskLearning/index.js+++ b/server/services/taskLearning/index.js@@ -18,7 +18,13 @@* every existing importer is unaffected.*/-export { clearLearningCache } from './store.js';+export {+ clearLearningCache,+ extractTaskType,+ classifyUntypedTask,+ isSandboxedTaskType,+ EXTERNAL_UNTYPED_TASK_TYPE+} from './store.js';export {recordTaskCompletion,diff --git a/server/services/taskLearning/metrics.test.js b/server/services/taskLearning/metrics.test.jsindex 59b3cddc85..839c4c998f 100644--- a/server/services/taskLearning/metrics.test.js+++ b/server/services/taskLearning/metrics.test.js@@ -90,7 +90,7 @@ describe('buildTaskTelemetryContext', () => {provider: null,model: null,modelTier: null,- taskType: 'unknown',+ taskType: 'external/untyped', // sandboxed fallback, no longer the blind 'unknown' (#2333)component: null,inputChars: null, // null, not 0 — description absent, not emptyroutingReason: null@@ -116,6 +116,54 @@ describe('buildTaskTelemetryContext', () => {expect(ctx.latency.queueMs).toBeNull();expect(ctx.latency.wallMs).toBe(300000); // wall still derivable from agent timestamps});++ it('harvests a failure signature for a previously-untyped task via the classification hook (#2333)', () => {+ // A failing task with no recognized type token: previously taskType would be+ // 'unknown' and bypass structured learning. Now the classifier maps the+ // free-form description to a concrete domain and the failure is captured.+ const agent = {+ ...baseAgent,+ metadata: { ...baseAgent.metadata, phase: 'diagnosing' },+ result: {+ success: false,+ duration: 5000,+ errorAnalysis: { category: 'tool-error', message: 'ripgrep not found' }+ }+ };+ const ctx = buildTaskTelemetryContext(agent, { description: 'investigate the failing deploy' });+ expect(ctx.executionContext.taskType).toBe('auto-fix'); // classified, not 'unknown'+ expect(ctx.failureSignature).toEqual({+ category: 'tool-error',+ messageSnippet: 'ripgrep not found',+ failurePosition: 'diagnosing'+ });++ // The harvested signature lands in the normalized telemetry schema.+ const data = { failureSignatures: {} };+ recordFailureSignature(data, ctx);+ expect(data.failureSignatures['tool-error'].count).toBe(1);+ expect(data.failureSignatures['tool-error'].recent[0]).toMatchObject({+ taskType: 'auto-fix',+ messageSnippet: 'ripgrep not found',+ failurePosition: 'diagnosing'+ });+ });++ it('harvests failures even for the sandboxed external/untyped fallback (#2333)', () => {+ const agent = {+ ...baseAgent,+ result: {+ success: false,+ duration: 3000,+ errorAnalysis: { category: 'timeout', message: 'exceeded wall clock' }+ }+ };+ const ctx = buildTaskTelemetryContext(agent, { description: 'ship the quarterly widgets' });+ expect(ctx.executionContext.taskType).toBe('external/untyped');+ const data = { failureSignatures: {} };+ recordFailureSignature(data, ctx);+ expect(data.failureSignatures['timeout'].recent[0].taskType).toBe('external/untyped');+ });});describe('recordFailureSignature', () => {diff --git a/server/services/taskLearning/routing.js b/server/services/taskLearning/routing.jsindex 8538b56fbe..f68c3c3ddf 100644--- a/server/services/taskLearning/routing.js+++ b/server/services/taskLearning/routing.js@@ -9,7 +9,7 @@* module.*/-import { loadLearningData, emitLog } from './store.js';+import { loadLearningData, emitLog, isSandboxedTaskType } from './store.js';import { resetTaskTypeLearning } from './metrics.js';/**@@ -86,6 +86,11 @@ export async function getTaskTypePriorityMultiplier(taskType) {* and prefers tiers with proven success for the task type*/export async function suggestModelTier(taskType) {+ // Sandboxed fallback (issue #2333): the `external/untyped` bucket aggregates+ // heterogeneous work, so its tier success rates are meaningless — never let it+ // drive a model-tier suggestion. Let the selector fall through to its default.+ if (isSandboxedTaskType(taskType)) return null;+const data = await loadLearningData();const metrics = data.byTaskType[taskType];@@ -285,6 +290,14 @@ export async function getPerformanceSummary() {* @returns {Object} Cooldown adjustment info*/export async function getAdaptiveCooldownMultiplier(taskType) {+ // Sandboxed fallback (issue #2333): never skip or throttle the heterogeneous+ // `external/untyped` bucket — a poor aggregate success rate here would create+ // a routing blind spot that silently drops ALL unclassified work. Keep it at+ // the default cooldown and always eligible.+ if (isSandboxedTaskType(taskType)) {+ return { multiplier: 1.0, reason: 'sandboxed-untyped', skip: false, successRate: null, completed: 0 };+ }+const data = await loadLearningData();const metrics = data.byTaskType[taskType];@@ -380,6 +393,8 @@ export async function getSkippedTaskTypes() {const skipped = [];for (const [taskType, metrics] of Object.entries(data.byTaskType)) {+ // Sandboxed fallback is never globally skipped (issue #2333).+ if (isSandboxedTaskType(taskType)) continue;// Skip if: completed >= 5 AND success rate < 30%if (metrics.completed >= 5 && metrics.successRate < 30) {skipped.push({diff --git a/server/services/taskLearning/store.js b/server/services/taskLearning/store.jsindex d2244f115b..4be0941ef8 100644--- a/server/services/taskLearning/store.js+++ b/server/services/taskLearning/store.js@@ -126,6 +126,87 @@ export async function saveLearningData(data) {_learningCacheTime = Date.now();}+/**+ * Sandboxed fallback type for executions the classifier can't map to a known+ * domain (issue #2333). Replaces the old blind `'unknown'` sink so untyped work+ * still flows through outcome learning + failure-signature harvesting, while+ * being explicitly walled off from routing influence (see `isSandboxedTaskType`+ * consumers in routing.js) — a heterogeneous grab-bag must never drive a tier+ * suggestion or globally skip all untyped work (which would create a routing+ * blind spot / loop).+ */+export const EXTERNAL_UNTYPED_TASK_TYPE = 'external/untyped';++const SANDBOXED_TASK_TYPES = new Set([EXTERNAL_UNTYPED_TASK_TYPE]);++/**+ * True when a task type is a sandboxed fallback bucket (not a real learned+ * domain). Callers in routing.js gate on this to keep the fallback from+ * influencing model-tier suggestions or skip/rehabilitation gating.+ */+export const isSandboxedTaskType = (taskType) => SANDBOXED_TASK_TYPES.has(taskType);++/**+ * Ordered description-keyword → concrete-type rules, tried only as a last resort+ * before the sandboxed fallback. First match wins. Patterns are whole-word/stem+ * tests (`\b…`) so a substring can't false-positive (e.g. "testing" ⊄ trigger of+ * an unrelated word). Kept deliberately conservative — a wrong concrete label is+ * worse than an honest `external/untyped`.+ */+const DESCRIPTION_CLASSIFIERS = [+ { type: 'auto-fix', re: /\b(fix|bug|crash|broken|failing|regression|investigate|stack ?trace)\b/ },+ { type: 'self-improve:general', re: /\b(refactor|clean ?up|simplif\w*|optimi[sz]\w*|improve|enhance)\b/ },+ { type: 'idle-review', re: /\b(review|audit|inspect)\b/ },+ { type: 'test-task', re: /\b(unit test|coverage|test suite|write tests?)\b/ }+];++/** Normalize a raw task-type token to a stable, low-cardinality slug. */+function slugTaskType(raw) {+ return String(raw).trim().toLowerCase().replace(/[^a-z0-9:_-]+/g, '-').replace(/^-+|-+$/g, '');+}++/**+ * Classify a task that the primary `extractTaskType` heuristics left untyped+ * (issue #2333). Pure, deterministic (idempotent — same input → same output),+ * and side-effect free / O(1) over a few short regexes, so it stays well under+ * the <50ms execution-entry budget. Inspects additional signals in priority+ * order — a self-improvement metadata hint, an explicit `task.taskType` the+ * primary extractor didn't special-case, then broader description keyword+ * signatures — and only falls back to the sandboxed `external/untyped` type+ * (never the old `'unknown'`) when nothing matches.+ */+export function classifyUntypedTask(task) {+ if (!task || typeof task !== 'object') return EXTERNAL_UNTYPED_TASK_TYPE;++ // 1) A self-improvement hint not paired with a taskApp (that pairing is+ // handled by the primary extractor upstream).+ const selfImprovementType = task?.metadata?.selfImprovementType;+ if (typeof selfImprovementType === 'string' && selfImprovementType.trim()) {+ return `self-improve:${slugTaskType(selfImprovementType)}`;+ }++ // 2) An explicit task.taskType the primary extractor didn't special-case+ // (user/internal are resolved upstream). Preserve it as a concrete domain+ // rather than collapsing distinct system domains into one bucket.+ const explicit = task?.taskType;+ if (typeof explicit === 'string' && explicit.trim() && explicit !== 'unknown') {+ const slug = slugTaskType(explicit);+ if (slug) return slug.includes(':') ? slug : `${slug}-task`;+ }++ // 3) Broader description keyword signatures (bracket-tag patterns already ran+ // upstream; this catches free-form descriptions).+ const desc = (task?.description || task?.metadata?.taskDescription || '').toLowerCase();+ if (desc) {+ for (const { type, re } of DESCRIPTION_CLASSIFIERS) {+ if (re.test(desc)) return type;+ }+ }++ // 4) Nothing matched — sandboxed fallback (never 'unknown').+ return EXTERNAL_UNTYPED_TASK_TYPE;+}+/*** Extract task type from task description or metadata*/@@ -183,7 +264,10 @@ export function extractTaskType(task) {return 'internal-task';}- return 'unknown';+ // Execution-entry classification hook (issue #2333): before giving up to the+ // old blind 'unknown' sink, inspect additional signals to infer a concrete+ // domain, else return the sandboxed `external/untyped` fallback.+ return classifyUntypedTask(task);}/**diff --git a/server/services/taskLearning/store.test.js b/server/services/taskLearning/store.test.jsindex fa19c437d0..7d9d95ce46 100644--- a/server/services/taskLearning/store.test.js+++ b/server/services/taskLearning/store.test.js@@ -1,5 +1,11 @@import { describe, it, expect } from 'vitest';-import { extractTaskType, calculateDurationETA } from './store.js';+import {+ extractTaskType,+ calculateDurationETA,+ classifyUntypedTask,+ isSandboxedTaskType,+ EXTERNAL_UNTYPED_TASK_TYPE+} from './store.js';// These two helpers are the pure foundation every other taskLearning submodule// builds on (duration math + task-type classification). They take no I/O, so we@@ -20,8 +26,8 @@ describe('store.extractTaskType', () => {});it('does not treat a non-idle reviewType as idle-review', () => {- // falls through to 'unknown' since nothing else matches- expect(extractTaskType({ metadata: { reviewType: 'manual' } })).toBe('unknown');+ // falls through to the sandboxed fallback since nothing else matches (#2333)+ expect(extractTaskType({ metadata: { reviewType: 'manual' } })).toBe(EXTERNAL_UNTYPED_TASK_TYPE);});it('classifies mission tasks by mission name', () => {@@ -30,8 +36,9 @@ describe('store.extractTaskType', () => {it('classifies app-improvement tasks only when both taskApp and selfImprovementType present', () => {expect(extractTaskType({ metadata: { taskApp: 'foo', selfImprovementType: 'perf' } })).toBe('app-improve:perf');- // taskApp without selfImprovementType falls through- expect(extractTaskType({ metadata: { taskApp: 'foo' } })).toBe('unknown');+ // taskApp with a selfImprovementType but no taskApp-pairing is caught by the+ // classifier as a self-improve domain (#2333)+ expect(extractTaskType({ metadata: { selfImprovementType: 'perf' } })).toBe('self-improve:perf');});it('parses a [self-improvement] description tag with a type token', () => {@@ -62,9 +69,72 @@ describe('store.extractTaskType', () => {expect(extractTaskType({ taskType: 'internal', description: 'do a thing' })).toBe('internal-task');});- it('returns unknown for an empty/undefined task', () => {- expect(extractTaskType()).toBe('unknown');- expect(extractTaskType({})).toBe('unknown');+ it('returns the sandboxed fallback (never the old unknown) for an empty/undefined task', () => {+ expect(extractTaskType()).toBe(EXTERNAL_UNTYPED_TASK_TYPE);+ expect(extractTaskType({})).toBe(EXTERNAL_UNTYPED_TASK_TYPE);+ // regression guard: the blind 'unknown' sink is gone+ expect(extractTaskType({})).not.toBe('unknown');+ });+});++describe('store.classifyUntypedTask (issue #2333)', () => {+ it('infers a self-improve domain from a bare selfImprovementType hint', () => {+ expect(classifyUntypedTask({ metadata: { selfImprovementType: 'Perf Tuning' } }))+ .toBe('self-improve:perf-tuning');+ });++ it('preserves an explicit task.taskType the primary extractor did not special-case', () => {+ // Previously these all collapsed to 'unknown'+ expect(classifyUntypedTask({ taskType: 'scheduled' })).toBe('scheduled-task');+ expect(classifyUntypedTask({ taskType: 'architect' })).toBe('architect-task');+ // an already-namespaced type keeps its colon rather than getting a -task suffix+ expect(classifyUntypedTask({ taskType: 'self-improve:ui' })).toBe('self-improve:ui');+ });++ it('classifies free-form descriptions by keyword when no type token is present', () => {+ expect(classifyUntypedTask({ description: 'Investigate the crash in the pipeline' })).toBe('auto-fix');+ expect(classifyUntypedTask({ description: 'Refactor and clean up the store module' })).toBe('self-improve:general');+ expect(classifyUntypedTask({ description: 'Audit the routing accuracy code' })).toBe('idle-review');+ expect(classifyUntypedTask({ description: 'Add unit test coverage for the parser' })).toBe('test-task');+ });++ it('reads a description from metadata.taskDescription when top-level description is absent', () => {+ expect(classifyUntypedTask({ metadata: { taskDescription: 'fix the broken build' } })).toBe('auto-fix');+ });++ it('does not false-positive on a substring of a trigger word', () => {+ // "testing" / "fixture" must not trip the \b-anchored keyword rules+ expect(classifyUntypedTask({ description: 'contesting the fixtures inventory' }))+ .toBe(EXTERNAL_UNTYPED_TASK_TYPE);+ });++ it('falls back to external/untyped (a sandboxed type) when nothing matches', () => {+ const t = classifyUntypedTask({ description: 'ship the quarterly widgets' });+ expect(t).toBe(EXTERNAL_UNTYPED_TASK_TYPE);+ expect(isSandboxedTaskType(t)).toBe(true);+ expect(classifyUntypedTask(null)).toBe(EXTERNAL_UNTYPED_TASK_TYPE);+ expect(classifyUntypedTask('nope')).toBe(EXTERNAL_UNTYPED_TASK_TYPE);+ });++ it('is idempotent: same input always yields the same output', () => {+ const inputs = [+ { description: 'Investigate the crash' },+ { taskType: 'scheduled' },+ { metadata: { selfImprovementType: 'perf' } },+ {}+ ];+ for (const input of inputs) {+ const first = classifyUntypedTask(input);+ expect(classifyUntypedTask(input)).toBe(first);+ // re-classifying its own output-shaped task is stable (no drift)+ expect(classifyUntypedTask({ taskType: first })).toBe(classifyUntypedTask({ taskType: first }));+ }+ });++ it('only marks the fallback bucket as sandboxed', () => {+ expect(isSandboxedTaskType(EXTERNAL_UNTYPED_TASK_TYPE)).toBe(true);+ expect(isSandboxedTaskType('auto-fix')).toBe(false);+ expect(isSandboxedTaskType('unknown')).toBe(false);});});