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

fix: ETA lookup follows scheduled-task renames by sharing the server's task-type bucket rules (#12966) (#13044)

[._.]/c1a52c8e1123
diff --git a/client/src/lib/cosTaskType.js b/client/src/lib/cosTaskType.js
index 0841e2deee..c2ac668752 100644
--- a/client/src/lib/cosTaskType.js
+++ b/client/src/lib/cosTaskType.js
@@ -1,75 +1,11 @@
-// CoS task-learning bucket resolver for client-side duration displays.
-//
-// MIRROR: keep this aligned with server/services/taskLearning/store.js's
-// extractTaskType(). The server owns outcome metrics; matching its bucket here
-// keeps an ETA attached to the same historical runs that produced it.
-
-export const EXTERNAL_UNTYPED_TASK_TYPE = 'external/untyped';
-
-const SANDBOXED_TASK_TYPES = new Set([EXTERNAL_UNTYPED_TASK_TYPE, 'unknown']);
-const KNOWN_UNSPECIALIZED_TASK_TYPES = new Set([
- 'scheduled', 'test', 'architect', 'layered-intelligence', 'all'
-]);
-
-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/ }
-];
-
-const slugTaskType = (raw) => String(raw).trim().toLowerCase()
- .replace(/[^a-z0-9:_-]+/g, '-')
- .replace(/^-+|-+$/g, '');
-
-function classifyUntypedTask(task) {
- if (!task || typeof task !== 'object') return EXTERNAL_UNTYPED_TASK_TYPE;
- if (SANDBOXED_TASK_TYPES.has(task.taskType)) return task.taskType;
-
- const selfImprovementType = task.metadata?.selfImprovementType;
- if (typeof selfImprovementType === 'string' && selfImprovementType.trim()) {
- return `self-improve:${slugTaskType(selfImprovementType)}`;
- }
-
- const explicit = task.taskType;
- if (typeof explicit === 'string' && explicit.trim() && explicit !== 'unknown') {
- const slug = slugTaskType(explicit);
- if (slug.includes(':')) return slug;
- if (KNOWN_UNSPECIALIZED_TASK_TYPES.has(slug)) return `${slug}-task`;
- }
-
- const desc = (task.description || task.metadata?.taskDescription || '').toLowerCase();
- for (const { type, re } of DESCRIPTION_CLASSIFIERS) {
- if (re.test(desc)) return type;
- }
- return EXTERNAL_UNTYPED_TASK_TYPE;
-}
-
-// Resolve the same low-cardinality task-learning bucket used by the server.
-// Accepts both live task records and archived agent metadata projections.
-export function extractCosTaskType(task) {
- const analysisType = task?.metadata?.analysisType || task?.metadata?.taskAnalysisType;
- if (analysisType) return `self-improve:${analysisType}`;
-
- const reviewType = task?.metadata?.reviewType || task?.metadata?.taskReviewType;
- if (reviewType === 'idle') return 'idle-review';
-
- if (task?.metadata?.missionName) return `mission:${task.metadata.missionName}`;
-
- if (task?.metadata?.taskApp && task?.metadata?.selfImprovementType) {
- return `app-improve:${task.metadata.selfImprovementType}`;
- }
-
- const desc = (task?.description || '').toLowerCase();
- if (desc.includes('[self-improvement]')) {
- const typeMatch = desc.match(/\[self-improvement\]\s*([\w-]+)/i);
- return typeMatch ? `self-improve:${typeMatch[1]}` : 'self-improve:general';
- }
- if (desc.includes('[idle review]')) return 'idle-review';
- if (desc.includes('[auto-fix]') || desc.includes('[auto] investigate')) return 'auto-fix';
- if (desc.includes('[app-improvement]') || desc.includes('[app improvement]')) return 'app-improvement';
- if (task?.taskType === 'user') return 'user-task';
- if (task?.taskType === 'internal') return 'internal-task';
-
- return classifyUntypedTask(task);
-}
+/**
+ * CoS task-learning bucket resolver for client-side duration displays.
+ *
+ * Re-export of `server/lib/taskTypeBucket.js` — the one definition of the
+ * bucket rules, imported rather than copied so an ETA key cannot drift from
+ * the history the server records (e.g. after a scheduled-task rename).
+ */
+export {
+ EXTERNAL_UNTYPED_TASK_TYPE,
+ extractTaskType as extractCosTaskType,
+} from '../../../server/lib/taskTypeBucket.js';
diff --git a/client/src/lib/cosTaskType.test.js b/client/src/lib/cosTaskType.test.js
index 6394cbf1ac..fe3bfa42f5 100644
--- a/client/src/lib/cosTaskType.test.js
+++ b/client/src/lib/cosTaskType.test.js
@@ -60,3 +60,15 @@ describe('extractCosTaskType', () => {
});
});
// @vitest-environment node
+
+describe('extractCosTaskType retired task names', () => {
+ it('buckets a retired analysis name under its current name, matching the server history', () => {
+ expect(extractCosTaskType({ metadata: { analysisType: 'react-lifecycle' } })).toBe('self-improve:ui-lifecycle');
+ });
+
+ it('buckets a retired app-improvement name under its current name', () => {
+ expect(extractCosTaskType({
+ metadata: { taskApp: 'app-1', selfImprovementType: 'release-check' }
+ })).toBe('app-improve:do-release');
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index a4820a7c9f..70fe5a73dc 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -574,6 +574,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `taskTargetBranch.js` | Pure task-branch contract: `resolveTaskTargetBranch(metadata)` reads a retry's legacy `existingBranch` or a review-loop follow-up's canonical `reviewLoopPRBranch`; `shouldStripTaskTargetBranch(metadata)` identifies only retry-owned pointers for terminal cleanup. |
| `claimContinuation.js` | Claim-flow relaunch pointer. `claimContinuationBranch(claimTarget)` is the `claim/issue-<n>` or `claim/<key>` branch a pinned target checks out. `claimContinuationPointer(...)` names the `claim-*` worktree already holding that branch when a relaunch should finish it in place (locked, prunable, unmanaged, or occupied by another running/paused agent → null). `claimContinuationWorkspace(...)` turns a still-on-disk pointer into the cwd the next agent uses without moving the directory. `claimOwnershipBinding(task)` is the branch (or "picks its own", for a swarm orchestrator; a pinned run is also "still choosing" until it binds) a claim run registers on its agent record; `bindClaimBranch` / `releaseClaimBranch` patch the concrete branches a run binds before cutting them (an epic's child, a picked issue), `ownsClaimBranch(agent, branch)` is explicit registered/bound ownership only (never a picker's "may pick"), `claimCheckoutOwnerReason(...)` names a live/possible claim owner for branch-reconcile (`claimCheckoutOwner(...)` adds the holder run ids a blocked cleanup records), and `claimBranchAdmission(...)` gates coordinator adoption and detach with the same branch/repository owners; `claimContinuationAdmission(...)` is the launch-time ownership check that re-reads holder, branch and live owners before a cached pointer may be entered (anything unreadable or changed → refuse, the caller defers; a possible swarm owner holds the launch until that run ends). |
| `scheduledTaskTypes.js` | Registered scheduled task names (`SELF_IMPROVEMENT_TASK_TYPES`), shared by schedule configuration and authoritative skill routing; plus the retired-name map (`TASK_TYPE_RENAMES`, `currentTaskTypeName`, `taskExecutionKey`) for tasks and records written before a task rename. |
+| `taskTypeBucket.js` | CoS task-learning bucket classifier (`extractTaskType`, `classifyUntypedTask`, `isSandboxedTaskType`); browser-safe, shared with the client ETA lookup via `client/src/lib/cosTaskType.js`. |
+| `taskTypeRenames.js` | Dependency-free retired-task-name map (`TASK_TYPE_RENAMES`, `currentTaskTypeName`); re-exported by `scheduledTaskTypes.js`. |
| `scheduleExecutionFieldsValidation.js` | `scheduleExecutionFieldsSchema` validates optional prompt and provider/model selections before schedule writes, preserving null/empty clears. |
| `scheduleRunOrder.js` | Storage rules for a task's advisory `suggestedAfter` list — which OTHER scheduled tasks to run first. `normalizeSuggestedAfter` drops blanks, duplicates and self-references and caps at `SUGGESTED_AFTER_MAX`; the shipped order it defaults to is `auditCatalog.AUDIT_SUGGESTED_AFTER`, layered at read time in `getScheduleStatus`. Advisory only — the ENFORCED dependency field is `runAfter`. Pure — no I/O. |
| `taskReadinessReasons.js` | Stable scheduled-task readiness reason codes, membership set, shared by the server and Schedule UI (pure browser-safe leaf). |
diff --git a/server/lib/index.js b/server/lib/index.js
index 5e4ece4e94..cd08c3c66d 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -522,6 +522,8 @@ export * from './taskStatusTransition.js';
export * from './taskTargetBranch.js';
export * from './claimContinuation.js';
export * from './scheduledTaskTypes.js';
+export * from './taskTypeBucket.js';
+export * from './taskTypeRenames.js';
export * from './scheduleRunOrder.js';
export * from './taskReadinessReasons.js';
export * from './taskTargetScope.js';
diff --git a/server/lib/scheduledTaskTypes.js b/server/lib/scheduledTaskTypes.js
index ebd45bba9e..8e68d79568 100644
--- a/server/lib/scheduledTaskTypes.js
+++ b/server/lib/scheduledTaskTypes.js
@@ -1,13 +1,11 @@
/** Registered scheduled task names, kept separate from schedule configuration. */
import { PRIVATE_SECURITY_TASK_TYPE } from './privateSecurityPolicy.js';
+import { currentTaskTypeName } from './taskTypeRenames.js';
import { PROGRAMMATIC_SCHEDULED_TASK_TYPES } from './taskTargetScope.js';
-// Retired scheduled task names → their current names. Each rename ships a
-// migration that moves persisted schedule state (408, 417); this map covers
-// what a migration cannot reach — queued/archived tasks carrying the old name
-// and the prompt-integrity history that follows the renamed key.
-export const TASK_TYPE_RENAMES = Object.freeze({ 'react-lifecycle': 'ui-lifecycle', 'release-check': 'do-release' });
-export const currentTaskTypeName = (taskType) => TASK_TYPE_RENAMES[taskType] || taskType;
+// Rename table lives in taskTypeRenames.js (dependency-free, shared with the browser-safe classifier).
+export { TASK_TYPE_RENAMES, currentTaskTypeName } from './taskTypeRenames.js';
+
// A task type's `task:`-prefixed schedule executions key, under its current name.
export const taskExecutionKey = (taskType) => `task:${currentTaskTypeName(taskType.startsWith('task:') ? taskType.slice(5) : taskType)}`;
diff --git a/server/lib/taskTypeBucket.js b/server/lib/taskTypeBucket.js
new file mode 100644
index 0000000000..d13c1bdc35
--- /dev/null
+++ b/server/lib/taskTypeBucket.js
@@ -0,0 +1,175 @@
+/**
+ * CoS task-learning bucket classifier. Pure and browser-safe: the server's
+ * outcome store and the client's ETA lookup (client/src/lib/cosTaskType.js
+ * re-exports this) must resolve a task to the same bucket, so there is one copy.
+ */
+import { currentTaskTypeName } from './taskTypeRenames.js';
+
+/**
+ * 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';
+
+// The new sandboxed fallback plus the legacy `'unknown'` sink it replaces. Older
+// installs still hold `'unknown'` buckets from before the classifier (and the
+// spawn-time key in agentModelSelection.js) migrated onto the sandboxed bucket, so
+// it keeps the same wall: stale/heterogeneous uncategorized data must never drive a
+// tier suggestion or globally skip work.
+const SANDBOXED_TASK_TYPES = new Set([EXTERNAL_UNTYPED_TASK_TYPE, 'unknown']);
+
+/**
+ * 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/ }
+];
+
+/**
+ * Concrete `task.taskType` values (beyond user/internal, resolved upstream) that
+ * map to a real learned domain. Allow-listed rather than accepting any string so
+ * an unexpected/high-cardinality taskType can't spawn a swarm of non-sandboxed
+ * singleton buckets that skew routing — anything not here falls through to the
+ * description heuristics and, failing that, the sandboxed fallback.
+ */
+const KNOWN_UNSPECIALIZED_TASK_TYPES = new Set([
+ 'scheduled', 'test', 'architect', 'layered-intelligence', 'all'
+]);
+
+/** 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;
+
+ // Round-trip safety: re-classifying an already-classified task by its own
+ // recorded type must be stable and preserve the sandboxed bucket (the fallback
+ // string's `/` would otherwise be slugged to a non-sandboxed `-task` below).
+ if (isSandboxedTaskType(task?.taskType)) return task.taskType;
+
+ // 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). Map an already-namespaced type
+ // (`a:b`) or an allow-listed known domain to a concrete bucket; anything
+ // else falls through so an unexpected value can't skew routing.
+ const explicit = task?.taskType;
+ if (typeof explicit === 'string' && explicit.trim() && explicit !== 'unknown') {
+ const slug = slugTaskType(explicit);
+ if (slug.includes(':')) return slug;
+ if (KNOWN_UNSPECIALIZED_TASK_TYPES.has(slug)) return `${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
+ */
+export function extractTaskType(task) {
+ // Check for self-improvement type in metadata (direct or forwarded from task)
+ // A task queued before a rename (TASK_TYPE_RENAMES) records into the current
+ // bucket, which migration 417 moved the pre-rename history into.
+ const analysisType = currentTaskTypeName(task?.metadata?.analysisType || task?.metadata?.taskAnalysisType);
+ if (analysisType) {
+ return `self-improve:${analysisType}`;
+ }
+
+ // Check for idle review
+ const reviewType = task?.metadata?.reviewType || task?.metadata?.taskReviewType;
+ if (reviewType === 'idle') {
+ return 'idle-review';
+ }
+
+ // Check for mission tasks
+ if (task?.metadata?.missionName) {
+ return `mission:${task.metadata.missionName}`;
+ }
+
+ // Check for app improvement tasks
+ if (task?.metadata?.taskApp && task?.metadata?.selfImprovementType) {
+ return `app-improve:${currentTaskTypeName(task.metadata.selfImprovementType)}`;
+ }
+
+ // Check description patterns
+ const desc = (task?.description || '').toLowerCase();
+
+ if (desc.includes('[self-improvement]')) {
+ const typeMatch = desc.match(/\[self-improvement\]\s*([\w-]+)/i);
+ if (typeMatch) return `self-improve:${typeMatch[1]}`;
+ return 'self-improve:general';
+ }
+
+ if (desc.includes('[idle review]')) {
+ return 'idle-review';
+ }
+
+ if (desc.includes('[auto-fix]') || desc.includes('[auto] investigate')) {
+ return 'auto-fix';
+ }
+
+ if (desc.includes('[app-improvement]') || desc.includes('[app improvement]')) {
+ return 'app-improvement';
+ }
+
+ // User task classification
+ if (task?.taskType === 'user') {
+ return 'user-task';
+ }
+
+ // Internal/system tasks that don't match a specific pattern
+ if (task?.taskType === 'internal') {
+ return 'internal-task';
+ }
+
+ // 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/lib/taskTypeRenames.js b/server/lib/taskTypeRenames.js
new file mode 100644
index 0000000000..36289820ac
--- /dev/null
+++ b/server/lib/taskTypeRenames.js
@@ -0,0 +1,11 @@
+/**
+ * Retired scheduled task names → their current names. Dependency-free so the
+ * browser-safe task-type classifier (taskTypeBucket.js) can use it without
+ * pulling in scheduledTaskTypes.js's validation imports.
+ *
+ * Each rename ships a migration that moves persisted schedule state (408, 417);
+ * this map covers what a migration cannot reach — queued/archived tasks carrying
+ * the old name and the prompt-integrity history that follows the renamed key.
+ */
+export const TASK_TYPE_RENAMES = Object.freeze({ 'react-lifecycle': 'ui-lifecycle', 'release-check': 'do-release' });
+export const currentTaskTypeName = (taskType) => TASK_TYPE_RENAMES[taskType] || taskType;
diff --git a/server/services/taskLearning/store.js b/server/services/taskLearning/store.js
index 02340cff18..44d724c7b3 100644
--- a/server/services/taskLearning/store.js
+++ b/server/services/taskLearning/store.js
@@ -12,7 +12,9 @@ import { join } from 'path';
import { cosEvents, emitLog } from '../cosEvents.js';
import { ensureDir, readJSONFile, PATHS, atomicWrite, tryReadFile } from '../../lib/fileUtils.js';
import { createMutex } from '../../lib/asyncMutex.js';
-import { currentTaskTypeName } from '../../lib/scheduledTaskTypes.js';
+import { EXTERNAL_UNTYPED_TASK_TYPE, isSandboxedTaskType, classifyUntypedTask, extractTaskType } from '../../lib/taskTypeBucket.js';
+
+export { EXTERNAL_UNTYPED_TASK_TYPE, isSandboxedTaskType, classifyUntypedTask, extractTaskType };
export const withLock = createMutex();
@@ -411,31 +413,6 @@ export async function saveLearningData(data) {
cosEvents.emit('learning:changed');
}
-/**
- * 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';
-
-// The new sandboxed fallback plus the legacy `'unknown'` sink it replaces. Older
-// installs still hold `'unknown'` buckets from before the classifier (and the
-// spawn-time key in agentModelSelection.js) migrated onto the sandboxed bucket, so
-// it keeps the same wall: stale/heterogeneous uncategorized data must never drive a
-// tier suggestion or globally skip work.
-const SANDBOXED_TASK_TYPES = new Set([EXTERNAL_UNTYPED_TASK_TYPE, 'unknown']);
-
-/**
- * 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);
-
/**
* Summarize the enriched `failureSignatures` map (issues #2329/#2333) into a
* ranked, display-ready list. Reads each category's `recent[]` samples to add
@@ -566,150 +543,6 @@ export function buildRecurrenceInsight({ category, count, taskType, agentId = nu
};
}
-/**
- * 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/ }
-];
-
-/**
- * Concrete `task.taskType` values (beyond user/internal, resolved upstream) that
- * map to a real learned domain. Allow-listed rather than accepting any string so
- * an unexpected/high-cardinality taskType can't spawn a swarm of non-sandboxed
- * singleton buckets that skew routing — anything not here falls through to the
- * description heuristics and, failing that, the sandboxed fallback.
- */
-const KNOWN_UNSPECIALIZED_TASK_TYPES = new Set([
- 'scheduled', 'test', 'architect', 'layered-intelligence', 'all'
-]);
-
-/** 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;
-
- // Round-trip safety: re-classifying an already-classified task by its own
- // recorded type must be stable and preserve the sandboxed bucket (the fallback
- // string's `/` would otherwise be slugged to a non-sandboxed `-task` below).
- if (isSandboxedTaskType(task?.taskType)) return task.taskType;
-
- // 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). Map an already-namespaced type
- // (`a:b`) or an allow-listed known domain to a concrete bucket; anything
- // else falls through so an unexpected value can't skew routing.
- const explicit = task?.taskType;
- if (typeof explicit === 'string' && explicit.trim() && explicit !== 'unknown') {
- const slug = slugTaskType(explicit);
- if (slug.includes(':')) return slug;
- if (KNOWN_UNSPECIALIZED_TASK_TYPES.has(slug)) return `${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
- */
-export function extractTaskType(task) {
- // Check for self-improvement type in metadata (direct or forwarded from task)
- // A task queued before a rename (TASK_TYPE_RENAMES) records into the current
- // bucket, which migration 417 moved the pre-rename history into.
- const analysisType = currentTaskTypeName(task?.metadata?.analysisType || task?.metadata?.taskAnalysisType);
- if (analysisType) {
- return `self-improve:${analysisType}`;
- }
-
- // Check for idle review
- const reviewType = task?.metadata?.reviewType || task?.metadata?.taskReviewType;
- if (reviewType === 'idle') {
- return 'idle-review';
- }
-
- // Check for mission tasks
- if (task?.metadata?.missionName) {
- return `mission:${task.metadata.missionName}`;
- }
-
- // Check for app improvement tasks
- if (task?.metadata?.taskApp && task?.metadata?.selfImprovementType) {
- return `app-improve:${currentTaskTypeName(task.metadata.selfImprovementType)}`;
- }
-
- // Check description patterns
- const desc = (task?.description || '').toLowerCase();
-
- if (desc.includes('[self-improvement]')) {
- const typeMatch = desc.match(/\[self-improvement\]\s*([\w-]+)/i);
- if (typeMatch) return `self-improve:${typeMatch[1]}`;
- return 'self-improve:general';
- }
-
- if (desc.includes('[idle review]')) {
- return 'idle-review';
- }
-
- if (desc.includes('[auto-fix]') || desc.includes('[auto] investigate')) {
- return 'auto-fix';
- }
-
- if (desc.includes('[app-improvement]') || desc.includes('[app improvement]')) {
- return 'app-improvement';
- }
-
- // User task classification
- if (task?.taskType === 'user') {
- return 'user-task';
- }
-
- // Internal/system tasks that don't match a specific pattern
- if (task?.taskType === 'internal') {
- return 'internal-task';
- }
-
- // 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);
-}
-
/**
* Load dismissed recommendations map: { [id]: { dismissedAt, snapshot } }
*/