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
fix(cos): align task estimates with learning buckets
[._.]/ Adam Eivy3985c99fd115
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsxindex fe77d8b766..5ed7a4c791 100644--- a/client/src/components/cos/tabs/AgentCard.jsx+++ b/client/src/components/cos/tabs/AgentCard.jsx@@ -30,33 +30,13 @@ import MarkdownOutput from '../MarkdownOutput';import Modal from '../../ui/Modal';import toast from '../../ui/Toast';import { copyToClipboard } from '../../../lib/clipboard';+import { extractCosTaskType } from '../../../lib/cosTaskType';import { DEFAULT_REVIEWER, normalizeReviewers } from '../constants';import { formatDurationMs, formatDateTime } from '../../../utils/formatters';import { useAutoRefetch } from '../../../hooks/useAutoRefetch';import ConfirmButtonPair from '../../ui/ConfirmButtonPair';import { useConfirmDelete } from '../../../hooks/useConfirmDelete';-// Extract task type from description (matches server-side extractTaskType)-function extractTaskType(description) {- if (!description) return 'general';- const d = description.toLowerCase();- if (d.includes('fix') || d.includes('bug') || d.includes('error') || d.includes('issue')) return 'bug-fix';- if (d.includes('refactor') || d.includes('clean up') || d.includes('improve') || d.includes('optimize')) return 'refactor';- if (d.includes('test')) return 'testing';- if (d.includes('document') || d.includes('readme') || d.includes('docs')) return 'documentation';- if (d.includes('review') || d.includes('audit')) return 'code-review';- if (d.includes('mobile') || d.includes('responsive')) return 'mobile-responsive';- if (d.includes('security') || d.includes('vulnerability')) return 'security';- if (d.includes('performance') || d.includes('speed')) return 'performance';- if (d.includes('ui') || d.includes('ux') || d.includes('design') || d.includes('style')) return 'ui-ux';- if (d.includes('api') || d.includes('endpoint') || d.includes('route')) return 'api';- if (d.includes('database') || d.includes('migration')) return 'database';- if (d.includes('deploy') || d.includes('ci') || d.includes('cd')) return 'devops';- if (d.includes('investigate') || d.includes('debug')) return 'investigation';- if (d.includes('self-improvement') || d.includes('improvement') || d.includes('feature idea')) return 'self-improvement';- return 'feature';-}-// Pre-compiled regexes for normalizeDescriptionToMarkdown// Avoid lookbehind to support older Safari/iOS runtimesconst RE_NUMBERED_LIST = /([.!?:]) (\d+)\. /g;@@ -266,7 +246,11 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,const durationEstimate = useMemo(() => {if (inactive || !durations) return null;- const taskType = extractTaskType(agent.metadata?.taskDescription);+ const taskType = extractCosTaskType({+ description: agent.metadata?.taskDescription,+ taskType: agent.metadata?.taskType,+ metadata: agent.metadata+ });const typeData = durations[taskType];const overallData = durations._overall;@@ -291,7 +275,7 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,}return null;- }, [inactive, durations, agent.metadata?.taskDescription]);+ }, [inactive, durations, agent.metadata]);// Calculate progress percentage using P80-based estimate// Cap at 99% for active tasks — only completion can land on 100%diff --git a/client/src/components/cos/tabs/AgentCard.test.jsx b/client/src/components/cos/tabs/AgentCard.test.jsxindex 7b1d164ca9..a4bda8fe78 100644--- a/client/src/components/cos/tabs/AgentCard.test.jsx+++ b/client/src/components/cos/tabs/AgentCard.test.jsx@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { MemoryRouter } from 'react-router-dom';@@ -30,7 +30,39 @@ beforeEach(() => {vi.clearAllMocks();});+afterEach(() => {+ vi.useRealTimers();+});+describe('AgentCard feedback', () => {+ it('uses the archived scheduled type for a running agent ETA', () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-07-13T10:00:00.000Z'));+ const runningAgent = {+ ...agent,+ status: 'running',+ startedAt: '2026-07-13T09:59:00.000Z',+ completedAt: null,+ metadata: {+ taskDescription: 'Fix the security configuration',+ taskType: 'internal',+ taskAnalysisType: 'security',+ },+ };+ const durations = {+ 'self-improve:security': { avgDurationMs: 600000, p80DurationMs: 600000, completed: 5 },+ _overall: { avgDurationMs: 1000, p80DurationMs: 1000, completed: 20 },+ };++ render(+ <MemoryRouter>+ <AgentCard agent={runningAgent} durations={durations} />+ </MemoryRouter>+ );++ expect(screen.getByText('10% complete')).toBeInTheDocument();+ });+it('returns the updated agent to its parent after a successful rating', async () => {const user = userEvent.setup();const updatedAgent = {diff --git a/client/src/components/cos/tabs/TaskItem.jsx b/client/src/components/cos/tabs/TaskItem.jsxindex 59052bbd10..2d0986a2c0 100644--- a/client/src/components/cos/tabs/TaskItem.jsx+++ b/client/src/components/cos/tabs/TaskItem.jsx@@ -26,6 +26,7 @@ import ConfirmButtonPair from '../../ui/ConfirmButtonPair';import { useConfirmDelete } from '../../../hooks/useConfirmDelete';import Modal from '../../ui/Modal';import CollapsibleText from '../../ui/CollapsibleText';+import { extractCosTaskType } from '../../../lib/cosTaskType';const statusIcons = {pending: <Clock size={16} aria-hidden="true" className="text-yellow-500" />,@@ -36,58 +37,6 @@ const statusIcons = {challenged: <Scale size={16} aria-hidden="true" className="text-port-warning" />};-// Extract task type from description for duration lookup (matches AgentCard logic)-function extractTaskType(description) {- if (!description) return 'general';- const d = description.toLowerCase();-- // Check for improvement task patterns first- if (d.includes('[self-improvement]') || d.includes('[improvement]')) {- if (d.includes('ui bug')) return 'task:ui-bugs';- if (d.includes('mobile')) return 'task:mobile-responsive';- if (d.includes('security')) return 'task:security';- if (d.includes('code quality')) return 'task:code-quality';- if (d.includes('console error')) return 'task:console-errors';- if (d.includes('performance')) return 'task:performance';- if (d.includes('test coverage')) return 'task:test-coverage';- if (d.includes('documentation')) return 'task:documentation';- if (d.includes('feature idea') || d.includes('brainstorm')) return 'task:feature-ideas';- if (d.includes('accessibility')) return 'task:accessibility';- if (d.includes('error handling')) return 'task:error-handling';- if (d.includes('typing') || d.includes('typescript')) return 'task:typing';- if (d.includes('release')) return 'task:release-check';- if (d.includes('dependency')) return 'task:dependency-updates';- if (d.includes('jira') && d.includes('report')) return 'task:jira-status-report';- if (d.includes('jira') || d.includes('sprint')) return 'task:jira-sprint-manager';- // plan-task matches before do-replan because both descriptions contain- // "plan.md" — plan-task's "Execute next PLAN.md item" must win over- // replan's "Audit plan.md" generic match.- if (d.includes('plan-task') || (d.includes('execute next') && d.includes('plan.md'))) return 'task:plan-task';- if (d.includes('replan') || d.includes('audit plan.md') || d.includes('plan.md')) return 'task:do-replan';- }-- // claim-issue carries a "[Claim Issue: <app>]" prefix (not the [improvement]- // marker), so classify it here before the generic "issue" → bug-fix fallback- // below would otherwise mislabel it (and skew its historical duration lookup).- if (d.includes('[claim issue:')) return 'task:claim-issue';-- // General task type classification- if (d.includes('fix') || d.includes('bug') || d.includes('error') || d.includes('issue')) return 'bug-fix';- if (d.includes('refactor') || d.includes('clean up') || d.includes('improve') || d.includes('optimize')) return 'refactor';- if (d.includes('test')) return 'testing';- if (d.includes('document') || d.includes('readme') || d.includes('docs')) return 'documentation';- if (d.includes('review') || d.includes('audit')) return 'code-review';- if (d.includes('mobile') || d.includes('responsive')) return 'mobile-responsive';- if (d.includes('security') || d.includes('vulnerability')) return 'security';- if (d.includes('performance') || d.includes('speed')) return 'performance';- if (d.includes('ui') || d.includes('ux') || d.includes('design') || d.includes('style')) return 'ui-ux';- if (d.includes('api') || d.includes('endpoint') || d.includes('route')) return 'api';- if (d.includes('database') || d.includes('migration')) return 'database';- if (d.includes('deploy') || d.includes('ci') || d.includes('cd')) return 'devops';- if (d.includes('investigate') || d.includes('debug')) return 'investigation';- return 'feature';-}-// Get success rate styling based on percentagefunction getSuccessRateStyle(rate) {if (rate >= 70) return { bg: 'bg-port-success/15', text: 'text-port-success', label: 'high' };@@ -134,7 +83,7 @@ export default function TaskItem({ task, isSystem, onRefresh, providers, duratioconst durationEstimate = useMemo(() => {if (!durations || task.status !== 'pending') return null;- const taskType = extractTaskType(task.description);+ const taskType = extractCosTaskType(task);const typeData = durations[taskType];const overallData = durations._overall;@@ -163,7 +112,7 @@ export default function TaskItem({ task, isSystem, onRefresh, providers, duratio}return null;- }, [durations, task.description, task.status]);+ }, [durations, task, task.status]);const handleStatusChange = async (newStatus, blockedReasonText = '') => {const updates = { status: newStatus, type: taskSource };diff --git a/client/src/components/cos/tabs/TaskItem.test.jsx b/client/src/components/cos/tabs/TaskItem.test.jsxindex 9bb44326ba..5bdf50738d 100644--- a/client/src/components/cos/tabs/TaskItem.test.jsx+++ b/client/src/components/cos/tabs/TaskItem.test.jsx@@ -29,6 +29,29 @@ beforeEach(() => {});describe('TaskItem task source', () => {+ it('uses the scheduled task learning bucket for its ETA instead of generic task text', () => {+ const scheduled = {+ ...task,+ id: 'sys-security',+ description: '[Self-Improvement] security audit: fix exposed configuration',+ taskType: 'internal',+ metadata: { analysisType: 'security' },+ };+ const durations = {+ 'self-improve:security': {+ avgDurationMin: 2,+ p80DurationMs: 120000,+ completed: 5,+ successRate: 100,+ },+ };++ render(<TaskItem task={scheduled} isSystem onRefresh={vi.fn()} providers={providers} durations={durations} />);++ expect(screen.getByTitle('Based on 5 completed self-improve:security tasks')).toBeInTheDocument();+ expect(screen.getByText('~2m')).toBeInTheDocument();+ });+it('updates a system task in the internal queue when saving its model', async () => {render(<TaskItem task={task} isSystem onRefresh={vi.fn()} providers={providers} />);diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex ea54cb00d3..75379f4870 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -87,6 +87,7 @@ grep -i "what you want to do" client/src/lib/README.md| `clipboard.js` | `copyToClipboard`, `writeClipboardSilently`, `readClipboard` — safe across insecure-origin contexts. Use these instead of `navigator.clipboard.writeText` inline. || `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`. |+| `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). || `diffWords.js` | `diffWords(oldText, newText)` → `{ tooLarge, oldRuns, newRuns }` — word-level Myers LCS core (tokenize on whitespace, common prefix/suffix trim, collapse to `{ text, changed }` runs, 4M-cell `DIFF_CELL_CAP` guard on the trimmed middle). Shared by `InlineDiff` (stacked), `SideBySideDiff` (columnar), and `HunkDiff`'s change blocks. || `dndTransform.js` | `dndTransformToCss(transform)` — render a dnd-kit `useSortable` transform (`{ x, y, scaleX, scaleY }` or `null`) as a CSS `transform` string. Owned replacement for `@dnd-kit/utilities`' `CSS.Transform.toString()`; use it in every `useSortable` style object instead of re-adding that dependency. |diff --git a/client/src/lib/cosTaskType.js b/client/src/lib/cosTaskType.jsnew file mode 100644index 0000000000..0841e2deee--- /dev/null+++ b/client/src/lib/cosTaskType.js@@ -0,0 +1,75 @@+// 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);+}diff --git a/client/src/lib/cosTaskType.test.js b/client/src/lib/cosTaskType.test.jsnew file mode 100644index 0000000000..30b7647170--- /dev/null+++ b/client/src/lib/cosTaskType.test.js@@ -0,0 +1,34 @@+import { describe, expect, it } from 'vitest';+import { EXTERNAL_UNTYPED_TASK_TYPE, extractCosTaskType } from './cosTaskType';++describe('extractCosTaskType', () => {+ it('keeps a scheduled analysis bucket ahead of generic words in its description', () => {+ expect(extractCosTaskType({+ description: '[Self-Improvement] security audit: fix exposed configuration',+ taskType: 'internal',+ metadata: { analysisType: 'security' }+ })).toBe('self-improve:security');+ });++ it('recognizes the archived agent analysis projection', () => {+ expect(extractCosTaskType({+ description: 'Improve the CoS task prompt',+ taskType: 'internal',+ metadata: { taskAnalysisType: 'feature-ideas' }+ })).toBe('self-improve:feature-ideas');+ });++ it('keeps user work in the user-task bucket used by learning metrics', () => {+ expect(extractCosTaskType({+ description: 'Fix the failing import',+ taskType: 'user'+ })).toBe('user-task');+ });++ it('supports tagged legacy tasks and safe untyped fallbacks', () => {+ expect(extractCosTaskType({ description: '[self-improvement] accessibility - fix labels' }))+ .toBe('self-improve:accessibility');+ expect(extractCosTaskType({ description: 'unclassified task' }))+ .toBe(EXTERNAL_UNTYPED_TASK_TYPE);+ });+});diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 42d1c19c3e..dfdf9c9eb4 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -63,6 +63,7 @@ export * from './clinicianReport.js';export * from './clipboard.js';export * from './compareHelpers.js';export * from './consoleFilters.js';+export * from './cosTaskType.js';export * from './diffLines.js';export * from './diffWords.js';export * from './dndTransform.js';diff --git a/docs/features/chief-of-staff.md b/docs/features/chief-of-staff.mdindex df8a029a68..8f3f950b9d 100644--- a/docs/features/chief-of-staff.md+++ b/docs/features/chief-of-staff.md@@ -22,6 +22,7 @@ Autonomous agent manager that watches task files, spawns sub-agents, and maintai7. **Script Generation**: Creates automation scripts for repetitive tasks8. **Report Generation**: Daily summaries of completed work9. **Durable Agent Feedback**: Completion notifications accept quick ratings, while the Agents tab keeps a filterable queue of loaded runs that still need feedback after a notification expires. Feedback details can be attached to helpful, unhelpful, or neutral ratings so learning has actionable context.+10. **Learning-Aligned ETAs**: Pending tasks and active agents resolve their estimates from the same metadata-first task-learning bucket that records outcomes, including archived scheduled-agent metadata, instead of inferring a potentially different category from task text.## Task File Format