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: hold forge-dependent tasks while the forge is unreachable instead of retrying

Adam Eivyd0f50da60cd0
diff --git a/server/services/cosForgeSpawnGate.js b/server/services/cosForgeSpawnGate.js
new file mode 100644
index 0000000000..8df76a6c1d
--- /dev/null
+++ b/server/services/cosForgeSpawnGate.js
@@ -0,0 +1,187 @@
+/**
+ * CoS forge-reachability spawn gate (issue #5110)
+ *
+ * A task whose shape promises a change request cannot finish while the forge is
+ * unreachable: the agent does the work, `git push` fails, and finalize records
+ * `forge-unreachable`. That verdict is non-actionable, so `resolveFailedTaskDecision`
+ * routes it into the ordinary retry ladder — and each retry re-runs the whole agent
+ * against the same dead network. One VPN drop cost three consecutive runs (101 + 50 +
+ * 23 minutes of Opus) to walk a single user task through its retry budget into
+ * `blocked`, plus the `[Auto] Investigate` task that followed, for a branch that
+ * already held all of its commits after run one and only ever needed a push.
+ *
+ * So hold at dispatch instead. Same posture as the runner-down hold beside it in
+ * subAgentSpawner's `task:ready` listener, and for the same reason recorded there:
+ * "a runner left off overnight walked every queued task through its retry budget
+ * into `blocked`". The task stays queued — no status write, no retry charged — and
+ * spawns on the far side of the outage. Retries funnel through the same chokepoint,
+ * so one hold covers both the first dispatch and every retry.
+ *
+ * Four deliberate narrowings, because a hold that fires wrongly stalls the queue
+ * silently:
+ *
+ * - **Only `unreachable` holds.** `not-installed` / `not-authenticated` / `error`
+ * are durable LOCAL misconfigurations that will not clear on their own, and the
+ * chokepoint's contract is "a condition that clears on its own". They fall
+ * through and spawn exactly as they do today. (This is also what keeps a
+ * non-GitHub host out: a Bitbucket or Forgejo remote answers `gh api rate_limit`
+ * with an HTTP 404, which classifies as `error`, not `unreachable`.)
+ * - **Only a `gh` forge is probed.** `checkGhHealth` shells out to `gh`, which
+ * answers nothing about a GitLab remote — probing one would report every
+ * `gitlab.*` repo unreachable and hold it forever.
+ * - **A one-shot re-dequeue arms the way out.** Nothing else fires when a network
+ * comes back, so a held task would otherwise wait for an unrelated dequeue
+ * trigger. Mirrors the runner-reconnect re-dequeue.
+ * - **The hold expires.** A host that stays unreachable past `MAX_HOLD_MS` stops
+ * holding, so a permanently-broken remote still reaches the `blocked` card that
+ * tells the user about it rather than sitting `pending` in silence.
+ *
+ * No dequeue-side pre-filter (the second altitude cosLocalEndpointSlots.js has):
+ * the probe spawns a process, so a per-task probe inside the dequeue loop would
+ * cost more than the hold it avoids. `checkGhHealth`'s 60s per-host cache makes the
+ * chokepoint check ~free instead.
+ */
+
+import { emitLog, cosEvents } from './cosEvents.js';
+import { checkGhHealth } from './github.js';
+import { getAppWorkspace, isClaimFlowTask } from './agentPromptBuilder.js';
+import { isTruthyMeta } from './agentState.js';
+import { parseGitRemote, detectForgeCli } from '../lib/gitForge.js';
+import { execGit } from '../lib/execGit.js';
+import { PATHS } from '../lib/fileUtils.js';
+
+// Just past `checkGhHealth`'s 60s cache, so the re-dequeue's probe is a fresh one
+// rather than the cached verdict that armed this timer.
+const FORGE_RECHECK_DELAY_MS = 65_000;
+
+// How long one host may hold tasks before the gate gives up on it. An outage that
+// outlasts this is no longer "a condition that clears on its own" from the queue's
+// point of view, and a silent `pending` task is worse than the Blocked card the
+// pre-gate behavior produced.
+const MAX_HOLD_MS = 60 * 60_000;
+
+// host → { firstHeldAt, warned, expiredWarned }. Cleared as soon as the host probes
+// healthy, so a later outage gets a fresh budget and a fresh warning.
+const heldHosts = new Map();
+
+let recheckTimer = null;
+
+/**
+ * Does this task need the forge to finish?
+ *
+ * `openPR` is the direct signal — the run must push and open a change request.
+ * A claim-flow task needs the forge even earlier: it cannot pick an issue to work
+ * on without reading the tracker.
+ *
+ * Everything else (a reasoning/discard run, a Creative Director deliverable, a
+ * read-only audit) can complete with the forge down and is left alone.
+ */
+export function taskNeedsForge(task) {
+ return isTruthyMeta(task?.metadata?.openPR) || isClaimFlowTask(task, isTruthyMeta);
+}
+
+/**
+ * The repo directory this task's agent will run against — resolved the same way
+ * `agentWorkspacePrep` resolves it, so the gate probes the host the run will
+ * actually push to.
+ *
+ * `null` means the app did not resolve. The gate does not hold in that case:
+ * `agentWorkspacePrep` already blocks that task with a message naming the app,
+ * which is a far better answer than an indefinite silent hold.
+ */
+async function resolveTaskRepoDir(task) {
+ if (!task?.metadata?.app) return PATHS.root;
+ return await getAppWorkspace(task.metadata.app).catch(() => null);
+}
+
+/**
+ * The forge host in a repo's `origin` URL, or `null` when there is no origin, the
+ * directory is not a repo, or the URL does not parse. Every `null` path means "we
+ * cannot name a host", which must not collapse into "the host is down" — the gate
+ * declines to hold rather than guessing.
+ */
+async function resolveForgeHost(dir) {
+ const result = await execGit(['remote', 'get-url', 'origin'], dir, { ignoreExitCode: true })
+ .catch(() => null);
+ if (!result || result.exitCode !== 0) return null;
+ return parseGitRemote((result.stdout || '').trim())?.host || null;
+}
+
+/**
+ * Ask for one more dequeue once the probe cache has expired, so a task held on a
+ * network outage spawns on its own when the network returns.
+ *
+ * One timer for the whole gate, not one per task: the dequeue drains every queued
+ * task, and a held task that is still held simply re-arms it. `unref` so it never
+ * holds the event loop open, and the emit is guarded because a `setTimeout`
+ * callback runs outside the request lifecycle — an uncaught throw there would take
+ * the process down.
+ */
+function scheduleForgeRecheck() {
+ if (recheckTimer) return;
+ recheckTimer = setTimeout(() => {
+ recheckTimer = null;
+ try {
+ cosEvents.emit('cos:dequeue-requested');
+ } catch (err) {
+ console.error(`❌ Forge re-check dequeue request failed: ${err.message}`);
+ }
+ }, FORGE_RECHECK_DELAY_MS);
+ recheckTimer.unref?.();
+}
+
+/**
+ * Should this task's dispatch be held because its forge is unreachable?
+ *
+ * @param {object} task - the task about to be dispatched
+ * @param {{ now?: number }} [opts] - injectable clock for the hold-expiry budget
+ * @returns {Promise<string|null>} a `holdTask` reason, or `null` to dispatch
+ */
+export async function forgeSpawnHoldReason(task, { now = Date.now() } = {}) {
+ if (!taskNeedsForge(task)) return null;
+
+ const dir = await resolveTaskRepoDir(task);
+ if (!dir) return null;
+
+ const host = await resolveForgeHost(dir);
+ if (!host) return null;
+ if (detectForgeCli(host) !== 'gh') return null;
+
+ const health = await checkGhHealth({ hostname: host }).catch(() => null);
+ if (health?.status !== 'unreachable') {
+ // Any other answer — including a probe that itself blew up — ends the outage
+ // as far as the gate is concerned, so the next one starts from zero.
+ heldHosts.delete(host);
+ return null;
+ }
+
+ const state = heldHosts.get(host) || { firstHeldAt: now, warned: false, expiredWarned: false };
+ if (now - state.firstHeldAt > MAX_HOLD_MS) {
+ if (!state.expiredWarned) {
+ emitLog('warn', `⚠️ ${host} has been unreachable for over an hour — dispatching ${task.id} anyway so it fails visibly instead of waiting forever`, { taskId: task.id });
+ heldHosts.set(host, { ...state, expiredWarned: true });
+ }
+ return null;
+ }
+
+ // Warned once per outage, not once per held task — the same discipline the
+ // runner-down hold uses, so a queue full of forge-dependent tasks produces one
+ // line naming the host rather than one per task.
+ if (!state.warned) {
+ const detail = health.detail ? ` — ${String(health.detail).split('\n')[0].slice(0, 120)}` : '';
+ emitLog('warn', `⏸️ Holding forge-dependent tasks: ${host} is unreachable${detail}`, { taskId: task.id });
+ }
+ heldHosts.set(host, { ...state, warned: true });
+ scheduleForgeRecheck();
+
+ return `${host} is unreachable`;
+}
+
+/** Test seam — drops the per-host hold ledger and any pending re-check. */
+export function __resetForgeSpawnGate() {
+ heldHosts.clear();
+ if (recheckTimer) {
+ clearTimeout(recheckTimer);
+ recheckTimer = null;
+ }
+}
diff --git a/server/services/cosForgeSpawnGate.test.js b/server/services/cosForgeSpawnGate.test.js
new file mode 100644
index 0000000000..c60d588e4a
--- /dev/null
+++ b/server/services/cosForgeSpawnGate.test.js
@@ -0,0 +1,262 @@
+/**
+ * The forge-reachability dispatch gate (issue #5110).
+ *
+ * The incident: a user task targeting a repo on an enterprise GitHub host ran
+ * three times and failed all three with `forge-unreachable`, because the VPN was
+ * down and the host did not resolve. The agent had done the work correctly on run
+ * one — the branch already held every commit — and only `git push` failed. Because
+ * `forge-unreachable` is (correctly) non-actionable, each failure bought a retry,
+ * so 101 + 50 + 23 minutes of Opus went into re-learning one DNS failure before the
+ * task reached `blocked`.
+ *
+ * These tests pin the two halves that make the fix safe: it holds for the
+ * transient network status and ONLY that one, and every "we could not tell" path
+ * declines to hold rather than guessing — because a hold that fires wrongly stalls
+ * the queue with no status write to show for it.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('./cosEvents.js', () => ({
+ emitLog: vi.fn(),
+ cosEvents: { emit: vi.fn() },
+}));
+vi.mock('./github.js', () => ({ checkGhHealth: vi.fn() }));
+// `isClaimFlowTask` is a plain seam here: this suite asserts the gate CONSULTS it
+// and honors its answer, not what it decides (that lives in agentPromptBuilder's
+// own tests, and re-deriving it here is how two copies drift).
+vi.mock('./agentPromptBuilder.js', () => ({
+ getAppWorkspace: vi.fn(),
+ isClaimFlowTask: vi.fn().mockReturnValue(false),
+}));
+vi.mock('../lib/execGit.js', () => ({ execGit: vi.fn() }));
+
+import { taskNeedsForge, forgeSpawnHoldReason, __resetForgeSpawnGate } from './cosForgeSpawnGate.js';
+import { emitLog, cosEvents } from './cosEvents.js';
+import { checkGhHealth } from './github.js';
+import { getAppWorkspace, isClaimFlowTask } from './agentPromptBuilder.js';
+import { execGit } from '../lib/execGit.js';
+
+const remote = (url) => execGit.mockResolvedValue({ stdout: `${url}\n`, stderr: '', exitCode: 0 });
+const probe = (status, detail = null) => checkGhHealth.mockResolvedValue({ status, ok: status === 'ok', detail });
+
+const prTask = (overrides = {}) => ({ id: 'task-1', metadata: { openPR: true, ...overrides } });
+
+describe('taskNeedsForge', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ isClaimFlowTask.mockReturnValue(false);
+ });
+
+ it('is true for a task that promised a change request', () => {
+ expect(taskNeedsForge({ metadata: { openPR: true } })).toBe(true);
+ });
+
+ // Task metadata round-trips through markdown, so booleans come back as strings.
+ it('accepts the string form openPR survives persistence as', () => {
+ expect(taskNeedsForge({ metadata: { openPR: 'true' } })).toBe(true);
+ });
+
+ it('is true for a claim-flow task, which cannot even pick an issue with the forge down', () => {
+ isClaimFlowTask.mockReturnValue(true);
+
+ expect(taskNeedsForge({ metadata: {} })).toBe(true);
+ });
+
+ it('is false for a task that can finish with the forge down', () => {
+ expect(taskNeedsForge({ metadata: { openPR: false } })).toBe(false);
+ expect(taskNeedsForge({ metadata: {} })).toBe(false);
+ expect(taskNeedsForge(null)).toBe(false);
+ });
+});
+
+describe('forgeSpawnHoldReason', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ __resetForgeSpawnGate();
+ isClaimFlowTask.mockReturnValue(false);
+ getAppWorkspace.mockResolvedValue('/repos/app');
+ remote('[email protected]:acme/app.git');
+ probe('ok');
+ });
+
+ it('holds a PR-shaped task when its forge is unreachable', async () => {
+ probe('unreachable', 'error connecting to forge.example.com');
+
+ expect(await forgeSpawnHoldReason(prTask())).toBe('forge.example.com is unreachable');
+ });
+
+ it('does not probe at all for a task that does not need the forge', async () => {
+ probe('unreachable');
+
+ expect(await forgeSpawnHoldReason({ id: 'task-2', metadata: {} })).toBeNull();
+ expect(checkGhHealth).not.toHaveBeenCalled();
+ });
+
+ it('probes the host in the repo\'s own origin, not gh\'s default host', async () => {
+ // A bare probe hits github.com. Gating an enterprise repo on github.com's
+ // health is exactly the wrong-forge verdict `checkGhHealth`'s host-keyed cache
+ // exists to prevent — and in this incident github.com was perfectly healthy
+ // while the host the push needed was not.
+ remote('https://ghes.example.com/acme/app.git');
+ probe('unreachable');
+
+ await forgeSpawnHoldReason(prTask());
+
+ expect(checkGhHealth).toHaveBeenCalledWith({ hostname: 'ghes.example.com' });
+ });
+
+ it('resolves the repo through the app registry when the task carries an app', async () => {
+ getAppWorkspace.mockResolvedValue('/repos/managed-app');
+
+ await forgeSpawnHoldReason(prTask({ app: 'app-id' }));
+
+ expect(getAppWorkspace).toHaveBeenCalledWith('app-id');
+ expect(execGit).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], '/repos/managed-app', expect.anything());
+ });
+
+ describe('holds only for the status that clears on its own', () => {
+ // The chokepoint's contract is "a condition that clears on its own". A missing
+ // binary or a missing credential never will, so holding on those would stall
+ // every forge-dependent task silently and forever — strictly worse than
+ // today's three failures and a Blocked card naming the problem.
+ it.each(['ok', 'not-installed', 'not-authenticated', 'error'])('dispatches on %s', async (status) => {
+ probe(status, 'some detail');
+
+ expect(await forgeSpawnHoldReason(prTask())).toBeNull();
+ });
+
+ it('dispatches when the probe itself blows up', async () => {
+ checkGhHealth.mockRejectedValue(new Error('probe exploded'));
+
+ expect(await forgeSpawnHoldReason(prTask())).toBeNull();
+ });
+ });
+
+ describe('declines to hold whenever it cannot name a reachable-or-not host', () => {
+ it('never probes a GitLab remote, which gh cannot answer for', async () => {
+ // `checkGhHealth` shells out to `gh`. Pointed at a GitLab host it answers
+ // nothing useful, so probing one would report every gitlab.* repo
+ // unreachable and hold it forever.
+ remote('[email protected]:group/app.git');
+ probe('unreachable');
+
+ expect(await forgeSpawnHoldReason(prTask())).toBeNull();
+ expect(checkGhHealth).not.toHaveBeenCalled();
+ });
+
+ it('dispatches when the directory has no origin remote', async () => {
+ execGit.mockResolvedValue({ stdout: '', stderr: 'no such remote', exitCode: 2 });
+ probe('unreachable');
+
+ expect(await forgeSpawnHoldReason(prTask())).toBeNull();
+ expect(checkGhHealth).not.toHaveBeenCalled();
+ });
+
+ it('dispatches when the origin URL does not parse into a host', async () => {
+ remote('/srv/local/bare-repo.git');
+ probe('unreachable');
+
+ expect(await forgeSpawnHoldReason(prTask())).toBeNull();
+ });
+
+ it('dispatches when git itself fails', async () => {
+ execGit.mockRejectedValue(new Error('not a git repository'));
+
+ expect(await forgeSpawnHoldReason(prTask())).toBeNull();
+ });
+
+ // agentWorkspacePrep already blocks an unresolvable app with a message naming
+ // it. An indefinite silent hold would replace that answer with nothing.
+ it('dispatches when the task\'s app resolves to no workspace', async () => {
+ getAppWorkspace.mockResolvedValue(null);
+ probe('unreachable');
+
+ expect(await forgeSpawnHoldReason(prTask({ app: 'ghost-app' }))).toBeNull();
+ expect(execGit).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('the way out', () => {
+ it('asks for another dequeue so a held task spawns when the network returns', async () => {
+ vi.useFakeTimers();
+ probe('unreachable');
+
+ await forgeSpawnHoldReason(prTask());
+ expect(cosEvents.emit).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(70_000);
+
+ expect(cosEvents.emit).toHaveBeenCalledWith('cos:dequeue-requested');
+ vi.useRealTimers();
+ });
+
+ it('arms one re-check for a whole queue of held tasks, not one each', async () => {
+ vi.useFakeTimers();
+ probe('unreachable');
+
+ await forgeSpawnHoldReason(prTask({ }));
+ await forgeSpawnHoldReason({ id: 'task-2', metadata: { openPR: true } });
+ await forgeSpawnHoldReason({ id: 'task-3', metadata: { openPR: true } });
+ await vi.advanceTimersByTimeAsync(70_000);
+
+ const dequeues = cosEvents.emit.mock.calls.filter(([event]) => event === 'cos:dequeue-requested');
+ expect(dequeues).toHaveLength(1);
+ vi.useRealTimers();
+ });
+
+ // A permanently-broken remote is not "a condition that clears on its own", and
+ // a task sitting `pending` in silence tells the user less than the Blocked card
+ // the pre-gate behavior produced.
+ it('stops holding a host that has been unreachable for over an hour', async () => {
+ probe('unreachable');
+ const start = 1_000_000;
+
+ expect(await forgeSpawnHoldReason(prTask(), { now: start })).toBe('forge.example.com is unreachable');
+ expect(await forgeSpawnHoldReason(prTask(), { now: start + 59 * 60_000 })).toBe('forge.example.com is unreachable');
+ expect(await forgeSpawnHoldReason(prTask(), { now: start + 61 * 60_000 })).toBeNull();
+ });
+
+ it('gives a recovered host a fresh budget, so the next outage holds again', async () => {
+ const start = 1_000_000;
+ probe('unreachable');
+ await forgeSpawnHoldReason(prTask(), { now: start });
+
+ probe('ok');
+ await forgeSpawnHoldReason(prTask(), { now: start + 10 * 60_000 });
+
+ // Without clearing the ledger on recovery, the second outage would inherit
+ // the first one's elapsed clock and stop holding early — or never hold.
+ probe('unreachable');
+ expect(await forgeSpawnHoldReason(prTask(), { now: start + 61 * 60_000 })).toBe('forge.example.com is unreachable');
+ });
+ });
+
+ describe('logging', () => {
+ it('warns once per outage naming the host, not once per held task', async () => {
+ probe('unreachable', 'error connecting to forge.example.com');
+
+ await forgeSpawnHoldReason(prTask());
+ await forgeSpawnHoldReason({ id: 'task-2', metadata: { openPR: true } });
+ await forgeSpawnHoldReason({ id: 'task-3', metadata: { openPR: true } });
+
+ const warnings = emitLog.mock.calls.filter(([level]) => level === 'warn');
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0][1]).toContain('forge.example.com is unreachable');
+ });
+
+ it('warns once when it gives up on a host, so the expiry is not silent', async () => {
+ probe('unreachable');
+ const start = 1_000_000;
+ await forgeSpawnHoldReason(prTask(), { now: start });
+ emitLog.mockClear();
+
+ await forgeSpawnHoldReason(prTask(), { now: start + 61 * 60_000 });
+ await forgeSpawnHoldReason(prTask(), { now: start + 62 * 60_000 });
+
+ const warnings = emitLog.mock.calls.filter(([level]) => level === 'warn');
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0][1]).toContain('over an hour');
+ });
+ });
+});
diff --git a/server/services/subAgentSpawner.dispatchHolds.test.js b/server/services/subAgentSpawner.dispatchHolds.test.js
index 5fb658e16c..b681ec6670 100644
--- a/server/services/subAgentSpawner.dispatchHolds.test.js
+++ b/server/services/subAgentSpawner.dispatchHolds.test.js
@@ -1,5 +1,5 @@
/**
- * The three dispatch HOLDS at the `task:ready` chokepoint, and what releases them.
+ * The dispatch HOLDS at the `task:ready` chokepoint, and what releases them.
*
* Each leaves the task queued for a condition that clears on its own, rather
* than failing it:
@@ -14,6 +14,11 @@
* pull / submodule update / npm install before `pm2 delete`. An agent spawned
* in that window is severed by the restart.
*
+ * - Forge unreachable (issue #5110). A task that promises a change request cannot
+ * finish with the forge down: the agent works, `git push` fails, and finalize
+ * records the non-actionable `forge-unreachable` — which retries, so one VPN
+ * drop re-ran the same agent three times before the task reached `blocked`.
+ *
* - Local inference endpoint at capacity (issue #4834). A CoS agent runs a
* vendor CLI that talks to the local model server directly, so promptRunner's
* in-flight gate never sees it; two agents at one GPU takes an accelerator
@@ -64,6 +69,13 @@ vi.mock('./cosState.js', () => ({ loadState: vi.fn().mockResolvedValue({ agents:
vi.mock('./cosLocalEndpointSlots.js', () => ({
acquireLocalEndpointSpawnSlot: vi.fn().mockResolvedValue({ ok: true, release: vi.fn() }),
}));
+// Same reason: the real gate reaches the app registry through agentPromptBuilder,
+// whose graph reads files at module load and pulls in cos.js. Its own decisions
+// (which statuses hold, which hosts are probed, the expiry) are covered directly
+// in cosForgeSpawnGate.test.js; here it is a seam for the LISTENER's wiring.
+vi.mock('./cosForgeSpawnGate.js', () => ({
+ forgeSpawnHoldReason: vi.fn().mockResolvedValue(null),
+}));
vi.mock('./agentOrchestrator.js', () => ({
completeAgent: vi.fn(),
spawnAgentForTask: vi.fn().mockResolvedValue('agent-1'),
@@ -82,6 +94,7 @@ import { isUpdateInProgress } from './updateChecker.js';
import { releaseMissionSubTask } from './missions.js';
import { setUseRunner } from './agentState.js';
import { acquireLocalEndpointSpawnSlot } from './cosLocalEndpointSlots.js';
+import { forgeSpawnHoldReason } from './cosForgeSpawnGate.js';
const dispatch = (task) => taskHandlers.get('task:ready')(task);
@@ -370,6 +383,75 @@ describe('subAgentSpawner — local-endpoint capacity hold (#4834)', () => {
});
});
+describe('subAgentSpawner — forge-unreachable hold (#5110)', () => {
+ // The pre-gate behavior: an agent whose task promises a change request did the
+ // work, failed to push, and finalized the non-actionable `forge-unreachable` —
+ // which retries, so one VPN drop re-ran the same 20-to-100-minute agent three
+ // times before the task reached `blocked`.
+ beforeEach(async () => {
+ await initSpawner();
+ vi.clearAllMocks();
+ vi.useRealTimers();
+ setUseRunner(true);
+ isRunnerReachable.mockResolvedValue(true);
+ isUpdateInProgress.mockReturnValue(false);
+ acquireLocalEndpointSpawnSlot.mockResolvedValue({ ok: true, release: vi.fn() });
+ forgeSpawnHoldReason.mockResolvedValue(null);
+ });
+
+ it('spawns normally when the gate declines to hold', async () => {
+ await dispatch({ id: 'cos-f1', metadata: { openPR: true } });
+
+ expect(spawnAgentForTask).toHaveBeenCalledTimes(1);
+ });
+
+ it('holds instead of dispatching an agent that cannot push what it builds', async () => {
+ forgeSpawnHoldReason.mockResolvedValue('forge.example.com is unreachable');
+
+ await dispatch({ id: 'cos-f2', metadata: { openPR: true } });
+
+ // Held, not failed: no agent, no retry charged, so the task keeps its full
+ // retry budget for a failure that is actually about the task.
+ expect(spawnAgentForTask).not.toHaveBeenCalled();
+ });
+
+ it('releases the app-review marker and the job reservation, same as the other holds', async () => {
+ forgeSpawnHoldReason.mockResolvedValue('forge.example.com is unreachable');
+
+ await dispatch({ id: 'cos-f3', metadata: { openPR: true, app: 'some-app', jobId: 'job-13' } });
+
+ expect(releaseAppReviewMarker).toHaveBeenCalledWith('some-app');
+ expect(cosEvents.emit).toHaveBeenCalledWith('job:spawn-failed', { jobId: 'job-13' });
+ });
+
+ it('holds BEFORE reserving a capacity slot, so a held task never books one', async () => {
+ forgeSpawnHoldReason.mockResolvedValue('forge.example.com is unreachable');
+
+ await dispatch({ id: 'cos-f4', metadata: { openPR: true } });
+
+ expect(acquireLocalEndpointSpawnSlot).not.toHaveBeenCalled();
+ });
+
+ it('probes the forge AFTER the update and runner holds, which are cheaper', async () => {
+ isUpdateInProgress.mockReturnValue(true);
+
+ await dispatch({ id: 'cos-f5', metadata: { openPR: true } });
+
+ expect(forgeSpawnHoldReason).not.toHaveBeenCalled();
+ });
+
+ it('resumes spawning once the forge returns — the hold is not sticky', async () => {
+ forgeSpawnHoldReason.mockResolvedValue('forge.example.com is unreachable');
+ await dispatch({ id: 'cos-f6', metadata: { openPR: true } });
+ expect(spawnAgentForTask).not.toHaveBeenCalled();
+
+ forgeSpawnHoldReason.mockResolvedValue(null);
+ await dispatch({ id: 'cos-f6', metadata: { openPR: true } });
+
+ expect(spawnAgentForTask).toHaveBeenCalledTimes(1);
+ });
+});
+
describe('subAgentSpawner — runner connection events', () => {
beforeEach(async () => {
await initSpawner();
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index 6b5cb46118..d311bd937f 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -49,6 +49,7 @@ import { isUpdateInProgress } from './updateChecker.js';
import { releaseMissionSubTask } from './missions.js';
import { loadState } from './cosState.js';
import { acquireLocalEndpointSpawnSlot } from './cosLocalEndpointSlots.js';
+import { forgeSpawnHoldReason } from './cosForgeSpawnGate.js';
import { acquireCosGlobalSlot } from './cosAdmissionReservations.js';
// This module's own event wiring drives three LIFECYCLE TRANSITIONS, so it takes
// them from the facade rather than from the three separate leaves that happen to
@@ -345,7 +346,7 @@ async function runInitSpawner() {
cosEvents.on('task:ready', async (task) => {
// ── HOLDS, at the one chokepoint all seven `task:ready` emitters funnel
- // through. Both leave the task queued (no status write, no retry charged)
+ // through. Each leaves the task queued (no status write, no retry charged)
// for a condition that clears on its own.
//
// Held HERE rather than inside `runAgentSpawn`: a hold below this line would
@@ -372,7 +373,16 @@ async function runInitSpawner() {
if (useRunner && !(await isRunnerReachable())) {
return holdTask(task, 'CoS Runner is down');
}
- // 3. Global capacity. Reserve across the spawn window so direct persistent
+ // 3. Forge unreachable, for a task that cannot finish without it (#5110). An
+ // agent whose task promises a change request does its work, fails to push,
+ // and finalizes `forge-unreachable` — non-actionable, so the task retries,
+ // and each retry re-runs the whole agent against the same dead network. One
+ // VPN drop cost three runs (101 + 50 + 23 minutes) to reach `blocked`. See
+ // cosForgeSpawnGate.js for the narrowings that keep the hold from becoming
+ // the silent wedge a wrong hold would be.
+ const forgeHold = await forgeSpawnHoldReason(task);
+ if (forgeHold) return holdTask(task, forgeHold);
+ // 4. Global capacity. Reserve across the spawn window so direct persistent
// turns and ordinary agents cannot both pass a stale pre-registration
// snapshot.
const capacityState = await loadState();
@@ -383,7 +393,7 @@ async function runInitSpawner() {
});
if (!globalSlot.ok) return holdTask(task, globalSlot.reason);
- // 4. Local inference endpoint at capacity (issue #4834). A CoS agent runs a
+ // 5. Local inference endpoint at capacity (issue #4834). A CoS agent runs a
// vendor CLI that opens its own connection to the local model server, so
// promptRunner's in-flight gate never sees it — without this, two agents
// can be dispatched at one GPU and the runtime kills a turn with an
diff --git a/server/services/subAgentSpawner.runnerPromotion.test.js b/server/services/subAgentSpawner.runnerPromotion.test.js
index 027280493a..ddcd0e7e9f 100644
--- a/server/services/subAgentSpawner.runnerPromotion.test.js
+++ b/server/services/subAgentSpawner.runnerPromotion.test.js
@@ -49,6 +49,11 @@ vi.mock('./agentOrchestrator.js', () => ({
spawnAgentForTask: vi.fn().mockResolvedValue('agent-1'),
terminateAgent: vi.fn(),
}));
+// Same reason cosLocalEndpointSlots is mocked in the dispatch-holds suite: the
+// real gate reaches the app registry through agentPromptBuilder, whose graph
+// reads files at module load — which this file's `fs` mock breaks. The gate's own
+// behavior is covered in cosForgeSpawnGate.test.js.
+vi.mock('./cosForgeSpawnGate.js', () => ({ forgeSpawnHoldReason: vi.fn().mockResolvedValue(null) }));
vi.mock('fs', () => ({ existsSync: vi.fn().mockReturnValue(false) }));
import { initSpawner } from './subAgentSpawner.js';