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

Stop an orchestrated lane from silently falling back onto the architect's provider

Adam Eivy60b0745316e6
diff --git a/client/src/components/cos/tabs/TaskItem.jsx b/client/src/components/cos/tabs/TaskItem.jsx
index 15e5be8f6d..2c53ca88fc 100644
--- a/client/src/components/cos/tabs/TaskItem.jsx
+++ b/client/src/components/cos/tabs/TaskItem.jsx
@@ -679,6 +679,22 @@ export default function TaskItem({ task, agent = null, isSystem, spawning = fals
{/* Clamped: server-side auto-blocks write `blockedReason` from
LLM error analysis / raw stderr, which can run very long. */}
<div className="min-w-0 flex-1">
+ {/* A fail-closed orchestration lane (#5993) reads as a bare
+ "agent failed" without this: the reason sentence is long
+ and gets clamped, so the two facts that make the fix
+ obvious — WHICH role stopped and WHICH provider it wanted
+ — get a headline of their own above the clamp. */}
+ {task.metadata?.blockedCategory === 'orchestration-lane-unavailable' && task.metadata?.orchestrationLane?.role && (
+ <div className="font-medium text-port-error mb-0.5">
+ {`${task.metadata.orchestrationLane.role} lane unavailable`}
+ {task.metadata.orchestrationLane.requestedProvider
+ ? ` — ${task.metadata.orchestrationLane.requestedProvider}`
+ : ''}
+ {task.metadata.orchestrationLane.requestedModel
+ ? ` / ${task.metadata.orchestrationLane.requestedModel}`
+ : ''}
+ </div>
+ )}
<CollapsibleText
id={`task-blocker-${idScope}-${task.id}`}
text={task.metadata.blocker || task.metadata.blockedReason}
diff --git a/client/src/components/cos/tabs/TaskItem.test.jsx b/client/src/components/cos/tabs/TaskItem.test.jsx
index 0d5db21c56..5edb8e88df 100644
--- a/client/src/components/cos/tabs/TaskItem.test.jsx
+++ b/client/src/components/cos/tabs/TaskItem.test.jsx
@@ -828,3 +828,34 @@ describe('TaskItem editing a pin whose instance has left the registry (#4520)',
expect(api.updateCosTask.mock.calls[0][1].targetInstanceId).toBe('peer-instance-id');
});
});
+
+describe('TaskItem fail-closed orchestration lane (#5993)', () => {
+ const blockedOnLane = {
+ ...task,
+ id: 'orch-lane',
+ status: 'blocked',
+ metadata: {
+ blockedCategory: 'orchestration-lane-unavailable',
+ blockedReason: 'Orchestrated implementer lane stopped: provider "p-cheap" model "m-cheap" is unavailable — not authenticated (no implementer.fallbackProvider is configured).',
+ orchestrationLane: { role: 'implementer', requestedProvider: 'p-cheap', requestedModel: 'm-cheap' },
+ },
+ };
+
+ it('headlines the role and provider so the fix is obvious', () => {
+ render(<TaskItem task={blockedOnLane} onRefresh={vi.fn()} providers={providers} />);
+
+ expect(screen.getByText('implementer lane unavailable — p-cheap / m-cheap')).toBeInTheDocument();
+ });
+
+ it('adds no headline to an ordinary block', () => {
+ const ordinary = {
+ ...blockedOnLane,
+ id: 'ordinary-block',
+ metadata: { blockedReason: 'Max spawn attempts reached', blockedCategory: 'max-spawns' },
+ };
+ render(<TaskItem task={ordinary} onRefresh={vi.fn()} providers={providers} />);
+
+ expect(screen.queryByText(/lane unavailable/)).toBeNull();
+ expect(screen.getByText('Max spawn attempts reached')).toBeInTheDocument();
+ });
+});
diff --git a/server/lib/agentRunEvents.js b/server/lib/agentRunEvents.js
index eeab5a6887..748c8084b0 100644
--- a/server/lib/agentRunEvents.js
+++ b/server/lib/agentRunEvents.js
@@ -99,7 +99,14 @@ export const AGENT_RUN_EVENT_KINDS = Object.freeze([
// `endTime` that no exit ever produced, and nothing would say where it came
// from. Adding this kind is not an envelope shape change — older builds fold
// unknown kinds as no-ops — so AGENT_RUN_EVENT_SCHEMA_VERSION stays at 1.
- 'run.reconciled'
+ 'run.reconciled',
+ // A configured orchestration lane refused to substitute providers and stopped
+ // the run before it spawned (#5993). Its own kind because the durable record
+ // this ledger annotates does NOT exist for it — no run directory is created —
+ // so without this line the only trace of a fail-closed lane is a blocked task,
+ // and "the cheap tier was down" is indistinguishable from every other block.
+ // Carries no runId (there is no run); keyed by agentId via `runEventKey`.
+ 'run.lane-refused'
]);
/** All writeable kinds in the shared machine-local ledger. */
@@ -508,8 +515,9 @@ export function projectRunStates(events) {
* Every non-terminal arm below is guarded by this: the ledger is read in append
* order, but a late-arriving annotation (a stop request that raced the exit, a
* reconnect logged after the process was already reaped) must not resurrect a
- * finished run as `running`. `run.finalized` is the only arm that may set a
- * terminal status, so once set it stays.
+ * finished run as `running`. Only `run.finalized` and `run.lane-refused` may set
+ * a terminal status — the second because a refused lane never spawned a process,
+ * so no finalize will ever arrive for it (#5993) — and once set it stays.
*/
const isTerminal = (state) => state.status === 'completed' || state.status === 'failed';
@@ -534,6 +542,24 @@ const canObserveRunning = (state) => !isTerminal(state) && !state.paused;
function applyKind(state, event) {
const data = event.data ?? {};
switch (event.kind) {
+ case 'run.lane-refused':
+ // Terminal, and the ONLY arm besides `run.finalized` allowed to say so:
+ // a refused lane never spawned a process, so no exit will ever arrive to
+ // finalize it, and leaving the projection `unknown` would read as "still
+ // being figured out" for a run that is definitively over. Guarded like
+ // every other arm so it can never overwrite a real verdict.
+ if (!isTerminal(state)) {
+ state.status = 'failed';
+ state.success = false;
+ }
+ state.endedAt = state.endedAt ?? event.at;
+ state.laneRefused = {
+ role: typeof data.role === 'string' ? data.role : null,
+ requestedProvider: typeof data.requestedProvider === 'string' ? data.requestedProvider : null,
+ requestedModel: typeof data.requestedModel === 'string' ? data.requestedModel : null,
+ reason: typeof data.reason === 'string' ? data.reason : null,
+ };
+ break;
case 'run.spawned':
// Guarded like every other non-terminal arm. A spawn should never follow a
// finalize for the same run, but the ledger is a stream several
@@ -544,6 +570,10 @@ function applyKind(state, event) {
state.startedAt = state.startedAt ?? event.at;
if (typeof data.providerId === 'string') state.providerId = data.providerId;
if (typeof data.model === 'string') state.model = data.model;
+ // The tier this run actually ran as, plus the same-role alternate it fell
+ // to, if any — so a diagnostic can show the split the user configured.
+ if (typeof data.orchestrationRole === 'string') state.orchestrationRole = data.orchestrationRole;
+ if (typeof data.laneSubstitutedFrom === 'string') state.laneSubstitutedFrom = data.laneSubstitutedFrom;
break;
case 'run.runner-recovered':
// A survivor is still running — recovery is an annotation on a live run,
diff --git a/server/lib/agentRunEvents.test.js b/server/lib/agentRunEvents.test.js
index bc9c834dae..1e159d7cb5 100644
--- a/server/lib/agentRunEvents.test.js
+++ b/server/lib/agentRunEvents.test.js
@@ -560,3 +560,62 @@ describe('projectRunStates — run.reconciled (#4540)', () => {
expect(state).toMatchObject({ reconciled: false, reconciledCount: 0 });
});
});
+
+describe('run.lane-refused — fail-closed orchestration lanes (#5993)', () => {
+ it('is terminal even though no run ever spawned', () => {
+ const event = buildRunEvent({
+ kind: 'run.lane-refused',
+ agentId: 'agent-1',
+ taskId: 'task-1',
+ at: AT,
+ data: { role: 'implementer', requestedProvider: 'p-cheap', requestedModel: 'm-cheap', reason: 'not authenticated' },
+ });
+ const [state] = projectRunStates([event]);
+ // Keyed by the agent: the refusal happens before a run id exists.
+ expect(state.id).toBe('agent:agent-1');
+ expect(state.status).toBe('failed');
+ expect(state.success).toBe(false);
+ expect(state.endedAt).toBe(AT);
+ expect(state.laneRefused).toEqual({
+ role: 'implementer',
+ requestedProvider: 'p-cheap',
+ requestedModel: 'm-cheap',
+ reason: 'not authenticated',
+ });
+ });
+
+ it('never talks a run that already reached a verdict back to failed', () => {
+ const finalized = buildRunEvent({
+ kind: 'run.finalized',
+ runId: 'run-1',
+ agentId: 'agent-2',
+ at: AT,
+ data: { exitCode: 0, success: true },
+ });
+ const refused = buildRunEvent({
+ kind: 'run.lane-refused',
+ runId: 'run-1',
+ agentId: 'agent-2',
+ at: '2026-08-18T12:05:00.000Z',
+ data: { role: 'reviewer', reason: 'down' },
+ });
+ const [state] = projectRunStates([finalized, refused]);
+ expect(state.status).toBe('completed');
+ expect(state.success).toBe(true);
+ expect(state.laneRefused.role).toBe('reviewer');
+ });
+
+ it('records the tier a spawned run actually ran as', () => {
+ const spawned = buildRunEvent({
+ kind: 'run.spawned',
+ runId: 'run-2',
+ agentId: 'agent-3',
+ at: AT,
+ data: { providerId: 'p-cheap-2', model: 'alt-m', orchestrationRole: 'architect', laneSubstitutedFrom: 'p-cheap' },
+ });
+ const [state] = projectRunStates([spawned]);
+ expect(state.orchestrationRole).toBe('architect');
+ expect(state.laneSubstitutedFrom).toBe('p-cheap');
+ expect(state.providerId).toBe('p-cheap-2');
+ });
+});
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index 57bfb49354..1314503bef 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -136,6 +136,11 @@ const orchestrationRoleSchema = z.object({
// Per-role reasoning effort. The architect's own rung for its planning pass;
// for the implementer it is the DEFAULT a spec's `REASONING:` line overrides.
effort: z.enum(EFFORT_LEVELS).optional(),
+ // The role's SAME-ROLE alternate (#5993) — the only provider swap a configured
+ // lane accepts. Without one, an unavailable lane stops the run rather than
+ // walking the run-level fallback chain back onto the architect's provider.
+ fallbackProvider: z.string().trim().min(1).max(120).optional(),
+ fallbackModel: z.string().trim().min(1).max(300).optional(),
}).strict();
export const orchestrationProfileSchema = z.object(
diff --git a/server/lib/orchestrationProfile.js b/server/lib/orchestrationProfile.js
index ea43b8dec3..ad50e0d96c 100644
--- a/server/lib/orchestrationProfile.js
+++ b/server/lib/orchestrationProfile.js
@@ -72,17 +72,29 @@ const trimmedString = (value, maxLength) => {
* only a model inherits the run's provider, and a role that pins nothing at all
* normalizes away entirely (null) rather than persisting an empty object that
* would read as a configured-but-blank override.
+ *
+ * `fallbackProvider` / `fallbackModel` are the role's SAME-ROLE alternate
+ * (#5993): the only substitution a configured lane accepts when its provider is
+ * unavailable. It is deliberately per-role rather than the run-level
+ * `metadata.fallbackProvider`, because the run-level chain is what silently
+ * collapses a cheap cross-vendor lane back onto the architect's provider. A
+ * fallback pinned with no primary `provider` is dropped — there is nothing for
+ * it to be an alternate TO, and keeping it would read as a second pin.
*/
function normalizeRoleAssignment(raw) {
if (!isPlainObject(raw)) return null;
const provider = trimmedString(raw.provider, MAX_PROVIDER_ID_LENGTH);
const model = trimmedString(raw.model, MAX_MODEL_ID_LENGTH);
const effort = EFFORT_LEVELS.includes(raw.effort) ? raw.effort : null;
+ const fallbackProvider = provider ? trimmedString(raw.fallbackProvider, MAX_PROVIDER_ID_LENGTH) : null;
+ const fallbackModel = fallbackProvider ? trimmedString(raw.fallbackModel, MAX_MODEL_ID_LENGTH) : null;
if (!provider && !model && !effort) return null;
return Object.freeze({
...(provider ? { provider } : {}),
...(model ? { model } : {}),
...(effort ? { effort } : {}),
+ ...(fallbackProvider ? { fallbackProvider } : {}),
+ ...(fallbackModel ? { fallbackModel } : {}),
});
}
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 0abdd60282..fa268ddd66 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -411,23 +411,50 @@ async function runAgentSpawn(task) {
// `in_progress` record clobbered to `blocked` — which outranks `in_progress`
// in the claim-aware merge. Transient failures fall through, skip the block,
// and stay pending to retry.
+ // A configured orchestration lane that refused to substitute providers
+ // (#5993) is its OWN terminal outcome, not a generic provider failure: the
+ // fix is specific to the role ("authenticate that CLI", "pick another model
+ // for the implementer", "give it a fallbackProvider"), and a run that
+ // stopped for it must never be reported as anything else. The structured
+ // detail rides along on the task metadata, the `agent:error` event, and the
+ // ledger below so each surface names the role and provider itself.
+ const lane = resolution.orchestrationLane || null;
if (resolution.permanent) {
await updateTask(task.id, {
status: 'blocked',
metadata: {
...task.metadata,
blockedReason: resolution.error,
- blockedCategory: 'provider-config',
+ blockedCategory: lane ? 'orchestration-lane-unavailable' : 'provider-config',
+ ...(lane ? { orchestrationLane: lane } : {}),
blockedAt: new Date().toISOString()
}
}, task.taskType || 'user').catch(() => {});
}
+ // Recorded BEFORE cleanup so the ledger holds the reason even if cleanup
+ // throws. No runId exists — the run never spawned — so this is keyed by the
+ // agent id, which is exactly the `agent:<id>` fallback `runEventKey` has.
+ if (lane) {
+ await appendRunEvent({
+ kind: 'run.lane-refused',
+ agentId,
+ taskId: task.id,
+ eventId: `lane-refused:${agentId}:${lane.role}`,
+ data: {
+ role: lane.role,
+ requestedProvider: lane.requestedProvider,
+ requestedModel: lane.requestedModel,
+ reason: lane.reason,
+ },
+ });
+ }
await cleanupOnError(resolution.error);
cosEvents.emit('agent:error', {
taskId: task.id,
error: resolution.error,
...(resolution.providerId && { providerId: resolution.providerId }),
...(resolution.providerStatus && { providerStatus: resolution.providerStatus }),
+ ...(lane && { orchestrationLane: lane }),
});
return null;
}
@@ -720,7 +747,8 @@ async function runAgentSpawn(task) {
model: selectedModel,
provider,
workspacePath,
- appName: resolvedAppName
+ appName: resolvedAppName,
+ orchestrationLane: resolution.orchestrationLane ?? null
});
const executionMode = !spawnHeadless ? (dispatchUseRunner ? 'runner-tui' : 'tui') : dispatchUseRunner ? 'runner' : 'direct';
diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.js
index d6c3b4f77e..74393abf20 100644
--- a/server/services/agentLifecycle.test.js
+++ b/server/services/agentLifecycle.test.js
@@ -612,19 +612,46 @@ describe('runAgentSpawn source — app-review marker release (issue #989)', () =
// re-dispatch. Without a block, the task stays pending and silently re-fails
// forever. Pin that the permanent branch flips the task to blocked BEFORE the
// lease is released, so a federated peer can't be clobbered.
+// Wide enough to cover the whole `if (!resolution.ok)` arm — its comments carry
+// the reasoning for the ordering these tests pin, so the window has to include
+// them rather than being trimmed to the statements.
+const RESOLUTION_FAILURE_WINDOW = 4000;
+
describe('runAgentSpawn source — permanent provider-config failure blocks the task', () => {
it('the resolution-failure path blocks a permanent failure with a provider-config reason', () => {
const idx = AGENT_LIFECYCLE_SRC.indexOf('const resolution = await resolveAgentProviderAndModel(task)');
expect(idx, 'resolution call must exist').toBeGreaterThan(-1);
- const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + 2000);
+ const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + RESOLUTION_FAILURE_WINDOW);
expect(body, 'gates the block on resolution.permanent').toMatch(/if\s*\(resolution\.permanent\)/);
expect(body, 'flips the task to blocked').toMatch(/status:\s*'blocked'/);
- expect(body, 'tags the block category').toMatch(/blockedCategory:\s*'provider-config'/);
+ expect(body, 'tags the block category').toMatch(/blockedCategory:[^\n]*'provider-config'/);
+ });
+
+ // A configured orchestration lane that refuses to substitute providers (#5993)
+ // is a DISTINCT terminal outcome: same block, its own category and structured
+ // detail, so the client can name the role and provider instead of showing a
+ // generic provider-config failure.
+ it('tags a refused orchestration lane with its own category and detail', () => {
+ const idx = AGENT_LIFECYCLE_SRC.indexOf('const resolution = await resolveAgentProviderAndModel(task)');
+ const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + RESOLUTION_FAILURE_WINDOW);
+ expect(body, 'reads the structured lane detail').toMatch(/const lane = resolution\.orchestrationLane/);
+ expect(body, 'has its own block category').toMatch(/'orchestration-lane-unavailable'/);
+ expect(body, 'carries the detail onto the task').toMatch(/orchestrationLane: lane/);
+ expect(body, 'records the refusal in the ledger').toMatch(/kind: 'run\.lane-refused'/);
+ });
+
+ it('records the lane refusal BEFORE cleanup, so the reason survives a failing cleanup', () => {
+ const idx = AGENT_LIFECYCLE_SRC.indexOf('const resolution = await resolveAgentProviderAndModel(task)');
+ const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + RESOLUTION_FAILURE_WINDOW);
+ const ledgerIdx = body.indexOf("kind: 'run.lane-refused'");
+ const cleanupIdx = body.indexOf('await cleanupOnError(resolution.error)');
+ expect(ledgerIdx, 'ledger append must exist').toBeGreaterThan(-1);
+ expect(ledgerIdx, 'ledger append must precede cleanup').toBeLessThan(cleanupIdx);
});
it('blocks BEFORE releasing the lease so a federated peer cannot be clobbered', () => {
const idx = AGENT_LIFECYCLE_SRC.indexOf('const resolution = await resolveAgentProviderAndModel(task)');
- const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + 2000);
+ const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + RESOLUTION_FAILURE_WINDOW);
const permanentIdx = body.indexOf('if (resolution.permanent)');
const cleanupIdx = body.indexOf('await cleanupOnError(resolution.error)');
expect(permanentIdx, 'permanent block must exist').toBeGreaterThan(-1);
diff --git a/server/services/agentProviderResolution.js b/server/services/agentProviderResolution.js
index 61f86d46cd..cecb11d4e7 100644
--- a/server/services/agentProviderResolution.js
+++ b/server/services/agentProviderResolution.js
@@ -112,6 +112,36 @@ async function resolvePublicReviewAgentProvider(task, posture) {
return { ok: true, provider, selectedModel, modelSelection };
}
+/**
+ * A configured orchestration lane refused to substitute providers (#5993).
+ *
+ * Shaped so every consumer reads one structure: the caller blocks the task with
+ * `error` as its reason, the `agent:error` event and the run ledger carry
+ * `orchestrationLane` verbatim, and the client names the role and provider from
+ * the same fields rather than re-parsing the sentence.
+ *
+ * Always PERMANENT. That is the point of a fail-closed lane: a rate-limited
+ * cheap provider that would recover in an hour is still a lane the user has to
+ * decide about, and quietly re-dispatching until it comes back is the silent
+ * behavior this replaces. Unblocking is one click once the CLI is authenticated
+ * or a `fallbackProvider` is configured; a lane that retried itself would spend
+ * the architect's budget with nobody watching.
+ */
+function laneUnavailable({ role, requestedProvider, requestedModel, reason }) {
+ const requested = requestedProvider
+ ? `its provider "${requestedProvider}"${requestedModel ? ` (model "${requestedModel}")` : ''} is unavailable`
+ : `its pinned model "${requestedModel}" has nothing to run on`;
+ return {
+ ok: false,
+ permanent: true,
+ error: `Orchestrated ${role} lane stopped — ${requested}: ${reason}. `
+ + `PortOS will not substitute another provider for a configured lane; authenticate or repair that provider, `
+ + `pick another model for the ${role} role, or configure ${role}.fallbackProvider.`,
+ providerId: requestedProvider || undefined,
+ orchestrationLane: { role, requestedProvider: requestedProvider || null, requestedModel: requestedModel || null, reason },
+ };
+}
+
async function resolveOrdinaryProviderAndModel(task) {
// A task can pin a specific provider via metadata.provider (e.g. a CoS job's
// per-job AI override). Resolve it BEFORE the active-provider availability
@@ -126,19 +156,54 @@ async function resolveOrdinaryProviderAndModel(task) {
// (availability, fallback swap, the model-pin invalidation a swap triggers)
// rather than growing a second, subtly-different resolution path. Null on a
// `direct` task, so the metadata pin stays authoritative as before.
- const userProviderId = roleAssignment(task, PRIMARY_ORCHESTRATION_ROLE)?.provider || task.metadata?.provider;
+ //
+ // …with ONE exception, and it is the whole of #5993. An orchestrated run's
+ // roles exist BECAUSE they are different providers: the implementer lane is
+ // cheap and cross-vendor on purpose. Swapping a configured lane onto whatever
+ // is healthy spends the architect's premium tokens on mechanical editing —
+ // the exact cost orchestration was turned on to avoid — and collapses the
+ // vendor split with nobody told. So when the role carries an assignment at
+ // all, this lane is FAIL-CLOSED: the only substitution it accepts is the
+ // role's own `fallbackProvider`, and anything else stops the run loudly.
+ // `direct`-mode runs keep the pin → active → fallback chain untouched
+ // (`roleAssignment` returns null for every role on one).
+ const laneRole = PRIMARY_ORCHESTRATION_ROLE;
+ const lane = roleAssignment(task, laneRole);
+ const userProviderId = lane?.provider || task.metadata?.provider;
let userProviderMissing = false;
if (userProviderId) {
const userProvider = await getProviderById(userProviderId);
if (userProvider) {
emitLog('info', `Using user-specified provider: ${userProviderId}`, { taskId: task.id });
provider = userProvider;
+ } else if (lane?.provider) {
+ // A configured lane whose provider record does not exist is a config error
+ // that re-fails identically forever — never "use the active provider".
+ return laneUnavailable({
+ role: laneRole,
+ requestedProvider: userProviderId,
+ requestedModel: lane.model || null,
+ reason: 'no provider with that id is configured on this install',
+ });
} else {
userProviderMissing = true;
emitLog('warn', `User-specified provider "${userProviderId}" not found, using active provider`, { taskId: task.id });
}
}
if (!provider) provider = await getActiveProvider();
+ // A lane that pins only a MODEL inherits the active provider — so when there
+ // is no active provider it is the LANE that has nowhere to run, and it says so
+ // in the lane's own shape. Falling through to the generic
+ // "No active AI provider configured" below would lose the role, leaving the
+ // client with nothing to name.
+ if (lane && !provider) {
+ return laneUnavailable({
+ role: laneRole,
+ requestedProvider: null,
+ requestedModel: lane.model || null,
+ reason: 'no active AI provider is configured for it to inherit',
+ });
+ }
if (!provider) {
return { ok: false, error: 'No active AI provider configured' };
@@ -163,6 +228,9 @@ async function resolveOrdinaryProviderAndModel(task) {
// Model" pin — it overrides the usual per-task model selection so the
// user's chosen fallback provider+model pair is honored on agent runs.
let fallbackModelPin = null;
+ // The one substitution a configured lane DID accept, recorded so the run
+ // ledger can show the tier really ran where the user said it could (#5993).
+ let laneSubstitution = null;
const providerAvailable = isProviderAvailable(provider.id);
if (!providerAvailable) {
const status = getProviderStatus(provider.id);
@@ -172,36 +240,68 @@ async function resolveOrdinaryProviderAndModel(task) {
reason: status.reason
});
- // Try to get a fallback provider (check task-level, then provider-level, then system default).
- // getFallbackProvider indexes its providers arg by id, so pass a map — NOT the
- // { activeProvider, providers: [...] } shape getAllProviders() returns (mirrors promptRunner.js).
- const { providers: providerList = [] } = await getAllProviders();
- const providersMap = Object.fromEntries(providerList.map((p) => [p.id, p]));
- const taskFallbackId = task.metadata?.fallbackProvider;
- const taskFallbackModel = task.metadata?.fallbackModel;
- const fallbackResult = await getFallbackProvider(provider.id, providersMap, taskFallbackId, taskFallbackModel);
-
- if (fallbackResult) {
- emitLog('info', `Using fallback provider: ${fallbackResult.provider.id} (source: ${fallbackResult.source})`, {
+ // A configured lane never walks the GENERIC chain (#5993). Its only accepted
+ // substitution is the same-role alternate the user named on the role itself,
+ // and that alternate must be a real, currently-available provider — an
+ // alternate that is itself down is not a lane, it is the same silent
+ // collapse one hop later.
+ if (lane) {
+ const alternateId = lane.fallbackProvider;
+ const alternate = alternateId ? await getProviderById(alternateId) : null;
+ if (!alternate || !isProviderAvailable(alternate.id)) {
+ const why = !alternateId
+ ? `${status.message} (no ${laneRole}.fallbackProvider is configured)`
+ : !alternate
+ ? `${status.message}, and its ${laneRole}.fallbackProvider "${alternateId}" is not a configured provider`
+ : `${status.message}, and its ${laneRole}.fallbackProvider "${alternateId}" is also unavailable (${getProviderStatus(alternate.id).message})`;
+ return laneUnavailable({
+ role: laneRole,
+ requestedProvider: provider.id,
+ requestedModel: lane.model || null,
+ reason: why,
+ });
+ }
+ emitLog('info', `Orchestrated ${laneRole} lane using its same-role alternate ${alternate.id}`, {
taskId: task.id,
primaryProvider: provider.id,
- fallbackProvider: fallbackResult.provider.id,
- fallbackSource: fallbackResult.source
+ fallbackProvider: alternate.id,
+ fallbackSource: `orchestration-${laneRole}`,
});
- provider = fallbackResult.provider;
- fallbackModelPin = fallbackResult.model || null;
+ laneSubstitution = { role: laneRole, from: provider.id, to: alternate.id, reason: status.message };
+ provider = alternate;
+ fallbackModelPin = lane.fallbackModel || null;
} else {
- const errorMsg = `Provider ${provider.id} unavailable (${status.message}) and no fallback available`;
- // TRANSIENT, never permanent: a null fallback here can mean a configured
- // CLI/TUI fallback is merely momentarily down (getFallbackProvider skips
- // unavailable candidates), so blocking would strand a task that recovers
- // when that fallback returns. Permanence is decided by PROVIDER TYPE where we
- // can actually inspect it — the harness check below, reached once the
- // provider is available again — not inferred from a transient unavailable +
- // null-fallback combination. A down api provider with no viable path retries
- // cheaply (it fails fast here, spawning no agent) and self-heals to a
- // permanent block the moment it becomes reachable.
- return { ok: false, error: errorMsg, providerId: provider.id, providerStatus: status };
+ // Try to get a fallback provider (check task-level, then provider-level, then system default).
+ // getFallbackProvider indexes its providers arg by id, so pass a map — NOT the
+ // { activeProvider, providers: [...] } shape getAllProviders() returns (mirrors promptRunner.js).
+ const { providers: providerList = [] } = await getAllProviders();
+ const providersMap = Object.fromEntries(providerList.map((p) => [p.id, p]));
+ const taskFallbackId = task.metadata?.fallbackProvider;
+ const taskFallbackModel = task.metadata?.fallbackModel;
+ const fallbackResult = await getFallbackProvider(provider.id, providersMap, taskFallbackId, taskFallbackModel);
+
+ if (fallbackResult) {
+ emitLog('info', `Using fallback provider: ${fallbackResult.provider.id} (source: ${fallbackResult.source})`, {
+ taskId: task.id,
+ primaryProvider: provider.id,
+ fallbackProvider: fallbackResult.provider.id,
+ fallbackSource: fallbackResult.source
+ });
+ provider = fallbackResult.provider;
+ fallbackModelPin = fallbackResult.model || null;
+ } else {
+ const errorMsg = `Provider ${provider.id} unavailable (${status.message}) and no fallback available`;
+ // TRANSIENT, never permanent: a null fallback here can mean a configured
+ // CLI/TUI fallback is merely momentarily down (getFallbackProvider skips
+ // unavailable candidates), so blocking would strand a task that recovers
+ // when that fallback returns. Permanence is decided by PROVIDER TYPE where we
+ // can actually inspect it — the harness check below, reached once the
+ // provider is available again — not inferred from a transient unavailable +
+ // null-fallback combination. A down api provider with no viable path retries
+ // cheaply (it fails fast here, spawning no agent) and self-heals to a
+ // permanent block the moment it becomes reachable.
+ return { ok: false, error: errorMsg, providerId: provider.id, providerStatus: status };
+ }
}
}
@@ -317,5 +417,23 @@ async function resolveOrdinaryProviderAndModel(task) {
...(modelSelection.learningReason && { learningReason: modelSelection.learningReason })
});
- return { ok: true, provider, selectedModel, modelSelection };
+ return {
+ ok: true,
+ provider,
+ selectedModel,
+ modelSelection,
+ // What the run ledger records so `/cos/runs` can show the tier split really
+ // happened (#5993): the role this run was dispatched as, the provider it
+ // ACTUALLY ran on, and the one substitution — if any — the lane accepted.
+ // Absent on a `direct`-mode run, which has no roles to account for.
+ ...(lane ? {
+ orchestrationLane: {
+ role: laneRole,
+ requestedProvider: lane.provider || directProviderId,
+ providerId: provider.id,
+ model: selectedModel,
+ ...(laneSubstitution ? { substitution: laneSubstitution } : {}),
+ },
+ } : {}),
+ };
}
diff --git a/server/services/agentProviderResolution.test.js b/server/services/agentProviderResolution.test.js
index a2f35fff61..2e24dc8449 100644
--- a/server/services/agentProviderResolution.test.js
+++ b/server/services/agentProviderResolution.test.js
@@ -513,3 +513,147 @@ describe('orchestration profiles (#5992)', () => {
expect(result.provider.id).toBe('p-pinned');
});
});
+
+/**
+ * Fail-closed orchestration lanes (#5993).
+ *
+ * The regression these exist for: a cheap cross-vendor implementer/architect
+ * lane silently becoming the expensive same-vendor lane. Every case below is a
+ * point where the generic pin → active → fallback chain WOULD have substituted
+ * a provider, and asserts it refuses instead.
+ */
+describe('resolveAgentProviderAndModel — fail-closed orchestration lanes', () => {
+ const orchestrated = (architect, extraMetadata = {}) => ({
+ id: 'task-orch',
+ metadata: {
+ orchestrationMode: 'orchestrated',
+ orchestrationProfile: { architect },
+ ...extraMetadata,
+ },
+ });
+
+ it('refuses to fall back to the active provider when the lane provider is not configured', async () => {
+ getProviderById.mockResolvedValue(null);
+ getActiveProvider.mockResolvedValue({ id: 'p-active', type: 'cli', defaultModel: 'm-active' });
+
+ const r = await resolveAgentProviderAndModel(orchestrated({ provider: 'p-cheap', model: 'm-cheap' }));
+
+ expect(r.ok).toBe(false);
+ expect(r.permanent).toBe(true);
+ expect(r.orchestrationLane).toEqual({
+ role: 'architect',
+ requestedProvider: 'p-cheap',
+ requestedModel: 'm-cheap',
+ reason: 'no provider with that id is configured on this install',
+ });
+ expect(r.error).toContain('architect');
+ expect(r.error).toContain('p-cheap');
+ expect(getActiveProvider).not.toHaveBeenCalled();
+ });
+
+ it('refuses the generic fallback chain when a lane provider is unavailable', async () => {
+ getProviderById.mockResolvedValue({ id: 'p-cheap', type: 'cli', defaultModel: 'm-cheap' });
+ isProviderAvailable.mockReturnValue(false);
+ getProviderStatus.mockReturnValue({ message: 'not authenticated', reason: 'auth' });
+
+ const r = await resolveAgentProviderAndModel(
+ // A run-level fallback is configured and must still be ignored: it is the
+ // exact silent collapse onto the architect's provider this closes.
+ orchestrated({ provider: 'p-cheap' }, { fallbackProvider: 'p-premium' }),
+ );
+
+ expect(r.ok).toBe(false);
+ expect(r.permanent).toBe(true);
+ expect(r.orchestrationLane.reason).toContain('not authenticated');
+ expect(r.orchestrationLane.reason).toContain('no architect.fallbackProvider is configured');
+ expect(getFallbackProvider).not.toHaveBeenCalled();
+ });
+
+ it('honors the same-role alternate and records the substitution', async () => {
+ const cheap = { id: 'p-cheap', type: 'cli', defaultModel: 'm-cheap' };
+ const alternate = { id: 'p-cheap-2', type: 'cli', models: ['alt-m'], defaultModel: 'alt-default' };
+ getProviderById.mockImplementation(async (id) => (id === 'p-cheap' ? cheap : alternate));
+ isProviderAvailable.mockImplementation((id) => id === 'p-cheap-2');
+ getProviderStatus.mockReturnValue({ message: 'rate limited', reason: 'limit' });
+
+ const r = await resolveAgentProviderAndModel(orchestrated({
+ provider: 'p-cheap',
+ fallbackProvider: 'p-cheap-2',
+ fallbackModel: 'alt-m',
+ }));
+
+ expect(r.ok).toBe(true);
+ expect(r.provider).toBe(alternate);
+ expect(r.selectedModel).toBe('alt-m');
+ expect(r.orchestrationLane).toEqual({
+ role: 'architect',
+ requestedProvider: 'p-cheap',
+ providerId: 'p-cheap-2',
+ model: 'alt-m',
+ substitution: { role: 'architect', from: 'p-cheap', to: 'p-cheap-2', reason: 'rate limited' },
+ });
+ expect(getFallbackProvider).not.toHaveBeenCalled();
+ });
+
+ it('refuses when the same-role alternate is itself unavailable', async () => {
+ getProviderById.mockImplementation(async (id) => ({ id, type: 'cli', defaultModel: `m-${id}` }));
+ isProviderAvailable.mockReturnValue(false);
+ getProviderStatus.mockImplementation((id) => ({ message: `${id} down`, reason: 'down' }));
+
+ const r = await resolveAgentProviderAndModel(orchestrated({
+ provider: 'p-cheap',
+ fallbackProvider: 'p-cheap-2',
+ }));
+
+ expect(r.ok).toBe(false);
+ expect(r.orchestrationLane.reason).toContain('p-cheap-2');
+ expect(r.orchestrationLane.reason).toContain('also unavailable');
+ });
+
+ it('refuses a model-only lane rather than inheriting a swapped provider', async () => {
+ getActiveProvider.mockResolvedValue(null);
+
+ const r = await resolveAgentProviderAndModel(orchestrated({ model: 'm-cheap' }));
+
+ expect(r.ok).toBe(false);
+ expect(r.permanent).toBe(true);
+ expect(r.orchestrationLane).toEqual({
+ role: 'architect',
+ requestedProvider: null,
+ requestedModel: 'm-cheap',
+ reason: 'no active AI provider is configured for it to inherit',
+ });
+ });
+
+ it('reports the lane a healthy orchestrated run actually ran on', async () => {
+ const cheap = { id: 'p-cheap', type: 'cli', models: ['m-default'] };
+ getProviderById.mockResolvedValue(cheap);
+
+ const r = await resolveAgentProviderAndModel(orchestrated({ provider: 'p-cheap' }));
+
+ expect(r.ok).toBe(true);
+ expect(r.orchestrationLane).toEqual({
+ role: 'architect',
+ requestedProvider: 'p-cheap',
+ providerId: 'p-cheap',
+ model: 'm-default',
+ });
+ });
+
+ it('leaves a direct-mode run on the generic fallback chain', async () => {
+ const primary = { id: 'p1', type: 'cli' };
+ const fallback = { id: 'p2', type: 'cli', models: ['m-fb'] };
+ getActiveProvider.mockResolvedValue(primary);
+ isProviderAvailable.mockReturnValue(false);
+ getProviderStatus.mockReturnValue({ message: 'usage-limit', reason: 'limit' });
+ getAllProviders.mockResolvedValue({ providers: [primary, fallback] });
+ getFallbackProvider.mockResolvedValue({ provider: fallback, source: 'system', model: 'm-fb' });
+
+ const r = await resolveAgentProviderAndModel({ id: 'task-direct-2', metadata: {} });
+
+ expect(r.ok).toBe(true);
+ expect(r.provider).toBe(fallback);
+ expect(r.orchestrationLane).toBeUndefined();
+ expect(getFallbackProvider).toHaveBeenCalled();
+ });
+});
diff --git a/server/services/agentRunTracking.js b/server/services/agentRunTracking.js
index e40e0143f3..88a02325e6 100644
--- a/server/services/agentRunTracking.js
+++ b/server/services/agentRunTracking.js
@@ -25,8 +25,12 @@ const RUNS_DIR = PATHS.runs;
* @param {{ id: string, name: string, defaultModel?: string }} options.provider
* @param {string} options.workspacePath
* @param {string} [options.appName] - Defaults to 'portos'.
+ * @param {{ role: string, requestedProvider?: string, providerId: string, model?: string,
+ * substitution?: { role: string, from: string, to: string, reason?: string } }}
+ * [options.orchestrationLane] - The tier this run was dispatched as, when the
+ * task runs under an orchestration profile (#5993). Absent for `direct` runs.
*/
-export async function createAgentRun({ agentId, task, model, provider, workspacePath, appName }) {
+export async function createAgentRun({ agentId, task, model, provider, workspacePath, appName, orchestrationLane = null }) {
const runId = uuidv4();
const runDir = join(RUNS_DIR, runId);
@@ -49,6 +53,7 @@ export async function createAgentRun({ agentId, task, model, provider, workspace
// Full prompt size (chars) for input-token estimation on completion —
// `prompt` above is truncated for display.
promptLength: (task.description || '').length,
+ ...(orchestrationLane ? { orchestrationLane } : {}),
startTime: new Date().toISOString(),
endTime: null,
duration: null,
@@ -83,7 +88,12 @@ export async function createAgentRun({ agentId, task, model, provider, workspace
model: metadata.model,
workspacePath,
workspaceName: metadata.workspaceName,
- promptChars: metadata.promptLength
+ promptChars: metadata.promptLength,
+ // Orchestration accounting (#5993): the role, and — when the lane took its
+ // configured same-role alternate — the provider it was configured for. Both
+ // omitted on a `direct` run so the event shape is unchanged there.
+ ...(orchestrationLane?.role ? { orchestrationRole: orchestrationLane.role } : {}),
+ ...(orchestrationLane?.substitution?.from ? { laneSubstitutedFrom: orchestrationLane.substitution.from } : {}),
}
});
diff --git a/server/services/promptSections/orchestrationDoctrine.js b/server/services/promptSections/orchestrationDoctrine.js
index ecb4b163ca..737f7a4e67 100644
--- a/server/services/promptSections/orchestrationDoctrine.js
+++ b/server/services/promptSections/orchestrationDoctrine.js
@@ -31,7 +31,13 @@ function roleLine(task, role) {
assignment?.effort ? `default reasoning \`${assignment.effort}\`` : null,
].filter(Boolean);
const target = pins.length ? pins.join(', ') : 'this run’s own provider and model';
- return `- **${role}** — ${ROLE_DUTIES[role]}. Runs on ${target}.`;
+ // The lane's ONE permitted substitution (#5993). Named here because the
+ // architect otherwise has no way to know a lane is fail-closed, and would plan
+ // around a fallback that does not exist.
+ const alternate = assignment?.fallbackProvider
+ ? ` If it is unavailable, the lane may use \`${assignment.fallbackProvider}\`${assignment.fallbackModel ? ` with model \`${assignment.fallbackModel}\`` : ''} — and nothing else.`
+ : (pins.length ? ' If it is unavailable, the run STOPS — no other provider is substituted for this lane.' : '');
+ return `- **${role}** — ${ROLE_DUTIES[role]}. Runs on ${target}.${alternate}`;
}
/**
diff --git a/server/services/promptSections/orchestrationDoctrine.test.js b/server/services/promptSections/orchestrationDoctrine.test.js
index 5fdbab2462..1c2b892450 100644
--- a/server/services/promptSections/orchestrationDoctrine.test.js
+++ b/server/services/promptSections/orchestrationDoctrine.test.js
@@ -46,3 +46,28 @@ describe('buildOrchestrationDoctrineSection', () => {
expect(section).toMatch(/never rounded/);
});
});
+
+describe('fail-closed lane doctrine (#5993)', () => {
+ const orchestrated = (profile) => ({
+ metadata: { orchestrationMode: 'orchestrated', orchestrationProfile: profile },
+ });
+
+ it('tells the architect a pinned lane has no substitute', () => {
+ const section = buildOrchestrationDoctrineSection(orchestrated({ implementer: { provider: 'p-cheap' } }));
+ expect(section).toContain('the run STOPS — no other provider is substituted for this lane');
+ });
+
+ it('names the one alternate a lane may use', () => {
+ const section = buildOrchestrationDoctrineSection(orchestrated({
+ implementer: { provider: 'p-cheap', fallbackProvider: 'p-cheap-2', fallbackModel: 'm-cheap-2' },
+ }));
+ expect(section).toContain('the lane may use `p-cheap-2` with model `m-cheap-2` — and nothing else');
+ expect(section).not.toContain('the run STOPS — no other provider is substituted for this lane.\n- **implementer**');
+ });
+
+ it('says nothing about substitution for a role that pins nothing', () => {
+ const section = buildOrchestrationDoctrineSection(orchestrated({ architect: { provider: 'p1' } }));
+ expect(section).toContain('- **reviewer** —');
+ expect(section.split('\n').find(l => l.startsWith('- **reviewer**'))).not.toContain('STOPS');
+ });
+});