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: collapse runAgentSpawn's eight block-and-bail epilogues into one helper (#6617)
[._.]/ Adam Eivy770d7af1280f
diff --git a/server/lib/README.md b/server/lib/README.mdindex 9b33ae6c4b..561efb3366 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -50,6 +50,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `agentOutputMarkers.js` | Status lines PortOS itself appends to an agent's output buffer: `SENTINEL_COMPLETION_MARKER` (the line `ingestDoneSentinel` writes just before the agent's `.agent-done` summary) plus `isAgentLifecycleLine(line)`/`stripLifecycleLines(lines)`, which match PortOS's telemetry on its actual message shapes rather than on a leading emoji (an agent's own summary may well start a line with `✅`). Pure — shared by the emitter (`services/agentTuiSpawning.js`) and by readers that must show only the agent's own words (notably the generated PR description). || `agentRunEvents.js` | CoS run lifecycle-event envelope (#4540) — pure half of the append-only ledger in `services/agentRunEventLog.js`. `AGENT_RUN_EVENT_KINDS` (closed vocabulary: spawned, handoff, output, reconnected, paused, resumed, interrupted, pr-verified, orphan-recovered, runner-recovered, finalized), `agentRunEventSchema` (Zod, `.strict()`), `buildRunEvent()` which redacts then mints a CONTENT-derived `eventId` (sha256 of the canonicalized envelope) so a redelivered lifecycle transition dedupes instead of double-counting, `redactRunEventData()` (drops prompt/description/output/result-class keys to a `{ redacted, chars }` stub, scrubs the home-dir prefix out of every remaining string via `scrubHomePath`, runs `redactOutput`, and caps string/array/key/depth per `RUN_EVENT_LIMITS`), and `projectRunStates()` — the clock-free fold that derives current run status from the ordered stream, so replay-after-restart and read-current-status are one code path. Unknown kinds fold as no-ops so a newer install's ledger replays on an older one. || `agentRunReconcile.js` | CoS run reconciliation (#4540) — pure diff between a ledger projection (`projectRunStates`) and the durable run record. Closed finding vocabulary `RUN_RECONCILE_FINDINGS` (`record-open`, `record-missing`, `verdict-mismatch`, `ledger-open`), `diffRunRecord()`, `reconcileRunRecords()` with a zero-filled per-kind summary, and `planRunRecordRepair()` — the metadata patch that closes a record the ledger proves is finished. Repairs are one-directional (ledger → record) by design: a record closed while the ledger missed the close is reported, never back-filled, so the stream stays an audit of the record rather than a copy of it. I/O half: `services/agentRunReconciler.js`. |+| `agentRegistrationRecord.js` | The `registerAgent` payload one spawn writes, projected from its task — `buildAgentRegistration({ task, provider, … })` plus `resolveExecutionMode({ spawnHeadless, useRunner })` (`direct` / `runner` / `tui` / `runner-tui`, replacing a nested ternary chain). `agent.metadata` is a HAND-PICKED projection of `task.metadata`, never a spread: every downstream reader (run cards, `perpetualRefillPlan`, `declaresNoCommitCriterion`, the quota-burn continuation, `featureAgents`) sees the agent record alone, so an unlisted field does not survive the spawn — which is how `quotaBurnStepId` shipped persisted but unprojected (#6406) while this list was maintained inline in a 900-line orchestrator. Pure and synchronous: `primaryCheckoutBaseline` and `providerEndpoint` arrive as VALUES (both were `await`/service calls inline) and `isTruthyMetaFn` is injected the way `inlinePrLifecycleSection` takes it, keeping this leaf out of the agent-state and local-endpoint graphs. || `agentScratchPaths.js` | Runtime scratch PortOS itself writes into an agent worktree and never commits — `PUBLIC_REVIEW_INPUT_FILENAME` / `PUBLIC_REVIEW_PATCH_DIRNAME` (the public-review bundle materialized by `services/modelAbuseGuard.js`), the `AGENT_SCRATCH_PATHS` list, prefix-aware `matchesScratchRoot(path, roots)` and `isAgentScratchPath(path)`. `classifyWorktreeDirt` (`services/worktreeManager.js`) subtracts these for EVERY caller and uses the same matcher for its per-call `ignoredPaths`, so a worktree holding only scratch reads as clean end to end — before this, it was preserved by `removeWorktree`, held by `reapMergedWorktrees`, filed as a repo-state recovery task, and dispatched to a branch-reconcile coordinator, forever. Only STATIC names live here; a run-scoped name like `.agent-done-<agentId>` (`agentSentinel.js`) is passed per call instead. || `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME`, `doneSentinelName(agentId)` → the per-instance filename `.agent-done-<agentId>` (worktree-less agents share one workspace, so a shared name lets concurrent runs clobber — and finalize on — each other's signal), `doneSentinelPath(workspacePath, agentId)` → the single path every producer and consumer resolves, + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. `extractSentinelPayloadFromTranscript(transcript, isPayload)` (async) is the third tier for programmatic-I/O types ONLY — scans the ANSI-stripped PTY transcript, newest balanced JSON block first, for a payload the model PRINTED instead of writing, and adopts it only if the owning hook's shape predicate accepts it (#3640). `PROGRAMMATIC_OUTPUT_COMPLETION_HEADING` names the briefing section that prints this run's absolute sentinel path — a task-type hook renders its prompt before spawn, so it points the agent at that section by name rather than at a filename it cannot know. || `persistentMind.js` | Pure persistent-CoS-mind runtime state: default-off durable shape, normalization, FIFO-message/self-wake selection, interrupted-wake requeue, accepted-route fingerprints/receipts, image-work rollback guard, bounded exponential backoff, watchdog staleness, and next-wake projection. |@@ -195,6 +196,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `pi.js` | Pi command identity, headless/TUI arguments, and positional prompt delivery. || `providerModels.js` | Provider model resolution sentinels + helpers (`CODEX_CONFIGURED_DEFAULT` / `ANTIGRAVITY_CONFIGURED_DEFAULT` / `GROK_CONFIGURED_DEFAULT` / `KIMI_CONFIGURED_DEFAULT`, `resolveCliModel`, `filterSelectableModels`, Bedrock/OpenCode model mappers, `localRuntimeNamespace(provider)` — the OpenCode namespace only when it names a LOCAL daemon, i.e. the composed "namespace and not a hosted gateway" test that `cliChildEnv.js`, `localProviderRuntime.js` and `providerVendors.js` all key on, `CODEX_OSS_LOCAL_PROVIDERS` / `CODEX_OSS_MIN_VERSION` / `codexOssLocalProvider` / `codexUnsupportedLocalRuntime` — the codex half of that same axis: which local runtimes Codex's `--local-provider` can serve, and which marked runtime it cannot, kept here beside the namespace they wrap so `providerPrerequisites.js` classifies a codex record without importing `codex.js` (the argv emitter, `buildCodexOssArgs`, stays there), `OPENCODE_PUBLIC_REVIEW_AGENT` — the read-only OpenCode agent a no-tool public-review stage runs as, kept in this leaf because `providerVendors.js` must not import `opencodeConfig.js`, `parseOpencodeConfigContent` — the shared "is this stored OPENCODE_CONFIG_CONTENT usable?" read — plus `opencodeConfigIsLocalOnly` / `opencodeProviderIsLocalOnly`, the ONE locality rule `providerVendors.js` (gate eligibility) and `cliChildEnv.js` (public-review env allowlist) must not disagree about: if eligibility says yes where the allowlist strips the config, the stage spawns against the user's own ~/.config/opencode with tools intact while still reporting an enforced tool-free gate, `normalizeClaudeModelId` / `resolveClaudeCliModel` — the Claude-argv chokepoint that rewrites a dotted first-party version (`claude-fable-5.1`) to the dashed id Claude Code actually serves before the Bedrock mapping runs, model-flag scan helpers incl. `stripBrokenModelFlags`, `isCodexProvider`, `isKimiProvider`, `isAntigravityProvider`, `isCursorProvider`) plus reasoning-effort helpers for the claude/codex/agy/cursor CLIs (`CLAUDE_EFFORT_LEVELS` / `CODEX_EFFORT_LEVELS` / `ANTIGRAVITY_EFFORT_LEVELS` / `CURSOR_EFFORT_LEVELS` / `EFFORT_LEVELS`, `effortLevelsForProvider`, `resolveCliEffort` — clamps an out-of-range effort to the nearest level the target CLI accepts rather than dropping it, so a value saved against a wider ladder survives a provider switch — `clampEffortToLadder` (that clamp over an explicit ladder; the client's own `resolveCliEffort` runs its published-field ladder through it), `hasEffortFlag`, `buildEffortArgs` — the one emitter of `--effort <level>` / `-c model_reasoning_effort=<level>`, and deliberately silent for cursor — and `foldCursorEffortIntoModel`, which carries a cursor level inside `--model` as Cursor’s own variant syntax (`gpt-5[effort=max]`) because `cursor-agent` has no `--effort` flag) plus codex startup-arg helpers (`CODEX_EFFORT_KEY`, `CODEX_UPDATE_CHECK_KEY`, `hasCodexUpdateCheckConfig`, `buildCodexStartupArgs` — the one emitter of `-c check_for_update_on_startup=false`, spread by every codex spawn builder to disable the blocking startup update modal) plus `PORTOS_CLI_CONFIG_KEYS` / `isPortosSuppliedConfigKey` — the exhaustive list of `-c <key>=<value>` config keys PortOS injects, read by the `cli-config-invalid` error analyzer to tell a rejected PortOS override apart from a bad line in the user's own CLI config file.; `isOpencodeLocalProvider` (the OpenCode-on-a-local-backend-or-gateway gate behind the OpenCode effort ladder) and `isCodexSubscriptionProvider` (the ChatGPT-subscription readiness key, housed here so the browser re-export skips `codexAccount.js`'s protocol tables) || `providerVendors.js` | `PROVIDER_VENDORS` — one row per coding-agent CLI/TUI vendor (claude/codex/antigravity/opencode/grok/kimi/cursor, plus a deliberately-incomplete legacy `gemini-cli` row), consumed by every dispatch site that used to hand-roll its own vendor if-chain across ~8 branches in 5 files (#3618): `applyCommandDefaults`/`prepareCliPrompt` (re-exported from `tuiHandshake.js`/`cliProviderArgs.js`), `buildVendorCliArgs`/`buildVendorSpawnConfig` (consumed by `cliProviderArgs.js#buildCliArgs` / `agentCliSpawning.js#buildCliSpawnConfig`), `inferTuiCommand` (re-exported from `tuiHandshake.js`), and `injectTuiModelAndEffort` — the shared antigravity-validates-the-pair-vs-everyone-else `--model`/`--effort` injection used by both `tuiHandshake.js#buildTuiInvocation` and `agentTuiSpawning.js#buildTuiSpawnConfig`, replacing a second copy of that split that had already drifted once before this file existed. Doesn't rewrite any vendor's argv-building logic — that stays in `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`/`codex.js`. Dependency-light on purpose, mirroring those files. |+| `publicReviewSpawnGate.js` | The ordered spawn-time preconditions a public-content review stage must clear before `runAgentSpawn` starts an agent for it — `checkPublicReviewSpawnPreconditions` returns the FIRST failing gate as `{ reason, category, emit }` (or null), running them in the order that is the contract: `publicReviewScanBlock` (the model-abuse scan cleared at least one PR), `publicReviewEligibilityBlock` (a complete eligibility verdict COVERING every PR the issue watcher saw — a partial gate is not a pass), `publicReviewProviderBlock` from `providerVendors.js` (the vendor row declares a maintained recipe for the requested posture; it owns the ordinary-task `null` posture, the re-derivation #5866 got wrong), then the model itself. `emit` tells the caller how to announce it: `warn-log` for the two fail-closed CONTENT gates, whose block must not raise an investigator that could retry the same unvalidated input, `agent:error` for a provider/model misconfiguration that should. `validateModel` is injected rather than imported — it is the one gate that probes a live runtime, so taking it as a parameter keeps this leaf out of the local-LLM graph and makes the gate ORDER testable with a stub. || `modelCapabilityTests.js` | Catalog + scoring for the CAPABILITY tests on `/models/performance` (run by `services/modelCapabilityTests.js`): `CAPABILITY_TESTS` (sandbox repair / image analysis / story outline / fiction scene / rhetoric evaluator, each gated on the capability badges the install catalog already shows), `applicabilityFor` + `applicableTests` (`applicable` / `not-applicable` / `unknown` — an UNCLAIMED capability is never a failure, and `null` capabilities mean the runtime reported none, which is distinct from `[]`), `scoreKeywords` + `VISION_FIXTURE_KEYWORDS` (required vs bonus terms, word-boundary matched with a negation guard so "no dog" doesn't score a dog), `scoreStoryBeats` + `HEROS_JOURNEY_BEATS` (coverage AND ordering, judged only over the beats present), `scoreSandboxRepair` (verdict from observed disk facts — editing the test instead of the module fails outright), `formatAgentEvent` (one agent stream frame → a transcript line), `rollUpVerdict`, and the verbatim `CAPABILITY_TEST_PROMPTS` / `SANDBOX_TASK_PROMPT` the consent gate shows. Pure, so any stored transcript can be re-scored with no provider call. || `modelPricing.js` | Per-model API billing rates for the /devtools/usage cost estimates — `resolveModelRates(providerId, model)` (exact → family regex → provider default → blended fallback, with a `matched` tier; also derives `cacheReadPer1M`/`cacheWritePer1M` from the input rate via per-family multipliers), `isFreeProvider` (ollama/lmstudio/`ollamaBacked`/localhost = free), `estimateCostUsd(tokensIn, tokensOut, rates, cache?)` — `tokensIn` is UNCACHED input; cache tiers are priced separately via the optional 4th arg — and `PRICING_AS_OF`. Informational only (PortOS runs on subscriptions); still excludes batch/long-context tiers. || `usageRange.js` | `resolveUsageRange({ period, from, to })` — pure period→inclusive-YYYY-MM-DD range resolution for the usage cost report (explicit dates win; `all` unbounded; default 7d). |@@ -407,6 +409,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `htmlToText.js` | Shared HTML → plain-text converter. `htmlToText(html, { extraEntities?, paragraphBreak?, collapseSpaces? })` — strips script/style/head/noscript blocks, converts `<br>`/block closes to newlines, strips remaining tags, decodes entities via `decodeXmlEntities`, collapses 3+ newlines, trims. Options preserve caller-specific output (Gmail: `paragraphBreak: '\n\n'` + `collapseSpaces`; SongBook import: defaults — space runs preserved for tab alignment). || `jsonExtract.js` | Pull JSON blocks out of LLM responses. `findBalancedBlocks` walks top-level blocks and stops at the first unbalanced one; `findAllBalancedBlocks` is the stack-based variant that scans past stray braces and returns nested blocks in closing order (reverse it for outermost-newest-first). || `taskParser.js` | Parse `TASKS.md` format. |+| `taskGenerationOverrides.js` | `applyTaskGenerationOverrides(provider, metadata)` — the per-RUN `temperature` / `thinking` / `effort` a task form or schedule entry pins, layered onto a COPY of the provider record (the saved record is shared by every other run; the child-env composer turns the copy into OpenCode’s dynamic `agent.build` config downstream). Every value arrives untrusted — a COS-TASKS.md round-trip hands back strings — so each override applies only when it validates, and an empty temperature field is absent rather than `0`, which would otherwise pin greedy decoding on a task whose author just cleared the box. || `cosTaskPrompt.js` | The CoS task prompt/note split (#4153) — `metadata.prompt` is the full agent-facing payload, `metadata.context` the one-line human note. `isPromptPayload(value)` is the single discriminator (a newline means it's a prompt, not a note), shared by the store's write path and the on-disk migration so they can't classify the same task differently. `getTaskPrompt(task)` prefers `metadata.prompt` and falls back to a legacy `metadata.context`; `getTaskContextNote(task)` returns the note only on an already-split task; `taskContextBlock(task)` renders both as one block so prompt templates (including customized ones) never see the split; `splitTaskPromptFields(metadata)` routes a multi-line `context` to `prompt` at CREATE time only. Pure, dependency-free. || `taskPauseHold.js` | The user-PAUSE hold — pure metadata helpers shared by the writer (`pauseAgent`), the reader (`resumeAgent`), and the clearer (`updateTask`). `AGENT_PAUSED_CATEGORY` is the `blockedCategory` a pause stamps; `PAUSE_METADATA_KEYS` names every key it writes; `pauseMetadata({agentId, pausedAt, workspacePath, runId})` arms it and `clearedPauseMetadata()` releases it (undefined-valued, so `updateTask` deletes rather than serializing `"null"`); `isAgentPausedTask(task)` / `isResumablePausedTask(task, agentId)` answer whether a pause is still live and whether it is THIS agent's. `updateTask` clears the whole set whenever the task leaves `blocked`, so a revive by any path (dedupe, cooldown expiry, manual unblock) can't leave a task running under a stale pause. Also carries the cycle-safe RELEASE adapter (#3730) `agentManagement.js` registers at load — `resolvePausedTaskResume(task)` hands `updateTask` the paused run's resume pointer before the write (so any un-block resumes on the preserved worktree, not just the Resume dialog) and `retirePausedAgent(agentId, taskId, branchName)` retires the paused record after it. || `taskBlockCategories.js` | The `blockedCategory` vocabulary — which blocks are the system's to clear and which are a person's, read by the pause logic, the failure reaper, and the investigation auto-retry so they can't drift into three literal sets. `PAUSED_BLOCKED_CATEGORIES` (paused until something outside the task changes — keeps the resume pointer), `USER_DECISION_BLOCKED_CATEGORIES` (user intent / open decision — the reaper's exemption), `NON_AUTO_RETRY_BLOCK_CATEGORIES` (their union — a completed investigation must never revive these), `TIMED_COOLDOWN_BLOCKED_CATEGORIES` (a timer clears these — the cooldown sweeper revives them, so block reporters stay quiet), `PROVIDER_CONFIG_BLOCKED_CATEGORY` (the shared literal the agent-spawn stamp site uses, so the stamp cannot drift from the two sets it belongs to). Pure. |diff --git a/server/lib/agentRegistrationRecord.js b/server/lib/agentRegistrationRecord.jsnew file mode 100644index 0000000000..4a2b0c3bde--- /dev/null+++ b/server/lib/agentRegistrationRecord.js@@ -0,0 +1,228 @@+/**+ * The agent record a spawn registers, projected from the task it is running.+ *+ * `agent.metadata` is a HAND-PICKED projection of `task.metadata`, never a+ * spread — every consumer downstream (the run cards, `perpetualRefillPlan`,+ * `declaresNoCommitCriterion`, the quota-burn continuation, `featureAgents`)+ * reads the agent record alone, so a field that is not listed here simply does+ * not survive the spawn. That is the whole reason this is one explicit literal+ * and not a merge: adding a task field is supposed to be a deliberate decision+ * about whether the agent needs it, and `quotaBurnStepId` shipped persisted but+ * unprojected (#6406) precisely because the list was being maintained inline in+ * the middle of a 900-line orchestrator.+ *+ * Pure and synchronous: everything it needs is already resolved by the caller.+ * `primaryCheckoutBaseline` and `providerEndpoint` arrive as VALUES rather than+ * being read here (both were `await`/service calls inline), and `isTruthyMetaFn`+ * is injected the same way `inlinePrLifecycleSection` takes it — which keeps+ * this leaf out of the agent-state and local-endpoint graphs.+ */++// From the module that DECLARES it, not the `validation.js` catch-all barrel:+// that barrel drags 123 modules into every suite this leaf reaches, for one+// pure helper (server/AGENTS.md, "Import scoping").+import { normalizeReviewers } from './reviewerConfig.js';+import { quotaBurnAgentMetadata } from './quotaBurnOrigin.js';++/**+ * How this run is dispatched, as one closed vocabulary rather than the nested+ * ternary chain it replaced: a headless run is `direct` or `runner`, and an+ * interactive PTY session is `tui` or `runner-tui`, with the `runner-` prefix+ * meaning the durable CoS runner owns the child instead of this process.+ */+export function resolveExecutionMode({ spawnHeadless, useRunner }) {+ if (spawnHeadless) return useRunner ? 'runner' : 'direct';+ return useRunner ? 'runner-tui' : 'tui';+}++/** The `registerAgent` payload for one spawn. See the module note above. */+export function buildAgentRegistration({+ task,+ provider,+ instanceId,+ workspacePath,+ sourceWorkspace,+ primaryCheckoutBaseline,+ worktreeInfo,+ explicitWorktree,+ jiraBranchName,+ providerEndpoint,+ localPromptBudget,+ leanMode,+ ownsPrWorkflow,+ claimFlowTask,+ selectedModel,+ modelSelection,+ runId,+ dispatchUseRunner,+ executionMode,+ publicReviewPosture,+ resolvedAppName,+ isTruthyMetaFn,+}) {+ return {+ instanceId,+ workspacePath,+ sourceWorkspace,+ // 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".+ primaryCheckoutBaseline,+ worktreeBranch: worktreeInfo?.branchName || null,+ isWorktree: !!worktreeInfo,+ isPersistentWorktree: !!worktreeInfo?.isPersistentWorktree,+ taskDescription: task.description,+ taskType: task.taskType,+ priority: task.priority,+ providerId: provider.id,+ // Persisted alongside the id because the cleanup path's `agentOwnsPR` gate+ // must derive from the SAME `canTypeSlashCommands` predicate the prompt used+ // to decide whether the agent opens its own PR (#3114). An id alone can't+ // answer that — a path-configured `claude` under a custom id is slashdo-+ // capable, and a lean `--bare` session is not.+ providerCommand: provider.command || null,+ // The endpoint this agent's inference actually lands on, stamped for the+ // same reason as the command above: the per-local-endpoint spawn cap+ // (#4834) must know which GPU a RUNNING agent is occupying, and an id+ // alone can't answer that once the provider record is edited or deleted+ // mid-run. Pre-#4834 agent records have no value here, so the counter+ // falls back to resolving the id against the live provider list.+ //+ // Resolved through the SAME helper the counter reads with, so writer and+ // reader can't drift — a CLI provider records its daemon in envVars or an+ // OpenCode config, not in `endpoint`. Stamped as the RAW url, never the+ // slot key: a slot key is null for a cloud provider, and stamping null+ // would re-open the mid-run-edit hole this exists to close.+ providerEndpoint,+ // What this run's prompt costs to prefill on a LOCAL endpoint, and the+ // duration estimate raised by it (#6117). `null` for a cloud provider and+ // for a run with nothing assembled to measure — the card must read that as+ // "no estimate", never as a small one, so it stays absent rather than 0.+ localPromptBudget,+ leanMode,+ // Whether THIS run's prompt told the agent to push, open, review, and merge+ // its own PR. Persisted rather than re-derived at cleanup time: the two+ // must agree exactly or PortOS double-fires `gh pr create`. A pre-upgrade+ // record has no value here, so cleanup falls back to the old+ // `canTypeSlashCommands` derivation — what those runs were prompted with.+ //+ // Stamped from `inlinePrLifecycleSection`, the SAME predicate that decided+ // whether the prompt above emitted the PR steps — NOT from `provider.type`+ // alone. Ownership depends on task shape too (read-only, no-code-output,+ // discard-worktree, JIRA/leave-open, and no-worktree runs are all told+ // PortOS owns the PR), and a provider-only stamp claimed ownership for+ // every one of them — routing a Creative Director reasoning run into the+ // did-you-open-it net, which then opened a PR for it and filed a HIGH+ // notification blaming the agent for skipping a step it was never given.+ ownsPrWorkflow,+ model: selectedModel,+ // The reasoning-effort override this run was dispatched with (null when the+ // task pinned none). Persisted next to the model because the Resume Agent+ // modal seeds its own effort select from here — without it a resume of an+ // effort-pinned run silently drops back to the provider default.+ effort: task.metadata?.effort || null,+ modelTier: modelSelection.tier,+ modelReason: modelSelection.reason,+ runId,+ phase: 'initializing',+ useRunner: dispatchUseRunner,+ executionMode,+ // The public-review posture this run executes under (null for an ordinary+ // task). Projected beside `executionMode` because the UI cannot otherwise+ // explain why the card has no "Open Shell" link: a public-review stage is+ // forced headless (`spawnHeadless` above) unless it is the sandboxed-+ // actions stage on a TUI provider whose vendor declares an attachable+ // recipe, so without this the card is indistinguishable from an agent+ // whose PTY failed to attach.+ publicReviewPosture,+ // Preserve privacy after the task becomes an archived agent.+ machineLocal: isTruthyMetaFn(task.metadata?.machineLocal),+ taskAnalysisType: task.metadata?.analysisType || null,+ taskReviewType: task.metadata?.reviewType || null,+ taskApp: task.metadata?.app || null,+ // Marks a run dispatched by an explicit "Run Now" (on-demand) trigger, so+ // the perpetual drain-on-completion refill (perpetualRefillPlan in cos.js)+ // continues a MANUAL drain in the user-initiated on-demand lane rather than+ // the auto-run-gated queue lane. `isTruthyMeta` accepts the boolean set at+ // spawn AND the string `"true"` a COS-TASKS.md round-trip yields.+ taskOnDemand: isTruthyMetaFn(task.metadata?.onDemand),+ // WHO asked for that on-demand run. `perpetualRefillPlan` needs it to tell+ // a human Run (which keeps draining) from an automated origin such as a+ // quota burn (which is one unit and stops).+ taskOnDemandOrigin: task.metadata?.onDemandOrigin || null,+ // The single PR a pr-reviewer run was narrowed to. Same hand-picked-projection+ // reason as the keys around it: perpetualRefillPlan must see from the AGENT+ // record that this run was scoped, or its untargeted re-issue silently widens+ // a per-row click back into a sweep of every open PR.+ taskTargetPullRequest: task.metadata?.targetPullRequest || null,+ // LI hand-off provenance (#2765): projected onto the agent so the completion+ // hook (recordTaskCompletion) can attribute the run's success/failure back to+ // the proposal's domain. agent.metadata is a hand-picked projection of+ // task.metadata (not a full spread), so this must be listed explicitly.+ taskLiProposal: task.metadata?.liProposal || null,+ // Quota-burn provenance. Same hand-picked-projection reason as+ // `taskLiProposal`: the runner listens for `agent:completed` and dispatches+ // the NEXT job in this family's burn plan when the previous one finishes,+ // so it must be able to tell a burn run from any other agent from the+ // agent record alone. Spread from the ONE block definition+ // (`lib/quotaBurnOrigin.js`) so every field that reaches disk reaches the+ // runner's continuation and the denial ledger — naming them here one at a+ // time is how `quotaBurnStepId` ended up persisted but unprojected (#6406).+ // Values are coerced on the way through: a COS-TASKS.md round-trip hands+ // every scalar back as a string.+ ...quotaBurnAgentMetadata(task.metadata),+ // Same reason as taskLiProposal — a hand-picked projection, so this must be+ // listed explicitly. `declaresNoCommitCriterion` (taskTypeHooks.js) reads it+ // to decide whether a run declared a commit criterion at all,+ // and taskLearning's history backfill re-processes the ARCHIVED agent shape+ // through that same predicate. Without the projection an archived+ // tracker-filing run (reference-watch/ux on a github/gitlab/jira app) looks+ // like a committing task during backfill, so its stale `validationPassed:+ // false` fossil survives the sanitizer (#3273). `?? null` — not `|| null` —+ // because `false` is the load-bearing value here.+ worktreeChangesExpected: task.metadata?.worktreeChangesExpected ?? null,+ taskAppName: resolvedAppName,+ selfImprovementType: task.metadata?.selfImprovementType || null,+ jobId: task.metadata?.jobId || null,+ missionName: task.metadata?.missionName || null,+ missionId: task.metadata?.missionId || null,+ jiraTicketId: task.metadata?.jiraTicketId || null,+ jiraTicketUrl: task.metadata?.jiraTicketUrl || null,+ jiraBranch: task.metadata?.jiraBranch || null,+ jiraInstanceId: task.metadata?.jiraInstanceId || null,+ jiraCreatePR: task.metadata?.jiraCreatePR ?? null,+ configOpenPR: isTruthyMetaFn(task.metadata?.openPR),+ // Claim prompts own their external claim/<item> worktree and forge+ // lifecycle even though CoS must keep configOpenPR/configUseWorktree off+ // to avoid provisioning a nested worktree. Preserve that distinction in+ // the run record so completion diagnostics cannot mistake the claim path+ // for the generic commit-only handoff.+ configClaimFlow: claimFlowTask,+ configSimplify: isTruthyMetaFn(task.metadata?.simplify),+ configReviewLoop: isTruthyMetaFn(task.metadata?.reviewLoop),+ configReviewers: normalizeReviewers(task.metadata),+ configUseWorktree: !!worktreeInfo,+ configWorktreeAutoDetected: !!worktreeInfo && !explicitWorktree,+ // A read-only run is given no worktree on purpose (agentWorkspacePrep) and+ // commits nothing, so it is not "coding on main" either. Projected as its own+ // key because the card has no other way to tell it from a commit-only handoff.+ configReadOnly: isTruthyMetaFn(task.metadata?.readOnly),+ // Coding on the default branch is the LEFTOVER posture: no CoS worktree, no+ // JIRA feature branch, no claim worktree of its own, and not read-only. Each+ // new branch-owning or non-committing flow has to be excluded here, or its+ // card wears a warning badge that is simply false — which is how every issue+ // claimed from the Issues page came to be badged "main" while the claim+ // command was working in its own `claim/<item>` worktree.+ configCodingOnMain: !worktreeInfo && !jiraBranchName && !claimFlowTask+ && !isTruthyMetaFn(task.metadata?.readOnly),+ // Feature-agent provenance must survive the in-memory runner handoff and+ // server restarts so featureAgents can clear currentAgentId and record the+ // run when the shared CoS lifecycle emits agent:completed.+ featureAgentId: task.metadata?.featureAgentId || null,+ featureAgentRun: isTruthyMetaFn(task.metadata?.featureAgentRun)+ };+}diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex cc2dab3f43..2b1c46602f 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -295,7 +295,19 @@ describe('deferred imports stay deferred (#6156)', () => {// and it pulls in nothing new (its only import, `generationModes.js`, was// already in every one of them). A leaf with nothing behind it to defer is the// tolerated shape. The allowance had drifted to ~30 again, so restore the ~1.5k.-const MAX_STATIC_INSTANTIATIONS = 98500;+//+// #6617 is that shape once more: collapsing `runAgentSpawn`'s eight hand-copied+// block-and-bail epilogues into one helper meant lifting the steps they were+// tangled with out of the orchestrator — `lib/publicReviewSpawnGate.js`,+// `lib/agentRegistrationRecord.js`, `lib/taskGenerationOverrides.js` and+// `services/publicReviewSpawnInput.js`. Measured 98,642 (+142 over main's+// 98,500): four modules appearing as +1 each in the closures that already+// reached `agentLifecycle.js`, pulling in nothing those closures lacked. The+// one edge that WOULD have been new — `agentRegistrationRecord.js` reaching+// `normalizeReviewers` through the 123-module `validation.js` catch-all — is+// narrowed to its declaring leaf, `reviewerConfig.js`, so it contributes+// nothing. Restore the ~1.5k allowance.+const MAX_STATIC_INSTANTIATIONS = 100000;const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);const serverTestFiles = (dir = SERVER_DIR, out = []) => {diff --git a/server/lib/index.js b/server/lib/index.jsindex b3cbfb755f..a27f11ae0a 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -202,6 +202,7 @@ export * from './providerPrerequisites.js';// collision check as flat exports.export * as providerVendors from './providerVendors.js';export * from './providerTranscriptUsage.js';+export * from './publicReviewSpawnGate.js';// Namespaced: reviewerConfig.js is re-exported flat by cosValidation.js (and so// by validation.js), so a flat `export *` here would trip the barrel's// duplicate-identifier collision check.@@ -290,6 +291,7 @@ export * from './agentGuard/index.js';export * from './agentOutputMarkers.js';export * from './agentRunEvents.js';export * from './agentRunReconcile.js';+export * from './agentRegistrationRecord.js';export * from './persistentMind.js';export * from './persistentMindCapabilities.js';export * from './persistentMindTrajectory.js';@@ -378,6 +380,7 @@ export * from './clientApiPaths.js';export * from './htmlToText.js';export * from './jsonExtract.js';export * from './taskParser.js';+export * from './taskGenerationOverrides.js';export * from './cosTaskPrompt.js';export * from './taskPauseHold.js';export * from './taskBlockCategories.js';diff --git a/server/lib/publicReviewSpawnGate.js b/server/lib/publicReviewSpawnGate.jsnew file mode 100644index 0000000000..a2ec949a6c--- /dev/null+++ b/server/lib/publicReviewSpawnGate.js@@ -0,0 +1,137 @@+/**+ * The spawn-time preconditions a public-content review stage must satisfy+ * before an agent is started for it.+ *+ * These four gates used to sit inline in `runAgentSpawn`, each followed by its+ * own hand-copied "block the task and bail" epilogue. Collecting them here+ * makes the ORDER the contract — the scan clears the input, the eligibility+ * gate names which pull requests may be touched, the vendor row must declare a+ * maintained recipe for the requested posture, and only then is the model+ * itself checked — instead of an ordering you have to reconstruct by reading+ * 180 lines of orchestrator.+ *+ * Every gate FAILS CLOSED: a stage whose preflight state is missing, partial,+ * or unrecognized is blocked, never spawned "optimistically". The two content+ * gates carry `emit: 'warn-log'` rather than `'agent:error'` because a+ * fail-closed safety outcome must not create an automatic investigator that+ * could retry the same unvalidated input; a provider/model misconfiguration is+ * an operator-visible failure and does raise one.+ *+ * `validateModel` is INJECTED rather than imported. The model check is the only+ * one of the four that touches a live runtime (it probes an Ollama catalog and+ * capability report), and importing that service here would drag the local-LLM+ * graph into a `lib/` leaf and invert the dependency direction this directory+ * exists to keep clean. Injecting it also makes the gate order testable on its+ * own, with a stub, rather than only through the spawn.+ */++import { publicReviewProviderBlock } from './providerVendors.js';+import { PUBLIC_REVIEW_NO_TOOL_POSTURE } from './agentExecutionProfiles.js';++const PUBLIC_REVIEW_SCAN_STATUSES = new Set(['passed', 'findings']);++/** Why this task's model-abuse scan does not clear it to spawn, or null. */+export function publicReviewScanBlock(task) {+ const scan = task?.metadata?.pipeline?.securityScan;+ const hasClearedPr = Number.isInteger(scan?.safePrCount) && scan.safePrCount > 0;+ if (scan?.completed === true && PUBLIC_REVIEW_SCAN_STATUSES.has(scan.status) && hasClearedPr) return null;++ if (scan?.completed === true && scan.status === 'findings' && !hasClearedPr) {+ return {+ reason: 'Public review withheld: the model-abuse scan cleared no pull requests',+ category: 'public-review-no-cleared-prs',+ };+ }+ return {+ reason: `Public review withheld: the model-abuse scan is incomplete${scan?.code ? ` (${scan.code})` : ''}`,+ category: 'public-review-security-scan-incomplete',+ };+}++/**+ * Why this task's eligibility gate does not clear it to take actions, or null.+ *+ * Demands COVERAGE, not merely a non-empty result: every pull request the issue+ * watcher saw must appear in `eligibleNumbers`, so a gate that silently skipped+ * one cannot pass as a complete verdict.+ */+export function publicReviewEligibilityBlock(task) {+ const eligibility = task?.metadata?.pipeline?.eligibility;+ const eligibleNumbers = Array.isArray(eligibility?.eligibleNumbers)+ ? eligibility.eligibleNumbers.filter((number) => Number.isInteger(number) && number > 0)+ : [];+ const expected = task?.metadata?.issueWatcher?.pullRequests;+ const expectedNumbers = Array.isArray(expected)+ ? expected.map((item) => item?.number).filter((number) => Number.isInteger(number) && number > 0)+ : [];+ const allowed = new Set(eligibleNumbers);+ const coverageMatches = expectedNumbers.length === eligibleNumbers.length+ && expectedNumbers.every((number) => allowed.has(number));+ if (eligibility?.complete === true && eligibleNumbers.length > 0 && coverageMatches) return null;+ if (eligibility?.complete === true && eligibleNumbers.length === 0) {+ return {+ reason: 'Public review withheld: the eligibility gate cleared no pull requests',+ category: 'public-review-no-eligible-prs',+ };+ }+ return {+ reason: 'Public review withheld: a complete eligibility gate result is required before actions',+ category: 'public-review-eligibility-incomplete',+ };+}++/**+ * The first spawn precondition this task fails, as+ * `{ reason, category, emit }`, or null when every one of them passes.+ *+ * `emit` names how the caller should announce the block: `'warn-log'` for a+ * fail-closed content outcome, `'agent:error'` for a misconfiguration worth an+ * investigator.+ *+ * An ORDINARY task (no execution profile, so `publicReviewPosture` is null)+ * passes straight through — `publicReviewProviderBlock` owns the+ * "no posture requested" case, which is what #5866 got wrong by re-deriving it+ * from a boolean support check.+ */+export async function checkPublicReviewSpawnPreconditions({+ task,+ provider,+ selectedModel,+ publicReviewPosture,+ publicReview,+ publicReviewActions,+ publicReviewNoTools,+ privateSecurity,+ validateModel,+} = {}) {+ if (publicReview && !privateSecurity) {+ const scanBlock = publicReviewScanBlock(task);+ if (scanBlock) return { ...scanBlock, emit: 'warn-log' };+ }+ if (publicReviewActions) {+ const eligibilityBlock = publicReviewEligibilityBlock(task);+ if (eligibilityBlock) return { ...eligibilityBlock, emit: 'warn-log' };+ }+ // One posture check for both stages. Eligibility is declared by the vendor+ // row and re-asserted HERE, at spawn time, because a schedule or API payload+ // can be edited without the browser: the picker is a convenience, never the+ // enforcement.+ const postureBlock = publicReviewProviderBlock(provider, publicReviewPosture);+ if (postureBlock) return { ...postureBlock, emit: 'agent:error' };++ if (publicReviewNoTools && !privateSecurity) {+ const modelPolicy = await validateModel({+ provider,+ model: selectedModel,+ posture: PUBLIC_REVIEW_NO_TOOL_POSTURE,+ });+ if (!modelPolicy.ok) {+ return {+ reason: `Public review model is unavailable or not tool-free (${modelPolicy.code})`,+ category: modelPolicy.code || 'public-review-model-unsupported',+ emit: 'agent:error',+ };+ }+ }+ return null;+}diff --git a/server/lib/taskGenerationOverrides.js b/server/lib/taskGenerationOverrides.jsnew file mode 100644index 0000000000..dff320d144--- /dev/null+++ b/server/lib/taskGenerationOverrides.js@@ -0,0 +1,41 @@+/**+ * Per-run generation controls a task may pin on top of its provider record.+ *+ * A task form or schedule entry can carry `temperature`, `thinking` and+ * `effort` for ONE dispatch. They are layered onto a copy of the provider here+ * rather than written back to it: the saved record is shared by every other+ * run, and the child-environment composer turns the copy into OpenCode's+ * dynamic `agent.build` config downstream.+ *+ * Every value arrives untrusted — a COS-TASKS.md round-trip hands back strings,+ * and the task form can submit an empty field — so each override applies only+ * when it validates, and an invalid one leaves the provider's own setting+ * alone rather than overwriting it with `NaN`/`undefined`.+ */++/** `thinking` values a provider record accepts, string forms included. */+const THINKING_VALUES = [true, false, 'true', 'false'];++/** The inclusive sampling-temperature range a provider record accepts. */+const MIN_TEMPERATURE = 0;+const MAX_TEMPERATURE = 2;++/**+ * `provider` with this task's valid generation overrides layered on top.+ *+ * An empty temperature field is treated as absent, not as 0 — `Number('')` is+ * 0, which would silently pin greedy decoding on a task whose author only+ * cleared the box.+ */+export function applyTaskGenerationOverrides(provider, metadata) {+ const temperature = metadata?.temperature === '' ? NaN : Number(metadata?.temperature);+ const thinking = metadata?.thinking;+ return {+ ...provider,+ ...(Number.isFinite(temperature) && temperature >= MIN_TEMPERATURE && temperature <= MAX_TEMPERATURE+ ? { temperature }+ : {}),+ ...(THINKING_VALUES.includes(thinking) ? { thinking } : {}),+ ...(typeof metadata?.effort === 'string' ? { effort: metadata.effort } : {}),+ };+}diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex c4adddcb9a..06c2cfb2d6 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -43,7 +43,7 @@ import { registerAgent, updateAgent, completeAgent } from './cosAgentLifecycle.j// paid to read one string. Same trap documented at agentWorktreeCleanup.js:562.import { getConfig, updateTask, getTaskById, getAgentRecord } from './cos.js';import { spawnAgentViaRunner, getRunnerHealth, classifyRunnerSpawnFailure, RUNNER_SPAWN_REFUSED, RUNNER_SPAWN_AMBIGUOUS } from './cosRunnerClient.js';-import { MAX_TOTAL_SPAWNS, normalizeReviewers } from '../lib/validation.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';@@ -59,17 +59,20 @@ import { buildAgentPrompt, getAppWorkspace, inlinePrLifecycleSection, isClaimFloimport { isOllamaClaudeProvider, isClaudeCommand, providerSuppliesGithubToken } from '../lib/providerModels.js';import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';import { prClaimWasVerified } from '../lib/prDisposition.js';-import { quotaBurnAgentMetadata } from '../lib/quotaBurnOrigin.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 { publicReviewProviderBlock, publicReviewPostureForProfile, supportsTuiPublicReviewActionsProvider, PUBLIC_REVIEW_NO_TOOL_POSTURE } from '../lib/providerVendors.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 { applyTaskGenerationOverrides } from '../lib/taskGenerationOverrides.js';import { PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE } from '../lib/agentExecutionProfiles.js';import { formatPublicReviewInputPrompt } from '../lib/modelAbuseGuard.js';-import { materializePublicReviewInput, materializePublicReviewPatches, readPublicReviewInputSnapshot, validatePublicReviewModel } from './modelAbuseGuard.js';+import { validatePublicReviewModel } from './modelAbuseGuard.js';+import { loadPublicReviewSpawnInput } from './publicReviewSpawnInput.js';import { releaseAppReviewMarker } from './appActivity.js';import { ensureInstanceId } from './instances.js';import { isClaimableBy, buildClaim, buildRelease, getClaimOwner, getTargetInstance, isTargetedElsewhere } from './cosTaskClaim.js';@@ -95,51 +98,6 @@ import { handleOrphanedTask } from './agentManagement.js';const ROOT_DIR = PATHS.root;const AGENTS_DIR = PATHS.cosAgents;-const PUBLIC_REVIEW_SCAN_STATUSES = new Set(['passed', 'findings']);--function publicReviewScanBlock(task) {- const scan = task?.metadata?.pipeline?.securityScan;- const hasClearedPr = Number.isInteger(scan?.safePrCount) && scan.safePrCount > 0;- if (scan?.completed === true && PUBLIC_REVIEW_SCAN_STATUSES.has(scan.status) && hasClearedPr) return null;-- if (scan?.completed === true && scan.status === 'findings' && !hasClearedPr) {- return {- reason: 'Public review withheld: the model-abuse scan cleared no pull requests',- category: 'public-review-no-cleared-prs',- };- }- return {- reason: `Public review withheld: the model-abuse scan is incomplete${scan?.code ? ` (${scan.code})` : ''}`,- category: 'public-review-security-scan-incomplete',- };-}--function publicReviewEligibilityBlock(task) {- const eligibility = task?.metadata?.pipeline?.eligibility;- const eligibleNumbers = Array.isArray(eligibility?.eligibleNumbers)- ? eligibility.eligibleNumbers.filter((number) => Number.isInteger(number) && number > 0)- : [];- const expected = task?.metadata?.issueWatcher?.pullRequests;- const expectedNumbers = Array.isArray(expected)- ? expected.map((item) => item?.number).filter((number) => Number.isInteger(number) && number > 0)- : [];- const allowed = new Set(eligibleNumbers);- const coverageMatches = expectedNumbers.length === eligibleNumbers.length- && expectedNumbers.every((number) => allowed.has(number));- if (eligibility?.complete === true && eligibleNumbers.length > 0 && coverageMatches) return null;- if (eligibility?.complete === true && eligibleNumbers.length === 0) {- return {- reason: 'Public review withheld: the eligibility gate cleared no pull requests',- category: 'public-review-no-eligible-prs',- };- }- return {- reason: 'Public review withheld: a complete eligibility gate result is required before actions',- category: 'public-review-eligibility-incomplete',- };-}--/*** Spawn an agent for a task.@@ -228,70 +186,40 @@ async function runAgentSpawn(task) {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`);- await updateTask(task.id, {- status: 'blocked',- metadata: {- ...task.metadata,- blockedReason: `Max total spawns exceeded (${totalSpawns}/${MAX_TOTAL_SPAWNS})`,- blockedCategory: 'max-spawns',- blockedAt: new Date().toISOString()- }- }, task.taskType || 'user').catch(() => {});- // Give up on this task — release the synthetic app-review marker so the app- // doesn't read "in review" forever (issue #989). No-op without metadata.app- // or when a real agent holds the marker.- await releaseAppReviewMarker(task.metadata?.app).catch(() => {});- return null;- }-- const 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 });- await releaseAppReviewMarker(task.metadata?.app).catch(() => {});- return null;- }-- // Create tool execution for state tracking- const toolExecution = createToolExecution('agent-spawn', agentId, {- taskId: task.id,- lane: laneName,- priority: task.priority- });- startExecution(toolExecution.id);-- // Set once the federation claim has been persisted (just below). cleanupOnError- // reads it to release the claim on any failed-setup early exit.+ // 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;-- // Helper to cleanup on early exit. Releases the dedup guard, 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` (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.// 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.- release(agentId);- errorExecution(toolExecution.id, { message: error });- completeExecution(toolExecution.id, { success: false });+ 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.@@ -311,6 +239,91 @@ async function runAgentSpawn(task) {}};+ /**+ * 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, 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') {+ 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@@ -400,35 +413,16 @@ async function runAgentSpawn(task) {// 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.- //- // Do this BEFORE cleanupOnError releases the federation lease, and while we- // still hold it: the block write itself frees the lease (updateTask strips- // the claim on any non-`in_progress` status change), so the terminal- // transition + lease release are one atomic write. Blocking AFTER the- // release would open a window where a federated peer could claim + start the- // task (e.g. with a working CLI provider) and then have its live- // `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.- if (resolution.permanent) {- await updateTask(task.id, {- status: 'blocked',- metadata: {- ...task.metadata,- blockedReason: resolution.error,- blockedCategory: PROVIDER_CONFIG_BLOCKED_CATEGORY,- blockedAt: new Date().toISOString()- }- }, task.taskType || 'user').catch(() => {});- }- await cleanupOnError(resolution.error);- cosEvents.emit('agent:error', {- taskId: task.id,- error: resolution.error,- ...(resolution.providerId && { providerId: resolution.providerId }),- ...(resolution.providerStatus && { providerStatus: resolution.providerStatus }),+ // Transient failures skip the block and stay pending to retry.+ return blockAndBail({+ reason: resolution.error,+ category: PROVIDER_CONFIG_BLOCKED_CATEGORY,+ persist: resolution.permanent,+ emitPayload: {+ ...(resolution.providerId && { providerId: resolution.providerId }),+ ...(resolution.providerStatus && { providerStatus: resolution.providerStatus }),+ },});- return null;}const { provider, selectedModel, modelSelection } = resolution;const privateSecurity = isPrivateSecurityTask(task);@@ -455,82 +449,23 @@ async function runAgentSpawn(task) {const publicReviewTui = publicReviewActions && isTui&& supportsTuiPublicReviewActionsProvider(provider);const spawnHeadless = !isTui || (publicReview && !publicReviewTui);- if (publicReview && !privateSecurity) {- const scanBlock = publicReviewScanBlock(task);- if (scanBlock) {- await updateTask(task.id, {- status: 'blocked',- metadata: {- ...task.metadata,- blockedReason: scanBlock.reason,- blockedCategory: scanBlock.category,- blockedAt: new Date().toISOString(),- },- }, task.taskType || 'user').catch(() => {});- await cleanupOnError(scanBlock.reason);- // This is an expected fail-closed safety outcome, not an agent/provider- // failure. Do not emit agent:error, which would create an automatic- // investigator and potentially retry the same unvalidated input.- emitLog('warn', `Public review withheld for task ${task.id}: ${scanBlock.category}`, { taskId: task.id });- return null;- }- }- if (publicReviewActions) {- const eligibilityBlock = publicReviewEligibilityBlock(task);- if (eligibilityBlock) {- await updateTask(task.id, {- status: 'blocked',- metadata: {- ...task.metadata,- blockedReason: eligibilityBlock.reason,- blockedCategory: eligibilityBlock.category,- blockedAt: new Date().toISOString(),- },- }, task.taskType || 'user').catch(() => {});- await cleanupOnError(eligibilityBlock.reason);- emitLog('warn', `Public review withheld for task ${task.id}: ${eligibilityBlock.category}`, { taskId: task.id });- return null;- }- }- // One posture check for both stages. Eligibility is declared by the vendor- // row and re-asserted HERE, at spawn time, because a schedule or API- // payload can be edited without the browser: the picker is a convenience,- // never the enforcement. The helper owns the "no posture requested" case,- // so an ordinary task (posture `null`) passes straight through (#5830).- const postureBlock = publicReviewProviderBlock(provider, publicReviewPosture);- if (postureBlock) {- const { reason, category } = postureBlock;- await updateTask(task.id, {- status: 'blocked',- metadata: {- ...task.metadata,- blockedReason: reason,- blockedCategory: category,- blockedAt: new Date().toISOString(),- },- }, task.taskType || 'user').catch(() => {});- await cleanupOnError(reason);- cosEvents.emit('agent:error', { taskId: task.id, error: reason });- return null;- }- if (publicReviewNoTools && !privateSecurity) {- const modelPolicy = await validatePublicReviewModel({ provider, model: selectedModel, posture: PUBLIC_REVIEW_NO_TOOL_POSTURE });- if (!modelPolicy.ok) {- const reason = `Public review model is unavailable or not tool-free (${modelPolicy.code})`;- await updateTask(task.id, {- status: 'blocked',- metadata: {- ...task.metadata,- blockedReason: reason,- blockedCategory: modelPolicy.code || 'public-review-model-unsupported',- blockedAt: new Date().toISOString(),- },- }, task.taskType || 'user').catch(() => {});- await cleanupOnError(reason);- cosEvents.emit('agent:error', { taskId: task.id, error: reason });- return null;- }- }+ // 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.@@ -559,55 +494,18 @@ async function runAgentSpawn(task) {}if (publicReview && !privateSecurity) {- const allowedPullRequestNumbers = publicReviewActions- ? task.metadata?.pipeline?.eligibility?.eligibleNumbers- : null;- const materialized = await materializePublicReviewInput({- scanKey: task.metadata?.pipeline?.reviewInputKey,- workspacePath,- allowedPullRequestNumbers,- });- const patchesMaterialized = !publicReviewActions || await materializePublicReviewPatches({+ // 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,- allowedPullRequestNumbers,- });- if (!materialized || !patchesMaterialized) {- const reason = 'The screened public-review input snapshot is unavailable or invalid';- await updateTask(task.id, {- status: 'blocked',- metadata: {- ...task.metadata,- blockedReason: reason,- blockedCategory: 'public-review-input-missing',- blockedAt: new Date().toISOString(),- },- }, task.taskType || 'user').catch(() => {});- await cleanupOnError(reason);- cosEvents.emit('agent:error', { taskId: task.id, error: reason });- return null;- }- publicReviewPromptData = await readPublicReviewInputSnapshot({- scanKey: task.metadata?.pipeline?.reviewInputKey,- allowedPullRequestNumbers,+ actionsStage: publicReviewActions,+ eligibleNumbers: task.metadata?.pipeline?.eligibility?.eligibleNumbers,+ noToolReviewer: publicReviewNoTools,});- if (!publicReviewPromptData) {- const reason = publicReviewNoTools- ? 'The screened public-review input could not be loaded for the no-tools reviewer'- : 'The screened public-review input could not be loaded for the final reviewer';- await updateTask(task.id, {- status: 'blocked',- metadata: {- ...task.metadata,- blockedReason: reason,- blockedCategory: 'public-review-input-missing',- blockedAt: new Date().toISOString(),- },- }, task.taskType || 'user').catch(() => {});- await cleanupOnError(reason);- cosEvents.emit('agent:error', { taskId: task.id, error: reason });- return null;- }+ if (reviewInput.block) return blockAndBail(reviewInput.block);+ publicReviewPromptData = reviewInput.promptData;}// Auto-snapshot the workspace context of the app CoS was last working in@@ -725,7 +623,7 @@ async function runAgentSpawn(task) {workspacePath,appName: resolvedAppName});- const executionMode = !spawnHeadless ? (dispatchUseRunner ? 'runner-tui' : 'tui') : dispatchUseRunner ? 'runner' : 'direct';+ const executionMode = resolveExecutionMode({ spawnHeadless, useRunner: dispatchUseRunner });// Register the agent with model info.//@@ -757,7 +655,9 @@ async function runAgentSpawn(task) {// `isTruthyMetaFn` argument — which is exactly the split that made a claim// run badge itself "main".const claimFlowTask = isClaimFlowTask(task, isTruthyMeta);- await registerAgent(agentId, task.id, {+ await registerAgent(agentId, task.id, buildAgentRegistration({+ task,+ provider,instanceId,workspacePath,sourceWorkspace,@@ -769,159 +669,26 @@ async function runAgentSpawn(task) {// worktree. Non-throwing: an unreadable checkout yields null, which the// detector reads as "nothing to check".primaryCheckoutBaseline: sourceWorkspace ? await capturePrimaryCheckoutState(sourceWorkspace) : null,- worktreeBranch: worktreeInfo?.branchName || null,- isWorktree: !!worktreeInfo,- isPersistentWorktree: !!worktreeInfo?.isPersistentWorktree,- taskDescription: task.description,- taskType: task.taskType,- priority: task.priority,- providerId: provider.id,- // Persisted alongside the id because the cleanup path's `agentOwnsPR` gate- // must derive from the SAME `canTypeSlashCommands` predicate the prompt used- // to decide whether the agent opens its own PR (#3114). An id alone can't- // answer that — a path-configured `claude` under a custom id is slashdo-- // capable, and a lean `--bare` session is not.- providerCommand: provider.command || null,- // The endpoint this agent's inference actually lands on, stamped for the- // same reason as the command above: the per-local-endpoint spawn cap- // (#4834) must know which GPU a RUNNING agent is occupying, and an id- // alone can't answer that once the provider record is edited or deleted- // mid-run. Pre-#4834 agent records have no value here, so the counter- // falls back to resolving the id against the live provider list.- //- // Resolved through the SAME helper the counter reads with, so writer and- // reader can't drift — a CLI provider records its daemon in envVars or an- // OpenCode config, not in `endpoint`. Stamped as the RAW url, never the- // slot key: a slot key is null for a cloud provider, and stamping null- // would re-open the mid-run-edit hole this exists to close.+ 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),- // What this run's prompt costs to prefill on a LOCAL endpoint, and the- // duration estimate raised by it (#6117). `null` for a cloud provider and- // for a run with nothing assembled to measure — the card must read that as- // "no estimate", never as a small one, so it stays absent rather than 0.localPromptBudget,leanMode,- // Whether THIS run's prompt told the agent to push, open, review, and merge- // its own PR. Persisted rather than re-derived at cleanup time: the two- // must agree exactly or PortOS double-fires `gh pr create`. A pre-upgrade- // record has no value here, so cleanup falls back to the old- // `canTypeSlashCommands` derivation — what those runs were prompted with.- //- // Stamped from `inlinePrLifecycleSection`, the SAME predicate that decided- // whether the prompt above emitted the PR steps — NOT from `provider.type`- // alone. Ownership depends on task shape too (read-only, no-code-output,- // discard-worktree, JIRA/leave-open, and no-worktree runs are all told- // PortOS owns the PR), and a provider-only stamp claimed ownership for- // every one of them — routing a Creative Director reasoning run into the- // did-you-open-it net, which then opened a PR for it and filed a HIGH- // notification blaming the agent for skipping a step it was never given.ownsPrWorkflow,- model: selectedModel,- // The reasoning-effort override this run was dispatched with (null when the- // task pinned none). Persisted next to the model because the Resume Agent- // modal seeds its own effort select from here — without it a resume of an- // effort-pinned run silently drops back to the provider default.- effort: task.metadata?.effort || null,- modelTier: modelSelection.tier,- modelReason: modelSelection.reason,+ claimFlowTask,+ selectedModel,+ modelSelection,runId,- phase: 'initializing',- useRunner: dispatchUseRunner,+ dispatchUseRunner,executionMode,- // The public-review posture this run executes under (null for an ordinary- // task). Projected beside `executionMode` because the UI cannot otherwise- // explain why the card has no "Open Shell" link: a public-review stage is- // forced headless (`spawnHeadless` above) unless it is the sandboxed-- // actions stage on a TUI provider whose vendor declares an attachable- // recipe, so without this the card is indistinguishable from an agent- // whose PTY failed to attach.publicReviewPosture,- // Preserve privacy after the task becomes an archived agent.- machineLocal: isTruthyMeta(task.metadata?.machineLocal),- taskAnalysisType: task.metadata?.analysisType || null,- taskReviewType: task.metadata?.reviewType || null,- taskApp: task.metadata?.app || null,- // Marks a run dispatched by an explicit "Run Now" (on-demand) trigger, so- // the perpetual drain-on-completion refill (perpetualRefillPlan in cos.js)- // continues a MANUAL drain in the user-initiated on-demand lane rather than- // the auto-run-gated queue lane. `isTruthyMeta` accepts the boolean set at- // spawn AND the string `"true"` a COS-TASKS.md round-trip yields.- taskOnDemand: isTruthyMeta(task.metadata?.onDemand),- // WHO asked for that on-demand run. `perpetualRefillPlan` needs it to tell- // a human Run (which keeps draining) from an automated origin such as a- // quota burn (which is one unit and stops).- taskOnDemandOrigin: task.metadata?.onDemandOrigin || null,- // The single PR a pr-reviewer run was narrowed to. Same hand-picked-projection- // reason as the keys around it: perpetualRefillPlan must see from the AGENT- // record that this run was scoped, or its untargeted re-issue silently widens- // a per-row click back into a sweep of every open PR.- taskTargetPullRequest: task.metadata?.targetPullRequest || null,- // LI hand-off provenance (#2765): projected onto the agent so the completion- // hook (recordTaskCompletion) can attribute the run's success/failure back to- // the proposal's domain. agent.metadata is a hand-picked projection of- // task.metadata (not a full spread), so this must be listed explicitly.- taskLiProposal: task.metadata?.liProposal || null,- // Quota-burn provenance. Same hand-picked-projection reason as- // `taskLiProposal`: the runner listens for `agent:completed` and dispatches- // the NEXT job in this family's burn plan when the previous one finishes,- // so it must be able to tell a burn run from any other agent from the- // agent record alone. Spread from the ONE block definition- // (`lib/quotaBurnOrigin.js`) so every field that reaches disk reaches the- // runner's continuation and the denial ledger — naming them here one at a- // time is how `quotaBurnStepId` ended up persisted but unprojected (#6406).- // Values are coerced on the way through: a COS-TASKS.md round-trip hands- // every scalar back as a string.- ...quotaBurnAgentMetadata(task.metadata),- // Same reason as taskLiProposal — a hand-picked projection, so this must be- // listed explicitly. `declaresNoCommitCriterion` (taskTypeHooks.js) reads it- // to decide whether a run declared a commit criterion at all,- // and taskLearning's history backfill re-processes the ARCHIVED agent shape- // through that same predicate. Without the projection an archived- // tracker-filing run (reference-watch/ux on a github/gitlab/jira app) looks- // like a committing task during backfill, so its stale `validationPassed:- // false` fossil survives the sanitizer (#3273). `?? null` — not `|| null` —- // because `false` is the load-bearing value here.- worktreeChangesExpected: task.metadata?.worktreeChangesExpected ?? null,- taskAppName: resolvedAppName,- selfImprovementType: task.metadata?.selfImprovementType || null,- jobId: task.metadata?.jobId || null,- missionName: task.metadata?.missionName || null,- missionId: task.metadata?.missionId || null,- jiraTicketId: task.metadata?.jiraTicketId || null,- jiraTicketUrl: task.metadata?.jiraTicketUrl || null,- jiraBranch: task.metadata?.jiraBranch || null,- jiraInstanceId: task.metadata?.jiraInstanceId || null,- jiraCreatePR: task.metadata?.jiraCreatePR ?? null,- configOpenPR: isTruthyMeta(task.metadata?.openPR),- // Claim prompts own their external claim/<item> worktree and forge- // lifecycle even though CoS must keep configOpenPR/configUseWorktree off- // to avoid provisioning a nested worktree. Preserve that distinction in- // the run record so completion diagnostics cannot mistake the claim path- // for the generic commit-only handoff.- configClaimFlow: claimFlowTask,- configSimplify: isTruthyMeta(task.metadata?.simplify),- configReviewLoop: isTruthyMeta(task.metadata?.reviewLoop),- configReviewers: normalizeReviewers(task.metadata),- configUseWorktree: !!worktreeInfo,- configWorktreeAutoDetected: !!worktreeInfo && !explicitWorktree,- // A read-only run is given no worktree on purpose (agentWorkspacePrep) and- // commits nothing, so it is not "coding on main" either. Projected as its own- // key because the card has no other way to tell it from a commit-only handoff.- configReadOnly: isTruthyMeta(task.metadata?.readOnly),- // Coding on the default branch is the LEFTOVER posture: no CoS worktree, no- // JIRA feature branch, no claim worktree of its own, and not read-only. Each- // new branch-owning or non-committing flow has to be excluded here, or its- // card wears a warning badge that is simply false — which is how every issue- // claimed from the Issues page came to be badged "main" while the claim- // command was working in its own `claim/<item>` worktree.- configCodingOnMain: !worktreeInfo && !jiraBranchName && !claimFlowTask- && !isTruthyMeta(task.metadata?.readOnly),- // Feature-agent provenance must survive the in-memory runner handoff and- // server restarts so featureAgents can clear currentAgentId and record the- // run when the shared CoS lifecycle emits agent:completed.- featureAgentId: task.metadata?.featureAgentId || null,- featureAgentRun: isTruthyMeta(task.metadata?.featureAgentRun)- });+ resolvedAppName,+ isTruthyMetaFn: isTruthyMeta,+ }));emitLog('info', `Agent ${agentId} initializing...${worktreeInfo ? ' (worktree)' : ''}${jiraBranchName ? ` (JIRA: ${jiraTicket?.ticketId})` : ''}`, { agentId, taskId: task.id });@@ -987,16 +754,7 @@ async function runAgentSpawn(task) {// 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 taskTemperature = task.metadata?.temperature === '' ? NaN : Number(task.metadata?.temperature);- const taskThinking = task.metadata?.thinking;- const requestedProvider = {- ...provider,- ...(Number.isFinite(taskTemperature) && taskTemperature >= 0 && taskTemperature <= 2- ? { temperature: taskTemperature }- : {}),- ...([true, false, 'true', 'false'].includes(taskThinking) ? { thinking: taskThinking } : {}),- ...(typeof task.metadata?.effort === 'string' ? { effort: task.metadata.effort } : {}),- };+ 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,@@ -1093,16 +851,15 @@ async function runAgentSpawn(task) {const setupError = isPrivateSecurityTask(task)? 'Private assessment setup failed. Verify its local model, isolated harness, and source access before retrying.': err.message;- if (isPrivateSecurityTask(task)) {- await updateTask(task.id, {- status: 'blocked',- metadata: { ...task.metadata, blockedCategory: 'private-security-setup-failed',- blockedReason: setupError, blockedAt: new Date().toISOString() },- }, task.taskType || 'user').catch(() => {});- }emitLog('error', `Agent spawn setup failed: ${setupError}`, { taskId: task.id, error: setupError });- await cleanupOnError(setupError);- cosEvents.emit('agent:error', { 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({+ reason: setupError,+ category: 'private-security-setup-failed',+ persist: isPrivateSecurityTask(task),+ });// 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 cleardiff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.jsindex 51513e9fce..0045a3f765 100644--- a/server/services/agentLifecycle.test.js+++ b/server/services/agentLifecycle.test.js@@ -40,6 +40,15 @@ const AGENT_LIFECYCLE_SRC = readFileSync(join(__dirname, 'agentLifecycle.js'), '// so both spawners can import them without cycling back through the lifecycle// orchestrator. The source-level assertions below follow them there.const AGENT_FINALIZATION_SRC = readFileSync(join(__dirname, 'agentFinalization.js'), 'utf-8');+// The four public-review spawn preconditions moved out of the orchestrator+// (#6617) once their block-and-bail epilogues collapsed into one helper. The+// wiring assertions below follow them there.+const PUBLIC_REVIEW_SPAWN_GATE_SRC = readFileSync(join(__dirname, '../lib/publicReviewSpawnGate.js'), 'utf-8');+// The registerAgent projection — agent.metadata is a hand-picked map of+// task.metadata — moved out of the orchestrator with the same change (#6617).+// The projection-CONTENT guards below follow it; the ORDERING guards (claim+// before register, identity before register) stay on the orchestrator.+const AGENT_REGISTRATION_SRC = readFileSync(join(__dirname, '../lib/agentRegistrationRecord.js'), 'utf-8');function deferred() {let resolve;@@ -305,39 +314,61 @@ describe('agentLifecycle — guard wiring', () => {expect(AGENT_LIFECYCLE_SRC).toMatch(/import \{ isUpdateInProgress \} from '\.\/updateChecker\.js'/);});- it('fails closed before spawning when public-review security screening is incomplete', () => {- expect(AGENT_LIFECYCLE_SRC).toContain('public-review-security-scan-incomplete');- expect(AGENT_LIFECYCLE_SRC).toContain('public-review-no-cleared-prs');- expect(AGENT_LIFECYCLE_SRC).toContain('public-review-eligibility-incomplete');- // The provider-unsupported categories moved to `publicReviewProviderBlock`- // with the gate decision itself; their exact values are asserted there- // (providerVendors.publicReview.test.js).- expect(AGENT_LIFECYCLE_SRC).toMatch(/if \(scanBlock\) \{[\s\S]*?status: 'blocked'/);- expect(AGENT_LIFECYCLE_SRC).toMatch(/expected fail-closed safety outcome/);- const gateStart = AGENT_LIFECYCLE_SRC.indexOf('const scanBlock = publicReviewScanBlock(task)');- const gateEnd = AGENT_LIFECYCLE_SRC.indexOf('const postureBlock = publicReviewProviderBlock(provider, publicReviewPosture', gateStart);- expect(gateEnd).toBeGreaterThan(gateStart);- expect(AGENT_LIFECYCLE_SRC.slice(gateStart, gateEnd)).not.toContain("cosEvents.emit('agent:error'");+ // The four gates themselves moved to `lib/publicReviewSpawnGate.js`, and+ // WHAT each one decides is now behavior-tested at the spawn boundary+ // (agentLifecycle.blockAndBail.test.js) rather than grepped for here. What+ // 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(+ /import \{ checkPublicReviewSpawnPreconditions \} from '\.\.\/lib\/publicReviewSpawnGate\.js'/+ );+ expect(AGENT_LIFECYCLE_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);');+ // 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\(/);});// #5830 collapsed the two per-stage provider gates into one and dropped the// `publicReview &&` guard with them, so an ORDINARY task — posture `null`,// which no vendor declares a recipe for — was blocked at spawn with- // "has no enforced null public-content review mode". The decision now lives- // in `publicReviewProviderBlock` (unit-tested in+ // "has no enforced null public-content review mode". The decision lives in+ // `publicReviewProviderBlock` (unit-tested in// providerVendors.publicReview.test.js), which returns null for a task that- // requested no posture. Pin the call so the caller cannot re-derive it from a- // boolean support check and reintroduce the same collapse.+ // requested no posture. Pin the call at its new home so neither the gate nor+ // the caller can re-derive it from a boolean support check and reintroduce+ // the same collapse.it('asks the posture helper for the provider gate rather than re-deriving it', () => {- expect(AGENT_LIFECYCLE_SRC).toContain('const postureBlock = publicReviewProviderBlock(provider, publicReviewPosture)');- expect(AGENT_LIFECYCLE_SRC).toMatch(/if \(postureBlock\) \{[\s\S]*?status: 'blocked'/);- // The helper owns the blocked category too, so the gate cannot pick its own.- expect(AGENT_LIFECYCLE_SRC).toContain('const { reason, category } = postureBlock;');- // The reason text belongs to the helper — building it here means the gate- // decided for itself whether the posture was supported.+ expect(PUBLIC_REVIEW_SPAWN_GATE_SRC).toContain('const postureBlock = publicReviewProviderBlock(provider, publicReviewPosture);');+ // The helper owns the reason and the blocked category, so the gate cannot+ // pick its own — building either here means it decided for itself whether+ // the posture was supported.+ expect(PUBLIC_REVIEW_SPAWN_GATE_SRC).toContain("if (postureBlock) return { ...postureBlock, emit: 'agent:error' };");+ expect(PUBLIC_REVIEW_SPAWN_GATE_SRC).not.toContain('public-content review mode');+ expect(PUBLIC_REVIEW_SPAWN_GATE_SRC).not.toMatch(/supportsPublicReviewPosture\(/);expect(AGENT_LIFECYCLE_SRC).not.toContain('public-content review mode');expect(AGENT_LIFECYCLE_SRC).not.toMatch(/supportsPublicReviewPosture\(/);});++ // The two CONTENT gates fail closed, which is not an agent failure: raising+ // an investigator for one could retry the same unvalidated input. That+ // distinction is a one-word `emit` field now, so it is easy to "tidy" away —+ // pin it beside the categories it applies to.+ it('withholds public review with a warn log, never an agent:error', () => {+ expect(PUBLIC_REVIEW_SPAWN_GATE_SRC).toContain('public-review-security-scan-incomplete');+ expect(PUBLIC_REVIEW_SPAWN_GATE_SRC).toContain('public-review-no-cleared-prs');+ expect(PUBLIC_REVIEW_SPAWN_GATE_SRC).toContain('public-review-eligibility-incomplete');+ expect(PUBLIC_REVIEW_SPAWN_GATE_SRC).toContain("if (scanBlock) return { ...scanBlock, emit: 'warn-log' };");+ expect(PUBLIC_REVIEW_SPAWN_GATE_SRC).toContain("if (eligibilityBlock) return { ...eligibilityBlock, emit: 'warn-log' };");+ // The gate returns a verdict; it never announces one itself.+ expect(PUBLIC_REVIEW_SPAWN_GATE_SRC).not.toContain('cosEvents');+ });});// ─── Coverage guard for the self-update spawn gate (issue #4124) ────────────@@ -544,9 +575,13 @@ describe('runAgentSpawn source — handedOff pre-spawn vs post-handoff split', (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 cleanupOnError + re-emits job:spawn-failed for- // autonomous-job tasks so cos.js can clear its job-level guard.- expect(RUN_SPAWN_BODY).toMatch(/cleanupOnError\(setupError\)/);+ // 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(RUN_SPAWN_BODY).toMatch(/job:spawn-failed/);expect(RUN_SPAWN_BODY).toMatch(/task\.metadata\??\.jobId/);});@@ -567,8 +602,11 @@ describe('runAgentSpawn source — handedOff pre-spawn vs post-handoff split', (describe('runAgentSpawn source — durable TUI ownership (#3202)', () => {it('routes TUI providers through the runner when it is available', () => {expect(RUN_SPAWN_BODY).toMatch(- /const executionMode = !spawnHeadless \? \(dispatchUseRunner \? 'runner-tui' : 'tui'\)/+ /const executionMode = resolveExecutionMode\(\{ spawnHeadless, useRunner: dispatchUseRunner \}\);/);+ // The four modes themselves, at their new home.+ expect(AGENT_REGISTRATION_SRC).toMatch(/if \(spawnHeadless\) return useRunner \? 'runner' : 'direct';/);+ expect(AGENT_REGISTRATION_SRC).toMatch(/return useRunner \? 'runner-tui' : 'tui';/);expect(RUN_SPAWN_BODY).toMatch(/spawnTuiAgent\(\{[\s\S]{0,1000}?useDurableRunner:\s*dispatchUseRunner/);expect(RUN_SPAWN_BODY).not.toMatch(/useRunner:\s*isTui\s*\?\s*false\s*:\s*useRunner/);});@@ -577,15 +615,18 @@ describe('runAgentSpawn source — durable TUI ownership (#3202)', () => {// Source-level assertion (issue #989): the synthetic app-review marker bound by// `bindAppReviewAgent` before this spawn MUST be released on every// pre-completion `return null` path, or the app reads "in review" until the next-// daemon restart. The shared `cleanupOnError` closure owns the release for the-// detected-error paths + the pre-spawn catch arm; the two earliest returns-// (max-spawns block, lane-acquire failure) release inline before cleanupOnError-// is defined.+// daemon restart. `cleanupOnError` is the SINGLE owner of that release now+// (#6617) — it is defined before the first gate, so the two earliest returns+// (max-spawns block, lane-acquire failure) route through it too instead of+// hand-rolling their own release, which is how two of the eight copies came to+// 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 + 900);+ const body = AGENT_LIFECYCLE_SRC.slice(start, start + 1400);expect(body, 'cleanupOnError must release the app-review marker').toMatch(/releaseAppReviewMarker\(task\.metadata\?\.app\)/);@@ -598,11 +639,78 @@ describe('runAgentSpawn source — app-review marker release (issue #989)', () =expect(bareCalls, 'all cleanupOnError calls must be awaited').toEqual([]);});- it('the max-spawns and lane-acquire early returns release the marker inline', () => {+ 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);- const prefix = AGENT_LIFECYCLE_SRC.slice(RUN_SPAWN_START, defIdx);- const inlineReleases = prefix.match(/await releaseAppReviewMarker\(task\.metadata\?\.app\)/g) || [];- expect(inlineReleases.length, 'max-spawns + lane-acquire returns must each release inline').toBe(2);+ 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;/);+ });+});++// ─── runAgentSpawn — the ONE block-and-bail epilogue (issue #6617) ───────────+//+// Nine gates used to each carry their own copy of "persist blocked, clean up,+// announce, return null". They drifted — two announced with a warn log and two+// skipped the app-review-marker release — and the suite could not see it,+// because it grepped for `status: 'blocked'`. Collapsing them into one+// 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', () => {+ 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, emit = 'agent:error', emitPayload = \{\}, persist = true \}\) => \{/+ );+ });++ // 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, start + 1200);+ const persistIdx = body.indexOf("status: 'blocked'");+ const cleanupIdx = body.indexOf('await 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(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, start + 1200);+ 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',/);});});@@ -618,14 +726,20 @@ describe('runAgentSpawn source — permanent provider-config failure blocks theconst 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);- expect(body, 'gates the block on resolution.permanent').toMatch(/if\s*\(resolution\.permanent\)/);- expect(body, 'flips the task to blocked').toMatch(/status:\s*'blocked'/);+ // `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\(\{/);// 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(/blockedCategory:\s*PROVIDER_CONFIG_BLOCKED_CATEGORY,/);- expect(body, 'does not re-hardcode the literal').not.toMatch(/blockedCategory:\s*'provider-config'/);+ 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'/);+ // 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/);});// The block only does its job if the vocabulary module agrees it is a config@@ -638,14 +752,16 @@ describe('runAgentSpawn source — permanent provider-config failure blocks theexpect(USER_DECISION_BLOCKED_CATEGORIES.has(PROVIDER_CONFIG_BLOCKED_CATEGORY), 'never auto-expired to completed').toBe(true);});- it('blocks BEFORE releasing the lease so a federated peer cannot be clobbered', () => {+ // The ordering this used to assert at this one call site is now a property of+ // `blockAndBail`, which every gate shares — pinned once, in+ // "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 permanentIdx = body.indexOf('if (resolution.permanent)');- const cleanupIdx = body.indexOf('await cleanupOnError(resolution.error)');- expect(permanentIdx, 'permanent block must exist').toBeGreaterThan(-1);- expect(cleanupIdx, 'cleanupOnError must exist').toBeGreaterThan(-1);- expect(permanentIdx, 'block must precede the lease release').toBeLessThan(cleanupIdx);+ 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\(\{/);});});@@ -664,7 +780,7 @@ describe('runAgentSpawn source — instance provenance + claim ordering (#1563)'it('resolves instanceId via ensureInstanceId() before registering the agent', () => {const resolveIdx = RUN_SPAWN_BODY.indexOf('await ensureInstanceId()');- const registerIdx = RUN_SPAWN_BODY.indexOf('registerAgent(agentId, task.id, {');+ const registerIdx = RUN_SPAWN_BODY.indexOf('registerAgent(agentId, task.id, buildAgentRegistration({');expect(resolveIdx, '`await ensureInstanceId()` must exist inside runAgentSpawn').toBeGreaterThan(-1);expect(registerIdx, '`registerAgent(...)` must exist inside runAgentSpawn').toBeGreaterThan(-1);expect(resolveIdx, 'instanceId must be resolved BEFORE registerAgent is called').toBeLessThan(registerIdx);@@ -672,7 +788,7 @@ describe('runAgentSpawn source — instance provenance + claim ordering (#1563)'it("refuses to spawn a task under another instance's live lease (claim guard)", () => {const guardIdx = RUN_SPAWN_BODY.indexOf('isClaimableBy(task.metadata, instanceId)');- const registerIdx = RUN_SPAWN_BODY.indexOf('registerAgent(agentId, task.id, {');+ const registerIdx = RUN_SPAWN_BODY.indexOf('registerAgent(agentId, task.id, buildAgentRegistration({');expect(guardIdx, 'must gate the spawn on isClaimableBy').toBeGreaterThan(-1);expect(guardIdx, 'the claim guard must run BEFORE registering the agent').toBeLessThan(registerIdx);});@@ -684,7 +800,7 @@ describe('runAgentSpawn source — instance provenance + claim ordering (#1563)'it('refuses to spawn a task pinned to another instance, before the lease check', () => {const targetIdx = RUN_SPAWN_BODY.indexOf('isTargetedElsewhere(task.metadata, instanceId)');const leaseIdx = RUN_SPAWN_BODY.indexOf('isClaimableBy(task.metadata, instanceId)');- const registerIdx = RUN_SPAWN_BODY.indexOf('registerAgent(agentId, task.id, {');+ const registerIdx = RUN_SPAWN_BODY.indexOf('registerAgent(agentId, task.id, buildAgentRegistration({');expect(targetIdx, 'must gate the spawn on isTargetedElsewhere').toBeGreaterThan(-1);expect(targetIdx, 'the pin guard must run BEFORE the lease guard').toBeLessThan(leaseIdx);expect(targetIdx, 'the pin guard must run BEFORE registering the agent').toBeLessThan(registerIdx);@@ -704,7 +820,7 @@ describe('runAgentSpawn source — instance provenance + claim ordering (#1563)'it('acquires the claim (updateTask with buildClaim) BEFORE registering the agent', () => {const acquireIdx = RUN_SPAWN_BODY.indexOf('metadata: buildClaim(instanceId)');- const registerIdx = RUN_SPAWN_BODY.indexOf('registerAgent(agentId, task.id, {');+ const registerIdx = RUN_SPAWN_BODY.indexOf('registerAgent(agentId, task.id, buildAgentRegistration({');expect(acquireIdx, 'must acquire the claim via updateTask(buildClaim) up front').toBeGreaterThan(-1);expect(acquireIdx, 'claim must be acquired BEFORE registerAgent').toBeLessThan(registerIdx);});@@ -724,7 +840,7 @@ describe('runAgentSpawn source — instance provenance + claim ordering (#1563)'it('refuses to spawn a task whose retry is held for its resume pointer', () => {const rereadIdx = RUN_SPAWN_BODY.indexOf('await getTaskById(task.id)');const holdIdx = RUN_SPAWN_BODY.indexOf('isRetryHeld(freshTask.metadata)');- const registerIdx = RUN_SPAWN_BODY.indexOf('registerAgent(agentId, task.id, {');+ const registerIdx = RUN_SPAWN_BODY.indexOf('registerAgent(agentId, task.id, buildAgentRegistration({');expect(holdIdx, 'must check the retry hold on the fresh metadata').toBeGreaterThan(rereadIdx);expect(holdIdx, 'the hold guard must run BEFORE registering the agent').toBeLessThan(registerIdx);});@@ -737,26 +853,19 @@ describe('runAgentSpawn source — instance provenance + claim ordering (#1563)'});it('stamps instanceId into the registerAgent metadata', () => {- const registerIdx = AGENT_LIFECYCLE_SRC.indexOf('registerAgent(agentId, task.id, {');- const metaSlice = AGENT_LIFECYCLE_SRC.slice(registerIdx, registerIdx + 400);- expect(metaSlice).toMatch(/\binstanceId,/);- expect(metaSlice.indexOf('instanceId,')).toBeLessThan(metaSlice.indexOf('workspacePath'));+ expect(AGENT_REGISTRATION_SRC).toMatch(/\binstanceId,/);+ expect(AGENT_REGISTRATION_SRC.indexOf('instanceId,')).toBeLessThan(AGENT_REGISTRATION_SRC.indexOf('workspacePath,'));});it('records claimFlow separately from CoS-managed PR/worktree flags', () => {- const registerIdx = AGENT_LIFECYCLE_SRC.indexOf('registerAgent(agentId, task.id, {');- // Slice to the END of the call, not a fixed byte window: the projected keys- // sit near the bottom of a growing metadata object, so a magic-number window- // makes an unrelated comment above them read as a missing key.- const metaSlice = AGENT_LIFECYCLE_SRC.slice(registerIdx, AGENT_LIFECYCLE_SRC.indexOf('\n });', registerIdx));- expect(metaSlice).toContain('configOpenPR: isTruthyMeta(task.metadata?.openPR)');+ expect(AGENT_REGISTRATION_SRC).toContain('configOpenPR: isTruthyMetaFn(task.metadata?.openPR)');// Derived from \`isClaimFlowTask\`, not re-implemented inline: the predicate also// 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(metaSlice).toContain('configClaimFlow: claimFlowTask');- expect(metaSlice.indexOf('configClaimFlow')).toBeGreaterThan(metaSlice.indexOf('configOpenPR'));+ expect(AGENT_REGISTRATION_SRC).toContain('configClaimFlow: claimFlowTask');+ expect(AGENT_REGISTRATION_SRC.indexOf('configClaimFlow')).toBeGreaterThan(AGENT_REGISTRATION_SRC.indexOf('configOpenPR'));});it('projects the public-review posture so the UI can explain the missing shell link', () => {@@ -765,9 +874,9 @@ describe('runAgentSpawn source — instance provenance + claim ordering (#1563)'// attachable recipe (#6062) — so its card usually gets no "Open Shell"// link. Without this projection the card cannot tell that apart from a PTY// that failed to attach, and the run reads as wedged.- const registerIdx = RUN_SPAWN_BODY.indexOf('registerAgent(agentId, task.id, {');- const metaSlice = RUN_SPAWN_BODY.slice(registerIdx, RUN_SPAWN_BODY.indexOf('\n });', registerIdx));- expect(metaSlice).toMatch(/^\s*publicReviewPosture,$/m);+ expect(AGENT_REGISTRATION_SRC).toMatch(/^\s*publicReviewPosture,$/m);+ // …and the orchestrator still hands it over, so the key cannot go stale.+ expect(RUN_SPAWN_BODY).toMatch(/^\s*publicReviewPosture,$/m);});});@@ -919,9 +1028,8 @@ describe('runAgentSpawn source — local prompt/prefill budget (#6117)', () => {});it('stamps the budget onto the agent record so the card can explain the silence', () => {- const registerIdx = AGENT_LIFECYCLE_SRC.indexOf('registerAgent(agentId, task.id, {');- const metaSlice = AGENT_LIFECYCLE_SRC.slice(registerIdx, AGENT_LIFECYCLE_SRC.indexOf('\n });', registerIdx));- expect(metaSlice).toMatch(/\blocalPromptBudget,/);+ expect(AGENT_REGISTRATION_SRC).toMatch(/\blocalPromptBudget,/);+ expect(RUN_SPAWN_BODY).toMatch(/\blocalPromptBudget,/);});});@@ -934,12 +1042,13 @@ describe('runAgentSpawn source — local prompt/prefill budget (#6117)', () => {// `taskQuotaBurn*` key by hand here is the regression.describe('runAgentSpawn source — quota-burn provenance projection (#6406)', () => {it('spreads the shared provenance block instead of naming its keys', () => {- expect(AGENT_LIFECYCLE_SRC).toMatch(/\.\.\.quotaBurnAgentMetadata\(task\.metadata\)/);+ expect(AGENT_REGISTRATION_SRC).toMatch(/\.\.\.quotaBurnAgentMetadata\(task\.metadata\)/);+ expect(AGENT_REGISTRATION_SRC.match(/^\s*taskQuotaBurn\w*\s*:/gm) || []).toEqual([]);expect(AGENT_LIFECYCLE_SRC.match(/^\s*taskQuotaBurn\w*\s*:/gm) || []).toEqual([]);});});// Archive classification must survive the task-to-agent metadata projection.it('preserves the machine-local privacy marker in spawned agent metadata', () => {- expect(AGENT_LIFECYCLE_SRC).toContain('machineLocal: isTruthyMeta(task.metadata?.machineLocal)');+ expect(AGENT_REGISTRATION_SRC).toContain('machineLocal: isTruthyMetaFn(task.metadata?.machineLocal)');});diff --git a/server/services/publicReviewSpawnInput.js b/server/services/publicReviewSpawnInput.jsnew file mode 100644index 0000000000..6537d9845f--- /dev/null+++ b/server/services/publicReviewSpawnInput.js@@ -0,0 +1,65 @@+/**+ * Put the screened public-review input in front of one spawning reviewer.+ *+ * `modelAbuseGuard.js` owns the three primitives — materialize the snapshot+ * into a workspace, materialize the read-only patch files, read the snapshot+ * back — and the spawn orchestrator was performing that sequence inline, with+ * the blocked-status write hand-copied twice inside it. This is the sequence,+ * once, returning a verdict the caller's block-and-bail epilogue takes.+ *+ * Its own module rather than a fourth export of `modelAbuseGuard.js` so the+ * suites that already stub those three primitives keep driving the REAL+ * composition: a suite mocking `./modelAbuseGuard.js` wholesale would otherwise+ * replace this logic with a stub and assert nothing about the order.+ */++import {+ materializePublicReviewInput,+ materializePublicReviewPatches,+ readPublicReviewInputSnapshot,+} from './modelAbuseGuard.js';++/**+ * `{ promptData }` once the screened input is in place and readable, or+ * `{ block }` carrying the `{ reason, category, emit }` that refuses the spawn.+ *+ * Fails closed: a snapshot that is missing, unwritable, or unreadable blocks+ * the spawn rather than letting a reviewer start against nothing.+ */+export async function loadPublicReviewSpawnInput({+ scanKey,+ workspacePath,+ actionsStage = false,+ eligibleNumbers = null,+ noToolReviewer = false,+} = {}) {+ // The actions stage is the only one narrowed to specific pull requests; the+ // no-tool gate reads whatever the scan cleared.+ const allowedPullRequestNumbers = actionsStage ? eligibleNumbers : null;+ const materialized = await materializePublicReviewInput({ scanKey, workspacePath, allowedPullRequestNumbers });+ // Only the actions stage may apply a patch, so only it needs the files.+ const patchesMaterialized = !actionsStage+ || await materializePublicReviewPatches({ scanKey, workspacePath, allowedPullRequestNumbers });+ if (!materialized || !patchesMaterialized) {+ return {+ block: {+ reason: 'The screened public-review input snapshot is unavailable or invalid',+ category: 'public-review-input-missing',+ emit: 'agent:error',+ },+ };+ }+ const promptData = await readPublicReviewInputSnapshot({ scanKey, allowedPullRequestNumbers });+ if (!promptData) {+ return {+ block: {+ reason: noToolReviewer+ ? 'The screened public-review input could not be loaded for the no-tools reviewer'+ : 'The screened public-review input could not be loaded for the final reviewer',+ category: 'public-review-input-missing',+ emit: 'agent:error',+ },+ };+ }+ return { promptData };+}