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
refactor: table-drive auto-approved admission gates so dry-run and execute share one order (#9611)
Adam Eivyfb33e10f9fb1
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex b6d8da956f..094fb795ea 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -132,10 +132,12 @@ export {export { buildSecurityScanPipelineOutput } from './prReviewerPipeline.js';/**- * Block a task that has exceeded the max spawn limit. Returns true if blocked.+ * Persist a `blocked` status on a task that has hit the max-total-spawns+ * ceiling. Unconditional: the caller has already established `exceedsMaxSpawns`.+ * The name carries the side effect — dry-run planning must only ever call the+ * pure `exceedsMaxSpawns` predicate.*/-export async function blockIfExceedsMaxSpawns(task, taskType) {- if (!exceedsMaxSpawns(task)) return false;+async function blockMaxSpawnsExceeded(task, taskType) {const totalSpawns = Number(task.metadata?.totalSpawnCount) || 0;emitLog('info', `🚫 Blocking task ${task.id} — exceeded max spawns (${totalSpawns}/${MAX_TOTAL_SPAWNS})`, { taskId: task.id });await updateTask(task.id, {@@ -144,13 +146,12 @@ export async function blockIfExceedsMaxSpawns(task, taskType) {}, taskType).catch(err => {emitLog('warn', `Failed to block task ${task.id}: ${err.message}`, { taskId: task.id });});- 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.+ * Pure predicate — true when a task has hit the max-total-spawns ceiling.+ * Never blocks or persists; the execute passes pair it with+ * `blockMaxSpawnsExceeded`, and the dry-run pass uses it alone.*/export function exceedsMaxSpawns(task) {return (Number(task.metadata?.totalSpawnCount) || 0) >= MAX_TOTAL_SPAWNS;@@ -235,10 +236,68 @@ export async function recordDeferredPerpetualDispatch(pendingPerpetualDispatch,return true;}+/**+ * The ordered per-task admission gates for auto-approved system tasks — the ONE+ * place their order lives. `selectDryRunAutoApproved` walks it for the plan+ * (never calling `onReject`); `admitAutoApprovedSystemTasks` walks it for the+ * real pass and runs the first rejecting gate's `onReject` effect. Adding or+ * reordering a gate here changes both passes at once, so the dry-run plan cannot+ * drift from what execute does.+ *+ * `rejects(task, hooks)` is pure (it may await a read-only probe); every side+ * effect (logging, persisting a block, deferral records) belongs to `onReject`.+ * `hooks` carries the engine-specific predicates: `notRunnableHere` (pinned to+ * another instance #4520, or a peer's live lease #1650 — returns a truthy+ * reason), `extraSkip` (disabled analysis type), `cooldownExempt`, `isOnCooldown`.+ */+const AUTO_APPROVED_GATES = Object.freeze([+ {+ name: 'not-runnable-here',+ rejects: (task, hooks) => hooks.notRunnableHere(task),+ onReject: async (task, { detail }) => {+ emitLog('debug', `Skipping system task ${task.id} — ${detail}`, { taskId: task.id });+ },+ },+ {+ name: 'max-spawns',+ rejects: (task) => exceedsMaxSpawns(task),+ onReject: (task) => blockMaxSpawnsExceeded(task, 'internal'),+ },+ {+ name: 'disabled-analysis-type',+ rejects: (task, hooks) => hooks.extraSkip(task),+ onReject: async (task) => {+ emitLog('info', `System task skipped — task type '${analysisTypeForTask(task)}' is disabled`, { taskId: task.id });+ },+ },+ {+ name: 'cooldown',+ rejects: async (task, hooks) => {+ const appId = task.metadata?.app;+ return Boolean(appId) && !hooks.cooldownExempt(task) && (await hooks.isOnCooldown(appId));+ },+ onReject: (task, { onDefer }) => onDefer({ type: 'cooldown', task, appId: task.metadata?.app }),+ },+]);++/**+ * First gate in `AUTO_APPROVED_GATES` that rejects `task`, as `{ gate, detail }`+ * (`detail` is the gate's truthy verdict, e.g. the not-runnable-here reason), or+ * null when the task clears them all. Pure — runs no `onReject` effect.+ */+async function firstRejectingGate(task, hooks) {+ for (const gate of AUTO_APPROVED_GATES) {+ const detail = await gate.rejects(task, hooks);+ if (detail) return { gate, detail };+ }+ return null;+}+/*** 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+ * file order applying the SAME gates execute mode uses — global slot cap, then+ * the shared `AUTO_APPROVED_GATES` table (one declarative list that+ * `admitAutoApprovedSystemTasks` also iterates), then 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@@ -274,6 +333,7 @@ export async function selectDryRunAutoApproved(autoApproved, ctx) {extraSkip = () => false,notRunnableHere = () => false} = ctx;+ const hooks = { isOnCooldown, cooldownExempt, extraSkip, notRunnableHere };const counts = { ...spawnProjectCounts };let spawned = alreadySpawned;@@ -281,12 +341,8 @@ export async function selectDryRunAutoApproved(autoApproved, ctx) {for (const task of autoApproved) {if (spawned >= availableSlots) break;- if (notRunnableHere(task)) continue;- 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 (await firstRejectingGate(task, hooks)) continue;+ const project = task.metadata?.app || '_self';if ((counts[project] || 0) >= perProjectLimit) continue;counts[project] = (counts[project] || 0) + 1;spawned++;@@ -830,7 +886,14 @@ export async function admitAutoApprovedSystemTasks(ctx, adapter) {? (cosTaskData.grouped?.pending || []).filter((task) => isAutoApprovableInvestigation(task, state.config)): [])];- const disabledAnalysisType = (task) => isDisabledAnalysisType(task, taskSchedule);+ // One hook set feeds both walks, so the dry-run plan and the execute pass+ // cannot disagree about what each gate means.+ const gateHooks = {+ isOnCooldown: (appId) => isAppOnCooldown(appId, state.config.appReviewCooldownMs),+ cooldownExempt: isCooldownExemptTask,+ extraSkip: (task) => isDisabledAnalysisType(task, taskSchedule),+ notRunnableHere: (task) => getSkipReason(task.metadata, instanceId)+ };if (cosAutonomyMode !== 'execute') {if (cosAutonomyMode !== 'dry-run') return [];@@ -839,10 +902,7 @@ export async function admitAutoApprovedSystemTasks(ctx, adapter) {alreadySpawned,perProjectLimit,spawnProjectCounts,- isOnCooldown: (appId) => isAppOnCooldown(appId, state.config.appReviewCooldownMs),- cooldownExempt: isCooldownExemptTask,- extraSkip: disabledAnalysisType,- notRunnableHere: (task) => getSkipReason(task.metadata, instanceId) !== null+ ...gateHooks});for (const task of wouldSpawn) {emitLog('info', `[dry-run] CoS auto-run would spawn system task: ${task.id}`, { taskId: task.id, domainAutonomy: 'cos' });@@ -854,21 +914,12 @@ export async function admitAutoApprovedSystemTasks(ctx, adapter) {let spawned = alreadySpawned;for (const task of autoApproved) {if (spawned >= autonomousSlotCeiling) break;- const skipReason = getSkipReason(task.metadata, instanceId);- if (skipReason) {- emitLog('debug', `Skipping system task ${task.id} — ${skipReason}`, { taskId: task.id });- continue;- }- if (await blockIfExceedsMaxSpawns(task, 'internal')) continue;- if (disabledAnalysisType(task)) {- emitLog('info', `System task skipped — task type '${analysisTypeForTask(task)}' is disabled`, { taskId: task.id });+ const rejection = await firstRejectingGate(task, gateHooks);+ if (rejection) {+ await rejection.gate.onReject(task, { detail: rejection.detail, onDefer });continue;}const appId = task.metadata?.app;- if (appId && !isCooldownExemptTask(task) && (await isAppOnCooldown(appId, state.config.appReviewCooldownMs))) {- await onDefer({ type: 'cooldown', task, appId });- continue;- }const sysTask = { ...task, taskType: 'internal' };if (!canSpawn(sysTask, autonomousSlotCeiling)) {await onDefer({ type: 'capacity', task, project: appId || '_self' });@@ -932,7 +983,10 @@ export async function admitPendingUserTasks({ pendingUserTasks, instanceId }, ademitLog('debug', `Skipping user task ${task.id} — recovered row is not auto-approved`, { taskId: task.id });continue;}- if (await blockIfExceedsMaxSpawns(task, 'user')) continue;+ if (exceedsMaxSpawns(task)) {+ await blockMaxSpawnsExceeded(task, 'user');+ continue;+ }const userTask = { ...task, taskType: 'user' };if (!canSpawn(userTask)) {await onDefer(userTask);diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.jsindex c6ed1744ac..df945f507b 100644--- a/server/services/cosTaskGenerator.test.js+++ b/server/services/cosTaskGenerator.test.js@@ -14,6 +14,7 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import { readFileSync } from 'fs';import * as taskStore from './cosTaskStore.js';+import * as appActivity from './appActivity.js';import { fileURLToPath } from 'url';import { dirname, join } from 'path';@@ -68,6 +69,7 @@ vi.mock('./github.js', async (importActual) => ({import {selectDryRunAutoApproved,+ admitAutoApprovedSystemTasks,admitPendingUserTasks,exceedsMaxSpawns,shouldParkUnchangedPerpetualWork,@@ -226,25 +228,6 @@ describe('dry-run hook wiring matches the shared execute path', () => {return src.slice(start, end);};- const callSite = () => {- // Anchor on the CALL (`await selectDryRunAutoApproved(`), not the function- // definition (`export async function selectDryRunAutoApproved(`).- const start = GEN_SRC.indexOf('await selectDryRunAutoApproved(');- expect(start, 'selectDryRunAutoApproved must be called').toBeGreaterThan(-1);- const end = GEN_SRC.indexOf('});', start);- expect(end, 'selectDryRunAutoApproved call must close').toBeGreaterThan(start);- return GEN_SRC.slice(start, end + 3);- };-- it('the shared pass applies cooldown exemption and disabled-analysis-type gates', () => {- const site = callSite();- expect(site).toContain('extraSkip: disabledAnalysisType');- // dequeue must exempt perpetual/pipeline tasks from cooldown in its dry-run- // plan too, mirroring its execute gate — otherwise the plan over-reports a- // perpetual drain as "would skip (cooldown)" that execute actually spawns.- expect(site).toContain('cooldownExempt: isCooldownExemptTask');- });-it('both engines delegate Priority 2 to admitAutoApprovedSystemTasks', () => {expect(between(COS_SRC, 'async function spawnDequeuePriority2AutoApproved', '/**\n * Priority 3')).toContain('admitAutoApprovedSystemTasks(');@@ -263,17 +246,6 @@ describe('dry-run hook wiring matches the shared execute path', () => {expect(between(GEN_SRC, 'async function spawnPriority1UserTasks', 'async function recordPendingUserDeferral')).toContain('admitPendingUserTasks(');});-- it('the shared EXECUTE loop gates cooldown on isCooldownExemptTask', () => {- // The spawn gate (not just the dry-run planner) must consult the shared- // predicate, or a perpetual task the refill queued is skipped at spawn time- // until the 30-min window expires — the manually-triggered-drain stall.- const sharedPass = GEN_SRC.slice(- GEN_SRC.indexOf('export async function admitAutoApprovedSystemTasks'),- GEN_SRC.indexOf('async function recordAutoApprovedDeferral')- );- expect(sharedPass).toMatch(/appId\s*&&\s*!isCooldownExemptTask\(task\)/);- });});// The two Priority-0 on-demand engines used to be hand-mirrored line for line,@@ -403,20 +375,13 @@ describe('not-runnable-here skip during candidate selection (#1650, #4520)', ()expect(GEN_SRC).toContain('const instanceId = await ensureInstanceId();');});- it('the two shared admission passes keep the not-runnable-here skip', () => {- // Both Priority-1 (admitPendingUserTasks) and Priority-2- // (admitAutoApprovedSystemTasks) consult getSkipReason exactly once, in- // cosTaskGenerator.js — the ONE place either spawn engine can drift this- // guard now that both delegate here instead of hand-mirroring it (#7523).- const genSkips = GEN_SRC.match(/getSkipReason\(task\.metadata,\s*instanceId\);\n\s*if \(skipReason\)/g) || [];+ it('the Priority-1 pass keeps its not-runnable-here skip; Priority-2 gets it from the shared gate table', () => {+ // Priority-1 (admitPendingUserTasks) consults getSkipReason inline; Priority-2+ // reaches it through AUTO_APPROVED_GATES (behaviorally pinned by the+ // dry-run/execute parity test below), so a second inline call must not return.+ const genSkips = GEN_SRC.match(/getSkipReason\(task\.metadata,\s*instanceId\)/g) || [];expect(genSkips.length).toBe(2);});-- it('the shared pass supplies notRunnableHere so both dry-run adapters match execute', () => {- // Covers BOTH reasons this instance passes over a task at spawn time: a- // peer's live lease (#1650) and a pin to another instance (#4520).- expect(GEN_SRC).toContain('notRunnableHere: (task) => getSkipReason(task.metadata, instanceId) !== null');- });});// isCooldownExemptTask is the single source of truth for "this task bypasses the@@ -2122,3 +2087,56 @@ describe('resolveAppClaimReviewers', () => {expect(result.overridden).toBe(true);});});++// The dry-run plan and the execute pass iterate ONE gate table+// (AUTO_APPROVED_GATES), so for identical inputs the plan must equal what execute+// emits. Driving both through admitAutoApprovedSystemTasks means any gate added to+// the table is covered here without a new assertion.+describe('admitAutoApprovedSystemTasks dry-run/execute parity', () => {+ const ctxFor = (cosAutonomyMode, tasks) => ({+ state: { config: { appReviewCooldownMs: 60000 } },+ cosTaskData: { exists: true, autoApproved: tasks },+ taskSchedule: { tasks: { 'enabled-type': { enabled: true } } },+ cosAutonomyMode,+ autonomousSlotCeiling: 4,+ alreadySpawned: 0,+ perProjectLimit: 1,+ spawnProjectCounts: {},+ instanceId: 'local',+ });+ const makeTasks = () => [+ task('pinned-elsewhere', { targetInstanceId: 'other-instance' }),+ task('exhausted', { totalSpawnCount: MAX_TOTAL_SPAWNS }),+ task('disabled-type', { analysisType: 'disabled-type' }),+ task('cooling', { app: 'coolApp' }),+ task('perpetual-exempt', { app: 'coolApp', perpetual: true }),+ task('enabled-type', { analysisType: 'enabled-type', app: 'appB' }),+ task('same-project-over-cap', { app: 'appB' }),+ task('plain'),+ ];++ const execAdapter = (limit) => {+ const counts = {};+ return {+ canSpawn: (t) => (counts[t.metadata?.app || '_self'] || 0) < limit,+ trackSpawn: (t) => { const k = t.metadata?.app || '_self'; counts[k] = (counts[k] || 0) + 1; },+ emitSpawn: () => {},+ };+ };++ it('plans exactly the tasks execute admits, and only execute persists the max-spawns block', async () => {+ vi.spyOn(appActivity, 'isAppOnCooldown').mockImplementation(async (appId) => appId === 'coolApp');+ const persist = vi.spyOn(taskStore, 'updateTask').mockResolvedValue({});++ const planned = await admitAutoApprovedSystemTasks(ctxFor('dry-run', makeTasks()), execAdapter(1));+ expect(persist).not.toHaveBeenCalled();++ const admitted = await admitAutoApprovedSystemTasks(ctxFor('execute', makeTasks()), execAdapter(1));+ expect(admitted.map(t => t.id)).toEqual(['perpetual-exempt', 'enabled-type', 'plain']);+ expect(planned.map(t => t.id)).toEqual(admitted.map(t => t.id));+ expect(persist).toHaveBeenCalledTimes(1);+ expect(persist).toHaveBeenCalledWith('exhausted', expect.objectContaining({ status: 'blocked' }), 'internal');++ vi.restoreAllMocks();+ });+});