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

test([issue-1849]): cover taskLearning store/durations/promptRecommendations + moltbook challengeSolver

[._.]/ Adam Eivyb3b2ac44f2d9
diff --git a/server/integrations/moltbook/challengeSolver.test.js b/server/integrations/moltbook/challengeSolver.test.js
new file mode 100644
index 0000000000..31dacdb5b2
--- /dev/null
+++ b/server/integrations/moltbook/challengeSolver.test.js
@@ -0,0 +1,94 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('../../lib/promptRunner.js', () => ({ runPromptThroughProvider: vi.fn() }));
+vi.mock('../../services/providers.js', () => ({
+ getActiveProvider: vi.fn(),
+ getProviderById: vi.fn(),
+}));
+
+import { runPromptThroughProvider } from '../../lib/promptRunner.js';
+import { getActiveProvider, getProviderById } from '../../services/providers.js';
+import { solveChallenge } from './challengeSolver.js';
+
+const provider = { id: 'p1', defaultModel: 'm', models: ['m'] };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getActiveProvider.mockResolvedValue(provider);
+ getProviderById.mockResolvedValue(null);
+});
+
+describe('solveChallenge — number extraction + formatting', () => {
+ it('returns a clean 2-decimal answer for a well-formed numeric reply', async () => {
+ runPromptThroughProvider.mockResolvedValue({ text: '47.00' });
+ expect(await solveChallenge('garbled 40 + 7')).toBe('47.00');
+ });
+
+ it('extracts the first number embedded in surrounding prose', async () => {
+ runPromptThroughProvider.mockResolvedValue({ text: 'The answer is 12.5 exactly.' });
+ expect(await solveChallenge('x')).toBe('12.50');
+ });
+
+ it('formats a bare integer reply to two decimals', async () => {
+ runPromptThroughProvider.mockResolvedValue({ text: '100' });
+ expect(await solveChallenge('x')).toBe('100.00');
+ });
+
+ it('trims leading whitespace before matching', async () => {
+ runPromptThroughProvider.mockResolvedValue({ text: ' 8.0' });
+ expect(await solveChallenge('x')).toBe('8.00');
+ });
+
+ it('returns null when the AI reply contains no number', async () => {
+ runPromptThroughProvider.mockResolvedValue({ text: 'I cannot solve this.' });
+ expect(await solveChallenge('x')).toBeNull();
+ });
+
+ it('returns null when the AI reply text is missing', async () => {
+ runPromptThroughProvider.mockResolvedValue({ text: undefined });
+ expect(await solveChallenge('x')).toBeNull();
+ });
+});
+
+describe('solveChallenge — provider selection and failure handling', () => {
+ it('returns null and never calls the runner when no provider is available', async () => {
+ getActiveProvider.mockResolvedValue(null);
+ expect(await solveChallenge('x')).toBeNull();
+ expect(runPromptThroughProvider).not.toHaveBeenCalled();
+ });
+
+ it('prefers an explicit providerId over the active provider', async () => {
+ const explicit = { id: 'explicit', defaultModel: 'em' };
+ getProviderById.mockResolvedValue(explicit);
+ runPromptThroughProvider.mockResolvedValue({ text: '5.00' });
+
+ await solveChallenge('x', { providerId: 'explicit' });
+
+ expect(getProviderById).toHaveBeenCalledWith('explicit');
+ expect(getActiveProvider).not.toHaveBeenCalled();
+ expect(runPromptThroughProvider).toHaveBeenCalledWith(
+ expect.objectContaining({ provider: explicit, model: 'em' }),
+ );
+ });
+
+ it('falls back to the active provider when getProviderById rejects', async () => {
+ getProviderById.mockRejectedValue(new Error('boom'));
+ runPromptThroughProvider.mockResolvedValue({ text: '3.00' });
+
+ expect(await solveChallenge('x', { providerId: 'missing' })).toBe('3.00');
+ expect(getActiveProvider).toHaveBeenCalled();
+ });
+
+ it('swallows a runner error and returns null', async () => {
+ runPromptThroughProvider.mockRejectedValue(new Error('LLM down'));
+ expect(await solveChallenge('x')).toBeNull();
+ });
+
+ it('uses an explicit model override when provided', async () => {
+ runPromptThroughProvider.mockResolvedValue({ text: '1.00' });
+ await solveChallenge('x', { model: 'custom-model' });
+ expect(runPromptThroughProvider).toHaveBeenCalledWith(
+ expect.objectContaining({ model: 'custom-model' }),
+ );
+ });
+});
diff --git a/server/services/taskLearning/durations.test.js b/server/services/taskLearning/durations.test.js
new file mode 100644
index 0000000000..233bf740fa
--- /dev/null
+++ b/server/services/taskLearning/durations.test.js
@@ -0,0 +1,145 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Mock only the persistence read; keep extractTaskType (a pure helper) real so
+// the description→taskType resolution inside getTaskDurationEstimate is exercised
+// end-to-end.
+vi.mock('./store.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, loadLearningData: vi.fn() };
+});
+
+import { loadLearningData } from './store.js';
+import { getTaskDurationEstimate, getAllTaskDurations, estimateQueueCompletion } from './durations.js';
+
+const baseData = (overrides = {}) => ({
+ byTaskType: {},
+ totals: { completed: 0, succeeded: 0, failed: 0, totalDurationMs: 0, avgDurationMs: 0 },
+ ...overrides,
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('durations.getTaskDurationEstimate', () => {
+ it('classifies confidence by completion count for a matched type', async () => {
+ loadLearningData.mockResolvedValue(baseData({
+ byTaskType: {
+ 'self-improve:ui': { completed: 12, avgDurationMs: 60000, p80DurationMs: 90000, successRate: 80 },
+ },
+ }));
+ const est = await getTaskDurationEstimate('[self-improvement] ui - tidy');
+ expect(est.taskType).toBe('self-improve:ui');
+ expect(est.estimatedDurationMin).toBe(1); // round(60000/60000)
+ expect(est.p80DurationMs).toBe(90000);
+ expect(est.confidence).toBe('high'); // >= 10
+ expect(est.basedOn).toBe(12);
+ });
+
+ it('reports medium and low confidence at the tier boundaries', async () => {
+ loadLearningData.mockResolvedValue(baseData({
+ byTaskType: {
+ 'self-improve:ui': { completed: 5, avgDurationMs: 60000, successRate: 50 },
+ },
+ }));
+ let est = await getTaskDurationEstimate('[self-improvement] ui');
+ expect(est.confidence).toBe('medium'); // 5..9
+ expect(est.p80DurationMs).toBe(60000); // falls back to avg when p80 absent
+
+ loadLearningData.mockResolvedValue(baseData({
+ byTaskType: {
+ 'self-improve:ui': { completed: 3, avgDurationMs: 60000, successRate: 50 },
+ },
+ }));
+ est = await getTaskDurationEstimate('[self-improvement] ui');
+ expect(est.confidence).toBe('low'); // 2..4
+ });
+
+ it('falls back to overall totals when the type has < 2 completions', async () => {
+ loadLearningData.mockResolvedValue(baseData({
+ byTaskType: { 'self-improve:ui': { completed: 1, avgDurationMs: 1000 } },
+ totals: { completed: 6, succeeded: 3, failed: 3, totalDurationMs: 1200000, avgDurationMs: 200000 },
+ }));
+ const est = await getTaskDurationEstimate('[self-improvement] ui');
+ expect(est.taskType).toBe('all');
+ expect(est.confidence).toBe('low');
+ expect(est.estimatedDurationMin).toBe(3); // round(200000/60000)
+ expect(est.successRate).toBe(50); // round(3/6*100)
+ });
+
+ it('returns the none sentinel when there is not enough data anywhere', async () => {
+ loadLearningData.mockResolvedValue(baseData({
+ totals: { completed: 2, succeeded: 1, failed: 1, totalDurationMs: 100, avgDurationMs: 50 },
+ }));
+ const est = await getTaskDurationEstimate('something brand new');
+ expect(est).toEqual({
+ estimatedDurationMs: null, estimatedDurationMin: null,
+ confidence: 'none', basedOn: 0, taskType: null, successRate: null,
+ });
+ });
+});
+
+describe('durations.getAllTaskDurations', () => {
+ it('includes every type with >= 1 completion plus an _overall row', async () => {
+ loadLearningData.mockResolvedValue(baseData({
+ byTaskType: {
+ a: { completed: 3, avgDurationMs: 60000, p80DurationMs: 90000, maxDurationMs: 120000, successRate: 66 },
+ b: { completed: 0, avgDurationMs: 5000 }, // skipped (0 completions)
+ },
+ totals: { completed: 5, succeeded: 4, failed: 1, totalDurationMs: 600000, avgDurationMs: 120000 },
+ }));
+ const out = await getAllTaskDurations();
+ expect(out.a).toMatchObject({ avgDurationMin: 1, p80DurationMs: 90000, maxDurationMs: 120000, completed: 3 });
+ expect(out.b).toBeUndefined();
+ expect(out._overall).toMatchObject({ completed: 5, successRate: 80 }); // round(4/5*100)
+ });
+
+ it('returns an empty object when there is no completed history', async () => {
+ loadLearningData.mockResolvedValue(baseData());
+ expect(await getAllTaskDurations()).toEqual({});
+ });
+});
+
+describe('durations.estimateQueueCompletion', () => {
+ it('matches tasks by type keyword and formats sub-hour estimates', async () => {
+ loadLearningData.mockResolvedValue(baseData({
+ byTaskType: {
+ 'self-improve:ui': { completed: 4, avgDurationMs: 600000, successRate: 50 }, // 10 min
+ },
+ totals: { completed: 4, succeeded: 2, failed: 2, totalDurationMs: 2400000, avgDurationMs: 600000 },
+ }));
+ const out = await estimateQueueCompletion([{ description: 'fix ui glitch' }], 0);
+ expect(out.taskCount).toBe(1);
+ expect(out.basedOnHistory).toBe(true);
+ expect(out.formatted).toBe('~10m');
+ expect(out.confidence).toBe(100);
+ });
+
+ it('uses the overall average for unmatched tasks and adds half a running task', async () => {
+ loadLearningData.mockResolvedValue(baseData({
+ byTaskType: { 'self-improve:ui': { completed: 4, avgDurationMs: 600000, successRate: 50 } },
+ totals: { completed: 4, succeeded: 2, failed: 2, totalDurationMs: 2400000, avgDurationMs: 600000 },
+ }));
+ // unmatched description → overallAvg 600000; runningCount 1 adds 0.5*600000=300000
+ const out = await estimateQueueCompletion([{ description: 'totally unrelated work' }], 1);
+ expect(out.totalMs).toBe(900000); // 600000 + 300000
+ expect(out.basedOnHistory).toBe(false);
+ expect(out.confidence).toBe(0); // 0 matched of 2 total
+ });
+
+ it('formats multi-hour estimates with hours and minutes', async () => {
+ loadLearningData.mockResolvedValue(baseData({
+ totals: { completed: 4, succeeded: 4, failed: 0, totalDurationMs: 4 * 5400000, avgDurationMs: 5400000 },
+ }));
+ // 90 min average; two unmatched tasks → 180 min = 3h 0m
+ const out = await estimateQueueCompletion([{ description: 'x' }, { description: 'y' }], 0);
+ expect(out.formatted).toBe('~3h');
+ });
+
+ it('reports "under 1m" for an empty queue', async () => {
+ loadLearningData.mockResolvedValue(baseData());
+ const out = await estimateQueueCompletion([], 0);
+ expect(out.formatted).toBe('under 1m');
+ expect(out.confidence).toBe(0);
+ });
+});
diff --git a/server/services/taskLearning/promptRecommendations.js b/server/services/taskLearning/promptRecommendations.js
index d215979325..efd618ec4f 100644
--- a/server/services/taskLearning/promptRecommendations.js
+++ b/server/services/taskLearning/promptRecommendations.js
@@ -276,7 +276,10 @@ export async function getAllPromptRecommendations() {
// Sort by priority (critical first, then needs-improvement, etc.)
const priorityOrder = { critical: 0, 'needs-improvement': 1, moderate: 2, good: 3, 'insufficient-data': 4 };
- allRecommendations.sort((a, b) => (priorityOrder[a.status] || 5) - (priorityOrder[b.status] || 5));
+ // Use ?? not || so the highest-priority status (`critical`, value 0) isn't
+ // treated as falsy and bumped to the catch-all 5 — that would sort the most
+ // urgent recommendations LAST, inverting the intended "critical first" order.
+ allRecommendations.sort((a, b) => (priorityOrder[a.status] ?? 5) - (priorityOrder[b.status] ?? 5));
return allRecommendations;
}
diff --git a/server/services/taskLearning/promptRecommendations.test.js b/server/services/taskLearning/promptRecommendations.test.js
new file mode 100644
index 0000000000..2be5ebb692
--- /dev/null
+++ b/server/services/taskLearning/promptRecommendations.test.js
@@ -0,0 +1,105 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('./store.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, loadLearningData: vi.fn() };
+});
+
+import { loadLearningData } from './store.js';
+import { getPromptImprovementRecommendations, getAllPromptRecommendations } from './promptRecommendations.js';
+
+const data = (overrides = {}) => ({ byTaskType: {}, errorPatterns: {}, ...overrides });
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('promptRecommendations.getPromptImprovementRecommendations', () => {
+ it('reports insufficient-data when the type is missing or under 3 completions', async () => {
+ loadLearningData.mockResolvedValue(data());
+ let rec = await getPromptImprovementRecommendations('absent-type');
+ expect(rec.hasData).toBe(false);
+ expect(rec.status).toBe('insufficient-data');
+
+ loadLearningData.mockResolvedValue(data({
+ byTaskType: { sparse: { completed: 2, failed: 1, successRate: 50, avgDurationMs: 1000 } },
+ }));
+ rec = await getPromptImprovementRecommendations('sparse');
+ expect(rec.status).toBe('insufficient-data');
+ expect(rec.message).toContain('2 completions');
+ });
+
+ it('flags a critical status with a major-revision suggestion under 30% success', async () => {
+ loadLearningData.mockResolvedValue(data({
+ byTaskType: { t: { completed: 10, failed: 8, successRate: 20, avgDurationMs: 60000 } },
+ }));
+ const rec = await getPromptImprovementRecommendations('t');
+ expect(rec.status).toBe('critical');
+ expect(rec.suggestions[0]).toMatchObject({ priority: 'high', type: 'major-revision' });
+ });
+
+ it('maps each success-rate band to the right status', async () => {
+ const bands = [
+ [40, 'needs-improvement'],
+ [60, 'moderate'],
+ [90, 'good'],
+ ];
+ for (const [successRate, status] of bands) {
+ loadLearningData.mockResolvedValue(data({
+ byTaskType: { t: { completed: 10, failed: 4, successRate, avgDurationMs: 60000 } },
+ }));
+ const rec = await getPromptImprovementRecommendations('t');
+ expect(rec.status).toBe(status);
+ }
+ });
+
+ it('derives error insights and prompt hints from task-specific error patterns', async () => {
+ loadLearningData.mockResolvedValue(data({
+ byTaskType: { t: { completed: 10, failed: 10, successRate: 20, avgDurationMs: 60000 } },
+ errorPatterns: {
+ 'context-length': { taskTypes: { t: 5 } },
+ 'rate-limit': { taskTypes: { t: 5 } },
+ 'uncategorized-no-insight': { taskTypes: { t: 1 } },
+ },
+ }));
+ const rec = await getPromptImprovementRecommendations('t');
+ const insightMsgs = rec.errorInsights.map(i => i.message).join(' ');
+ expect(insightMsgs).toMatch(/context length/);
+ expect(insightMsgs).toMatch(/rate limiting/);
+ // categories without a known insight/hint contribute nothing
+ expect(rec.errorInsights).toHaveLength(2);
+ expect(rec.promptHints.some(h => h.hint === 'Reduce scope of file analysis')).toBe(true);
+ });
+
+ it('adds a scope suggestion when the average duration exceeds 30 minutes', async () => {
+ loadLearningData.mockResolvedValue(data({
+ byTaskType: { t: { completed: 10, failed: 1, successRate: 90, avgDurationMs: 40 * 60000 } },
+ }));
+ const rec = await getPromptImprovementRecommendations('t');
+ expect(rec.suggestions.some(s => s.type === 'scope')).toBe(true);
+ });
+
+ it('appends general hints based on task-type keywords', async () => {
+ loadLearningData.mockResolvedValue(data({
+ byTaskType: { 'self-improve:security-audit': { completed: 10, failed: 1, successRate: 90, avgDurationMs: 1000 } },
+ }));
+ const rec = await getPromptImprovementRecommendations('self-improve:security-audit');
+ expect(rec.promptHints.some(h => h.hint === 'Add severity classification')).toBe(true);
+ });
+});
+
+describe('promptRecommendations.getAllPromptRecommendations', () => {
+ it('returns only types with >= 3 completions, sorted critical-first', async () => {
+ loadLearningData.mockResolvedValue(data({
+ byTaskType: {
+ good: { completed: 10, failed: 1, successRate: 90, avgDurationMs: 1000 },
+ broken: { completed: 10, failed: 9, successRate: 10, avgDurationMs: 1000 },
+ tiny: { completed: 2, failed: 1, successRate: 50, avgDurationMs: 1000 },
+ },
+ }));
+ const all = await getAllPromptRecommendations();
+ // critical (priority 0) must sort first — regression guard against the
+ // `priorityOrder[status] || 5` footgun that treated 0 as falsy and sorted
+ // the most urgent recommendation last.
+ expect(all.map(r => r.taskType)).toEqual(['broken', 'good']);
+ expect(all[0].status).toBe('critical');
+ });
+});
diff --git a/server/services/taskLearning/store.test.js b/server/services/taskLearning/store.test.js
new file mode 100644
index 0000000000..fa19c437d0
--- /dev/null
+++ b/server/services/taskLearning/store.test.js
@@ -0,0 +1,109 @@
+import { describe, it, expect } from 'vitest';
+import { extractTaskType, calculateDurationETA } 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
+// exercise every branch arm directly without mocking the persistence layer.
+
+describe('store.extractTaskType', () => {
+ it('prefers metadata.analysisType (self-improve) over everything else', () => {
+ expect(extractTaskType({ metadata: { analysisType: 'ui-bugs' } })).toBe('self-improve:ui-bugs');
+ });
+
+ it('accepts the forwarded taskAnalysisType alias', () => {
+ expect(extractTaskType({ metadata: { taskAnalysisType: 'console' } })).toBe('self-improve:console');
+ });
+
+ it('maps an idle reviewType to idle-review', () => {
+ expect(extractTaskType({ metadata: { reviewType: 'idle' } })).toBe('idle-review');
+ expect(extractTaskType({ metadata: { taskReviewType: 'idle' } })).toBe('idle-review');
+ });
+
+ 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');
+ });
+
+ it('classifies mission tasks by mission name', () => {
+ expect(extractTaskType({ metadata: { missionName: 'cleanup' } })).toBe('mission:cleanup');
+ });
+
+ 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');
+ });
+
+ it('parses a [self-improvement] description tag with a type token', () => {
+ expect(extractTaskType({ description: '[self-improvement] accessibility - fix labels' }))
+ .toBe('self-improve:accessibility');
+ });
+
+ it('falls back to self-improve:general when the tag has no type token', () => {
+ expect(extractTaskType({ description: '[self-improvement] !!!' })).toBe('self-improve:general');
+ });
+
+ it('matches description tags case-insensitively', () => {
+ expect(extractTaskType({ description: '[IDLE REVIEW] poke around' })).toBe('idle-review');
+ });
+
+ it('recognizes the auto-fix description variants', () => {
+ expect(extractTaskType({ description: '[auto-fix] retry' })).toBe('auto-fix');
+ expect(extractTaskType({ description: '[auto] investigate the crash' })).toBe('auto-fix');
+ });
+
+ it('recognizes both app-improvement spellings in the description', () => {
+ expect(extractTaskType({ description: '[app-improvement] thing' })).toBe('app-improvement');
+ expect(extractTaskType({ description: '[app improvement] thing' })).toBe('app-improvement');
+ });
+
+ it('classifies user and internal tasks by taskType when no pattern matches', () => {
+ expect(extractTaskType({ taskType: 'user', description: 'do a thing' })).toBe('user-task');
+ 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');
+ });
+});
+
+describe('store.calculateDurationETA', () => {
+ it('uses success-only stats when successDurationMs is present', () => {
+ const out = calculateDurationETA({
+ successDurationMs: 600000, succeeded: 6, successMaxDurationMs: 200000,
+ totalDurationMs: 9999999, completed: 99,
+ });
+ expect(out.avgDurationMs).toBe(100000); // 600000 / 6
+ expect(out.maxDurationMs).toBe(200000);
+ // p80 = round(min(avg*3, avg + 0.6*(max-avg))) = round(min(300000, 160000)) = 160000
+ expect(out.p80DurationMs).toBe(160000);
+ });
+
+ it('falls back to total stats when there is no success data', () => {
+ const out = calculateDurationETA({
+ successDurationMs: 0, succeeded: 0,
+ totalDurationMs: 400000, completed: 4,
+ });
+ expect(out.avgDurationMs).toBe(100000); // 400000 / 4
+ // no success data → max defaults to avg, so p80 collapses to avg
+ expect(out.maxDurationMs).toBe(100000);
+ expect(out.p80DurationMs).toBe(100000);
+ });
+
+ it('returns all-zero stats when the count base is zero or missing', () => {
+ expect(calculateDurationETA({ totalDurationMs: 100, completed: 0 }))
+ .toEqual({ avgDurationMs: 0, maxDurationMs: 0, p80DurationMs: 0 });
+ expect(calculateDurationETA({}))
+ .toEqual({ avgDurationMs: 0, maxDurationMs: 0, p80DurationMs: 0 });
+ });
+
+ it('clamps p80 to at most avg*3 when the spread is very wide', () => {
+ const out = calculateDurationETA({
+ successDurationMs: 100000, succeeded: 1, successMaxDurationMs: 10000000,
+ });
+ expect(out.avgDurationMs).toBe(100000);
+ // avg + 0.6*(max-avg) would be huge; the avg*3 cap wins → 300000
+ expect(out.p80DurationMs).toBe(300000);
+ });
+});