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: continue a manual (Run Now) perpetual claim drain in the on-demand lane

Adam Eivy6159c252bda1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 18c8665696..f85f279f1e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -9,6 +9,7 @@
## Fixed
- **[issue-3396] CyberCity's ambient music no longer drifts under main-thread load.** The chord changes (every 2400ms) and the 16th-note arp plucks (every 150ms) rode two independent `setInterval`s that each read `ctx.currentTime` at fire time — so under load both drifted against the audio clock *and* against each other, the failure mode the sibling synth players adopted the shared lookahead scheduler to avoid. Both now come off one 16th-note step counter (16 steps per chord, so the arp is phase-locked to the chord changes by construction) and every event is written to the audio clock at an absolute grid time, `gridOrigin + step × 0.15s`, which cannot accumulate drift. The timing constants come from `SYNTH_TIMING` in `lib/lookaheadTransport.js` so the feel stays shared; the transport body itself is deliberately not reused, because it reads its clock from the shared `lib/audioContext.js` singleton while `cityAudioEngine` is a documented holdout that owns (and closes) its own `AudioContext` — scheduling this graph against a clock it doesn't run on would be worse than the drift. A backgrounded tab now re-anchors to the grid on return instead of dumping every missed step into one burst. Generative behavior (chord walk, mood sets, energy-driven arp gain) and the stop-ramp contract are unchanged.
+- **A manually-triggered ("Run Now") perpetual claim drain no longer stalls after one item.** A `claim-issue` / `claim-work` schedule set to *perpetual* is meant to drain actionable work back-to-back. When the daemon's own scheduler drives it that works, but a manual "Run Now" (`RunTaskButton` → `POST /api/cos/schedule/trigger`) did not: the on-demand trigger only gates on the master Improve flag, so the first item ran, but `refillPerpetualForCompletedAgent` then gated the *continuation* on `canQueueImprovementTasks` — which additionally requires idle-review ON **and** CoS auto-run = `execute`. Those are exactly the postures in which a user reaches for "Run Now" (auto-run off/dry-run, or idle-review off), so the drain refused to spin up the next item even with a queue of claimable issues. The refill now routes a manual drain through `perpetualRefillPlan`'s `onDemand` lane: it re-issues an on-demand request for the same task type + app, gated only on the master Improve flag (matching what let the manual run START), and returns before the auto-run-gated queue lane — so a manual perpetual drain keeps draining, scoped to that one type+app (it can't leak unrelated rotation/idle autonomous work past the auto-run kill switch), until the work-detector parks. The on-demand spawn engines mark generated tasks `metadata.onDemand` (projected onto the agent as `taskOnDemand`) and forward the completion's `ignoreTaskId` to `addTask`, so the re-issued claim isn't rejected as a duplicate of the still-`in_progress` run that just triggered it. Scheduled perpetual drains are unchanged.
- **[issue-3400] Rendering two storyboard scenes at once no longer loses one of the jobs.** `enqueueStoryboardSceneVideo`, `enqueueStoryboardShotStartFrame`, and `refineStoryboardScenePrompt` each read `stages.storyboards.scenes` up front, then wrote the whole pre-read array back through `updateStage`. That write *is* serialized, but the array it shallow-merges was built outside the lock — so two enqueues for different scenes that both read before either wrote would revert each other's freshly-stamped `sceneVideoJobId` / `startFrameJobId`, and the losing render would run to completion with nothing left pointing at it. All three now patch a single scene through `updateStageWithLatest`, so the read-modify-write of `scenes` happens inside the write region and only the targeted index is replaced. A scene that disappeared between the caller's read and the write now 404s instead of resurrecting itself.
- **[issue-3407] Stacker News sync works again.** Stacker News renamed its territory listing route from `/recent` to `/new`, so every browser-transport sync was refused with "landed on a different page than the one requested" — the redirect guard correctly caught the rename. Syncs now request the new route directly; the guard stays strict.
- **A completed TUI agent could be recorded as failed by a duplicate finalize.** `cleanupOrphanedAgents` runs every 15 minutes and calls `syncRunnerAgents`, which only checked `runnerAgents` for "already tracked" — but a runner-backed TUI agent is owned by the live `spawnTuiAgent` closure, which registers in `activeAgents` and never in `runnerAgents`. Any TUI run outliving one health-check tick was therefore hoisted into `runnerAgents` mid-flight, so the `agent:completed` event the runner emits when the TUI spawner's own `finish()` kills the session slipped past the `if (!agent) return` guard and ran a *second* `finalizeAgent`. That overwrote a sentinel-signalled success with `success: false, exitCode: 143` plus a bogus `startup-failure` analysis (computed from an output buffer that path can't read — a TUI writes `output.txt` under the dated run dir, not `AGENTS_DIR/<id>`), which in turn flipped the agent card to Failed and requeued the already-finished task as `pending`. Observed on a 55-minute release-check run that had already published v2.37.0 and merged all three of its PRs.
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 7346d83f10..3f88bc41c5 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -463,6 +463,12 @@ async function runAgentSpawn(task) {
taskAnalysisType: task.metadata?.analysisType || null,
taskReviewType: task.metadata?.reviewType || null,
taskApp: task.metadata?.app || null,
+ // Marks a run dispatched by an explicit "Run Now" (on-demand) trigger, so
+ // the perpetual drain-on-completion refill (perpetualRefillPlan in cos.js)
+ // continues a MANUAL drain in the user-initiated on-demand lane rather than
+ // the auto-run-gated queue lane. `isTruthyMeta` accepts the boolean set at
+ // spawn AND the string `"true"` a COS-TASKS.md round-trip yields.
+ taskOnDemand: isTruthyMeta(task.metadata?.onDemand),
// LI hand-off provenance (#2765): projected onto the agent so the completion
// hook (recordTaskCompletion) can attribute the run's success/failure back to
// the proposal's domain. agent.metadata is a hand-picked projection of
diff --git a/server/services/cos.js b/server/services/cos.js
index f258a9e5b7..5e5cb75ef1 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -758,7 +758,7 @@ async function tryImmediateSpawn(task) {
* the on-demand request queue, generating + persisting a task per request.
*/
async function spawnDequeuePriority0OnDemand(ctx) {
- const { state, capacity } = ctx;
+ const { state, capacity, ignoreTaskId } = ctx;
const taskScheduleMod = await import('./taskSchedule.js');
const taskSchedule = await taskScheduleMod.loadSchedule();
@@ -842,7 +842,17 @@ async function spawnDequeuePriority0OnDemand(ctx) {
}
if (task && capacity.canSpawn(task)) {
- const persisted = await addTask(task, 'internal', { raw: true });
+ // Mark this as a MANUAL (on-demand) run so a completed perpetual drain
+ // continues in the same user-initiated lane instead of the auto-run-gated
+ // queue path (see perpetualRefillPlan). Stamped before addTask so the
+ // blocked-revive branch below inherits it via `task.metadata` too.
+ task.metadata = { ...(task.metadata || {}), onDemand: true };
+ // Forward `ignoreTaskId` so a completion-triggered re-issue is dedup-safe:
+ // the perpetual drain regenerates an identical first-line for the same app,
+ // and `agent:completed` fires before the completing task's updateTask
+ // settles it to `completed` — so without excluding it the re-issued claim is
+ // rejected as a duplicate of the run that just finished and the drain stalls.
+ const persisted = await addTask(task, 'internal', { raw: true, ignoreTaskId });
if (!persisted?.duplicate) {
cosEvents.emit('task:ready', task);
capacity.trackSpawn(task);
@@ -1158,25 +1168,68 @@ async function dequeueNextTask({ ignoreTaskId = null } = {}) {
* the analysis type the same way `queueEligibleImprovementTasks` /
* `isDisabledAnalysisType` do, and never throws on partial inputs.
*/
-export function isPerpetualRefillCandidate(agent, schedule) {
- const analysisType = agent?.metadata?.taskAnalysisType
+/**
+ * The scheduled task type a completed agent belongs to, if any — the key
+ * `schedule.tasks` and the perpetual-refill gates look up. Reads the same three
+ * projections agentLifecycle stamps onto the agent, newest-name first.
+ */
+function agentScheduledType(agent) {
+ return agent?.metadata?.taskAnalysisType
|| agent?.metadata?.analysisType
- || agent?.metadata?.selfImprovementType;
+ || agent?.metadata?.selfImprovementType
+ || null;
+}
+
+export function isPerpetualRefillCandidate(agent, schedule) {
+ const analysisType = agentScheduledType(agent);
if (!analysisType) return false;
const taskDef = schedule?.tasks?.[analysisType];
return Boolean(taskDef?.enabled) && taskDef.type === 'perpetual';
}
/**
- * When a perpetual-schedule agent finishes, re-queue the next eligible
- * improvement task right away so the backlog drains back-to-back rather than
- * stalling until the next improvement-check tick. Mirrors the gates the
- * improvement-check timer applies (daemon running, not paused, idle-review on,
- * CoS auto-run = execute) and reuses the same `queueEligibleImprovementTasks`
- * path — which already enforces per-app cooldown, the one-pending-per-app cap,
- * and the perpetual work-detector park, so this converges (when no actionable
- * work remains the task parks and nothing is re-queued) and can't fan out past
- * the concurrency limits in `dequeueNextTask`.
+ * Decide which "lane" a completed perpetual run's drain must continue in. Pure,
+ * so the branch is unit-testable without a live daemon.
+ *
+ * - `'skip'` — not a perpetual refill candidate (disabled/non-perpetual/no
+ * analysis type); nothing to refill.
+ * - `'onDemand'` — the completed run was a MANUAL "Run Now" drain, marked by
+ * the on-demand spawn engines (`metadata.onDemand`, projected
+ * onto the agent as `taskOnDemand`). It continues in the SAME
+ * user-initiated lane it started in: re-issue an on-demand
+ * request for the exact `taskType` + `appId`, gated only on the
+ * master Improve flag — what `RunTaskButton` itself gates on —
+ * NOT on `canQueueImprovementTasks`. This is the fix for a
+ * manual drain stalling after ONE item whenever CoS auto-run is
+ * off/dry-run or idle-review is off: those are exactly the
+ * postures in which a user reaches for "Run Now". The manual
+ * run is allowed to START (Priority-0 on-demand only checks
+ * `isImprovementEnabled`), but the autonomous refill's
+ * `canQueueImprovementTasks` gate then refuses to continue it.
+ * Re-issuing an on-demand request is scoped to just that
+ * type+app, so it can't leak unrelated rotation/idle autonomous
+ * work past the auto-run kill switch, and the on-demand path
+ * re-runs the work-detector and PARKS when the drain is done —
+ * so it converges exactly like the scheduled drain.
+ * - `'queue'` — a SCHEDULED perpetual run: the autonomous queue path, gated
+ * on `canQueueImprovementTasks` (auto-run = execute).
+ */
+export function perpetualRefillPlan(agent, schedule) {
+ if (!isPerpetualRefillCandidate(agent, schedule)) return { lane: 'skip' };
+ if (agent?.metadata?.taskOnDemand) {
+ return { lane: 'onDemand', taskType: agentScheduledType(agent), appId: agent?.metadata?.taskApp || null };
+ }
+ return { lane: 'queue' };
+}
+
+/**
+ * When a perpetual-schedule agent finishes, re-queue the next eligible task
+ * right away so the backlog drains back-to-back rather than stalling until the
+ * next improvement-check tick. `perpetualRefillPlan` picks the lane (see there):
+ * a MANUAL drain re-issues an on-demand request; a SCHEDULED drain uses the
+ * auto-run-gated `queueEligibleImprovementTasks` (which already enforces per-app
+ * cooldown, the one-pending-per-app cap, and the work-detector park, so it
+ * converges and can't fan out past the `dequeueNextTask` concurrency limits).
*/
async function refillPerpetualForCompletedAgent(agent) {
if (!isDaemonRunning()) return;
@@ -1192,9 +1245,22 @@ async function refillPerpetualForCompletedAgent(agent) {
const taskScheduleMod = await import('./taskSchedule.js');
const schedule = await taskScheduleMod.loadSchedule();
- if (!isPerpetualRefillCandidate(agent, schedule)) return;
+ const plan = perpetualRefillPlan(agent, schedule);
+ if (plan.lane === 'skip') return;
const state = await loadState();
+
+ if (plan.lane === 'onDemand') {
+ // Manual drain: gate on the master Improve flag (what the manual trigger
+ // itself uses), NOT canQueueImprovementTasks, and re-issue an on-demand
+ // request. The completion handler's subsequent dequeueNextTask({ ignoreTaskId })
+ // processes it dedup-safely against the still-`in_progress` completing task.
+ if (!isImprovementEnabled(state)) return;
+ await taskScheduleMod.triggerOnDemandTask(plan.taskType, plan.appId);
+ return;
+ }
+
+ // Scheduled drain — autonomous queue path, gated on CoS auto-run.
if (!canQueueImprovementTasks(state)) return;
// `agent:completed` fires from `completeAgent` BEFORE the completion flow's
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index cb342e7808..51543b046e 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -34,7 +34,7 @@ import { describe, it, expect } from 'vitest';
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
-import { firstLine, isPerpetualRefillCandidate } from './cos.js';
+import { firstLine, isPerpetualRefillCandidate, perpetualRefillPlan } from './cos.js';
import { canQueueImprovementTasks } from './cosState.js';
import { createDequeueCapacity, isMissionTierEligible, isIdleTierEligible } from './cosDequeue.js';
@@ -1260,6 +1260,66 @@ describe('isPerpetualRefillCandidate — perpetual drain on completion', () => {
});
});
+// `perpetualRefillPlan` chooses which lane a completed perpetual run continues
+// in. The load-bearing case: a MANUAL "Run Now" drain (metadata.taskOnDemand)
+// must continue in the user-initiated on-demand lane — gated on the master
+// Improve flag, NOT canQueueImprovementTasks — so it keeps draining even when
+// CoS auto-run is off/dry-run or idle-review is off (the postures in which the
+// user reaches for "Run Now" and the manual run is allowed to START but the
+// auto-run-gated queue lane would otherwise stall the drain after one item).
+describe('perpetualRefillPlan — manual vs scheduled drain lane', () => {
+ const schedule = {
+ tasks: {
+ 'claim-issue': { type: 'perpetual', enabled: true },
+ 'claim-issue-disabled': { type: 'perpetual', enabled: false },
+ 'plan-task': { type: 'daily', enabled: true },
+ },
+ };
+ const agent = (metadata) => ({ metadata });
+
+ it('routes a scheduled perpetual run to the auto-run-gated queue lane', () => {
+ expect(perpetualRefillPlan(agent({ taskAnalysisType: 'claim-issue' }), schedule))
+ .toEqual({ lane: 'queue' });
+ });
+
+ it('routes a MANUAL (on-demand) perpetual run to the on-demand lane, carrying type + app', () => {
+ expect(perpetualRefillPlan(
+ agent({ taskAnalysisType: 'claim-issue', taskOnDemand: true, taskApp: 'app-42' }),
+ schedule,
+ )).toEqual({ lane: 'onDemand', taskType: 'claim-issue', appId: 'app-42' });
+ });
+
+ it('a manual run with no app resolves appId to null (global on-demand re-issue)', () => {
+ expect(perpetualRefillPlan(
+ agent({ taskAnalysisType: 'claim-issue', taskOnDemand: true }),
+ schedule,
+ )).toEqual({ lane: 'onDemand', taskType: 'claim-issue', appId: null });
+ });
+
+ it('skips a non-candidate even when it is marked on-demand (disabled / non-perpetual / unknown)', () => {
+ expect(perpetualRefillPlan(agent({ taskAnalysisType: 'claim-issue-disabled', taskOnDemand: true }), schedule))
+ .toEqual({ lane: 'skip' });
+ expect(perpetualRefillPlan(agent({ taskAnalysisType: 'plan-task', taskOnDemand: true }), schedule))
+ .toEqual({ lane: 'skip' });
+ expect(perpetualRefillPlan(agent({ taskAnalysisType: 'ghost', taskOnDemand: true }), schedule))
+ .toEqual({ lane: 'skip' });
+ });
+
+ it('resolves the on-demand type from the analysisType / selfImprovementType fallbacks', () => {
+ expect(perpetualRefillPlan(agent({ analysisType: 'claim-issue', taskOnDemand: true }), schedule).lane)
+ .toBe('onDemand');
+ expect(perpetualRefillPlan(agent({ selfImprovementType: 'claim-issue', taskOnDemand: true }), schedule).lane)
+ .toBe('onDemand');
+ });
+
+ it('never throws on missing agent / metadata / schedule', () => {
+ expect(perpetualRefillPlan(null, schedule)).toEqual({ lane: 'skip' });
+ expect(perpetualRefillPlan(agent({}), schedule)).toEqual({ lane: 'skip' });
+ expect(perpetualRefillPlan(agent({ taskAnalysisType: 'claim-issue', taskOnDemand: true }), null))
+ .toEqual({ lane: 'skip' });
+ });
+});
+
// Source-level guard: the agent:completed handler must wire the perpetual
// refill so completion drains back-to-back instead of waiting for the hourly
// improvement-check timer.
@@ -1283,20 +1343,70 @@ describe('cos.js source — agent:completed triggers perpetual refill', () => {
// drain stalls. Pin the ignoreTaskId thread so a refactor can't reintroduce it.
const fnIdx = COS_SRC.indexOf('async function refillPerpetualForCompletedAgent');
expect(fnIdx, 'refillPerpetualForCompletedAgent must exist').toBeGreaterThan(-1);
- const fnSlice = COS_SRC.slice(fnIdx, fnIdx + 2500);
+ const fnSlice = COS_SRC.slice(fnIdx, fnIdx + 3600);
expect(
/queueEligibleImprovementTasks\(\s*state\s*,\s*cosTaskData\s*,\s*\{\s*ignoreTaskId:\s*agent\?\.taskId\s*\}\s*\)/.test(fnSlice),
'refill must forward { ignoreTaskId: agent?.taskId } to queueEligibleImprovementTasks'
).toBe(true);
});
+ it('a MANUAL (on-demand) drain continues via triggerOnDemandTask under isImprovementEnabled, returning before the auto-run queue lane', () => {
+ // The bug fixed here: a "Run Now" perpetual drain is allowed to START in a
+ // posture where canQueueImprovementTasks is false (auto-run off/dry-run or
+ // idle-review off), but the scheduled queue lane refuses to continue it —
+ // stalling the drain after one item. The manual lane must instead re-issue an
+ // on-demand request (scoped to the same type+app) under the same
+ // isImprovementEnabled gate the manual trigger used, and RETURN before the
+ // queueEligibleImprovementTasks path. Assert the ordering rather than the
+ // absence of a keyword in a comment (fragile): Improve gate → re-issue →
+ // return → (only then) the queue lane.
+ const fnIdx = COS_SRC.indexOf('async function refillPerpetualForCompletedAgent');
+ const fnSlice = COS_SRC.slice(fnIdx, fnIdx + 3600);
+ expect(
+ fnSlice.includes('const plan = perpetualRefillPlan(agent, schedule)'),
+ 'refill must resolve the lane via perpetualRefillPlan'
+ ).toBe(true);
+ expect(/plan\.lane === 'onDemand'/.test(fnSlice), 'refill must branch on the on-demand lane').toBe(true);
+
+ const improveGateIdx = fnSlice.indexOf('if (!isImprovementEnabled(state)) return;');
+ const triggerIdx = fnSlice.indexOf('triggerOnDemandTask(plan.taskType, plan.appId)');
+ const queueIdx = fnSlice.indexOf('queueEligibleImprovementTasks(state, cosTaskData');
+ expect(improveGateIdx, 'manual lane must gate on isImprovementEnabled').toBeGreaterThan(-1);
+ expect(triggerIdx, 'manual lane must re-issue via triggerOnDemandTask(plan.taskType, plan.appId)').toBeGreaterThan(-1);
+ expect(queueIdx, 'scheduled queue lane must still exist').toBeGreaterThan(-1);
+ // Improve gate precedes the re-issue; the manual lane returns before the queue lane.
+ expect(improveGateIdx).toBeLessThan(triggerIdx);
+ expect(triggerIdx).toBeLessThan(queueIdx);
+ const returnAfterTrigger = fnSlice.indexOf('return;', triggerIdx);
+ expect(returnAfterTrigger, 'manual lane must return before falling through to the queue lane').toBeGreaterThan(-1);
+ expect(returnAfterTrigger).toBeLessThan(queueIdx);
+ });
+
+ it('the on-demand spawn engine marks generated tasks on-demand and forwards ignoreTaskId to addTask', () => {
+ // For the manual continuation to be recognized on completion, the on-demand
+ // engine must stamp metadata.onDemand; and the completion-triggered re-issue
+ // must be dedup-safe against the still-in_progress completing task, so the
+ // engine's addTask must forward the dequeue's ignoreTaskId.
+ const engIdx = COS_SRC.indexOf('async function spawnDequeuePriority0OnDemand');
+ expect(engIdx, 'spawnDequeuePriority0OnDemand must exist').toBeGreaterThan(-1);
+ const engSlice = COS_SRC.slice(engIdx, engIdx + 5600);
+ expect(
+ /onDemand:\s*true/.test(engSlice),
+ 'on-demand engine must stamp metadata.onDemand: true before addTask'
+ ).toBe(true);
+ expect(
+ /addTask\(\s*task\s*,\s*'internal'\s*,\s*\{\s*raw:\s*true\s*,\s*ignoreTaskId\s*\}\s*\)/.test(engSlice),
+ 'on-demand engine must forward ignoreTaskId to addTask'
+ ).toBe(true);
+ });
+
it('the refill only fires on a SUCCESSFUL completion (no back-to-back spin on failures)', () => {
// Perpetual completions skip the per-app cooldown, so refilling after a failed
// run would spin the daemon through repeated failures (the work-detector still
// sees the same issue as actionable). The refill must bail on a non-success
// result and let task-retry/backoff + the recheck cadence handle failures.
const fnIdx = COS_SRC.indexOf('async function refillPerpetualForCompletedAgent');
- const fnSlice = COS_SRC.slice(fnIdx, fnIdx + 2500);
+ const fnSlice = COS_SRC.slice(fnIdx, fnIdx + 3600);
expect(
/if\s*\(\s*!agent\?\.result\?\.success\s*\)\s*return/.test(fnSlice),
'refill must early-return when the completed agent did not succeed'
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index d027f15743..da940b429e 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -780,6 +780,11 @@ async function spawnPriority0OnDemand(ctx) {
}
if (task && canSpawnTask(task)) {
+ // Mark this a MANUAL (on-demand) run so its perpetual drain continues in
+ // the on-demand lane (see perpetualRefillPlan in cos.js). BOTH on-demand
+ // engines must stamp it — either may drain a given request. Stamped before
+ // addTask so the blocked-revive branch inherits it via `task.metadata`.
+ task.metadata = { ...(task.metadata || {}), onDemand: true };
const persisted = await addTask(task, 'internal', { raw: true });
if (!persisted?.duplicate) {
tasksToSpawn.push(task);
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index 4854976d10..ea75a08e7f 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -87,6 +87,32 @@ describe('dry-run hook wiring matches each engine execute path', () => {
});
});
+// Both on-demand spawn engines must stamp `metadata.onDemand` on the generated
+// task, or a MANUAL "Run Now" perpetual drain processed by whichever engine
+// forgot would refill through the auto-run-gated queue lane and stall after one
+// item (see perpetualRefillPlan in cos.js). The cos.js engine's stamp +
+// ignoreTaskId forwarding is pinned in cos.test.js; this pins the sibling
+// evaluateTasks engine here so the two-engine mirror can't drift by a comment.
+describe('both on-demand engines stamp metadata.onDemand', () => {
+ const onDemandStamp = (src, engineFn) => {
+ const start = src.indexOf(engineFn);
+ expect(start, `${engineFn} must exist`).toBeGreaterThan(-1);
+ // Scan to the next top-level function so the assertion is scoped to this engine.
+ const next = src.indexOf('\nasync function ', start + 1);
+ return src.slice(start, next === -1 ? src.length : next);
+ };
+
+ it('evaluateTasks engine (spawnPriority0OnDemand) stamps onDemand before addTask', () => {
+ const engine = onDemandStamp(GEN_SRC, 'async function spawnPriority0OnDemand');
+ expect(/task\.metadata = \{ \.\.\.\(task\.metadata \|\| \{\}\), onDemand: true \}/.test(engine)).toBe(true);
+ });
+
+ it('dequeueNextTask engine (spawnDequeuePriority0OnDemand) stamps onDemand before addTask', () => {
+ const engine = onDemandStamp(COS_SRC, 'async function spawnDequeuePriority0OnDemand');
+ expect(/task\.metadata = \{ \.\.\.\(task\.metadata \|\| \{\}\), onDemand: true \}/.test(engine)).toBe(true);
+ });
+});
+
// #1650: once a peer's claim/lease is visible via task-record federation, a
// task whose live lease belongs to ANOTHER instance must be skipped during
// candidate selection — BEFORE the engine emits `task:ready` + trackSpawn.