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
extract admitPendingUserTasks so both CoS engines share one Priority-1 admission ladder
[._.]/ Adam Eivy5e86d3b69946
diff --git a/server/services/cos.js b/server/services/cos.jsindex 74a47a6cb8..e1420034b6 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -86,7 +86,7 @@ import { firstLine, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskByIexport { getPendingTaskIds } from './cosTaskStore.js';export { firstLine, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, reviveBlockedTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks };import { ensureInstanceId } from './instanceIdentity.js';-import { isHeldByOther, buildRenewal, buildClaim, getClaimOwner, getSkipReason } from './cosTaskClaim.js';+import { isHeldByOther, buildRenewal, buildClaim, getClaimOwner } from './cosTaskClaim.js';import { retryTasksResolvedByInvestigation } from './investigationRetry.js';import { notifyIfPrLeftOrphaned } from './orphanedPrNotifier.js';@@ -131,8 +131,8 @@ import {generateIdleReviewTask,queueEligibleImprovementTasks,recordDeferredPerpetualDispatch,- blockIfExceedsMaxSpawns,admitAutoApprovedSystemTasks,+ admitPendingUserTasks,resolveAutonomyBudget,countRunningAgentsByProject,isWithinProjectLimit,@@ -159,7 +159,7 @@ import {// predicate are shared with the scheduler unit tests so they exercise the real// guards instead of a local replica. The async tiers stay here as// `spawnDequeuePriorityN(ctx)` helpers.-import { closeStolenIdleReviewCard, createDequeueCapacity, countRunningAgentsByLocalEndpoint, isIdleTierEligible, isUserTaskRunnableUnattended } from './cosDequeue.js';+import { closeStolenIdleReviewCard, createDequeueCapacity, countRunningAgentsByLocalEndpoint, isIdleTierEligible } from './cosDequeue.js';import { buildLocalEndpointSlotContext, localEndpointCapacityError } from './cosLocalEndpointSlots.js';import {initializePersistentMindSupervisor,@@ -1035,37 +1035,18 @@ async function spawnDequeuePriority0OnDemand(ctx) {* `hasPendingUserTasks` on `ctx` for the idle tier below.*/async function spawnDequeuePriority1UserTasks(ctx) {- const { state, instanceId, capacity } = ctx;+ const { instanceId, capacity } = ctx;const userTaskData = await getUserTasks();const pendingUserTasks = userTaskData.grouped?.pending || [];ctx.hasPendingUserTasks = pendingUserTasks.length > 0;- for (const task of pendingUserTasks) {- if (capacity.spawned >= capacity.availableSlots) break;- // Not runnable here: the task is pinned to another instance (#4520), or a- // federated peer holds a live lease on it (#1650) and is working it on the- // other machine. Skip it during candidate selection so it doesn't consume- // this cycle's spawn slot (the spawn guard would return null anyway) and- // starve later runnable tasks.- const skipReason = getSkipReason(task.metadata, instanceId);- if (skipReason) {- emitLog('debug', `Skipping user task ${task.id} — ${skipReason}`, { taskId: task.id });- continue;- }- // A user row that says it is NOT auto-approved is withheld from the unattended- // spawn (#7300) — see isUserTaskRunnableUnattended for why, and for why the- // rule lives in cosDequeue.js rather than once per engine.- if (!isUserTaskRunnableUnattended(task)) {- emitLog('debug', `Skipping user task ${task.id} — recovered row is not auto-approved`, { taskId: task.id });- continue;- }- if (await blockIfExceedsMaxSpawns(task, 'user')) continue;- const userTask = { ...task, taskType: 'user' };- if (!capacity.canSpawn(userTask)) continue;- cosEvents.emit('task:ready', userTask);- capacity.trackSpawn(userTask);- }+ await admitPendingUserTasks({ pendingUserTasks, instanceId }, {+ capacityExhausted: () => capacity.spawned >= capacity.availableSlots,+ canSpawn: (task) => capacity.canSpawn(task),+ emitSpawn: (task) => cosEvents.emit('task:ready', task),+ trackSpawn: (task) => capacity.trackSpawn(task),+ });}/**diff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex 7df00fdb31..374e026c9e 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -1331,17 +1331,21 @@ describe('cos.js source — priority + capacity invariants', () => {// so the guard narrows nothing that was already running.expect(priorityDequeue(buckets, capacity).map(t => t.id)).toEqual(['task-real', 'task-fieldless']);- // Both engines run their own user tier, so the rule has to be called in each —- // one is a fix, two is the fix. The shared body is cosDequeue.js's.+ // Both engines used to run their own copy of this tier, verified only by+ // grepping each body for the guard in source order — one is a fix, two is+ // the fix. #7523 replaced the duplicated ladder with one shared pass+ // (admitPendingUserTasks in cosTaskGenerator.js); now the only thing either+ // engine's body needs to prove is that it DELEGATES there, and the ladder's+ // own ordering (including this #7300 hold) is pinned once, behaviorally,+ // against the shared pass in cosTaskGenerator.test.js's+ // `describe('admitPendingUserTasks', …)` block.const cosTier = extractFnBody(COS_SRC, COS_SRC.indexOf('async function spawnDequeuePriority1UserTasks'));const genTier = extractFnBody(GEN_SRC, GEN_SRC.indexOf('async function spawnPriority1UserTasks'));- for (const [label, body, emit] of [- ['cos.js', cosTier, "cosEvents.emit('task:ready', userTask)"],- ['cosTaskGenerator.js', genTier, 'tasksToSpawn.push(userTask)'],+ for (const [label, body] of [+ ['cos.js', cosTier],+ ['cosTaskGenerator.js', genTier],]) {- const guardIdx = body.indexOf('isUserTaskRunnableUnattended(task)');- expect(guardIdx, `${label} user tier must consult isUserTaskRunnableUnattended`).toBeGreaterThan(-1);- expect(body.indexOf(emit), `${label} must admit the task only after the guard`).toBeGreaterThan(guardIdx);+ expect(body, `${label} user tier must delegate to the shared admitPendingUserTasks pass`).toContain('admitPendingUserTasks(');}});diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 5c9ffb7d60..241fc57b7b 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -886,6 +886,51 @@ async function recordAutoApprovedDeferral({ type, task, appId, project }, state,);}+/**+ * Run the one Priority-1 admission pass shared by the periodic evaluator and+ * event-driven dequeue engine (#7523 — the two used to hand-mirror this+ * ordered ladder, and #4520/#7300 each landed as two synchronized edits).+ * Owns the ordered not-runnable-here, approval, and max-spawn gates for+ * pending user tasks; adapters only decide how an admitted task is emitted,+ * how per-cycle capacity is tracked, and (optionally) what happens when+ * capacity denies a candidate.+ */+export async function admitPendingUserTasks({ pendingUserTasks, instanceId }, adapter) {+ const { capacityExhausted, canSpawn, emitSpawn, trackSpawn, onDefer = async () => {} } = adapter;++ const admitted = [];+ for (const task of pendingUserTasks) {+ if (capacityExhausted()) break;+ // Not runnable here: the task is pinned to another instance (#4520), or a+ // federated peer holds a live lease on it (#1650) and is working it on the+ // other machine. Skip it during candidate selection so it doesn't consume+ // this cycle's spawn slot (the spawn guard would return null anyway) and+ // starve later runnable tasks.+ const skipReason = getSkipReason(task.metadata, instanceId);+ if (skipReason) {+ emitLog('debug', `Skipping user task ${task.id} — ${skipReason}`, { taskId: task.id });+ continue;+ }+ // A user row that says it is NOT auto-approved is withheld from the unattended+ // spawn (#7300) — see isUserTaskRunnableUnattended for why, and for why the+ // rule lives in cosDequeue.js rather than once per engine.+ if (!isUserTaskRunnableUnattended(task)) {+ emitLog('debug', `Skipping user task ${task.id} — recovered row is not auto-approved`, { taskId: task.id });+ continue;+ }+ if (await blockIfExceedsMaxSpawns(task, 'user')) continue;+ const userTask = { ...task, taskType: 'user' };+ if (!canSpawn(userTask)) {+ await onDefer(userTask);+ continue;+ }+ emitSpawn(userTask);+ trackSpawn(userTask);+ admitted.push(userTask);+ }+ return admitted;+}+/*** Priority 0: On-demand task requests (highest priority — user explicitly* requested these). Reads the live schedule's `onDemandRequests`, clears each@@ -914,40 +959,23 @@ async function spawnPriority0OnDemand(ctx) {*/async function spawnPriority1UserTasks(ctx) {const { pendingUserTasks, availableSlots, perProjectLimit, tasksToSpawn, canSpawnTask, trackSpawn, instanceId } = ctx;- for (const task of pendingUserTasks) {- if (tasksToSpawn.length >= availableSlots) break;- // Not runnable here: the task is pinned to another instance (#4520), or a- // federated peer holds a live lease on it (#1650) and is working it on the- // other machine. Skip it during candidate selection so it doesn't consume- // this cycle's spawn slot (the spawn guard would return null anyway) and- // starve later runnable tasks.- const skipReason = getSkipReason(task.metadata, instanceId);- if (skipReason) {- emitLog('debug', `Skipping user task ${task.id} — ${skipReason}`, { taskId: task.id });- continue;- }- // A user row that says it is NOT auto-approved is withheld from the unattended- // spawn (#7300) — see isUserTaskRunnableUnattended for why, and for why the- // rule lives in cosDequeue.js rather than once per engine.- if (!isUserTaskRunnableUnattended(task)) {- emitLog('debug', `Skipping user task ${task.id} — recovered row is not auto-approved`, { taskId: task.id });- continue;- }- if (await blockIfExceedsMaxSpawns(task, 'user')) continue;- const userTask = { ...task, taskType: 'user' };- if (!canSpawnTask(userTask)) {- const project = task.metadata?.app || '_self';- emitLog('debug', `⏳ Queued user task ${task.id} - per-project limit reached for ${project}`);- await recordDecision(- DECISION_TYPES.CAPACITY_FULL,- `User task ${task.id} deferred — per-project limit (${perProjectLimit}) reached for ${project}`,- { taskId: task.id, project, limit: perProjectLimit }- );- continue;- }- tasksToSpawn.push(userTask);- trackSpawn(userTask);- }+ await admitPendingUserTasks({ pendingUserTasks, instanceId }, {+ capacityExhausted: () => tasksToSpawn.length >= availableSlots,+ canSpawn: (task) => canSpawnTask(task),+ emitSpawn: (task) => tasksToSpawn.push(task),+ trackSpawn,+ onDefer: (task) => recordPendingUserDeferral(task, perProjectLimit),+ });+}++async function recordPendingUserDeferral(task, perProjectLimit) {+ const project = task.metadata?.app || '_self';+ emitLog('debug', `⏳ Queued user task ${task.id} - per-project limit reached for ${project}`);+ await recordDecision(+ DECISION_TYPES.CAPACITY_FULL,+ `User task ${task.id} deferred — per-project limit (${perProjectLimit}) reached for ${project}`,+ { taskId: task.id, project, limit: perProjectLimit }+ );}/**diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.jsindex 561fc7a08c..2cb1878f26 100644--- a/server/services/cosTaskGenerator.test.js+++ b/server/services/cosTaskGenerator.test.js@@ -68,6 +68,7 @@ vi.mock('./github.js', async (importActual) => ({import {selectDryRunAutoApproved,+ admitPendingUserTasks,exceedsMaxSpawns,shouldParkUnchangedPerpetualWork,resolveIssueExcludeLabelsBlock,@@ -251,6 +252,18 @@ describe('dry-run hook wiring matches the shared execute path', () => {.toContain('admitAutoApprovedSystemTasks(');});+ it('both engines delegate Priority 1 to admitPendingUserTasks (#7523)', () => {+ // The two Priority-1 tiers used to hand-mirror the same ordered ladder+ // (not-runnable-here → approval → max-spawn → capacity), verified only by a+ // source-order check against each body. Now both are thin adapters over the+ // one shared pass — this pins the delegation itself, not the ladder's order,+ // which the shared pass's own tests below cover.+ expect(between(COS_SRC, 'async function spawnDequeuePriority1UserTasks', 'async function spawnDequeuePriority2AutoApproved'))+ .toContain('admitPendingUserTasks(');+ 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@@ -409,9 +422,12 @@ describe('the on-demand consent flip reaches every drain path', () => {// evaluateTasks here) must apply it, in both their execute loops AND their// dry-run plan. `getSkipReason` answers both halves in one call.describe('not-runnable-here skip during candidate selection (#1650, #4520)', () => {- it('both engines import getSkipReason from the shared claim module', () => {- expect(COS_SRC).toContain("from './cosTaskClaim.js'");- expect(COS_SRC).toMatch(/import\s*\{[^}]*getSkipReason[^}]*\}\s*from\s*'\.\/cosTaskClaim\.js'/);+ it('cosTaskGenerator.js imports getSkipReason from the shared claim module', () => {+ // Both the Priority-1 (admitPendingUserTasks) and Priority-2+ // (admitAutoApprovedSystemTasks) shared passes live here (#7523) and both+ // consult getSkipReason, so this is the one module that needs the import.+ // cos.js no longer imports it directly — dequeueNextTask's Priority-1 tier+ // delegates to admitPendingUserTasks instead of re-checking the lease itself.expect(GEN_SRC).toMatch(/import\s*\{[^}]*getSkipReason[^}]*\}\s*from\s*'\.\/cosTaskClaim\.js'/);});@@ -420,11 +436,13 @@ describe('not-runnable-here skip during candidate selection (#1650, #4520)', ()expect(GEN_SRC).toContain('const instanceId = await ensureInstanceId();');});- it('both engines keep user-task skips and share the auto-approved execute skip', () => {- const cosSkips = COS_SRC.match(/getSkipReason\(task\.metadata,\s*instanceId\);\n\s*if \(skipReason\)/g) || [];+ 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) || [];- expect(cosSkips.length).toBeGreaterThanOrEqual(1);- expect(genSkips.length).toBeGreaterThanOrEqual(2);+ expect(genSkips.length).toBe(2);});it('the shared pass supplies notRunnableHere so both dry-run adapters match execute', () => {@@ -1020,6 +1038,108 @@ describe('selectDryRunAutoApproved', () => {});});+// admitPendingUserTasks is the one ordered Priority-1 admission pass shared by+// evaluateTasks (spawnPriority1UserTasks, cosTaskGenerator.js) and+// dequeueNextTask (spawnDequeuePriority1UserTasks, cos.js) — #7523. Both+// engines used to hand-mirror the not-runnable-here / approval / max-spawn /+// capacity ladder; the delegation itself is pinned by the source guard above,+// and these are the behavioral boundary tests against the shared pass both+// engines now call, driven through mocked adapters exactly like the real+// engines wire them (no live store/socket needed since the adapter functions+// ARE the seam each engine supplies).+describe('admitPendingUserTasks', () => {+ const makeAdapter = (overrides = {}) => {+ const emitted = [];+ const tracked = [];+ const deferred = [];+ return {+ emitted,+ tracked,+ deferred,+ adapter: {+ capacityExhausted: () => false,+ canSpawn: () => true,+ emitSpawn: (t) => emitted.push(t.id),+ trackSpawn: (t) => tracked.push(t.id),+ onDefer: (t) => { deferred.push(t.id); },+ ...overrides,+ },+ };+ };++ it('admits ordinary and fieldless pending rows, in order', async () => {+ const pendingUserTasks = [task('ordinary', { app: 'appA' }), task('fieldless')];+ const { adapter, emitted, tracked } = makeAdapter();+ const admitted = await admitPendingUserTasks({ pendingUserTasks, instanceId: 'local' }, adapter);+ expect(admitted.map(t => t.id)).toEqual(['ordinary', 'fieldless']);+ expect(emitted).toEqual(['ordinary', 'fieldless']);+ expect(tracked).toEqual(['ordinary', 'fieldless']);+ // Priority 1 stamps taskType for the spawner, same as both engines did inline.+ expect(admitted.every(t => t.taskType === 'user')).toBe(true);+ });++ it('withholds a row that says it is not auto-approved (#7300), while ordinary/fieldless rows still run', async () => {+ const pendingUserTasks = [+ { ...task('recovered'), autoApproved: false },+ task('ordinary', { app: 'appA' }),+ task('fieldless'),+ ];+ const { adapter, emitted } = makeAdapter();+ const admitted = await admitPendingUserTasks({ pendingUserTasks, instanceId: 'local' }, adapter);+ expect(admitted.map(t => t.id)).toEqual(['ordinary', 'fieldless']);+ expect(emitted).toEqual(['ordinary', 'fieldless']);+ });++ it('skips a task pinned to another instance without consuming a slot or stopping later rows (#4520)', async () => {+ const pendingUserTasks = [+ task('elsewhere', { targetInstanceId: 'other-instance' }),+ task('here'),+ ];+ const { adapter } = makeAdapter();+ const admitted = await admitPendingUserTasks({ pendingUserTasks, instanceId: 'local' }, adapter);+ expect(admitted.map(t => t.id)).toEqual(['here']);+ });++ it('stops admitting once capacityExhausted() reports true, without touching later rows', async () => {+ const pendingUserTasks = [task('one'), task('two')];+ let calls = 0;+ const { adapter, emitted } = makeAdapter({ capacityExhausted: () => calls++ > 0 });+ const admitted = await admitPendingUserTasks({ pendingUserTasks, instanceId: 'local' }, adapter);+ expect(admitted.map(t => t.id)).toEqual(['one']);+ expect(emitted).toEqual(['one']);+ });++ it('defers (does not emit/track/admit) a task canSpawn denies, and keeps evaluating later rows', async () => {+ const pendingUserTasks = [task('full', { app: 'appA' }), task('fits', { app: 'appB' })];+ const { adapter, emitted, tracked, deferred } = makeAdapter({+ canSpawn: (t) => t.metadata?.app !== 'appA',+ });+ const admitted = await admitPendingUserTasks({ pendingUserTasks, instanceId: 'local' }, adapter);+ expect(admitted.map(t => t.id)).toEqual(['fits']);+ expect(emitted).toEqual(['fits']);+ expect(tracked).toEqual(['fits']);+ expect(deferred).toEqual(['full']);+ });++ it('onDefer is optional — a denial is silently dropped when the adapter omits it', async () => {+ const pendingUserTasks = [task('denied')];+ const { adapter } = makeAdapter({ canSpawn: () => false, onDefer: undefined });+ const admitted = await admitPendingUserTasks({ pendingUserTasks, instanceId: 'local' }, adapter);+ expect(admitted).toEqual([]);+ });++ it('blocks (does not admit) a task that has hit the max-total-spawns ceiling', async () => {+ const persist = vi.spyOn(taskStore, 'updateTask').mockResolvedValue({});+ const pendingUserTasks = [task('exhausted', { totalSpawnCount: MAX_TOTAL_SPAWNS }), task('fresh')];+ const { adapter, emitted } = makeAdapter();+ const admitted = await admitPendingUserTasks({ pendingUserTasks, instanceId: 'local' }, adapter);+ expect(admitted.map(t => t.id)).toEqual(['fresh']);+ expect(emitted).toEqual(['fresh']);+ expect(persist).toHaveBeenCalledWith('exhausted', expect.objectContaining({ status: 'blocked' }), 'user');+ persist.mockRestore();+ });+});+// Layered Intelligence's on-demand feedback bridge (emitHandlerBackedOnDemand) was// removed when LI migrated off the handler-backed path onto a normal agent task// (see taskTypeHooks.js + layeredIntelligenceHooks.js). A "Run now" now generates a