Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor(agent-spawn): split preparation and dispatch (#8175)
[._.]/ Adam Eivydecc00140f95
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex e0e4a69549..999e36cb2a 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -30,69 +30,29 @@ import { join } from 'path';import { readFile } from 'fs/promises';import { existsSync } from 'fs';import { cosEvents, emitLog } from './cosEvents.js';-// The DEFINING module, not a barrel (#3450) — see the note in-// `agentManagement.js`. This module owns the `spawnAgentForTask` transition the-// facade re-exports, so it is permanently inside the facade's closure and must-// name `completeAgent`'s home directly.-import { registerAgent, updateAgent, completeAgent } from './cosAgentLifecycle.js';-// `getAgentRecord`, NOT `getAgent`: the record without its transcript. Both-// consumers below want only `.status` / `.metadata`, and `getAgent` hydrates a-// completed or paused record by reading the whole output.txt, line-splitting it-// into per-line objects, and running `repairCodexTaskSummary` (which can write-// metadata.json back). That is megabytes and a disk write on a long TUI run —-// paid to read one string. Same trap documented at agentWorktreeCleanup.js:562.-import { getConfig, updateTask, getTaskById, getAgentRecord } from './cos.js';+import { updateAgent, completeAgent } from './cosAgentLifecycle.js';+import { getTaskById, updateTask, getAgentRecord } from './cos.js';import { spawnAgentViaRunner, getRunnerHealth, classifyRunnerSpawnFailure, RUNNER_SPAWN_REFUSED, RUNNER_SPAWN_AMBIGUOUS } from './cosRunnerClient.js';-import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';import { isInternalTaskId } from '../lib/taskParser.js';-import { isRetryHeld } from '../lib/taskRetryHold.js';-import { PROVIDER_CONFIG_BLOCKED_CATEGORY } from '../lib/taskBlockCategories.js';-import { ensureDir, PATHS, sleep, tryReadFile, writeFileGuarded } from '../lib/fileUtils.js';-import { createToolExecution, startExecution, completeExecution, errorExecution } from './toolStateMachine.js';-import { determineLane, acquire, release } from './executionLanes.js';+import { PATHS, sleep, tryReadFile } from '../lib/fileUtils.js';+import { completeExecution, errorExecution } from './toolStateMachine.js';+import { release } from './executionLanes.js';import { analyzeAgentFailure } from './agentErrorAnalysis.js';-import { createAgentRun } from './agentRunTracking.js';import { appendRunEvent } from './agentRunEventLog.js';import { committedDuringRun, toEpochMs } from '../lib/gitCommitProbe.js';-import { repoIssueUrlBase, resolveAppForgeTarget, resolveRepoForgeTarget } from '../lib/workTracker.js';-import { capturePrimaryCheckoutState } from '../lib/primaryCheckoutGuard.js';-import { buildAgentPrompt, getAppWorkspace, isClaimFlowTask, promptOpensOwnPr } from './agentPromptBuilder.js';-import { isOllamaClaudeProvider, isClaudeCommand, providerSuppliesGithubToken } from '../lib/providerModels.js';+import { providerSuppliesGithubToken } from '../lib/providerModels.js';import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';import { prClaimWasVerified } from '../lib/prDisposition.js';import { composeProviderEnv } from '../lib/cliChildEnv.js';import { cliProviderAuthDescriptor } from '../lib/processEnv.js';-import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';-import { buildCliSpawnConfig, isClaudeCliProvider, isTuiProvider, getClaudeSettingsEnv, spawnDirectly } from './agentCliSpawning.js';-import { dropUnsupportedOllamaThinking } from './ollamaAgentContext.js';-import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';-import { publicReviewPostureForProfile, supportsTuiPublicReviewActionsProvider, PUBLIC_REVIEW_NO_TOOL_POSTURE } from '../lib/providerVendors.js';-import { checkPublicReviewSpawnPreconditions } from '../lib/publicReviewSpawnGate.js';-import { buildAgentRegistration, resolveExecutionMode } from '../lib/agentRegistrationRecord.js';-import { hasCredentialBootstrap } from '../lib/credentialBootstrap.js';-import { applyTaskGenerationOverrides } from '../lib/taskGenerationOverrides.js';-import { PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE } from '../lib/agentExecutionProfiles.js';-import { formatPublicReviewInputPrompt } from '../lib/modelAbuseGuard.js';-import { validatePublicReviewModel } from './modelAbuseGuard.js';-import { loadPublicReviewSpawnInput } from './publicReviewSpawnInput.js';-import { releaseAppReviewMarker } from './appActivity.js';-import { ensureInstanceId } from './instanceIdentity.js';-import { isClaimableBy, buildClaim, buildRelease, getClaimOwner, getTargetInstance, isTargetedElsewhere } from './cosTaskClaim.js';+import { isClaudeCliProvider, getClaudeSettingsEnv } from './agentCliSpawning.js';import { resolveForgeTokenEnv } from './forgeAuth.js';import { resolveAgentApiEnv } from './agentApiAuth.js';-import { runnerAgents, pausedAgents, consumePausedAgentExit, spawningTasks, useRunner, isTruthyMeta } from './agentState.js';+import { runnerAgents, pausedAgents, consumePausedAgentExit, spawningTasks, isTruthyMeta } from './agentState.js';import { withSpawnDedupGuard, withMapEntryCleanup, withUpdateInProgressGuard, SPAWN_DEDUP_SKIP, SPAWN_UPDATE_SKIP } from './agentGuards.js';import { isUpdateInProgress } from './updateChecker.js';-import { v4 as uuidv4 } from '../lib/uuid.js';--// Extracted helpers — these carve the two giant orchestrators-// (spawnAgentForTask / handleAgentCompletion) into focused, testable modules.-// Imported for use here only; the pass-through re-exports that used to sit-// below them were retired with the `subAgentSpawner.js` barrel (#3450).-import { resolveAgentProviderAndModel } from './agentProviderResolution.js';-import { cloudSwarmThreadCapacity, localEndpointOfProvider, providerBaseUrl } from './cosLocalEndpointSlots.js';-import { describeLocalPromptBudget, planLocalPromptBudget } from '../lib/localPromptBudget.js';-import { prepareAgentWorkspace } from './agentWorkspacePrep.js';+import { createAgentSpawnContext, prepareAgentSpawn } from './agentSpawnPreparation.js';+import { dispatchAgentRun } from './agentSpawnDispatch.js';import { releaseRetryHold } from './agentWorktreeCleanup.js';import { runAgentCompletionCleanup, removeCompletionSentinel } from './agentCompletionCleanup.js';import { dispatchRecoveredTaskOutputHook, finalizeAgent, releaseAgentLane, stampLiExecutionVerdict } from './agentFinalization.js';@@ -144,786 +104,28 @@ export async function spawnAgentForTask(task) {* early `return null` and any throw is covered by the wrapper's release.*/async function runAgentSpawn(task) {- // Normalize taskType once, up front (issue #2633). Direct `task:ready` emits —- // the Creative Director bridge, `dequeueNextTask`, and `spawnPriority0OnDemand` —- // publish task records without a `taskType`. Every claim/in_progress `updateTask`- // below falls back to `task.taskType || 'user'`, so an internal-file (`sys-*`)- // task without taskType would target TASKS.md instead of COS-TASKS.md, miss the- // record, and return a truthy `{ error }` object the `if (!updateResult)` check- // does not catch. Derive the type from the id here (mirrors the completion path,- // ~line 1084) so every write below routes to the correct file.- if (task && !task.taskType) {- task.taskType = isInternalTaskId(task.id || '') ? 'internal' : 'user';- }-- // Cross-instance claim guard (issue #1563, acceptance criterion 2). When this- // task list is shared with a federated peer (full-sync mode, #1561), the peer- // may already be working this task. Refuse to spawn while another instance- // holds a live lease — otherwise both peers spawn an agent for the same task,- // create conflicting `cos/<taskId>/<agentId>` worktrees on the same repo, and- // race the orphan-reset. This is a cheap, no-I/O fast-reject on the dequeued- // task; the authoritative acquire-with-fresh-reread happens below, before any- // spawn setup. No-op for a non-federated install (no claim metadata) and for- // re-claiming our own task on retry/resume.- // Resolve identity defensively: a cold-start identity failure (e.g. writing- // data/instances.json fails) returns null here; the wrapper's finally still- // releases the dedup guard, so the task id is never stranded in spawningTasks.- let instanceId;+ const context = createAgentSpawnContext(task);try {- instanceId = await ensureInstanceId();+ const prepared = await prepareAgentSpawn(task, context);+ if (!prepared) return null;+ return await dispatchAgentRun(prepared, { spawnViaRunner });} catch (err) {- emitLog('error', `Failed to resolve instance identity for task ${task.id}: ${err?.message || err}`, { taskId: task.id });- return null;- }- // Targeted assignment guard (issue #4520). A task pinned to a specific- // federated instance runs ONLY there — every other peer passes over it, even- // when it is unclaimed and this instance is idle. Checked before the lease so- // the log names the standing decision rather than a transient claim. Unpinned- // tasks (the default) reach the opportunistic lease check unchanged.- if (isTargetedElsewhere(task.metadata, instanceId)) {- console.log(`📍 Task ${task.id} is assigned to instance ${getTargetInstance(task.metadata)} — skipping spawn on ${instanceId}`);- return null;- }- if (!isClaimableBy(task.metadata, instanceId)) {- console.log(`🔒 Task ${task.id} is claimed by instance ${getClaimOwner(task.metadata)} (live lease) — skipping spawn on ${instanceId}`);- return null;- }-- // Spawn-local state `cleanupOnError` releases. Declared with `let` — and- // BEFORE the first gate — so one cleanup closure covers every early exit,- // including the two that run before the lane and tool execution exist. Each- // release is guarded on the thing having actually been acquired, so an early- // gate cannot release a lane nobody took.- let agentId = null;- let toolExecution = null;- let laneAcquired = false;- // Set once the federation claim has been persisted. cleanupOnError reads it- // to release the claim on any failed-setup early exit.- let claimAcquired = false;- // The throwaway worktree this attempt cut (set once prepareAgentWorkspace- // returns one), so every setup failure after that point removes it. Without- // this each failed spawn left a full checkout behind: the task stayed pending- // and every retry cut another.- let spawnWorktree = null;-- // Helper to cleanup on early exit. Releases the execution lane and the- // tool-execution state — and the synthetic app-review marker bound by- // `bindAppReviewAgent` before this spawn. Without the marker release, a- // pre-completion `return null` (max spawns, lane acquire, provider- // resolution, prep deferred/blocked, in_progress updateTask failure) strands- // the app reading "in review" until the next daemon restart (issue #989).- // The release is a no-op when the task carries no `metadata.app` or the- // marker is a real `agent-*` id from a different live agent.- const cleanupOnError = async (error) => {- // The spawn-dedup guard is released by withSpawnDedupGuard's finally around- // this whole body (see spawnAgentForTask) — cleanupOnError only owns the- // lane, tool-execution, claim, app-review marker, and setup-worktree releases.- if (laneAcquired) release(agentId);- if (toolExecution) {- errorExecution(toolExecution.id, { message: error });- completeExecution(toolExecution.id, { success: false });- }- // Release the federation claim acquired before setup (issue #1563) so a- // failed spawn never strands the task as claimed-but-not-running, which- // would block both this instance's retry and a peer for a full lease window.- if (claimAcquired) {- await updateTask(task.id, { metadata: buildRelease() }, task.taskType || 'user').catch(() => {});- }- await releaseAppReviewMarker(task.metadata?.app).catch(err => {- emitLog('warn', `Failed to release app review marker for ${task.metadata?.app}: ${err.message}`, { taskId: task.id });- });- if (spawnWorktree) {- // No agent ever ran in it, so nothing in it is worth keeping.- const { removeWorktree } = await import('./worktreeManager.js');- const sourceWorkspace = task.metadata?.app ? await getAppWorkspace(task.metadata.app).catch(() => ROOT_DIR) : ROOT_DIR;- await removeWorktree(agentId, sourceWorkspace, spawnWorktree.branchName, { discardDirt: true }).catch((cleanupErr) => {- emitLog('warn', `Failed to remove the worktree of failed spawn ${agentId}: ${cleanupErr.message}`, { agentId, taskId: task.id });- });- }- };-- /**- * The one way this spawn refuses a task: persist the terminal `blocked`- * transition, release everything this attempt acquired, announce it, and- * return null for the caller to `return`.- *- * Every eligibility gate below ends here. They used to end in eight hand-- * copies of this epilogue, which drifted: two announced with a warn log and- * two skipped the app-review-marker release, and no test could see either —- * the suite grepped the source for the blocked-status literal, which every- * copy still had. The three axes they legitimately differ on are the- * parameters:- *- * - `persist` — false leaves the task PENDING so the next dispatch retries- * it. Only a failure that would repeat identically forever gets blocked.- * - `emit` — `'agent:error'` raises an investigator; `'warn-log'` is for a- * fail-closed safety outcome that must NOT create one, because the- * investigator could retry the same unvalidated input; `'none'` is for a- * standing decision that is neither.- * - `emitPayload` — extra event fields (the provider identity on a- * provider-config failure).- *- * The block write itself frees the federation lease (updateTask strips the- * claim on any non-`in_progress` status change), so persisting BEFORE- * `cleanupOnError` keeps the terminal transition and the lease release as one- * write. Blocking after the release would open a window where a peer could- * claim and start the task, then have its live `in_progress` record clobbered- * to `blocked` — which outranks `in_progress` in the claim-aware merge.- */- const blockAndBail = async ({ reason, category, infrastructureCode, emit = 'agent:error', emitPayload = {}, persist = true }) => {- if (persist) {- await updateTask(task.id, {- status: 'blocked',- metadata: {- ...task.metadata,- blockedReason: reason,- blockedCategory: category,- blockedAt: new Date().toISOString(),- },- }, task.taskType || 'user').catch(() => {});- }- await cleanupOnError(reason);- if (emit === 'agent:error' && publicReviewPostureForProfile(task.metadata?.executionProfile) === PUBLIC_REVIEW_NO_TOOL_POSTURE- && (infrastructureCode || category?.startsWith('public-review-model-') || category === 'public-review-provider-unsupported')) {- const { reportReviewInfrastructureFailure } = await import('./reviewInfrastructureFailure.js');- await reportReviewInfrastructureFailure({ code: infrastructureCode || category, task }).catch(() => {- emitLog('warn', 'Could not report PR review infrastructure failure', { taskId: task.id });- });- // The generic agent:error handler copies task context into an investigator.- // This boundary reports only trusted diagnostics through the safe producer.- emit = 'warn-log';- }- if (emit === 'agent:error') {- cosEvents.emit('agent:error', { taskId: task.id, error: reason, ...emitPayload });- } else if (emit === 'warn-log') {- emitLog('warn', `Public review withheld for task ${task.id}: ${category}`, { taskId: task.id });- }- return null;- };-- // Check total spawn count across all retry types to prevent runaway respawning- const totalSpawns = Number(task.metadata?.totalSpawnCount) || 0;- if (totalSpawns >= MAX_TOTAL_SPAWNS) {- console.log(`🚫 Task ${task.id} hit max total spawns (${totalSpawns}/${MAX_TOTAL_SPAWNS}), blocking`);- // A standing decision, not an agent failure: an agent:error here would- // spawn an investigator for the same runaway task on every dispatch.- return blockAndBail({- reason: `Max total spawns exceeded (${totalSpawns}/${MAX_TOTAL_SPAWNS})`,- category: 'max-spawns',- emit: 'none',- });- }-- agentId = `agent-${uuidv4().slice(0, 8)}`;-- // Tag agent with execution lane (priority/observability only — concurrency- // is gated upstream by maxConcurrentAgents + maxConcurrentAgentsPerProject).- const laneName = determineLane(task);- const laneResult = acquire(laneName, agentId, { taskId: task.id });- if (!laneResult.success) {- emitLog('warn', `Failed to tag lane ${laneName}: ${laneResult.error}`, { taskId: task.id });- // A lane is a transient resource, so the task stays PENDING and retries —- // but the marker still has to come back, which is cleanupOnError's job.- await cleanupOnError(`Failed to tag lane ${laneName}`);- return null;- }- laneAcquired = true;-- // Create tool execution for state tracking- toolExecution = createToolExecution('agent-spawn', agentId, {- taskId: task.id,- lane: laneName,- priority: task.priority- });- startExecution(toolExecution.id);-- // Acquire the federation lease BEFORE any spawn setup (issue #1563, addressing- // the codex review: the claim must be taken up front, not at the in_progress- // flip after worktree/agent registration). Re-read the freshest persisted task- // so a peer's claim that synced in since this `task` was dequeued is honored,- // then write our claim immediately. Acquiring up front — rather than after- // setup — narrows the cross-peer window in which both instances pass the check- // and spawn, and the fresh re-read means we never clobber a claim that landed- // during the gap. cleanupOnError releases it on any failed-setup exit. (Full- // cross-machine atomicity completes with the task-record sync wiring in #1650;- // within one install the `spawningTasks` guard already prevents duplicates.)- const freshTask = await getTaskById(task.id).catch(() => null);- if (freshTask) {- // A retry held for its resume pointer (#3373) is not spawnable, however this- // dispatch reached us. The dequeue tiers can't see it (they select `pending`),- // but a `task:ready` emitted before the hold was armed — or a stale generator- // snapshot — arrives with a task object from before the failure, and the claim- // check below passes because the hold keeps OUR OWN lease. Spawning here is- // exactly the race the hold exists to close: the retry would start clean while- // the pointer naming its predecessor's branch is still being resolved. The- // release re-emits `tasks:changed`, which re-runs the dequeue.- if (isRetryHeld(freshTask.metadata)) {- console.log(`⏳ Task ${task.id} is held for its retry pointer — not spawning until cleanup releases it`);- await cleanupOnError('retry held pending cleanup');- return null;- }- // Re-check the pin against the freshest record (#4520): the dequeued snapshot- // may predate a reassignment that synced in from a peer, and a task- // reassigned mid-dispatch must not be started here.- if (isTargetedElsewhere(freshTask.metadata, instanceId)) {- console.log(`📍 Task ${task.id} is assigned to instance ${getTargetInstance(freshTask.metadata)} — yielding on ${instanceId}`);- await cleanupOnError('assigned to another instance');- return null;- }- // The task is persisted — honor a peer's claim that synced in since dispatch,- // then take the lease up front.- if (!isClaimableBy(freshTask.metadata, instanceId)) {- console.log(`🔒 Task ${task.id} was claimed by instance ${getClaimOwner(freshTask.metadata)} during dispatch — yielding on ${instanceId}`);- await cleanupOnError('claimed by another instance');- return null;- }- const claimUpdate = await updateTask(task.id, {- metadata: buildClaim(instanceId)- }, task.taskType || 'user').catch(() => null);- if (claimUpdate && !claimUpdate.error) {- claimAcquired = true;- // Keep the in-memory task's metadata in sync with the persisted claim so- // the downstream in_progress update merges against the freshest shape.- task.metadata = claimUpdate.metadata;- }- // If the claim write failed, fall through: the in_progress update below still- // stamps the claim, preserving the prior single-write behavior for any task- // shape that isn't separately updatable here.- }- // A not-yet-persisted task (getTaskById miss) falls through unchanged — its- // claim is stamped at the in_progress update below, exactly as before.-- // Single try wraps setup + the spawn handoff so all locals stay in- // scope. The `handedOff` flag tells the catch arm which kind of- // failure we're recovering from:- //- // - `handedOff === false` (pre-spawn): any uncaught throw from- // buildAgentPrompt / writeFile / createAgentRun / registerAgent /- // worktree + JIRA provisioning. cleanupOnError releases the execution- // lane and the tool-execution state (the dedup guard itself is released- // by withSpawnDedupGuard's finally around this whole body). Also re-emit- // `job:spawn-failed` for autonomous-job tasks so cos.js can clear- // its job-level guard immediately instead of waiting 5 minutes.- //- // - `handedOff === true` (post-handoff): the rejection came from- // spawnTuiAgent / spawnViaRunner / spawnDirectly, which may have- // created a live runner agent or child process. Re-throw so the- // caller (subAgentSpawner's task:ready listener) handles it as- // pre-fix; the spawn helper owns lane/execution cleanup via its- // child's `on('error')` handler.- let handedOff = false;- try {- // Get configuration- const config = await getConfig();- // Resolve provider (with availability/fallback + user override) and the- // per-task model. A resolvable failure returns { ok: false } so we can- // fire cleanupOnError + the matching agent:error event here, where the- // spawn-local guard/lane/execution state lives.- const resolution = await resolveAgentProviderAndModel(task);- if (!resolution.ok) {- // A PERMANENT provider-config failure (e.g. an `api`-only provider pinned- // to an agent task, which has no file-writing harness) fails identically on- // every re-dispatch. Leaving the task pending makes it silently re-fail- // forever AND wedge its app's single improvement slot. Block it with an- // actionable reason so it stops re-dispatching and surfaces in the UI.- // Transient failures skip the block and stay pending to retry.- return blockAndBail({- reason: resolution.error,- infrastructureCode: resolution.infrastructureCode,- category: PROVIDER_CONFIG_BLOCKED_CATEGORY,- persist: resolution.permanent,- emitPayload: {- ...(resolution.providerId && { providerId: resolution.providerId }),- ...(resolution.providerStatus && { providerStatus: resolution.providerStatus }),- },- });- }- const { provider, selectedModel, modelSelection } = resolution;+ if (!context.setupCatchArmed || context.handedOff) throw err;const privateSecurity = isPrivateSecurityTask(task);- const executionProfile = task.metadata?.executionProfile;- const publicReviewPosture = publicReviewPostureForProfile(executionProfile);- const publicReviewNoTools = publicReviewPosture === PUBLIC_REVIEW_NO_TOOL_POSTURE;- const publicReviewActions = executionProfile === PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE;- const publicReview = Boolean(publicReviewPosture);- const isTui = isTuiProvider(provider);- // Stage 3 (`sandboxed-actions`) is the longest-running and least- // predictable stage in the pr-reviewer pipeline — it applies a screened- // patch and runs the repo's tests — so it is the one an operator actually- // wants to attach to and steer. It may run as an interactive session when- // its configured provider is a TUI record AND that vendor declares an- // attachable recipe (`tuiSpawnArgs`), which keeps every enforcement flag and- // drops only the headless output flags.- //- // Everything else stays headless. The `no-tool` postures (Stage 1's- // security scan, Stage 2's eligibility gate) are excluded by design: an- // interactive session for a reasoner with no tools buys nothing and widens- // the boundary for free. A TUI record whose vendor has no attachable- // recipe also stays headless — its ordinary recipe emits `--print`/`exec`- // argv that a PTY can neither prompt nor enforce.- const publicReviewTui = publicReviewActions && isTui- && supportsTuiPublicReviewActionsProvider(provider);- const spawnHeadless = !isTui || (publicReview && !publicReviewTui);- // Every public-review spawn precondition, in one ordered gate: the scan- // clears the input, the eligibility gate names the touchable PRs, the- // vendor row must declare a maintained recipe for the requested posture,- // and only then is the model checked. The helper owns the "no posture- // requested" case, so an ordinary task passes straight through (#5830).- const publicReviewBlock = await checkPublicReviewSpawnPreconditions({- task,- provider,- selectedModel,- publicReviewPosture,- publicReview,- publicReviewActions,- publicReviewNoTools,- privateSecurity,- validateModel: validatePublicReviewModel,- });- if (publicReviewBlock) return blockAndBail(publicReviewBlock);- // Every public-content stage is direct-only. The CoS runner is a shared- // process and may inherit ambient tool configuration; the final stage's- // provider-specific direct CLI recipe is what enforces its sandbox.- // GitHub mutations still belong to the deterministic output hook.- //- // A credential-bootstrap-configured provider is ALSO direct-only: the- // runner is a separate process that validates the command it's asked to- // spawn against a static allowlist of known harness binaries- // (cos-runner/allowedCommands.js) and has no way to know about a user's- // arbitrary bootstrap CLI, so routing it there would 400 at spawn time.- const dispatchUseRunner = (publicReview || hasCredentialBootstrap(provider)) ? false : useRunner;- let publicReviewPromptData = null;-- // Resolve the workspace and provision any worktree / JIRA branch the task- // needs. A git conflict defers the task; an explicitly-requested worktree- // that fails to create blocks it. Both outcomes are finished here so the- // dedup guard / lane / execution state are released consistently.- const prep = await prepareAgentWorkspace({ agentId, task });- if (prep.outcome === 'deferred') {- await cleanupOnError(prep.reason);- cosEvents.emit('agent:deferred', { taskId: task.id, reason: prep.deferReason, branch: prep.branch });- return null;- }- if (prep.outcome === 'blocked') {- await cleanupOnError(prep.reason);- cosEvents.emit('agent:error', { taskId: task.id, error: prep.reason });- return null;- }- const { workspacePath, resolvedApp, resolvedAppName, worktreeInfo, jiraTicket, jiraBranchName, explicitWorktree } = prep;- if (worktreeInfo?.branchName && !worktreeInfo.existingBranch && !worktreeInfo.isPersistentWorktree) {- spawnWorktree = { branchName: worktreeInfo.branchName };- }-- if (publicReview && !privateSecurity) {- // Materialize the screened snapshot (and, for the actions stage, its- // read-only patch files) into the workspace, then read it back for the- // prompt. Fails closed on any of those, through the same epilogue.- const reviewInput = await loadPublicReviewSpawnInput({- scanKey: task.metadata?.pipeline?.reviewInputKey,- workspacePath,- actionsStage: publicReviewActions,- eligibleNumbers: task.metadata?.pipeline?.eligibility?.eligibleNumbers,- noToolReviewer: publicReviewNoTools,- });- if (reviewInput.block) return blockAndBail(reviewInput.block);- publicReviewPromptData = reviewInput.promptData;- }-- // Auto-snapshot the workspace context of the app CoS was last working in- // when this dispatch switches to a different app/repo (#2035). Snapshot-only- // — it never restores and never calls an LLM. Dynamic import avoids pulling- // the workspace-context graph into this hot module's load path; the call is- // defensive so a missing current context (or any failure) can't break the- // spawn.- await import('./workspaceContext.js')- .then((ws) => ws.snapshotOnRepoSwitch(task.metadata?.app || null))- .catch((err) => {- emitLog('warn', `Workspace auto-snapshot skipped for task ${task.id}: ${err?.message || err}`, { taskId: task.id });- });-- // Lean mode: an Ollama-backed Claude session gets `--bare --strict-mcp-config`- // (see applyLeanClaudeArgs) so the user's personal environment — hooks,- // plugins, MCP servers, the global ~/.claude/CLAUDE.md — doesn't drown the small local- // model. This is orthogonal to the prompt split below.- const leanMode = isOllamaClaudeProvider(provider);-- // System/user prompt split: for ANY Claude Code session (TUI or headless- // CLI), the PortOS operating contract rides in a real system prompt via- // `--append-system-prompt-file` while the pasted/stdin prompt carries only- // the task — so the model weights the contract as instructions, not- // conversation (and hosted providers get better prompt-cache reuse on the- // stable system block). Gated on a light-context Claude command: non-Claude- // providers (codex, antigravity, opencode) have no equivalent flag and keep- // the combined prompt; API providers never take the light path so the split- // is a no-op for them. `--append-system-prompt-file` validated on claude CLI- // v2.1.201 in both `--print` and stream-json arg shapes.- const isLightContext = isTui || provider.type === PROVIDER_TYPES.CLI;- const splitSystemPrompt = isLightContext && isClaudeCommand(provider.command);-- // Build the agent prompt. `provider.type` drives the light-vs-full split- // inside buildAgentPrompt — see its doc comment.- const privatePrompt = privateSecurity- ? await import('./privateSecurityAssessment.js').then(({ preparePrivateSecurityAssessment }) => preparePrivateSecurityAssessment(task, provider, selectedModel))- : null;- const promptResult = privateSecurity ? privatePrompt : await buildAgentPrompt(task, config, workspacePath, worktreeInfo, isTruthyMeta, {- providerType: provider.type,- providerId: provider.id,- providerCommand: provider.command,- // The planner identity a filing agent stamps as `planner:<model>` — the- // model this run RESOLVED to (post-fallback), which the agent cannot- // report about itself.- providerModel: selectedModel,- agentId, // scopes the completion sentinel filename — see doneSentinelName- leanMode,- split: splitSystemPrompt- });- const basePrompt = typeof promptResult === 'string' ? promptResult : promptResult.userPrompt;- const prompt = publicReview && !privateSecurity- ? `${basePrompt}\n\n${formatPublicReviewInputPrompt(publicReviewPromptData)}`- : basePrompt;- const systemPrompt = typeof promptResult === 'string' ? null : promptResult.systemPrompt;-- // What this prompt costs to PREFILL on a model server running on this box- // (#6117). A public-review stage inlines the whole screened envelope — ~100K- // tokens is ordinary — and a local endpoint spends minutes on that before it- // can emit a single line. Nothing else in the dispatch path compares the- // assembled prompt against the throughput of the endpoint it is aimed at, so- // the run's duration estimate was the review's estimate with none of the- // prefill in it, and the card was indistinguishable from a wedged run.- //- // The dispatch is NEVER refused here: the user chose this provider, and the- // window the prompt has to fit is the model's own context window — a- // separate condition the provider reports for itself. All we do is raise the- // estimate and say so.- //- // Task-level OpenCode/Ollama generation controls override provider defaults- // for this one run. The child-environment composer turns these into the- // dynamic `agent.build` config instead of mutating saved provider state.- const requestedProvider = applyTaskGenerationOverrides(provider, task.metadata);- // Ollama 400s the whole request when a model that never implements thinking- // is asked to think, so a non-reasoning local model dispatched at any effort- // level dies on its first turn with exit 1 and no output. Resolved here,- // once, on the provider EVERY spawn path shares — so the two carriers of the- // level (the `--effort` argv and OpenCode's `agent.*.reasoningEffort` config)- // drop it together. Resolve task-over-provider defaults before recording the- // run so the registered effort and every launch path use the same value.- // The argv builders no-op it for providers without an effort control.- //- // Resolved BEFORE the duration estimate below (#8001): that lookup keys off- // the effort this run will actually execute at, and the learning store records- // the same post-drop `taskEffort` through `buildAgentRegistration`. Reading a- // pre-drop level here would look up a bucket nothing ever writes.- const { provider: runProvider, effort: taskEffort } = await dropUnsupportedOllamaThinking(- requestedProvider,- selectedModel,- requestedProvider.effort || null,- );-- // Cloud runs take no async hop at all: `localEndpointOfProvider` answers null- // for anything not on this machine, and `planLocalPromptBudget` is skipped.- const localEndpoint = localEndpointOfProvider(provider);- const localPromptBudget = localEndpoint- ? planLocalPromptBudget({- prompt,- endpoint: localEndpoint,- // The learned average for THIS run's execution identity — task type ×- // provider × model × effort, falling outward to the plain task-type- // average when that bucket is still thin (#8001). The identity matters- // most for exactly this caller: the estimate being raised is a local- // model's, and a cloud run of the same task type is no guide to it. A- // dynamic import for the same reason the workspace snapshot above uses- // one: it keeps the task-learning graph out of this hot module's load- // path, and a failed read means "nothing learned", not "zero".- baseDurationMs: await import('./taskLearning.js')- .then((tl) => tl.getTaskDurationEstimate(task.description, {- providerId: provider.id,- model: selectedModel,- effort: taskEffort,- }))- .then((estimate) => estimate?.estimatedDurationMs ?? null)- .catch(() => null),- })- : null;- if (localPromptBudget?.longPrefill) {- emitLog('info', `🐢 Agent ${agentId} ${describeLocalPromptBudget(localPromptBudget)}`, {- agentId,- taskId: task.id,- promptTokens: localPromptBudget.promptTokens,- });- }-- // Create agent directory- const agentDir = join(AGENTS_DIR, agentId);- if (!existsSync(agentDir)) {- await ensureDir(agentDir);- }-- // Save prompt to file- await writeFileGuarded(join(agentDir, 'prompt.txt'), prompt);- let systemPromptFile = null;- if (systemPrompt) {- systemPromptFile = join(agentDir, 'system-prompt.md');- await writeFileGuarded(systemPromptFile, systemPrompt);- }-- // Create run entry for usage tracking- const { runId } = await createAgentRun({- agentId,- task,- model: selectedModel,- provider,- workspacePath,- appName: resolvedAppName- });- const executionMode = resolveExecutionMode({ spawnHeadless, useRunner: dispatchUseRunner });-- // Register the agent with model info.- //- // `instanceId` stamps the producing machine's federation identity onto every- // spawned agent (issue #1563, acceptance criterion 1). It flows through to- // the completed-agent archive's `metadata.json` automatically (completeAgent- // serializes `.metadata`), so once CoS agent history federates across peers a- // node pair can attribute each agent + its worktree branch to the instance- // that produced it.- //- // `instanceId` was resolved up front via `ensureInstanceId()` for the claim- // guard, and is reused here so the warm-path cached read happens once.- // The checkout the worktree was cut FROM (null for a non-worktree run, which- // works in the primary directly and so has nothing to protect).- const sourceWorkspace = worktreeInfo- ? (task.metadata?.app ? await getAppWorkspace(task.metadata.app) : ROOT_DIR)- : null;-- // WHO opens this run's PR, per the prompt just built for it — the SAME- // predicate that decided what the completion section says, so the record and- // the prompt cannot disagree (#6869). Read back at cleanup by- // `resolvePrOpenedBy`.- const prOpenedBy = promptOpensOwnPr(task, {- providerType: provider.type,- providerId: provider.id,- providerCommand: provider.command,- leanMode,- worktreeInfo,- isTruthyMetaFn: isTruthyMeta,- });- // Evaluated once: `configClaimFlow` and `configCodingOnMain` below are two- // faces of the same fact, and two separate calls could drift on the- // `isTruthyMetaFn` argument — which is exactly the split that made a claim- // run badge itself "main".- const claimFlowTask = isClaimFlowTask(task, isTruthyMeta);- // Two independent reads of two different checkouts — run them together- // rather than letting the object literal below serialize them.- //- // The forge target is where a bare `#7640` in this run's own summary points.- // Resolved through the shared resolver (not a hostname guess) so the app's- // own `workTracker` pin decides for a self-hosted forge, and read from the- // WORKSPACE so a run on a managed app links to THAT app's tracker.- //- // `primaryCheckoutBaseline` is the branch-jack baseline (#3680): the primary- // checkout's branch + HEAD at the instant this worktree agent started.- // finalizeAgent re-reads it at the end of the run — every spawn mode funnels- // through that one chokepoint — and fails the run when the primary moved,- // instead of recording a silent "completed" for an agent that wrote- // unreviewed commits outside its worktree. Non-throwing: an unreadable- // checkout yields null, which the detector reads as "nothing to check".- const [forgeTarget, primaryCheckoutBaseline] = await Promise.all([- resolvedApp- ? resolveAppForgeTarget(resolvedApp, { repoPath: workspacePath }).then(r => r.target)- : resolveRepoForgeTarget(workspacePath),- sourceWorkspace ? capturePrimaryCheckoutState(sourceWorkspace) : null,- ]);- await registerAgent(agentId, task.id, buildAgentRegistration({- task,- provider,- instanceId,- workspacePath,- sourceWorkspace,- repoIssueUrl: repoIssueUrlBase(forgeTarget),- primaryCheckoutBaseline,- worktreeInfo,- explicitWorktree,- jiraBranchName,- // The endpoint this agent's inference actually lands on, resolved through- // the SAME helper the per-local-endpoint spawn cap (#4834) reads with, so- // writer and reader cannot drift.- providerEndpoint: providerBaseUrl(provider),- localPromptBudget,- leanMode,- prOpenedBy,- claimFlowTask,- selectedModel,- effort: taskEffort,- modelSelection,- runId,- dispatchUseRunner,- executionMode,- publicReviewPosture,- resolvedAppName,- isTruthyMetaFn: isTruthyMeta,- }));-- emitLog('info', `Agent ${agentId} initializing...${worktreeInfo ? ' (worktree)' : ''}${jiraBranchName ? ` (JIRA: ${jiraTicket?.ticketId})` : ''}`, { agentId, taskId: task.id });-- // NOTE: the agent is already registered as `running` above, so until this- // write lands the task still reads `pending` — one task, two live states.- // Readers that pair the task list with the agent list must reconcile that- // (forceSpawnTask's live-agent refusal, activeProcessing's queued count, the- // CoS Tasks tab). Widening this gap widens their window.- //- // Mark the task as in_progress, increment the total spawn count, and refresh- // the federation claim (issue #1563). The claim was already acquired up front- // (above); re-stamping it here renews the lease at the moment the agent- // actually spawns. A federated peer sharing this task list sees the task as- // live-claimed and backs off (the orphan-reset honors the same lease). The- // lease is then renewed on the health-check heartbeat while the agent runs,- // and released when the task leaves `in_progress`.- const newSpawnCount = (Number(task.metadata?.totalSpawnCount) || 0) + 1;- const updateResult = await updateTask(task.id, {- status: 'in_progress',- metadata: {- ...task.metadata,- totalSpawnCount: newSpawnCount,- lastSpawnedAt: new Date().toISOString(),- ...buildClaim(instanceId)- }- }, task.taskType || 'user')- .catch(err => {- console.error(`❌ Failed to mark task ${task.id} as in_progress: ${err.message}`);- return null;- });- // Surface a silent `{ error }` miss (issue #2633) — the task id wasn't present- // in the file for `task.taskType`, so the claim didn't land. This is EXPECTED- // for legitimately-unpersisted autonomous emits: Priority 3 idle-review tasks- // (cos.js `spawnDequeuePriority3IdleReview`) carry `taskType: 'internal'` but- // are never written to COS-TASKS.md, so their in_progress `updateTask` returns- // `{ error: 'Task not found' }`. Warn-log it for visibility, but do NOT block- // the spawn on it — the pre-#2633 behavior spawned these anyway, and treating- // the error as fatal would silently kill every idle-review autonomous spawn.- // Only a `null` (updateTask threw) is fatal.- if (updateResult?.error) {- emitLog('warn', `⚠️ in_progress claim for task ${task.id} returned an error (taskType=${task.taskType}): ${updateResult.error}`, { taskId: task.id, error: updateResult.error });- }- if (!updateResult) {- await cleanupOnError('Failed to update task status');- return null;- }-- // Record autonomous job execution now that the task is confirmed spawning- if (task.metadata?.autonomousJob && task.metadata?.jobId) {- cosEvents.emit('job:spawned', { jobId: task.metadata.jobId });- }-- // Read ~/.claude/settings.json env BEFORE building the argv so the Bedrock- // model-id mapping in buildCliSpawnConfig sees the same CLAUDE_CODE_USE_BEDROCK- // the child is actually spawned with (the spawn helpers merge this env too).- // Without it, a host that supplies Bedrock mode only via settings.json would- // bake a bare, Bedrock-invalid --model into the argv. Cached (5-min TTL), so- // the spawn helper's own getClaudeSettingsEnv() call is effectively free.- const cliSettingsEnv = !publicReview && isClaudeCliProvider(provider)- ? await getClaudeSettingsEnv()- : {};- // Codex counts the root orchestrator against its per-session thread cap.- // Lift that cap to root + configured workers for cloud swarms so a six-way- // claim run can actually fan out six issue agents. Never lift it for a- // provider whose inference lands on this machine: local runtimes retain- // their deliberately bounded GPU concurrency posture.- const maxConcurrentThreads = cloudSwarmThreadCapacity(runProvider, task.metadata?.swarmCount);- const safetyProfile = publicReview ? executionProfile : null;- const cliConfig = !spawnHeadless- ? buildTuiSpawnConfig(runProvider, selectedModel, { systemPromptFile, effort: taskEffort, maxConcurrentThreads, safetyProfile })- : buildCliSpawnConfig(runProvider, selectedModel, cliSettingsEnv, { systemPromptFile, effort: taskEffort, maxConcurrentThreads, safetyProfile });-- emitLog('success', `Spawning agent for task ${task.id}`, {- agentId,- model: selectedModel,- mode: executionMode,- cli: cliConfig.command,- lane: laneName,- worktree: !!worktreeInfo- });-- // Dedup-window fix: the `spawningTasks` guard stays held across the actual- // spawn call, not just up to the in_progress flip — withSpawnDedupGuard- // (around this whole body) only releases it once runAgentSpawn settles.- // Releasing between `updateTask` and `spawnViaRunner` / `spawnDirectly`- // opened a window where a concurrent `spawnAgentForTask(task)` call (e.g. a- // re-fired `task:ready` from a follow-up scheduler tick) saw an empty set- // and a task whose registered agent hadn't yet been queued to the runner,- // and proceeded to spawn a second agent for the same task id. release()- // must NOT run here on the success path; the lane is released by the- // agent-completion handler when the work finishes.- handedOff = true;- if (!spawnHeadless) {- return await spawnTuiAgent({- agentId,- task,- prompt,- workspacePath,- model: selectedModel,- provider: runProvider,- runId,- tuiConfig: cliConfig,- agentDir,- executionId: toolExecution.id,- laneName,- isTruthyMetaFn: isTruthyMeta,- leanMode,- prOpenedBy,- useDurableRunner: dispatchUseRunner,- safetyProfile,- });- }- if (dispatchUseRunner) {- return await spawnViaRunner(agentId, task, { prompt, workspacePath, model: selectedModel, provider: runProvider, runId, cliConfig, executionId: toolExecution.id, laneName });- }- // Direct spawn mode (fallback)- return await spawnDirectly({- agentId,- task,- prompt,- workspacePath,- model: selectedModel,- provider: runProvider,- runId,- cliConfig,- agentDir,- executionId: toolExecution.id,- laneName,- isTruthyMetaFn: isTruthyMeta,- prOpenedBy,- safetyProfile,- });- } catch (err) {- if (handedOff) {- // Spawn helper rejected — may have created a live runner agent or- // child process. Re-throw so the caller (subAgentSpawner's- // task:ready listener) handles it as pre-fix; the spawn helper- // owns lane/execution cleanup via its child's `on('error')`- // handler. The finally still releases the dedup guard.- throw err;- }- const setupError = isPrivateSecurityTask(task)+ const setupError = privateSecurity? 'Private assessment setup failed. Verify its local model, isolated harness, and source access before retrying.': err.message;emitLog('error', `Agent spawn setup failed: ${setupError}`, { taskId: task.id, error: setupError });- // Only a private assessment is blocked here: its setup failure names a- // missing local model / isolated harness that will not fix itself, while an- // ordinary task's is transient and must stay pending to retry.- await blockAndBail({+ await context.blockAndBail({reason: setupError,category: 'private-security-setup-failed',- persist: isPrivateSecurityTask(task),+ persist: privateSecurity,});- // Preserve the autonomous-job retry contract. Pre-widening, an uncaught- // throw here propagated to subAgentSpawner's `task:ready` listener,- // which emitted `job:spawn-failed` so cos.js could clear- // `spawningJobIds` and re-register the cron schedule.if (task.metadata?.jobId) {cosEvents.emit('job:spawn-failed', { jobId: task.metadata.jobId });}return null;}- // No finally here: withSpawnDedupGuard (around runAgentSpawn) owns the- // spawningTasks release, so it fires whether this body returns or throws.}/**diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.jsindex 2317b3b9c0..7f278d97ec 100644--- a/server/services/agentLifecycle.test.js+++ b/server/services/agentLifecycle.test.js@@ -36,6 +36,9 @@ import { PROVIDER_CONFIG_BLOCKED_CATEGORY, PAUSED_BLOCKED_CATEGORIES, USER_DECISconst __dirname = dirname(fileURLToPath(import.meta.url));const AGENT_LIFECYCLE_SRC = readFileSync(join(__dirname, 'agentLifecycle.js'), 'utf-8');+const AGENT_SPAWN_PREPARATION_SRC = readFileSync(join(__dirname, 'agentSpawnPreparation.js'), 'utf-8');+const AGENT_SPAWN_DISPATCH_SRC = readFileSync(join(__dirname, 'agentSpawnDispatch.js'), 'utf-8');+const AGENT_SPAWN_OWNER_SRC = `${AGENT_SPAWN_PREPARATION_SRC}\n${AGENT_SPAWN_DISPATCH_SRC}`;// finalizeAgent + stampLiExecutionVerdict moved to their own module (issue #2837)// so both spawners can import them without cycling back through the lifecycle// orchestrator. The source-level assertions below follow them there.@@ -320,19 +323,19 @@ describe('agentLifecycle — guard wiring', () => {// stays greppable is the wiring: that the orchestrator delegates to the gate// instead of growing a second copy beside it.it('delegates every public-review spawn precondition to the extracted gate', () => {- expect(AGENT_LIFECYCLE_SRC).toMatch(+ expect(AGENT_SPAWN_DISPATCH_SRC).toMatch(/import \{ checkPublicReviewSpawnPreconditions \} from '\.\.\/lib\/publicReviewSpawnGate\.js'/);- expect(AGENT_LIFECYCLE_SRC).toMatch(+ expect(AGENT_SPAWN_DISPATCH_SRC).toMatch(/const publicReviewBlock = await checkPublicReviewSpawnPreconditions\(\{[\s\S]{0,400}?validateModel: validatePublicReviewModel,/);// One bail, through the shared epilogue — not a hand-rolled block write.- expect(AGENT_LIFECYCLE_SRC).toContain('if (publicReviewBlock) return blockAndBail(publicReviewBlock);');+ expect(AGENT_SPAWN_DISPATCH_SRC).toContain('if (publicReviewBlock) return context.blockAndBail(publicReviewBlock);');// A second, inline copy of any gate here is the drift this extraction// exists to prevent.- expect(AGENT_LIFECYCLE_SRC).not.toMatch(/publicReviewScanBlock\(/);- expect(AGENT_LIFECYCLE_SRC).not.toMatch(/publicReviewEligibilityBlock\(/);- expect(AGENT_LIFECYCLE_SRC).not.toMatch(/publicReviewProviderBlock\(/);+ expect(AGENT_SPAWN_DISPATCH_SRC).not.toMatch(/publicReviewScanBlock\(/);+ expect(AGENT_SPAWN_DISPATCH_SRC).not.toMatch(/publicReviewEligibilityBlock\(/);+ expect(AGENT_SPAWN_DISPATCH_SRC).not.toMatch(/publicReviewProviderBlock\(/);});// #5830 collapsed the two per-stage provider gates into one and dropped the@@ -413,7 +416,7 @@ describe('self-update spawn gate — funnel coverage (#4124)', () => {expect(invokersOf('spawnAgentForTask'),'a new caller of spawnAgentForTask must also carry the self-update hold (see subAgentSpawner.js)'- ).toEqual(['agentLifecycle.js', 'subAgentSpawner.js']);+ ).toEqual(['subAgentSpawner.js']);});it('the three low-level spawn helpers are invoked only from the gated dispatch', () => {@@ -423,7 +426,7 @@ describe('self-update spawn gate — funnel coverage (#4124)', () => {expect(invokersOf(helper),`${helper} must stay reachable only through spawnAgentForTask`- ).toEqual(['agentLifecycle.js']);+ ).toEqual(['agentSpawnDispatch.js']);}});@@ -565,36 +568,27 @@ function trackedCompletionPreamble() {// body and can't be reached without mocking its 40+ imports. Anchored on// `runAgentSpawn` (the guarded body extracted from spawnAgentForTask, #2548).-const RUN_SPAWN_START = AGENT_LIFECYCLE_SRC.indexOf('async function runAgentSpawn');-const RUN_SPAWN_BODY = AGENT_LIFECYCLE_SRC.slice(RUN_SPAWN_START, RUN_SPAWN_START + 60_000);+const RUN_SPAWN_START = AGENT_SPAWN_OWNER_SRC.indexOf('export async function prepareAgentSpawn');+const RUN_SPAWN_BODY = AGENT_SPAWN_OWNER_SRC;describe('runAgentSpawn source — handedOff pre-spawn vs post-handoff split', () => {it('uses a mutable handedOff flag to distinguish the two failure modes', () => {- // The flag is declared with `let` so the catch arm can read which side of- // the spawn handoff a throw came from.- expect(RUN_SPAWN_BODY).toMatch(/let\s+handedOff\s*=\s*false\s*;/);- // The catch arm rethrows for post-handoff failures (a live agent may exist).- expect(RUN_SPAWN_BODY).toMatch(/if\s*\(\s*handedOff\s*\)\s*\{[\s\S]{0,800}?throw\s+err\s*;/);- // The pre-spawn branch runs the shared block-and-bail epilogue — blocking- // ONLY a private assessment, whose setup failure will not fix itself —- // then re-emits job:spawn-failed for autonomous-job tasks so cos.js can- // clear its job-level guard.- expect(RUN_SPAWN_BODY).toMatch(- /await blockAndBail\(\{\s*reason: setupError,\s*category: 'private-security-setup-failed',\s*persist: isPrivateSecurityTask\(task\),/+ expect(AGENT_SPAWN_PREPARATION_SRC).toMatch(/handedOff:\s*false/);+ expect(AGENT_LIFECYCLE_SRC).toMatch(/context\.handedOff/);+ expect(AGENT_LIFECYCLE_SRC).toMatch(/if\s*\(!context\.setupCatchArmed\s*\|\|\s*context\.handedOff\)\s*throw\s+err\s*;/);+ expect(AGENT_LIFECYCLE_SRC).toMatch(+ /await context\.blockAndBail\(\{[\s\S]{0,300}?reason: setupError,[\s\S]{0,200}?category: 'private-security-setup-failed',/);- expect(RUN_SPAWN_BODY).toMatch(/job:spawn-failed/);- expect(RUN_SPAWN_BODY).toMatch(/task\.metadata\??\.jobId/);+ expect(AGENT_LIFECYCLE_SRC).toMatch(/job:spawn-failed/);+ expect(AGENT_LIFECYCLE_SRC).toMatch(/task\.metadata\??\.jobId/);});it('sets handedOff = true BEFORE the first spawn helper invocation', () => {- // Setting it after would misclassify a synchronous throw from building the- // helper's argument object as a pre-spawn failure even though the helper- // may have begun work.- const flipIdx = RUN_SPAWN_BODY.indexOf('handedOff = true');- expect(flipIdx, '`handedOff = true` must exist inside runAgentSpawn').toBeGreaterThan(-1);+ const flipIdx = AGENT_SPAWN_DISPATCH_SRC.indexOf('context.handedOff = true');+ expect(flipIdx, '`context.handedOff = true` must exist in dispatchAgentRun').toBeGreaterThan(-1);for (const helper of ['spawnTuiAgent(', 'spawnViaRunner(', 'spawnDirectly(']) {- const idx = RUN_SPAWN_BODY.indexOf(helper);- expect(idx, `${helper} must appear AFTER \`handedOff = true\``).toBeGreaterThan(flipIdx);+ const idx = AGENT_SPAWN_DISPATCH_SRC.indexOf(helper);+ expect(idx, `${helper} must appear AFTER \`context.handedOff = true\``).toBeGreaterThan(flipIdx);}});});@@ -622,46 +616,30 @@ describe('runAgentSpawn source — durable TUI ownership (#3202)', () => {// omit it. What each gate actually releases is behavior-tested in// agentLifecycle.blockAndBail.test.js; these pin the structure that keeps a// NEW gate from re-opening the hole.-describe('runAgentSpawn source — app-review marker release (issue #989)', () => {- it('cleanupOnError releases the synthetic app-review marker', () => {- const start = AGENT_LIFECYCLE_SRC.indexOf('const cleanupOnError =');- expect(start, 'cleanupOnError must exist').toBeGreaterThan(-1);- const body = AGENT_LIFECYCLE_SRC.slice(start, start + 1400);- expect(body, 'cleanupOnError must release the app-review marker').toMatch(- /releaseAppReviewMarker\(task\.metadata\?\.app\)/- );+describe('agent spawn preparation — app-review marker release (issue #989)', () => {+ it('releases the synthetic app-review marker from the shared cleanup owner', () => {+ const start = AGENT_SPAWN_PREPARATION_SRC.indexOf('context.cleanupOnError =');+ expect(start, 'cleanup owner must exist').toBeGreaterThan(-1);+ const body = AGENT_SPAWN_PREPARATION_SRC.slice(start, start + 1400);+ expect(body).toMatch(/releaseAppReviewMarker\(context\.task\.metadata\?\.app\)/);+ });++ it('awaits every cleanup call before returning null', () => {+ const bareCalls = AGENT_SPAWN_OWNER_SRC.match(/(?<!await )(?<!const )context\.cleanupOnError\(/g) || [];+ expect(bareCalls, 'all cleanup calls must be awaited').toEqual([]);+ });++ it('keeps one marker release site in preparation', () => {+ const releases = AGENT_SPAWN_PREPARATION_SRC.match(/releaseAppReviewMarker\(/g) || [];+ expect(releases).toHaveLength(1);});- it('every cleanupOnError call is awaited so the release persists before return null', () => {- // A bare `cleanupOnError(` call would fire the async marker release without- // awaiting it, racing the `return null`.- const bareCalls = RUN_SPAWN_BODY.match(/(?<!await )(?<!const )cleanupOnError\(/g) || [];- expect(bareCalls, 'all cleanupOnError calls must be awaited').toEqual([]);- });-- it('routes the marker release through cleanupOnError alone, with no inline copy', () => {- // `cleanupOnError` is now defined ahead of every gate, so an inline release- // anywhere in the body means a gate grew its own epilogue again.- const releases = RUN_SPAWN_BODY.match(/releaseAppReviewMarker\(/g) || [];- expect(releases.length, 'exactly one release site: inside cleanupOnError').toBe(1);- const defIdx = AGENT_LIFECYCLE_SRC.indexOf('const cleanupOnError =', RUN_SPAWN_START);- expect(defIdx, 'cleanupOnError must be defined inside runAgentSpawn').toBeGreaterThan(RUN_SPAWN_START);- // Ahead of the first gate that can bail, so no early return can outrun it.- const firstGateIdx = AGENT_LIFECYCLE_SRC.indexOf('if (totalSpawns >= MAX_TOTAL_SPAWNS)', RUN_SPAWN_START);- expect(firstGateIdx, 'the max-spawns gate must exist').toBeGreaterThan(-1);- expect(defIdx, 'cleanupOnError must be defined before the first gate').toBeLessThan(firstGateIdx);- });-- // The state cleanupOnError releases is acquired at different points, so each- // release is guarded on its own flag. Without the guards, the max-spawns gate- // — which runs before an agent id exists — would release a lane nobody took.- it('guards each release on the thing having actually been acquired', () => {- const start = AGENT_LIFECYCLE_SRC.indexOf('const cleanupOnError =', RUN_SPAWN_START);- const body = AGENT_LIFECYCLE_SRC.slice(start, start + 1400);- expect(body).toMatch(/if \(laneAcquired\) release\(agentId\);/);- expect(body).toMatch(/if \(toolExecution\) \{[\s\S]{0,200}?errorExecution\(toolExecution\.id/);- expect(body).toMatch(/if \(claimAcquired\) \{/);- expect(RUN_SPAWN_BODY).toMatch(/laneAcquired = true;/);+ it('guards each release on the acquired resource', () => {+ const body = AGENT_SPAWN_PREPARATION_SRC;+ expect(body).toMatch(/if \(context\.laneAcquired\) release\(context\.agentId\);/);+ expect(body).toMatch(/if \(context\.toolExecution\) \{[\s\S]{0,200}?errorExecution\(context\.toolExecution\.id/);+ expect(body).toMatch(/if \(context\.claimAcquired\) \{/);+ expect(body).toMatch(/context\.laneAcquired = true;/);});});@@ -674,43 +652,29 @@ describe('runAgentSpawn source — app-review marker release (issue #989)', () =// parameterized helper is what makes each gate's behavior assertable, so pin// that the collapse holds: a tenth gate must reuse the helper, not paste a// tenth copy.-describe('runAgentSpawn source — one block-and-bail epilogue', () => {+describe('agent spawn preparation — one block-and-bail epilogue', () => {it('writes the blocked status in exactly one place', () => {- const blockWrites = RUN_SPAWN_BODY.match(/status: 'blocked'/g) || [];- expect(blockWrites.length, 'only blockAndBail may persist a blocked status').toBe(1);- expect(RUN_SPAWN_BODY).toMatch(- /const blockAndBail = async \(\{ reason, category, infrastructureCode, emit = 'agent:error', emitPayload = \{\}, persist = true \}\) => \{/- );+ const blockWrites = AGENT_SPAWN_OWNER_SRC.match(/status: 'blocked'/g) || [];+ expect(blockWrites).toHaveLength(1);+ expect(AGENT_SPAWN_PREPARATION_SRC).toContain('context.blockAndBail = async');});- // The block write itself frees the federation lease (updateTask strips the- // claim on any non-`in_progress` status change). Releasing FIRST would open a- // window where a peer could claim and start the task, then have its live- // `in_progress` record clobbered to `blocked` — which outranks `in_progress`- // in the claim-aware merge. One helper means one ordering to get right.- it('persists the block BEFORE releasing the lease', () => {- const start = RUN_SPAWN_BODY.indexOf('const blockAndBail =');- expect(start, 'blockAndBail must exist').toBeGreaterThan(-1);- const body = RUN_SPAWN_BODY.slice(start, RUN_SPAWN_BODY.indexOf('\n };', start));+ it('persists the block before releasing the lease', () => {+ const body = AGENT_SPAWN_PREPARATION_SRC;const persistIdx = body.indexOf("status: 'blocked'");- const cleanupIdx = body.indexOf('await cleanupOnError(reason)');+ const cleanupIdx = body.indexOf('await context.cleanupOnError(reason)');expect(persistIdx).toBeGreaterThan(-1);expect(cleanupIdx).toBeGreaterThan(-1);- expect(persistIdx, 'the block write must precede the lease release').toBeLessThan(cleanupIdx);- // …and the announcement comes last, after the state is settled.+ expect(persistIdx).toBeLessThan(cleanupIdx);expect(body.indexOf("cosEvents.emit('agent:error'")).toBeGreaterThan(cleanupIdx);});- // A fail-closed content outcome must not raise an investigator; a runaway- // respawn is a standing decision and raises neither. Both are one word now.- it('supports the three announcement modes the gates actually differ on', () => {- const start = RUN_SPAWN_BODY.indexOf('const blockAndBail =');- const body = RUN_SPAWN_BODY.slice(start, RUN_SPAWN_BODY.indexOf('\n };', start));- expect(body).toMatch(/if \(emit === 'agent:error'\) \{/);- expect(body).toMatch(/\} else if \(emit === 'warn-log'\) \{/);- expect(body).toMatch(/emitLog\('warn', `Public review withheld for task \$\{task\.id\}: \$\{category\}`/);- // 'none' is the absence of a branch — pin the one caller that relies on it.- expect(RUN_SPAWN_BODY).toMatch(/category: 'max-spawns',\s*emit: 'none',/);+ it('supports the three announcement modes the gates differ on', () => {+ const body = AGENT_SPAWN_PREPARATION_SRC;+ expect(body).toMatch(/if \(emit === 'agent:error'\)/);+ expect(body).toMatch(/\} else if \(emit === 'warn-log'\)/);+ expect(body).toMatch(/emitLog\('warn', `Public review withheld for task \$\{context\.task\.id\}: \$\{category\}`/);+ expect(body).toMatch(/category: 'max-spawns',\s*emit: 'none',/);});});@@ -723,20 +687,20 @@ describe('runAgentSpawn source — one block-and-bail epilogue', () => {// lease is released, so a federated peer can't be clobbered.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)');+ const idx = AGENT_SPAWN_DISPATCH_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_SPAWN_DISPATCH_SRC.slice(idx, idx + 2000);// `persist` carries what used to be an `if (resolution.permanent)` wrapper// around a hand-copied block write: a transient failure stays pending, a// permanent one is blocked. Same decision, one line, one epilogue.expect(body, 'gates the block on resolution.permanent').toMatch(/persist:\s*resolution\.permanent,/);- expect(body, 'routes through the shared epilogue').toMatch(/return blockAndBail\(\{/);+ expect(body, 'routes through the shared epilogue').toMatch(/return context\.blockAndBail\(\{/);// The category is the SHARED constant, not a hand-written literal: the pause// and reaper-exemption sets in lib/taskBlockCategories.js key on the same// value, and a stamp-site literal is exactly how those three drift apart.expect(body, 'tags the block category from the shared constant').toMatch(/category:\s*PROVIDER_CONFIG_BLOCKED_CATEGORY,/);expect(body, 'does not re-hardcode the literal').not.toMatch(/'provider-config'/);- expect(AGENT_LIFECYCLE_SRC, 'imports the shared constant').toMatch(/import \{[^}]*PROVIDER_CONFIG_BLOCKED_CATEGORY[^}]*\} from '\.\.\/lib\/taskBlockCategories\.js'/);+ expect(AGENT_SPAWN_DISPATCH_SRC, 'imports the shared constant').toMatch(/import \{[^}]*PROVIDER_CONFIG_BLOCKED_CATEGORY[^}]*\} from '\.\.\/lib\/taskBlockCategories\.js'/);// The provider identity rides the agent:error event, so the investigator// names which provider failed rather than only the message.expect(body).toMatch(/emitPayload: \{[\s\S]{0,300}?resolution\.providerId[\s\S]{0,200}?resolution\.providerStatus/);@@ -757,11 +721,11 @@ describe('runAgentSpawn source — permanent provider-config failure blocks the// "one block-and-bail epilogue" above. What is left to pin here is that this// path still goes through it rather than re-inlining its own write.it('blocks through the shared epilogue, which persists before releasing the lease', () => {- const idx = AGENT_LIFECYCLE_SRC.indexOf('const resolution = await resolveAgentProviderAndModel(task)');- const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + 2000);+ const idx = AGENT_SPAWN_DISPATCH_SRC.indexOf('const resolution = await resolveAgentProviderAndModel(task)');+ const body = AGENT_SPAWN_DISPATCH_SRC.slice(idx, idx + 2000);expect(body, 'no hand-rolled block write on this path').not.toMatch(/status:\s*'blocked'/);expect(body, 'no hand-rolled lease release on this path').not.toMatch(/await cleanupOnError\(/);- expect(body).toMatch(/if \(!resolution\.ok\) \{[\s\S]{0,1200}?return blockAndBail\(\{/);+ expect(body).toMatch(/if \(!resolution\.ok\) \{[\s\S]{0,1200}?return context\.blockAndBail\(\{/);});});@@ -773,7 +737,7 @@ describe('runAgentSpawn source — permanent provider-config failure blocks the// same task. These orderings live inside runAgentSpawn with no behavioral seam.describe('runAgentSpawn source — instance provenance + claim ordering (#1563)', () => {it('imports the identity resolver from the instance identity leaf', () => {- expect(AGENT_LIFECYCLE_SRC).toMatch(+ expect(AGENT_SPAWN_PREPARATION_SRC).toMatch(/import\s*\{\s*ensureInstanceId\s*\}\s*from\s*'\.\/instanceIdentity\.js';/);});@@ -815,7 +779,7 @@ describe('runAgentSpawn source — instance provenance + claim ordering (#1563)'});it('stamps the federation claim into the in_progress task update', () => {- expect(AGENT_LIFECYCLE_SRC).toMatch(/\.\.\.buildClaim\(instanceId\)/);+ expect(AGENT_SPAWN_DISPATCH_SRC).toMatch(/\.\.\.buildClaim\(instanceId\)/);});it('acquires the claim (updateTask with buildClaim) BEFORE registering the agent', () => {@@ -846,10 +810,10 @@ describe('runAgentSpawn source — instance provenance + claim ordering (#1563)'});it('releases the claim on a failed-setup early exit (cleanupOnError)', () => {- const fnStart = AGENT_LIFECYCLE_SRC.indexOf('const cleanupOnError = async');- const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 1200);- expect(fnBody.indexOf('claimAcquired'), 'cleanupOnError must gate on claimAcquired').toBeGreaterThan(-1);- expect(fnBody.indexOf('buildRelease()'), 'cleanupOnError must release the claim via buildRelease').toBeGreaterThan(-1);+ const fnStart = AGENT_SPAWN_PREPARATION_SRC.indexOf('context.cleanupOnError = async');+ const fnBody = AGENT_SPAWN_PREPARATION_SRC.slice(fnStart, fnStart + 1200);+ expect(fnBody.indexOf('context.claimAcquired'), 'cleanup owner must gate on claimAcquired').toBeGreaterThan(-1);+ expect(fnBody.indexOf('buildRelease()'), 'cleanup owner must release the claim via buildRelease').toBeGreaterThan(-1);});it('stamps instanceId into the registerAgent metadata', () => {@@ -863,7 +827,7 @@ describe('runAgentSpawn source — instance provenance + claim ordering (#1563)'// recognises a claim run by its \`analysisType\`, which an inline// \`isTruthyMeta(task.metadata?.claimFlow)\` would silently drop. Hoisted to one// const because \`configCodingOnMain\` reads the same fact.- expect(AGENT_LIFECYCLE_SRC).toContain('const claimFlowTask = isClaimFlowTask(task, isTruthyMeta);');+ expect(AGENT_SPAWN_DISPATCH_SRC).toContain('const claimFlowTask = isClaimFlowTask(task, isTruthyMeta);');expect(AGENT_REGISTRATION_SRC).toContain('configClaimFlow: claimFlowTask');expect(AGENT_REGISTRATION_SRC.indexOf('configClaimFlow')).toBeGreaterThan(AGENT_REGISTRATION_SRC.indexOf('configOpenPR'));});diff --git a/server/services/agentSpawnDispatch.js b/server/services/agentSpawnDispatch.jsnew file mode 100644index 0000000000..66e36fae4e--- /dev/null+++ b/server/services/agentSpawnDispatch.js@@ -0,0 +1,310 @@+import { join } from 'path';+import { existsSync } from 'fs';+import { getConfig, updateTask } from './cos.js';+import { isPrivateSecurityTask } from '../lib/privateSecurityPolicy.js';+import { PROVIDER_CONFIG_BLOCKED_CATEGORY } from '../lib/taskBlockCategories.js';+import { ensureDir, PATHS, writeFileGuarded } from '../lib/fileUtils.js';+import { repoIssueUrlBase, resolveAppForgeTarget, resolveRepoForgeTarget } from '../lib/workTracker.js';+import { capturePrimaryCheckoutState } from '../lib/primaryCheckoutGuard.js';+import { buildAgentPrompt, getAppWorkspace, isClaimFlowTask, promptOpensOwnPr } from './agentPromptBuilder.js';+import { isOllamaClaudeProvider, isClaudeCommand } from '../lib/providerModels.js';+import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';+import { buildCliSpawnConfig, isClaudeCliProvider, isTuiProvider, getClaudeSettingsEnv, spawnDirectly } from './agentCliSpawning.js';+import { dropUnsupportedOllamaThinking } from './ollamaAgentContext.js';+import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';+import { publicReviewPostureForProfile, supportsTuiPublicReviewActionsProvider, PUBLIC_REVIEW_NO_TOOL_POSTURE } from '../lib/providerVendors.js';+import { checkPublicReviewSpawnPreconditions } from '../lib/publicReviewSpawnGate.js';+import { buildAgentRegistration, resolveExecutionMode } from '../lib/agentRegistrationRecord.js';+import { hasCredentialBootstrap } from '../lib/credentialBootstrap.js';+import { applyTaskGenerationOverrides } from '../lib/taskGenerationOverrides.js';+import { PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE } from '../lib/agentExecutionProfiles.js';+import { formatPublicReviewInputPrompt } from '../lib/modelAbuseGuard.js';+import { validatePublicReviewModel } from './modelAbuseGuard.js';+import { loadPublicReviewSpawnInput } from './publicReviewSpawnInput.js';+import { registerAgent } from './cosAgentLifecycle.js';+import { createAgentRun } from './agentRunTracking.js';+import { isTruthyMeta, useRunner } from './agentState.js';+import { cloudSwarmThreadCapacity, localEndpointOfProvider, providerBaseUrl } from './cosLocalEndpointSlots.js';+import { describeLocalPromptBudget, planLocalPromptBudget } from '../lib/localPromptBudget.js';+import { resolveAgentProviderAndModel } from './agentProviderResolution.js';+import { prepareAgentWorkspace } from './agentWorkspacePrep.js';+import { buildClaim } from './cosTaskClaim.js';+import { cosEvents, emitLog } from './cosEvents.js';++const ROOT_DIR = PATHS.root;+const AGENTS_DIR = PATHS.cosAgents;++export async function dispatchAgentRun(context, { spawnViaRunner } = {}) {+ const { task, agentId, laneName, toolExecution, instanceId } = context;+ const config = await getConfig();+ const resolution = await resolveAgentProviderAndModel(task);+ if (!resolution.ok) {+ return context.blockAndBail({+ reason: resolution.error,+ infrastructureCode: resolution.infrastructureCode,+ category: PROVIDER_CONFIG_BLOCKED_CATEGORY,+ persist: resolution.permanent,+ emitPayload: {+ ...(resolution.providerId && { providerId: resolution.providerId }),+ ...(resolution.providerStatus && { providerStatus: resolution.providerStatus }),+ },+ });+ }+ const { provider, selectedModel, modelSelection } = resolution;+ const privateSecurity = isPrivateSecurityTask(task);+ const executionProfile = task.metadata?.executionProfile;+ const publicReviewPosture = publicReviewPostureForProfile(executionProfile);+ const publicReviewNoTools = publicReviewPosture === PUBLIC_REVIEW_NO_TOOL_POSTURE;+ const publicReviewActions = executionProfile === PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE;+ const publicReview = Boolean(publicReviewPosture);+ const isTui = isTuiProvider(provider);+ const publicReviewTui = publicReviewActions && isTui+ && supportsTuiPublicReviewActionsProvider(provider);+ const spawnHeadless = !isTui || (publicReview && !publicReviewTui);+ const publicReviewBlock = await checkPublicReviewSpawnPreconditions({+ task,+ provider,+ selectedModel,+ publicReviewPosture,+ publicReview,+ publicReviewActions,+ publicReviewNoTools,+ privateSecurity,+ validateModel: validatePublicReviewModel,+ });+ if (publicReviewBlock) return context.blockAndBail(publicReviewBlock);+ const dispatchUseRunner = (publicReview || hasCredentialBootstrap(provider)) ? false : useRunner;+ let publicReviewPromptData = null;++ const prep = await prepareAgentWorkspace({ agentId, task });+ if (prep.outcome === 'deferred') {+ await context.cleanupOnError(prep.reason);+ cosEvents.emit('agent:deferred', { taskId: task.id, reason: prep.deferReason, branch: prep.branch });+ return null;+ }+ if (prep.outcome === 'blocked') {+ await context.cleanupOnError(prep.reason);+ cosEvents.emit('agent:error', { taskId: task.id, error: prep.reason });+ return null;+ }+ const { workspacePath, resolvedApp, resolvedAppName, worktreeInfo, jiraTicket, jiraBranchName, explicitWorktree } = prep;+ if (worktreeInfo?.branchName && !worktreeInfo.existingBranch && !worktreeInfo.isPersistentWorktree) {+ context.spawnWorktree = { branchName: worktreeInfo.branchName };+ }++ if (publicReview && !privateSecurity) {+ const reviewInput = await loadPublicReviewSpawnInput({+ scanKey: task.metadata?.pipeline?.reviewInputKey,+ workspacePath,+ actionsStage: publicReviewActions,+ eligibleNumbers: task.metadata?.pipeline?.eligibility?.eligibleNumbers,+ noToolReviewer: publicReviewNoTools,+ });+ if (reviewInput.block) return context.blockAndBail(reviewInput.block);+ publicReviewPromptData = reviewInput.promptData;+ }++ await import('./workspaceContext.js')+ .then((ws) => ws.snapshotOnRepoSwitch(task.metadata?.app || null))+ .catch((err) => {+ emitLog('warn', `Workspace auto-snapshot skipped for task ${task.id}: ${err?.message || err}`, { taskId: task.id });+ });++ const leanMode = isOllamaClaudeProvider(provider);+ const isLightContext = isTui || provider.type === PROVIDER_TYPES.CLI;+ const splitSystemPrompt = isLightContext && isClaudeCommand(provider.command);+ const privatePrompt = privateSecurity+ ? await import('./privateSecurityAssessment.js').then(({ preparePrivateSecurityAssessment }) => preparePrivateSecurityAssessment(task, provider, selectedModel))+ : null;+ const promptResult = privateSecurity ? privatePrompt : await buildAgentPrompt(task, config, workspacePath, worktreeInfo, isTruthyMeta, {+ providerType: provider.type,+ providerId: provider.id,+ providerCommand: provider.command,+ providerModel: selectedModel,+ agentId,+ leanMode,+ split: splitSystemPrompt,+ });+ const basePrompt = typeof promptResult === 'string' ? promptResult : promptResult.userPrompt;+ const prompt = publicReview && !privateSecurity+ ? `${basePrompt}\n\n${formatPublicReviewInputPrompt(publicReviewPromptData)}`+ : basePrompt;+ const systemPrompt = typeof promptResult === 'string' ? null : promptResult.systemPrompt;+ const requestedProvider = applyTaskGenerationOverrides(provider, task.metadata);+ const { provider: runProvider, effort: taskEffort } = await dropUnsupportedOllamaThinking(+ requestedProvider,+ selectedModel,+ requestedProvider.effort || null,+ );+ const localEndpoint = localEndpointOfProvider(provider);+ const localPromptBudget = localEndpoint+ ? planLocalPromptBudget({+ prompt,+ endpoint: localEndpoint,+ baseDurationMs: await import('./taskLearning.js')+ .then((tl) => tl.getTaskDurationEstimate(task.description, {+ providerId: provider.id,+ model: selectedModel,+ effort: taskEffort,+ }))+ .then((estimate) => estimate?.estimatedDurationMs ?? null)+ .catch(() => null),+ })+ : null;+ if (localPromptBudget?.longPrefill) {+ emitLog('info', `🐢 Agent ${agentId} ${describeLocalPromptBudget(localPromptBudget)}`, {+ agentId,+ taskId: task.id,+ promptTokens: localPromptBudget.promptTokens,+ });+ }++ const agentDir = join(AGENTS_DIR, agentId);+ if (!existsSync(agentDir)) {+ await ensureDir(agentDir);+ }+ await writeFileGuarded(join(agentDir, 'prompt.txt'), prompt);+ let systemPromptFile = null;+ if (systemPrompt) {+ systemPromptFile = join(agentDir, 'system-prompt.md');+ await writeFileGuarded(systemPromptFile, systemPrompt);+ }+ const { runId } = await createAgentRun({+ agentId,+ task,+ model: selectedModel,+ provider,+ workspacePath,+ appName: resolvedAppName,+ });+ const executionMode = resolveExecutionMode({ spawnHeadless, useRunner: dispatchUseRunner });+ const sourceWorkspace = worktreeInfo+ ? (task.metadata?.app ? await getAppWorkspace(task.metadata.app) : ROOT_DIR)+ : null;+ const prOpenedBy = promptOpensOwnPr(task, {+ providerType: provider.type,+ providerId: provider.id,+ providerCommand: provider.command,+ leanMode,+ worktreeInfo,+ isTruthyMetaFn: isTruthyMeta,+ });+ const claimFlowTask = isClaimFlowTask(task, isTruthyMeta);+ const [forgeTarget, primaryCheckoutBaseline] = await Promise.all([+ resolvedApp+ ? resolveAppForgeTarget(resolvedApp, { repoPath: workspacePath }).then(r => r.target)+ : resolveRepoForgeTarget(workspacePath),+ sourceWorkspace ? capturePrimaryCheckoutState(sourceWorkspace) : null,+ ]);+ await registerAgent(agentId, task.id, buildAgentRegistration({+ task,+ provider,+ instanceId,+ workspacePath,+ sourceWorkspace,+ repoIssueUrl: repoIssueUrlBase(forgeTarget),+ primaryCheckoutBaseline,+ worktreeInfo,+ explicitWorktree,+ jiraBranchName,+ providerEndpoint: providerBaseUrl(provider),+ localPromptBudget,+ leanMode,+ prOpenedBy,+ claimFlowTask,+ selectedModel,+ effort: taskEffort,+ modelSelection,+ runId,+ dispatchUseRunner,+ executionMode,+ publicReviewPosture,+ resolvedAppName,+ isTruthyMetaFn: isTruthyMeta,+ }));++ emitLog('info', `Agent ${agentId} initializing...${worktreeInfo ? ' (worktree)' : ''}${jiraBranchName ? ` (JIRA: ${jiraTicket?.ticketId})` : ''}`, { agentId, taskId: task.id });+ const newSpawnCount = (Number(task.metadata?.totalSpawnCount) || 0) + 1;+ const updateResult = await updateTask(task.id, {+ status: 'in_progress',+ metadata: {+ ...task.metadata,+ totalSpawnCount: newSpawnCount,+ lastSpawnedAt: new Date().toISOString(),+ ...buildClaim(instanceId),+ },+ }, task.taskType || 'user')+ .catch(err => {+ console.error(`❌ Failed to mark task ${task.id} as in_progress: ${err.message}`);+ return null;+ });+ if (updateResult?.error) {+ emitLog('warn', `⚠️ in_progress claim for task ${task.id} returned an error (taskType=${task.taskType}): ${updateResult.error}`, { taskId: task.id, error: updateResult.error });+ }+ if (!updateResult) {+ await context.cleanupOnError('Failed to update task status');+ return null;+ }++ if (task.metadata?.autonomousJob && task.metadata?.jobId) {+ cosEvents.emit('job:spawned', { jobId: task.metadata.jobId });+ }+ const cliSettingsEnv = !publicReview && isClaudeCliProvider(provider)+ ? await getClaudeSettingsEnv()+ : {};+ const maxConcurrentThreads = cloudSwarmThreadCapacity(runProvider, task.metadata?.swarmCount);+ const safetyProfile = publicReview ? executionProfile : null;+ const cliConfig = !spawnHeadless+ ? buildTuiSpawnConfig(runProvider, selectedModel, { systemPromptFile, effort: taskEffort, maxConcurrentThreads, safetyProfile })+ : buildCliSpawnConfig(runProvider, selectedModel, cliSettingsEnv, { systemPromptFile, effort: taskEffort, maxConcurrentThreads, safetyProfile });++ emitLog('success', `Spawning agent for task ${task.id}`, {+ agentId,+ model: selectedModel,+ mode: executionMode,+ cli: cliConfig.command,+ lane: laneName,+ worktree: !!worktreeInfo,+ });++ context.handedOff = true;+ if (!spawnHeadless) {+ return await spawnTuiAgent({+ agentId,+ task,+ prompt,+ workspacePath,+ model: selectedModel,+ provider: runProvider,+ runId,+ tuiConfig: cliConfig,+ agentDir,+ executionId: toolExecution.id,+ laneName,+ isTruthyMetaFn: isTruthyMeta,+ leanMode,+ prOpenedBy,+ useDurableRunner: dispatchUseRunner,+ safetyProfile,+ });+ }+ if (dispatchUseRunner) {+ return await spawnViaRunner(agentId, task, { prompt, workspacePath, model: selectedModel, provider: runProvider, runId, cliConfig, executionId: toolExecution.id, laneName });+ }+ return await spawnDirectly({+ agentId,+ task,+ prompt,+ workspacePath,+ model: selectedModel,+ provider: runProvider,+ runId,+ cliConfig,+ agentDir,+ executionId: toolExecution.id,+ laneName,+ isTruthyMetaFn: isTruthyMeta,+ prOpenedBy,+ safetyProfile,+ });+}diff --git a/server/services/agentSpawnPreparation.js b/server/services/agentSpawnPreparation.jsnew file mode 100644index 0000000000..55d7e6c9a2--- /dev/null+++ b/server/services/agentSpawnPreparation.js@@ -0,0 +1,165 @@+import { cosEvents, emitLog } from './cosEvents.js';+import { getTaskById, updateTask } from './cos.js';+import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';+import { isInternalTaskId } from '../lib/taskParser.js';+import { isRetryHeld } from '../lib/taskRetryHold.js';+import { createToolExecution, startExecution, completeExecution, errorExecution } from './toolStateMachine.js';+import { determineLane, acquire, release } from './executionLanes.js';+import { PATHS } from '../lib/fileUtils.js';+import { getAppWorkspace } from './agentPromptBuilder.js';+import { publicReviewPostureForProfile, PUBLIC_REVIEW_NO_TOOL_POSTURE } from '../lib/providerVendors.js';+import { ensureInstanceId } from './instanceIdentity.js';+import { isClaimableBy, buildClaim, buildRelease, getClaimOwner, getTargetInstance, isTargetedElsewhere } from './cosTaskClaim.js';+import { releaseAppReviewMarker } from './appActivity.js';+import { v4 as uuidv4 } from '../lib/uuid.js';++const ROOT_DIR = PATHS.root;++export function createAgentSpawnContext(task) {+ const context = {+ task,+ instanceId: null,+ agentId: null,+ laneName: null,+ toolExecution: null,+ laneAcquired: false,+ claimAcquired: false,+ spawnWorktree: null,+ handedOff: false,+ setupCatchArmed: false,+ };++ context.cleanupOnError = async (error) => {+ if (context.laneAcquired) release(context.agentId);+ if (context.toolExecution) {+ errorExecution(context.toolExecution.id, { message: error });+ completeExecution(context.toolExecution.id, { success: false });+ }+ if (context.claimAcquired) {+ await updateTask(context.task.id, { metadata: buildRelease() }, context.task.taskType || 'user').catch(() => {});+ }+ await releaseAppReviewMarker(context.task.metadata?.app).catch(err => {+ emitLog('warn', `Failed to release app review marker for ${context.task.metadata?.app}: ${err.message}`, { taskId: context.task.id });+ });+ if (context.spawnWorktree) {+ const { removeWorktree } = await import('./worktreeManager.js');+ const sourceWorkspace = context.task.metadata?.app+ ? await getAppWorkspace(context.task.metadata.app).catch(() => ROOT_DIR)+ : ROOT_DIR;+ await removeWorktree(context.agentId, sourceWorkspace, context.spawnWorktree.branchName, { discardDirt: true }).catch((cleanupErr) => {+ emitLog('warn', `Failed to remove the worktree of failed spawn ${context.agentId}: ${cleanupErr.message}`, { agentId: context.agentId, taskId: context.task.id });+ });+ }+ };++ context.blockAndBail = async ({ reason, category, infrastructureCode, emit = 'agent:error', emitPayload = {}, persist = true }) => {+ if (persist) {+ await updateTask(context.task.id, {+ status: 'blocked',+ metadata: {+ ...context.task.metadata,+ blockedReason: reason,+ blockedCategory: category,+ blockedAt: new Date().toISOString(),+ },+ }, context.task.taskType || 'user').catch(() => {});+ }+ await context.cleanupOnError(reason);+ if (emit === 'agent:error'+ && publicReviewPostureForProfile(context.task.metadata?.executionProfile) === PUBLIC_REVIEW_NO_TOOL_POSTURE+ && (infrastructureCode || category?.startsWith('public-review-model-') || category === 'public-review-provider-unsupported')) {+ const { reportReviewInfrastructureFailure } = await import('./reviewInfrastructureFailure.js');+ await reportReviewInfrastructureFailure({ code: infrastructureCode || category, task: context.task }).catch(() => {+ emitLog('warn', 'Could not report PR review infrastructure failure', { taskId: context.task.id });+ });+ emit = 'warn-log';+ }+ if (emit === 'agent:error') {+ cosEvents.emit('agent:error', { taskId: context.task.id, error: reason, ...emitPayload });+ } else if (emit === 'warn-log') {+ emitLog('warn', `Public review withheld for task ${context.task.id}: ${category}`, { taskId: context.task.id });+ }+ return null;+ };++ return context;+}++export async function prepareAgentSpawn(task, context = createAgentSpawnContext(task)) {+ if (task && !task.taskType) {+ task.taskType = isInternalTaskId(task.id || '') ? 'internal' : 'user';+ }++ let instanceId;+ try {+ instanceId = await ensureInstanceId();+ } catch (err) {+ emitLog('error', `Failed to resolve instance identity for task ${task.id}: ${err?.message || err}`, { taskId: task.id });+ return null;+ }+ context.instanceId = instanceId;+ if (isTargetedElsewhere(task.metadata, instanceId)) {+ console.log(`📍 Task ${task.id} is assigned to instance ${getTargetInstance(task.metadata)} — skipping spawn on ${instanceId}`);+ return null;+ }+ if (!isClaimableBy(task.metadata, instanceId)) {+ console.log(`🔒 Task ${task.id} is claimed by instance ${getClaimOwner(task.metadata)} (live lease) — skipping spawn on ${instanceId}`);+ return null;+ }++ const totalSpawns = Number(task.metadata?.totalSpawnCount) || 0;+ if (totalSpawns >= MAX_TOTAL_SPAWNS) {+ console.log(`🚫 Task ${task.id} hit max total spawns (${totalSpawns}/${MAX_TOTAL_SPAWNS}), blocking`);+ return context.blockAndBail({+ reason: `Max total spawns exceeded (${totalSpawns}/${MAX_TOTAL_SPAWNS})`,+ category: 'max-spawns',+ emit: 'none',+ });+ }++ context.agentId = `agent-${uuidv4().slice(0, 8)}`;+ context.laneName = determineLane(task);+ const laneResult = acquire(context.laneName, context.agentId, { taskId: task.id });+ if (!laneResult.success) {+ emitLog('warn', `Failed to tag lane ${context.laneName}: ${laneResult.error}`, { taskId: task.id });+ await context.cleanupOnError(`Failed to tag lane ${context.laneName}`);+ return null;+ }+ context.laneAcquired = true;++ context.toolExecution = createToolExecution('agent-spawn', context.agentId, {+ taskId: task.id,+ lane: context.laneName,+ priority: task.priority,+ });+ startExecution(context.toolExecution.id);++ const freshTask = await getTaskById(task.id).catch(() => null);+ if (freshTask) {+ if (isRetryHeld(freshTask.metadata)) {+ console.log(`⏳ Task ${task.id} is held for its retry pointer — not spawning until cleanup releases it`);+ await context.cleanupOnError('retry held pending cleanup');+ return null;+ }+ if (isTargetedElsewhere(freshTask.metadata, instanceId)) {+ console.log(`📍 Task ${task.id} is assigned to instance ${getTargetInstance(freshTask.metadata)} — yielding on ${instanceId}`);+ await context.cleanupOnError('assigned to another instance');+ return null;+ }+ if (!isClaimableBy(freshTask.metadata, instanceId)) {+ console.log(`🔒 Task ${task.id} was claimed by instance ${getClaimOwner(freshTask.metadata)} during dispatch — yielding on ${instanceId}`);+ await context.cleanupOnError('claimed by another instance');+ return null;+ }+ const claimUpdate = await updateTask(task.id, {+ metadata: buildClaim(instanceId),+ }, task.taskType || 'user').catch(() => null);+ if (claimUpdate && !claimUpdate.error) {+ context.claimAcquired = true;+ task.metadata = claimUpdate.metadata;+ }+ }++ context.setupCatchArmed = true;+ return context;+}diff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex 1abb531197..c7ad91d432 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -1514,10 +1514,8 @@ describe('cos.js source — priority + capacity invariants', () => {it('agentLifecycle stamps the resolved endpoint onto the agent record (#4834)', () => {// Counting a running agent by provider id alone breaks when the provider is// edited or deleted while the agent still holds the GPU.- const LIFECYCLE_SRC = readFileSync(join(__dirname, 'agentLifecycle.js'), 'utf-8');- // Stamped through the SAME resolver the counter reads with, so writer and- // reader cannot drift on where a CLI provider records its daemon.- expect(LIFECYCLE_SRC).toMatch(/providerEndpoint:\s*providerBaseUrl\(provider\)/);+ const DISPATCH_SRC = readFileSync(join(__dirname, 'agentSpawnDispatch.js'), 'utf-8');+ expect(DISPATCH_SRC).toMatch(/providerEndpoint:\s*providerBaseUrl\(provider\)/);});it('forceSpawnTask refuses synchronously when the local endpoint is full (#4834)', () => {