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

feat(cos): add confidence-based auto-approval for task types

Adam Eivy6f51f5412a2b
diff --git a/PLAN.md b/PLAN.md
index ad9c7728f2..bdb690df7e 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -78,7 +78,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
- [x] **Chronotype-Aware Scheduling** — Genome sleep markers for peak-focus task scheduling
- **Identity Context Injection** — Per-task-type digital twin preamble toggle
-- **Agent Confidence & Autonomy Levels** — Dynamic tiers based on success rates
+- [x] **Agent Confidence & Autonomy Levels** — Dynamic tiers based on success rates
- **Content Calendar** — Unified calendar across platforms
- [x] **Proactive Insight Alerts** — Brain connections, success drops, goal stalls, cost spikes
- **Goal Decomposition Engine** — Auto-decompose goals into task sequences
diff --git a/client/src/components/cos/tabs/LearningTab.jsx b/client/src/components/cos/tabs/LearningTab.jsx
index eb0723904d..f7db585c2e 100644
--- a/client/src/components/cos/tabs/LearningTab.jsx
+++ b/client/src/components/cos/tabs/LearningTab.jsx
@@ -17,7 +17,11 @@ import {
ChevronRight,
Database,
RotateCcw,
- Crosshair
+ Crosshair,
+ Shield,
+ ShieldCheck,
+ ShieldAlert,
+ ShieldQuestion
} from 'lucide-react';
import toast from '../../ui/Toast';
import * as api from '../../../services/api';
@@ -28,10 +32,12 @@ export default function LearningTab() {
const [skipped, setSkipped] = useState(null);
const [durations, setDurations] = useState(null);
const [routing, setRouting] = useState(null);
+ const [confidence, setConfidence] = useState(null);
const [loading, setLoading] = useState(true);
const [backfilling, setBackfilling] = useState(false);
const [resettingType, setResettingType] = useState(null);
const [expandedSections, setExpandedSections] = useState({
+ confidence: true,
taskTypes: true,
skipped: true,
durations: false,
@@ -42,18 +48,20 @@ export default function LearningTab() {
const loadData = useCallback(async () => {
setLoading(true);
- const [learningData, performanceData, skippedData, durationsData, routingData] = await Promise.all([
+ const [learningData, performanceData, skippedData, durationsData, routingData, confidenceData] = await Promise.all([
api.getCosLearning().catch(() => null),
api.getCosLearningPerformance().catch(() => null),
api.getCosLearningSkipped().catch(() => null),
api.getCosLearningDurations().catch(() => null),
- api.getCosLearningRouting().catch(() => null)
+ api.getCosLearningRouting().catch(() => null),
+ api.getCosLearningConfidence().catch(() => null)
]);
setLearning(learningData);
setPerformance(performanceData);
setSkipped(skippedData);
setDurations(durationsData);
setRouting(routingData);
+ setConfidence(confidenceData);
setLoading(false);
}, []);
@@ -241,6 +249,86 @@ export default function LearningTab() {
</div>
)}
+ {/* Confidence & Autonomy */}
+ {confidence?.summary && (
+ <div>
+ <button
+ onClick={() => toggleSection('confidence')}
+ className="flex items-center gap-2 w-full text-left mb-3"
+ >
+ {expandedSections.confidence ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
+ <Shield size={16} className="text-port-accent" />
+ <span className="font-medium text-white">Confidence & Autonomy</span>
+ <span className="text-xs text-gray-500">
+ ({confidence.summary.total} task types)
+ </span>
+ {confidence.summary.requireApproval > 0 && (
+ <span className="text-xs bg-port-warning/20 text-port-warning px-1.5 py-0.5 rounded ml-auto">
+ {confidence.summary.requireApproval} require approval
+ </span>
+ )}
+ </button>
+ {expandedSections.confidence && (
+ <div className="space-y-3">
+ {/* Confidence Summary */}
+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
+ <div className="bg-port-card border border-port-success/30 rounded-lg p-3 text-center">
+ <ShieldCheck size={16} className="text-port-success mx-auto mb-1" />
+ <div className="text-lg font-bold text-port-success">{confidence.summary.high}</div>
+ <div className="text-xs text-gray-500">High Confidence</div>
+ </div>
+ <div className="bg-port-card border border-port-accent/30 rounded-lg p-3 text-center">
+ <Shield size={16} className="text-port-accent mx-auto mb-1" />
+ <div className="text-lg font-bold text-port-accent">{confidence.summary.medium}</div>
+ <div className="text-xs text-gray-500">Medium</div>
+ </div>
+ <div className="bg-port-card border border-port-warning/30 rounded-lg p-3 text-center">
+ <ShieldAlert size={16} className="text-port-warning mx-auto mb-1" />
+ <div className="text-lg font-bold text-port-warning">{confidence.summary.low}</div>
+ <div className="text-xs text-gray-500">Low (Approval)</div>
+ </div>
+ <div className="bg-port-card border border-port-border rounded-lg p-3 text-center">
+ <ShieldQuestion size={16} className="text-gray-400 mx-auto mb-1" />
+ <div className="text-lg font-bold text-gray-400">{confidence.summary.new}</div>
+ <div className="text-xs text-gray-500">New (No Data)</div>
+ </div>
+ </div>
+
+ {/* Thresholds Info */}
+ <div className="text-xs text-gray-500 bg-port-card border border-port-border rounded-lg px-3 py-2">
+ Thresholds: High &ge; {confidence.thresholds.highThreshold}% &middot; Low &lt; {confidence.thresholds.lowThreshold}% &middot; Min samples: {confidence.thresholds.minSamples}
+ </div>
+
+ {[
+ { items: confidence.levels.low, color: 'port-warning', Icon: ShieldAlert, title: 'Requires Approval', desc: 'These task types have low success rates and will require human approval before spawning' },
+ { items: confidence.levels.high, color: 'port-success', Icon: ShieldCheck, title: 'High Confidence', desc: 'Consistently successful — auto-approved without hesitation' }
+ ].filter(g => g.items?.length > 0).map(({ items, color, Icon, title, desc }) => (
+ <div key={title} className={`bg-port-card border border-${color}/30 rounded-lg overflow-hidden`}>
+ <div className={`px-4 py-2 bg-${color}/10 border-b border-port-border`}>
+ <span className={`text-sm font-medium text-${color} flex items-center gap-2`}>
+ <Icon size={14} />
+ {title} ({items.length})
+ </span>
+ <p className="text-xs text-gray-500 mt-0.5">{desc}</p>
+ </div>
+ <div className="divide-y divide-port-border">
+ {items.map((t) => (
+ <div key={t.taskType} className="px-4 py-2 flex items-center justify-between">
+ <span className="text-sm text-gray-300 font-mono">{t.taskType}</span>
+ <div className="flex items-center gap-3">
+ <span className="text-xs text-gray-500">{t.completed} runs</span>
+ <span className={`text-sm text-${color} font-medium`}>{t.successRate}%</span>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+
{/* Task Type Performance */}
<div>
<button
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index 04dd8e8232..c8be819ab0 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -109,6 +109,7 @@ export const getCosLearningSkipped = () => request('/cos/learning/skipped');
export const getCosLearningPerformance = () => request('/cos/learning/performance');
export const getCosLearningRouting = () => request('/cos/learning/routing');
export const getCosLearningSummary = (options) => request('/cos/learning/summary', options);
+export const getCosLearningConfidence = () => request('/cos/learning/confidence');
export const backfillCosLearning = () => request('/cos/learning/backfill', { method: 'POST' });
export const resetCosTaskTypeLearning = (taskType) => request(`/cos/learning/reset/${encodeURIComponent(taskType)}`, { method: 'POST' });
diff --git a/server/routes/cosLearningRoutes.js b/server/routes/cosLearningRoutes.js
index da205dd94d..ea34983d08 100644
--- a/server/routes/cosLearningRoutes.js
+++ b/server/routes/cosLearningRoutes.js
@@ -5,6 +5,7 @@
import { Router } from 'express';
import * as taskLearning from '../services/taskLearning.js';
import * as weeklyDigest from '../services/weeklyDigest.js';
+import { loadState } from '../services/cosState.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
const router = Router();
@@ -142,6 +143,22 @@ router.post('/learning/recalculate-durations', asyncHandler(async (req, res) =>
res.json({ success: true, ...result });
}));
+// GET /api/cos/learning/confidence - Get confidence levels for all task types
+router.get('/learning/confidence', asyncHandler(async (req, res) => {
+ const state = await loadState();
+ const thresholds = state.config?.confidenceAutoApproval ?? {};
+ const confidence = await taskLearning.getConfidenceLevels(thresholds);
+ res.json(confidence);
+}));
+
+// GET /api/cos/learning/confidence/:taskType - Get confidence for specific task type
+router.get('/learning/confidence/:taskType', asyncHandler(async (req, res) => {
+ const state = await loadState();
+ const thresholds = state.config?.confidenceAutoApproval ?? {};
+ const confidence = await taskLearning.getTaskTypeConfidence(req.params.taskType, thresholds);
+ res.json(confidence);
+}));
+
// ============================================================
// Weekly Digest Routes
// ============================================================
diff --git a/server/services/cos.js b/server/services/cos.js
index b4044385d3..620739b22c 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -22,7 +22,7 @@ import { getActiveProvider } from './providers.js';
import { parseTasksMarkdown, groupTasksByStatus, getNextTask, getAutoApprovedTasks, getAwaitingApprovalTasks, updateTaskStatus, generateTasksMarkdown } from '../lib/taskParser.js';
import { isAppOnCooldown, getNextAppForReview, markAppReviewStarted, markIdleReviewStarted } from './appActivity.js';
import { getActiveApps, getAppTaskTypeOverrides } from './apps.js';
-import { getAdaptiveCooldownMultiplier, getSkippedTaskTypes, getPerformanceSummary, checkAndRehabilitateSkippedTasks, getLearningInsights } from './taskLearning.js';
+import { getAdaptiveCooldownMultiplier, getSkippedTaskTypes, getPerformanceSummary, checkAndRehabilitateSkippedTasks, getLearningInsights, getTaskTypeConfidence } from './taskLearning.js';
import { schedule as scheduleEvent, cancel as cancelEvent, getStats as getSchedulerStats, parseCronToNextRun } from './eventScheduler.js';
import { generateProactiveTasks as generateMissionTasks, getStats as getMissionStats } from './missions.js';
import { generateTaskFromJob, recordJobExecution, recordJobGateSkip, isScriptJob, executeScriptJob, isShellJob, executeShellJob } from './autonomousJobs.js';
@@ -1249,6 +1249,21 @@ async function generateSelfImprovementTask(state) {
return await generateSelfImprovementTaskForType(nextType, state, taskDescriptions);
}
+/**
+ * Resolve auto-approval for a task based on confidence scoring.
+ * Returns { autoApproved, approvalRequired } ready to spread into task objects.
+ */
+async function resolveConfidenceApproval(state, taskTypeKey, logLabel) {
+ const config = state?.config?.confidenceAutoApproval ?? {};
+ if (config.enabled === false) return { autoApproved: true, approvalRequired: false };
+
+ const confidence = await getTaskTypeConfidence(taskTypeKey, config);
+ if (!confidence.autoApprove) {
+ emitLog('info', `🔒 ${logLabel} requires approval (${confidence.reason})`, {}, '[Confidence]');
+ }
+ return { autoApproved: confidence.autoApprove, approvalRequired: !confidence.autoApprove };
+}
+
/**
* Helper function to generate a self-improvement task for a specific type
* Used by both normal rotation and on-demand task requests
@@ -1282,6 +1297,8 @@ async function generateSelfImprovementTaskForType(taskType, state, taskDescripti
metadata.model = 'claude-opus-4-5-20251101';
}
+ const approval = await resolveConfidenceApproval(state, `self-improve:${taskType}`, `Task self-improve:${taskType}`);
+
const task = {
id: `self-improve-${taskType}-${Date.now().toString(36)}`,
status: 'pending',
@@ -1290,7 +1307,7 @@ async function generateSelfImprovementTaskForType(taskType, state, taskDescripti
description,
metadata,
taskType: 'internal',
- autoApproved: true
+ ...approval
};
return task;
@@ -1793,6 +1810,8 @@ async function generateManagedAppImprovementTask(app, state) {
metadata.model = 'claude-opus-4-5-20251101';
}
+ const approval = await resolveConfidenceApproval(state, `app-improve:${nextType}`, `Task app-improve:${nextType} for ${app.name}`);
+
const task = {
id: `app-improve-${app.id}-${nextType}-${Date.now().toString(36)}`,
status: 'pending',
@@ -1801,7 +1820,7 @@ async function generateManagedAppImprovementTask(app, state) {
description,
metadata,
taskType: 'internal',
- autoApproved: true
+ ...approval
};
return task;
@@ -1877,6 +1896,8 @@ async function generateManagedAppImprovementTaskForType(taskType, app, state, {
metadata.model = 'claude-opus-4-5-20251101';
}
+ const approval = await resolveConfidenceApproval(state, `app-improve:${taskType}`, `Task app-improve:${taskType} for ${app.name}`);
+
const task = {
id: `app-improve-${app.id}-${taskType}-${Date.now().toString(36)}`,
status: 'pending',
@@ -1885,7 +1906,7 @@ async function generateManagedAppImprovementTaskForType(taskType, app, state, {
description,
metadata,
taskType: 'internal',
- autoApproved: true
+ ...approval
};
return task;
diff --git a/server/services/cosState.js b/server/services/cosState.js
index 8d72399f71..509e8b4746 100644
--- a/server/services/cosState.js
+++ b/server/services/cosState.js
@@ -61,6 +61,12 @@ export const DEFAULT_CONFIG = {
'typo-fix',
'import-cleanup'
]
+ },
+ confidenceAutoApproval: {
+ enabled: true,
+ highThreshold: 80,
+ lowThreshold: 50,
+ minSamples: 5
}
};
diff --git a/server/services/taskLearning.js b/server/services/taskLearning.js
index 0237db9254..7cd636326e 100644
--- a/server/services/taskLearning.js
+++ b/server/services/taskLearning.js
@@ -64,21 +64,43 @@ const DEFAULT_LEARNING_DATA = {
}
};
+// In-memory cache for learning data — avoids redundant disk reads during
+// evaluation cycles where multiple functions read the same file.
+let _learningCache = null;
+let _learningCacheTime = 0;
+const LEARNING_CACHE_TTL_MS = 5000;
+
+/**
+ * Clear the learning data cache. Exposed for testing.
+ */
+export function clearLearningCache() {
+ _learningCache = null;
+ _learningCacheTime = 0;
+}
+
/**
- * Load learning data from file
+ * Load learning data from file (cached for 5s)
*/
async function loadLearningData() {
+ if (_learningCache && (Date.now() - _learningCacheTime) < LEARNING_CACHE_TTL_MS) {
+ return _learningCache;
+ }
+
if (!existsSync(DATA_DIR)) {
await ensureDir(DATA_DIR);
}
- return readJSONFile(LEARNING_FILE, { ...DEFAULT_LEARNING_DATA });
+ const data = await readJSONFile(LEARNING_FILE, { ...DEFAULT_LEARNING_DATA });
+ _learningCache = data;
+ _learningCacheTime = Date.now();
+ return data;
}
/**
* Save learning data to file
*/
async function saveLearningData(data) {
+ _learningCache = null;
data.lastUpdated = new Date().toISOString();
// Prune task types with fewer than 2 completions and last seen > 30 days ago
@@ -1740,3 +1762,87 @@ export async function getLearningSummary() {
totalCompleted: data.totals.completed
};
}
+
+/**
+ * Pure classifier — returns { tier, autoApprove } for a given metrics object.
+ * Shared by getTaskTypeConfidence() and getConfidenceLevels().
+ */
+function classifyConfidenceTier(metrics, { highThreshold = 80, lowThreshold = 50, minSamples = 5 } = {}) {
+ const completed = metrics?.completed ?? 0;
+ const successRate = metrics?.successRate ?? 0;
+
+ if (completed < minSamples) return { tier: 'new', autoApprove: true };
+ if (successRate >= highThreshold) return { tier: 'high', autoApprove: true };
+ if (successRate >= lowThreshold) return { tier: 'medium', autoApprove: true };
+ return { tier: 'low', autoApprove: false };
+}
+
+/**
+ * Calculate confidence tier for a specific task type based on learning data.
+ *
+ * @param {string} taskType - The task type to evaluate
+ * @param {Object} [thresholds] - Override default thresholds
+ * @returns {Promise<Object>} Confidence assessment
+ */
+export async function getTaskTypeConfidence(taskType, thresholds = {}) {
+ const data = await loadLearningData();
+ const metrics = data.byTaskType[taskType];
+ const { tier, autoApprove } = classifyConfidenceTier(metrics, thresholds);
+
+ const reasons = {
+ new: `Fewer than ${thresholds.minSamples ?? 5} completions — auto-approve by default`,
+ high: `${metrics?.successRate}% success across ${metrics?.completed} runs — high confidence`,
+ medium: `${metrics?.successRate}% success — acceptable confidence`,
+ low: `${metrics?.successRate}% success after ${metrics?.completed} attempts — requires approval`
+ };
+
+ return {
+ taskType,
+ tier,
+ autoApprove,
+ successRate: metrics?.successRate ?? null,
+ completed: metrics?.completed ?? 0,
+ reason: reasons[tier]
+ };
+}
+
+/**
+ * Get confidence levels for all tracked task types.
+ * Returns a summary suitable for display in the Learning tab UI.
+ *
+ * @param {Object} [thresholds] - Override default thresholds
+ * @returns {Promise<Object>} All task types grouped by confidence tier
+ */
+export async function getConfidenceLevels(thresholds = {}) {
+ const data = await loadLearningData();
+ const levels = { high: [], medium: [], low: [], new: [] };
+
+ for (const [taskType, metrics] of Object.entries(data.byTaskType)) {
+ const { tier, autoApprove } = classifyConfidenceTier(metrics, thresholds);
+ levels[tier].push({
+ taskType,
+ successRate: metrics.successRate ?? 0,
+ completed: metrics.completed || 0,
+ autoApprove,
+ lastCompleted: metrics.lastCompleted
+ });
+ }
+
+ for (const tier of Object.values(levels)) {
+ tier.sort((a, b) => b.successRate - a.successRate);
+ }
+
+ const { highThreshold = 80, lowThreshold = 50, minSamples = 5 } = thresholds;
+ return {
+ levels,
+ thresholds: { highThreshold, lowThreshold, minSamples },
+ summary: {
+ high: levels.high.length,
+ medium: levels.medium.length,
+ low: levels.low.length,
+ new: levels.new.length,
+ total: Object.values(levels).reduce((sum, arr) => sum + arr.length, 0),
+ requireApproval: levels.low.length
+ }
+ };
+}
diff --git a/server/services/taskLearning.test.js b/server/services/taskLearning.test.js
index 64c8229a11..e14d20e30e 100644
--- a/server/services/taskLearning.test.js
+++ b/server/services/taskLearning.test.js
@@ -35,7 +35,7 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => {
});
import { readFile, writeFile } from 'fs/promises';
-import { resetTaskTypeLearning, getSkippedTaskTypes, recordTaskCompletion, getRoutingAccuracy, suggestModelTier, recalculateModelTierMetrics } from './taskLearning.js';
+import { resetTaskTypeLearning, getSkippedTaskTypes, recordTaskCompletion, getRoutingAccuracy, suggestModelTier, recalculateModelTierMetrics, clearLearningCache } from './taskLearning.js';
const makeLearningData = (overrides = {}) => ({
version: 1,
@@ -96,6 +96,7 @@ describe('TaskLearning - resetTaskTypeLearning', () => {
beforeEach(() => {
vi.clearAllMocks();
+ clearLearningCache();
savedData = null;
writeFile.mockImplementation(async (_path, content) => {
savedData = JSON.parse(content);
@@ -191,6 +192,7 @@ describe('TaskLearning - resetTaskTypeLearning', () => {
describe('TaskLearning - getSkippedTaskTypes', () => {
beforeEach(() => {
vi.clearAllMocks();
+ clearLearningCache();
});
it('should return task types with <30% success and 5+ attempts', async () => {
@@ -360,6 +362,7 @@ describe('TaskLearning - recordTaskCompletion routing accuracy', () => {
beforeEach(() => {
vi.clearAllMocks();
+ clearLearningCache();
savedData = null;
writeFile.mockImplementation(async (_path, content) => {
savedData = JSON.parse(content);
@@ -426,6 +429,7 @@ describe('TaskLearning - recordTaskCompletion routing accuracy', () => {
describe('TaskLearning - getRoutingAccuracy', () => {
beforeEach(() => {
vi.clearAllMocks();
+ clearLearningCache();
});
it('should return routing accuracy matrix with misroutes', async () => {
@@ -491,6 +495,7 @@ describe('TaskLearning - getRoutingAccuracy', () => {
describe('TaskLearning - suggestModelTier with routing signals', () => {
beforeEach(() => {
vi.clearAllMocks();
+ clearLearningCache();
});
it('should suggest avoiding failing tiers', async () => {
@@ -558,6 +563,7 @@ describe('TaskLearning - recalculateModelTierMetrics', () => {
beforeEach(() => {
vi.clearAllMocks();
+ clearLearningCache();
savedData = null;
writeFile.mockImplementation(async (_path, content) => {
savedData = JSON.parse(content);