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([issue-915]): dry-run logs only auto-approved tasks execute would spawn

Adam Eivyde6f5f2c2fa4
diff --git a/server/services/cos.js b/server/services/cos.js
index 7ab78401ab..c468779200 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -83,6 +83,7 @@ import {
generateSelfImprovementTaskForType,
generateManagedAppImprovementTaskForType,
blockIfExceedsMaxSpawns,
+ selectDryRunAutoApproved,
countRunningAgentsByProject,
isWithinProjectLimit,
checkStagePrecondition,
@@ -750,30 +751,51 @@ async function dequeueNextTask() {
const autoApproved = cosTaskData.autoApproved || [];
const cosAutonomyMode = getDomainMode(state.config, 'cos');
- for (const task of autoApproved) {
- if (spawned >= availableSlots) break;
- if (cosAutonomyMode !== 'execute') {
- if (cosAutonomyMode === 'dry-run') {
+ // Engine-specific gate shared by execute and dry-run: improvement tasks whose
+ // task type was disabled after queuing are skipped.
+ const isDisabledAnalysisType = (task) => {
+ const analysisType = task.metadata?.analysisType || task.metadata?.selfImprovementType;
+ return Boolean(analysisType) && !taskSchedule.tasks[analysisType]?.enabled;
+ };
+
+ if (cosAutonomyMode !== 'execute') {
+ // off/dry-run withhold the unattended spawn; dry-run logs only the tasks
+ // execute mode would ACTUALLY spawn — applying the same max-spawns /
+ // disabled-type / cooldown / per-project gates against virtual capacity —
+ // rather than every auto-approved task regardless of eligibility.
+ if (cosAutonomyMode === 'dry-run') {
+ const wouldSpawn = await selectDryRunAutoApproved(autoApproved, {
+ availableSlots,
+ alreadySpawned: spawned,
+ perProjectLimit,
+ spawnProjectCounts,
+ isOnCooldown: (appId) => isAppOnCooldown(appId, state.config.appReviewCooldownMs),
+ extraSkip: isDisabledAnalysisType
+ });
+ for (const task of wouldSpawn) {
emitLog('info', `[dry-run] CoS auto-run would spawn system task: ${task.id}`, { taskId: task.id, domainAutonomy: 'cos' });
}
- continue;
}
- if (await blockIfExceedsMaxSpawns(task, 'internal')) continue;
- // Skip improvement tasks whose type was disabled after queuing
- const analysisType = task.metadata?.analysisType || task.metadata?.selfImprovementType;
- if (analysisType && !taskSchedule.tasks[analysisType]?.enabled) {
- emitLog('info', `System task skipped — task type '${analysisType}' is disabled`, { taskId: task.id });
- continue;
- }
- const appId = task.metadata?.app;
- if (appId) {
- const onCooldown = await isAppOnCooldown(appId, state.config.appReviewCooldownMs);
- if (onCooldown) continue;
+ } else {
+ for (const task of autoApproved) {
+ if (spawned >= availableSlots) break;
+ if (await blockIfExceedsMaxSpawns(task, 'internal')) continue;
+ // Skip improvement tasks whose type was disabled after queuing
+ if (isDisabledAnalysisType(task)) {
+ const analysisType = task.metadata?.analysisType || task.metadata?.selfImprovementType;
+ emitLog('info', `System task skipped — task type '${analysisType}' is disabled`, { taskId: task.id });
+ continue;
+ }
+ const appId = task.metadata?.app;
+ if (appId) {
+ const onCooldown = await isAppOnCooldown(appId, state.config.appReviewCooldownMs);
+ if (onCooldown) continue;
+ }
+ const sysTask = { ...task, taskType: 'internal' };
+ if (!canSpawn(sysTask)) continue;
+ cosEvents.emit('task:ready', sysTask);
+ trackSpawn(sysTask);
}
- const sysTask = { ...task, taskType: 'internal' };
- if (!canSpawn(sysTask)) continue;
- cosEvents.emit('task:ready', sysTask);
- trackSpawn(sysTask);
}
const hasPendingUserTasks = pendingUserTasks.length > 0;
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 15e3c2a22b..34b50acde5 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -39,8 +39,8 @@ import { isRecoveryTask } from './recoveryTasks.js';
* Block a task that has exceeded the max spawn limit. Returns true if blocked.
*/
export async function blockIfExceedsMaxSpawns(task, taskType) {
+ if (!exceedsMaxSpawns(task)) return false;
const totalSpawns = Number(task.metadata?.totalSpawnCount) || 0;
- if (totalSpawns < MAX_TOTAL_SPAWNS) return false;
emitLog('info', `🚫 Blocking task ${task.id} — exceeded max spawns (${totalSpawns}/${MAX_TOTAL_SPAWNS})`, { taskId: task.id });
await updateTask(task.id, {
status: 'blocked',
@@ -51,6 +51,73 @@ export async function blockIfExceedsMaxSpawns(task, taskType) {
return true;
}
+/**
+ * Non-mutating sibling of `blockIfExceedsMaxSpawns` — true when a task has hit
+ * the max-total-spawns ceiling, WITHOUT blocking/persisting it. Used by the
+ * dry-run eligibility pass, which must predict execute's skip without mutating.
+ */
+export function exceedsMaxSpawns(task) {
+ return (Number(task.metadata?.totalSpawnCount) || 0) >= MAX_TOTAL_SPAWNS;
+}
+
+/**
+ * Dry-run eligibility pass over auto-approved system tasks. Walks the tasks in
+ * file order applying the SAME gates execute mode uses — global slot cap,
+ * max-total-spawns, app cooldown, per-project cap — while tracking virtual
+ * capacity, and returns the ordered subset execute mode WOULD spawn. It never
+ * blocks, persists, or emits anything, so a dry-run can log exactly the set
+ * execute would spawn instead of over-reporting (logging tasks execute would
+ * skip) or under-reporting (stopping early before applying the gates).
+ *
+ * The two spawn engines (`dequeueNextTask` in cos.js and `evaluateTasks` here)
+ * have small execute-path differences, expressed via the optional per-task
+ * hooks so each engine's dry-run plan matches its own execute path:
+ * `extraSkip` adds an engine-specific gate (dequeue's disabled-analysis-type
+ * check); `cooldownExempt` exempts a task from the cooldown gate (this engine's
+ * pipeline-continuation bypass).
+ *
+ * @param {object[]} autoApproved - auto-approved system tasks, file order
+ * @param {object} ctx
+ * @param {number} ctx.availableSlots - global free slots at the start of this cycle
+ * @param {number} ctx.alreadySpawned - slots already consumed by higher-priority picks (on-demand/user)
+ * @param {number} ctx.perProjectLimit - per-project concurrent cap
+ * @param {Record<string, number>} ctx.spawnProjectCounts - running+spawned counts per project (cloned, not mutated)
+ * @param {(appId: string) => Promise<boolean>} ctx.isOnCooldown - async cooldown probe
+ * @param {(task: object) => boolean} [ctx.cooldownExempt] - true ⇒ skip the cooldown gate for this task
+ * @param {(task: object) => boolean} [ctx.extraSkip] - true ⇒ task ineligible (engine-specific gate)
+ * @returns {Promise<object[]>} the tasks execute mode would spawn, in order
+ */
+export async function selectDryRunAutoApproved(autoApproved, ctx) {
+ const {
+ availableSlots,
+ alreadySpawned = 0,
+ perProjectLimit,
+ spawnProjectCounts = {},
+ isOnCooldown,
+ cooldownExempt = () => false,
+ extraSkip = () => false
+ } = ctx;
+
+ const counts = { ...spawnProjectCounts };
+ let spawned = alreadySpawned;
+ const spawnable = [];
+
+ for (const task of autoApproved) {
+ if (spawned >= availableSlots) break;
+ if (exceedsMaxSpawns(task)) continue;
+ if (extraSkip(task)) continue;
+ const appId = task.metadata?.app;
+ if (appId && !cooldownExempt(task) && (await isOnCooldown(appId))) continue;
+ const project = appId || '_self';
+ if ((counts[project] || 0) >= perProjectLimit) continue;
+ counts[project] = (counts[project] || 0) + 1;
+ spawned++;
+ spawnable.push(task);
+ }
+
+ return spawnable;
+}
+
// Task types where the scheduler reads PLAN.md to find an in-flight-aware pick.
// `do-replan` is excluded — it assigns IDs rather than picking one off the list.
const PLAN_PICK_TASK_TYPES = new Set(['feature-ideas', 'plan-task']);
@@ -357,7 +424,18 @@ export async function evaluateTasks(options) {
// what would have run so the user can see the plan without it executing.
if (tasksToSpawn.length < availableSlots && cosTaskData.exists && cosAutonomyMode !== 'execute') {
if (cosAutonomyMode === 'dry-run') {
- for (const task of (cosTaskData.autoApproved || [])) {
+ // Log only the tasks execute mode would ACTUALLY spawn — applying the same
+ // max-spawns / cooldown / per-project gates against virtual capacity —
+ // rather than every auto-approved task regardless of eligibility.
+ const wouldSpawn = await selectDryRunAutoApproved(cosTaskData.autoApproved || [], {
+ availableSlots,
+ alreadySpawned: tasksToSpawn.length,
+ perProjectLimit,
+ spawnProjectCounts,
+ isOnCooldown: (appId) => isAppOnCooldown(appId, state.config.appReviewCooldownMs),
+ cooldownExempt: (task) => task.metadata?.pipeline?.currentStage > 0
+ });
+ for (const task of wouldSpawn) {
emitLog('info', `[dry-run] CoS auto-run would spawn system task: ${task.id}`, { taskId: task.id, domainAutonomy: 'cos' });
}
}
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
new file mode 100644
index 0000000000..7496a9889f
--- /dev/null
+++ b/server/services/cosTaskGenerator.test.js
@@ -0,0 +1,168 @@
+/**
+ * Tests for the dry-run eligibility helpers in cosTaskGenerator.js.
+ *
+ * `selectDryRunAutoApproved` is the shared, non-mutating pass both spawn
+ * engines (`dequeueNextTask` in cos.js and `evaluateTasks` here) use to log
+ * exactly the auto-approved system tasks execute mode WOULD spawn — applying
+ * the same global-slot / max-spawns / cooldown / per-project gates against
+ * virtual capacity, without blocking, persisting, or emitting anything. The
+ * pre-fix dry-run logged every auto-approved task regardless of eligibility
+ * (over-report) and, in dequeue, stopped once user tasks filled the slots
+ * (under-report). These tests pin both behaviors.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'fs';
+import { fileURLToPath } from 'url';
+import { dirname, join } from 'path';
+import { selectDryRunAutoApproved, exceedsMaxSpawns } from './cosTaskGenerator.js';
+import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const GEN_SRC = readFileSync(join(__dirname, 'cosTaskGenerator.js'), 'utf-8');
+const COS_SRC = readFileSync(join(__dirname, 'cos.js'), 'utf-8');
+
+const task = (id, metadata = {}) => ({ id, metadata });
+const noCooldown = () => Promise.resolve(false);
+
+// The unit tests above exercise selectDryRunAutoApproved with synthetic hooks;
+// these source-level guards pin that each ENGINE wires the hook set matching
+// its own execute path — so a future edit can't silently swap or drop a hook
+// (e.g. give dequeue the pipeline cooldown bypass it doesn't have in execute).
+describe('dry-run hook wiring matches each engine execute path', () => {
+ // Isolate each engine's selectDryRunAutoApproved call site.
+ const callSite = (src) => {
+ // Anchor on the CALL (`await selectDryRunAutoApproved(`), not the function
+ // definition (`export async function selectDryRunAutoApproved(`).
+ const start = src.indexOf('await selectDryRunAutoApproved(');
+ expect(start, 'selectDryRunAutoApproved must be called').toBeGreaterThan(-1);
+ return src.slice(start, src.indexOf('});', start) + 3);
+ };
+
+ it('dequeueNextTask (cos.js) passes extraSkip (disabled-analysis-type) but NOT cooldownExempt', () => {
+ const site = callSite(COS_SRC);
+ expect(site).toContain('extraSkip: isDisabledAnalysisType');
+ expect(site).not.toContain('cooldownExempt');
+ });
+
+ it('evaluateTasks (cosTaskGenerator.js) passes cooldownExempt (pipeline continuation) but NOT extraSkip', () => {
+ const site = callSite(GEN_SRC);
+ expect(site).toContain('cooldownExempt:');
+ expect(site).toContain('pipeline?.currentStage > 0');
+ expect(site).not.toContain('extraSkip');
+ });
+});
+
+describe('exceedsMaxSpawns', () => {
+ it('is false below the ceiling and true at/above it — no mutation', () => {
+ expect(exceedsMaxSpawns(task('a', { totalSpawnCount: 0 }))).toBe(false);
+ expect(exceedsMaxSpawns(task('b', { totalSpawnCount: MAX_TOTAL_SPAWNS - 1 }))).toBe(false);
+ expect(exceedsMaxSpawns(task('c', { totalSpawnCount: MAX_TOTAL_SPAWNS }))).toBe(true);
+ expect(exceedsMaxSpawns(task('d', { totalSpawnCount: MAX_TOTAL_SPAWNS + 3 }))).toBe(true);
+ });
+
+ it('treats a missing/NaN totalSpawnCount as zero', () => {
+ expect(exceedsMaxSpawns(task('a'))).toBe(false);
+ expect(exceedsMaxSpawns(task('b', { totalSpawnCount: 'nope' }))).toBe(false);
+ });
+});
+
+describe('selectDryRunAutoApproved', () => {
+ const baseCtx = {
+ availableSlots: 5,
+ alreadySpawned: 0,
+ perProjectLimit: 5,
+ spawnProjectCounts: {},
+ isOnCooldown: noCooldown
+ };
+
+ it('returns all tasks when nothing gates them out', async () => {
+ const tasks = [task('1'), task('2'), task('3')];
+ const out = await selectDryRunAutoApproved(tasks, baseCtx);
+ expect(out.map(t => t.id)).toEqual(['1', '2', '3']);
+ });
+
+ it('stops at the global slot cap (does not over-report)', async () => {
+ const tasks = [task('1'), task('2'), task('3'), task('4')];
+ const out = await selectDryRunAutoApproved(tasks, { ...baseCtx, availableSlots: 2 });
+ expect(out.map(t => t.id)).toEqual(['1', '2']);
+ });
+
+ it('honors slots already consumed by higher-priority picks (under-report fix)', async () => {
+ // Two of three slots already taken by on-demand/user tasks → only one auto-approved fits.
+ const tasks = [task('1'), task('2'), task('3')];
+ const out = await selectDryRunAutoApproved(tasks, { ...baseCtx, availableSlots: 3, alreadySpawned: 2 });
+ expect(out.map(t => t.id)).toEqual(['1']);
+ });
+
+ it('skips tasks that have hit the max-spawns ceiling', async () => {
+ const tasks = [
+ task('1', { totalSpawnCount: MAX_TOTAL_SPAWNS }),
+ task('2', { totalSpawnCount: 1 }),
+ task('3', { totalSpawnCount: MAX_TOTAL_SPAWNS + 1 })
+ ];
+ const out = await selectDryRunAutoApproved(tasks, baseCtx);
+ expect(out.map(t => t.id)).toEqual(['2']);
+ });
+
+ it('skips tasks whose app is on cooldown', async () => {
+ const tasks = [task('1', { app: 'appA' }), task('2', { app: 'appB' }), task('3')];
+ const isOnCooldown = (appId) => Promise.resolve(appId === 'appA');
+ const out = await selectDryRunAutoApproved(tasks, { ...baseCtx, isOnCooldown });
+ expect(out.map(t => t.id)).toEqual(['2', '3']);
+ });
+
+ it('exempts cooldown when cooldownExempt returns true (pipeline continuation)', async () => {
+ const tasks = [task('1', { app: 'appA', pipeline: { currentStage: 2 } })];
+ const out = await selectDryRunAutoApproved(tasks, {
+ ...baseCtx,
+ isOnCooldown: () => Promise.resolve(true),
+ cooldownExempt: (t) => t.metadata?.pipeline?.currentStage > 0
+ });
+ expect(out.map(t => t.id)).toEqual(['1']);
+ });
+
+ it('enforces the per-project cap including running agents', async () => {
+ // appA already has 1 running; per-project limit is 2 → only one more appA task fits.
+ const tasks = [task('1', { app: 'appA' }), task('2', { app: 'appA' }), task('3', { app: 'appB' })];
+ const out = await selectDryRunAutoApproved(tasks, {
+ ...baseCtx,
+ perProjectLimit: 2,
+ spawnProjectCounts: { appA: 1 }
+ });
+ expect(out.map(t => t.id)).toEqual(['1', '3']);
+ });
+
+ it('applies the engine-specific extraSkip gate (disabled analysis type)', async () => {
+ const tasks = [task('1', { analysisType: 'security' }), task('2', { analysisType: 'perf' })];
+ const out = await selectDryRunAutoApproved(tasks, {
+ ...baseCtx,
+ extraSkip: (t) => t.metadata?.analysisType === 'security'
+ });
+ expect(out.map(t => t.id)).toEqual(['2']);
+ });
+
+ it('does not mutate the passed-in spawnProjectCounts', async () => {
+ const counts = { appA: 1 };
+ await selectDryRunAutoApproved([task('1', { app: 'appA' })], { ...baseCtx, spawnProjectCounts: counts });
+ expect(counts).toEqual({ appA: 1 });
+ });
+
+ it('returns nothing when no slots remain', async () => {
+ const out = await selectDryRunAutoApproved([task('1')], { ...baseCtx, availableSlots: 3, alreadySpawned: 3 });
+ expect(out).toEqual([]);
+ });
+
+ it('a skipped task does not consume virtual project capacity (skip-before-increment)', async () => {
+ // Both tasks are on appX with a per-project limit of 1. Task 1 is gated out
+ // (extraSkip) → it must NOT consume appX's only slot, so task 2 still fits.
+ // If a skipped task counted toward capacity, task 2 would be wrongly dropped.
+ const tasks = [task('1', { app: 'appX' }), task('2', { app: 'appX' })];
+ const out = await selectDryRunAutoApproved(tasks, {
+ ...baseCtx,
+ perProjectLimit: 1,
+ extraSkip: (t) => t.id === '1'
+ });
+ expect(out.map(t => t.id)).toEqual(['2']);
+ });
+});