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: one shared metadata-flag predicate, drop isTruthyMetaFn injection (#9158)
Adam Eivy6272f8021255
diff --git a/server/lib/README.md b/server/lib/README.mdindex a3519f5bfe..32ff6f0a5c 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -57,7 +57,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. |+| `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) 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), `doneSentinelCandidateNames(agentId)` → the canonical name plus the bounded one-character truncation recovery candidate for generated ids, `doneSentinelPath(workspacePath, agentId)` → the canonical path every producer resolves, `doneSentinelAgentId(filename)` → its inverse (`''` for the bare unscoped name, `null` for a non-sentinel), so the stale-sentinel sweep in `services/agentSentinelSweep.js` matches leftovers to runs the same way the producer named them, + 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. |@@ -73,6 +73,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `persistentMindPrompt.js` | Editable persistent-mind identity and operating-instructions schema/defaults; saving it never starts inference. || `persistentMindPlaybook.js` | Continuous-play / explore→interact→reflect→invent Persistent Mind operating modes and prompt framing. Pure. || `persistentMindPlaybookPhase.js` | Maturity-aware continuous-play phase picker (explore/construct/maintain/coordinate) from bounded Eidoverse world signals — density, recent failure rate, active peers. Pure. |+| `metadataFlags.js` | The one owner of the persisted metadata-boolean rule — `isTruthyMeta(v)` (`true`/`'true'` = set) and `isFalsyMeta(v)` (`false`/`'false'` = cleared); anything else is unset. TASKS.md round-trips flags as strings, so a bare `if (metadata.x)` is a bug. Pure leaf; import directly, never inject. || `mindBundleCrypto.js` | Persistent Mind portable-bundle container (#7621) — `sealMindBundle` / `openMindBundle` / `readMindBundleHeader`, scrypt-from-passphrase + AES-256-GCM with the cleartext header as AAD. Passphrase-derived, never `PRIVACY_VAULT_KEY`: that key is machine-bound and a bundle sealed with it could not open on the destination install. Format names live in `mindBundleFormat.js`. || `mindBundleFormat.js` | Mind bundle format vocabulary, free of node builtins so the browser reads the same definitions (`client/src/lib/mindBundle.js`) — magic/versions/extension, scrypt parameters, export scopes (`PERSISTENT_MIND_BUNDLE_SCOPES`), import groups and their source scopes (`PERSISTENT_MIND_BUNDLE_GROUPS`, `MIND_BUNDLE_GROUP_SCOPES`, `MIND_BUNDLE_GROUP_CHOICES`), size/passphrase bounds, and the named refusal reasons (`MIND_BUNDLE_REFUSALS`, `mindBundleRefusal`). || `mindLocalContextClamp.js` | RAM/GPU safety ceilings for mind-driven local `numCtx` adjustments (CPU-only tiers, free-RAM + PortOS headroom). Pure. |diff --git a/server/lib/agentRegistrationRecord.js b/server/lib/agentRegistrationRecord.jsindex 244034dcb6..909172756c 100644--- a/server/lib/agentRegistrationRecord.js+++ b/server/lib/agentRegistrationRecord.js@@ -1,3 +1,4 @@+import { isTruthyMeta } from './metadataFlags.js';import { processAuditRecoveryOriginSchema } from './persistentMindProcessAudit.js';/*** The agent record a spawn registers, projected from the task it is running.@@ -14,9 +15,8 @@ import { processAuditRecoveryOriginSchema } from './persistentMindProcessAudit.j** 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.+ * being read here (both were `await`/service calls inline), 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:@@ -61,7 +61,6 @@ export function buildAgentRegistration({executionMode,publicReviewPosture,resolvedAppName,- isTruthyMetaFn,}) {return {instanceId,@@ -91,7 +90,7 @@ export function buildAgentRegistration({worktreeBranch: worktreeInfo?.branchName || null,isWorktree: !!worktreeInfo,isPersistentWorktree: !!worktreeInfo?.isPersistentWorktree,- isRecovery: isTruthyMetaFn(task.metadata?.isRecovery),+ isRecovery: isTruthyMeta(task.metadata?.isRecovery),recoveryOrigin: processAuditRecoveryOriginSchema.safeParse(task.metadata?.recoveryOrigin).data || null,taskDescription: task.description,taskType: task.taskType,@@ -200,7 +199,7 @@ export function buildAgentRegistration({// which mysteriously stopped.resumedFromAgentId: task.metadata?.resumedFromAgentId || null,// Preserve privacy after the task becomes an archived agent.- machineLocal: isTruthyMetaFn(task.metadata?.machineLocal),+ machineLocal: isTruthyMeta(task.metadata?.machineLocal),taskAnalysisType: task.metadata?.analysisType || null,taskReviewType: task.metadata?.reviewType || null,taskApp: task.metadata?.app || null,@@ -209,7 +208,7 @@ export function buildAgentRegistration({// 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),+ 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).@@ -253,22 +252,22 @@ export function buildAgentRegistration({jiraBranch: task.metadata?.jiraBranch || null,jiraInstanceId: task.metadata?.jiraInstanceId || null,jiraCreatePR: task.metadata?.jiraCreatePR ?? null,- configOpenPR: isTruthyMetaFn(task.metadata?.openPR),+ 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: isTruthyMetaFn(task.metadata?.simplify),- configReviewLoop: isTruthyMetaFn(task.metadata?.reviewLoop),+ 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: isTruthyMetaFn(task.metadata?.readOnly),+ 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@@ -276,11 +275,11 @@ export function buildAgentRegistration({// 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),+ && !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: isTruthyMetaFn(task.metadata?.featureAgentRun)+ featureAgentRun: isTruthyMeta(task.metadata?.featureAgentRun)};}diff --git a/server/lib/agentRegistrationRecord.test.js b/server/lib/agentRegistrationRecord.test.jsindex 4fac8303d4..6f8d9861cd 100644--- a/server/lib/agentRegistrationRecord.test.js+++ b/server/lib/agentRegistrationRecord.test.js@@ -29,7 +29,6 @@ const args = (taskMetadata, provider = { id: 'claude', command: 'claude' }) => (executionMode: 'direct',publicReviewPosture: null,resolvedAppName: null,- isTruthyMetaFn: (v) => v === true || v === 'true',});describe('buildAgentRegistration — resume provenance', () => {diff --git a/server/lib/auditCatalog.js b/server/lib/auditCatalog.jsindex 7ef25cfd29..298a7d5725 100644--- a/server/lib/auditCatalog.js+++ b/server/lib/auditCatalog.js@@ -1,3 +1,4 @@+import { isTruthyMeta } from './metadataFlags.js';/*** Shared catalog of scheduled AUDIT task types — the ones that can either* implement a fix or just file tracker issues, matching the quota-burn@@ -629,7 +630,7 @@ export function auditDoWorkRequiresWorktree(taskType) {*/function explicitFileIssues(metadata) {const raw = metadata?.fileIssues;- if (raw === true || raw === 'true') return true;+ if (isTruthyMeta(raw)) return true;if (raw === false || raw === 'false') return false;return null;}diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.jsindex 20a245a69e..f2ea980816 100644--- a/server/lib/catalogValidation.js+++ b/server/lib/catalogValidation.js@@ -24,6 +24,7 @@ import { csvIdsParam } from './sharedSchemas.js';import { SCRAP_SOURCE_KIND_IDS } from './catalogSourceKinds.js';import { GENERATION_METADATA_LIMITS } from './pngMetadata.js';+import { isTruthyMeta } from './metadataFlags.js';// Derived from the shared type registry (`catalogTypes.js`) — adding a SYSTEM// type there flows through to consumers automatically. Kept as a frozen// re-export so existing `import { INGREDIENT_TYPES }` callers are unaffected.@@ -43,7 +44,7 @@ const ingredientTypeGate = z.string().trim().min(1).max(32)// boolean; anything else (including absent) collapses to undefined so an// `.optional()` field reads cleanly as "not set" rather than truthy-by-presence.const booleanish = z.preprocess((v) => {- if (v === true || v === 'true') return true;+ if (isTruthyMeta(v)) return true;if (v === false || v === 'false') return false;return undefined;}, z.boolean());diff --git a/server/lib/developmentWorkIdentity.js b/server/lib/developmentWorkIdentity.jsindex afedb38c56..ccedb9b1dc 100644--- a/server/lib/developmentWorkIdentity.js+++ b/server/lib/developmentWorkIdentity.js@@ -1,3 +1,4 @@+import { isTruthyMeta } from './metadataFlags.js';/** Structured work ownership shared by scheduler, manual actions and watchdog. */export const DEVELOPMENT_ACTIVE_STATUSES = new Set(['pending', 'queued', 'running', 'in_progress', 'finalizing', 'blocked', 'paused']);@@ -9,7 +10,7 @@ export function developmentWorkIdentity(task) {const match = url.match(/^https?:\/\/([^/]+)\/(.+?)\/(?:pull|merge_requests|\-\/merge_requests)\/(\d+)(?:[/?#]|$)/);if (match) return { app, key: `${match[1]}/${match[2]}/pr/${match[3]}`.toLowerCase(), kind: 'pr' };}- if (m.claimFlow === true || m.claimFlow === 'true' || ['claim-work', 'claim-issue', 'claim-issue-gitlab'].includes(m.taskAnalysisType)) {+ if (isTruthyMeta(m.claimFlow) || ['claim-work', 'claim-issue', 'claim-issue-gitlab'].includes(m.taskAnalysisType)) {return { app, kind: 'issue', key: m.claimTarget ? `issue/${m.claimTarget}` : '*' };}if ((m.analysisType || m.taskAnalysisType) === 'pr-watcher') return { app, kind: 'pr', key: '*' };diff --git a/server/lib/goalFidelity.js b/server/lib/goalFidelity.jsindex 86e4e8c743..3a53a60b6f 100644--- a/server/lib/goalFidelity.js+++ b/server/lib/goalFidelity.js@@ -23,6 +23,7 @@import { LOCAL_LLM_REVIEWERS, normalizeReviewerEffort, normalizeReviewerModel } from './reviewerConfig.js';import { taskContextBlock } from './cosTaskPrompt.js';+import { isTruthyMeta } from './metadataFlags.js';/*** The three answers the review may return, ordered least → most disruptive.*@@ -271,8 +272,7 @@ export function mergeOutcomeObjective(task) {const metadata = task?.metadata;if (!metadata || typeof metadata !== 'object') return null;// Stored Markdown metadata may carry booleans as strings.- const truthy = (value) => value === true || value === 'true';- if (!truthy(metadata.reviewLoopFollowUp) || truthy(metadata.reviewLoopLeaveOpen)) return null;+ if (!isTruthyMeta(metadata.reviewLoopFollowUp) || isTruthyMeta(metadata.reviewLoopLeaveOpen)) return null;const number = Number(metadata.reviewLoopPRNumber);const branch = typeof metadata.reviewLoopPRBranch === 'string' ? metadata.reviewLoopPRBranch.trim() : '';// Both are required: the number is what the forge is asked about, and thediff --git a/server/lib/index.js b/server/lib/index.jsindex ab04bf7687..63e772e876 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -772,3 +772,4 @@ export * as trackLimits from './trackLimits.js';export * from './shellLimits.js';export * from './layeredIntelligenceRejectionLabels.js';export * from './muscriptorModels.js';+export * from './metadataFlags.js';diff --git a/server/lib/investigationTasks.js b/server/lib/investigationTasks.jsindex a65281294d..ccb9321c05 100644--- a/server/lib/investigationTasks.js+++ b/server/lib/investigationTasks.js@@ -12,6 +12,7 @@import { NON_AUTO_RETRY_BLOCK_CATEGORIES } from './taskBlockCategories.js';import { PR_COMPLETIONS } from './prDisposition.js';+import { isTruthyMeta } from './metadataFlags.js';export { NON_AUTO_RETRY_BLOCK_CATEGORIES };// Stable headline every investigation task created by `agentErrorAnalysis` has@@ -97,7 +98,6 @@ export function clientInvestigationFingerprint({ description, app } = {}) {// Task metadata survives a markdown round-trip, so booleans come back as the// strings 'true'/'false'. Local to keep this module import-free of the services// layer, where the generic `isTruthyMeta` lives.-const truthyMeta = (value) => value === true || value === 'true';/*** Is this task an investigation task? Prefers the durable metadata marker and@@ -105,7 +105,7 @@ const truthyMeta = (value) => value === true || value === 'true';* the marker existed are still recognized. Pure.*/export function isInvestigationTask(task) {- if (truthyMeta(task?.metadata?.isInvestigation)) return true;+ if (isTruthyMeta(task?.metadata?.isInvestigation)) return true;return typeof task?.description === 'string'&& task.description.trimStart().startsWith(INVESTIGATION_HEADLINE_PREFIX);}diff --git a/server/lib/metadataFlags.js b/server/lib/metadataFlags.jsnew file mode 100644index 0000000000..06b23831de--- /dev/null+++ b/server/lib/metadataFlags.js@@ -0,0 +1,9 @@+/**+ * Persisted task-metadata boolean flags.+ *+ * Contract: a metadata boolean is `true`/`'true'` when set and `false`/`'false'`+ * when cleared (TASKS.md round-trips values as strings); anything else is unset.+ * A bare `if (metadata.x)` is a bug for exactly that reason — `'false'` is truthy.+ */+export const isTruthyMeta = (value) => value === true || value === 'true';+export const isFalsyMeta = (value) => value === false || value === 'false';diff --git a/server/lib/metadataFlags.test.js b/server/lib/metadataFlags.test.jsnew file mode 100644index 0000000000..f50116fb36--- /dev/null+++ b/server/lib/metadataFlags.test.js@@ -0,0 +1,12 @@+import { describe, it, expect } from 'vitest';+import { isTruthyMeta, isFalsyMeta } from './metadataFlags.js';++describe('metadataFlags', () => {+ it.each([+ [true, true, false], ['true', true, false], [false, false, true], ['false', false, true],+ [undefined, false, false], [null, false, false], [1, false, false], ['1', false, false],+ ])('%j → truthy=%s falsy=%s', (value, truthy, falsy) => {+ expect(isTruthyMeta(value)).toBe(truthy);+ expect(isFalsyMeta(value)).toBe(falsy);+ });+});diff --git a/server/lib/opencodeConfig.js b/server/lib/opencodeConfig.jsindex d957ba0104..9ff1ab5cc0 100644--- a/server/lib/opencodeConfig.js+++ b/server/lib/opencodeConfig.js@@ -47,6 +47,7 @@ import { isPublicReviewNoToolProfile } from './agentExecutionProfiles.js';import { isPlainObject } from './objects.js';import { PORTS } from './ports.js';+import { isTruthyMeta } from './metadataFlags.js';const LLAMA_SERVER_BASE_URL = `http://127.0.0.1:${PORTS.LLAMA_SERVER}/v1`;const VLLM_QWEN_BASE_URL = `http://127.0.0.1:${PORTS.VLLM_QWEN}/v1`;const SGLANG_QWEN_BASE_URL = `http://127.0.0.1:${PORTS.SGLANG_QWEN}/v1`;@@ -272,7 +273,7 @@ const numberInRange = (value, min, max) => {// `'true'`/`'false'`. Accept both wire forms without treating an absent or// malformed value as an intentional override.const readBoolean = (value) =>- value === true || value === 'true'+ isTruthyMeta(value)? true: value === false || value === 'false'? falsediff --git a/server/lib/prDisposition.js b/server/lib/prDisposition.jsindex 7cdb550f6f..b4de4d365c 100644--- a/server/lib/prDisposition.js+++ b/server/lib/prDisposition.js@@ -1,3 +1,4 @@+import { isTruthyMeta } from './metadataFlags.js';/*** PR disposition for CoS agent tasks — how a pull request completes.*@@ -82,7 +83,7 @@ export const isSelfReviewMode = (mode) => mode === PR_REVIEW_MODES.SELF;*/export function resolvePrCompletion(metadata = {}) {if (PR_COMPLETION_SET.has(metadata?.prCompletion)) return metadata.prCompletion;- return metadata?.reviewLoop === true || metadata?.reviewLoop === 'true'+ return isTruthyMeta(metadata?.reviewLoop)? PR_COMPLETIONS.REVIEW_THEN_MERGE: PR_COMPLETIONS.MERGE_ON_GREEN;}diff --git a/server/lib/slashdoInvocation.js b/server/lib/slashdoInvocation.jsindex f0a81adfe2..9a79c78109 100644--- a/server/lib/slashdoInvocation.js+++ b/server/lib/slashdoInvocation.js@@ -22,6 +22,7 @@* providers receive a self-contained body. Explicitly pinned reviewer choices* prune unreachable variants before either form is rendered.*/+import { isTruthyMeta } from './metadataFlags.js';import { isClaudeProvider, isOpencodeProvider } from './providerModels.js';import { inferTuiCommand } from './providerVendors.js';import { PROVIDER_TYPES } from './aiToolkit/constants.js';@@ -628,7 +629,6 @@ export function resolvePrOpenedBy({** @param {Object} opts* @param {Object} opts.task- * @param {(value: unknown) => boolean} opts.isTruthyMeta* @param {string|undefined} opts.persistedPrOpenedBy - `metadata.prOpenedBy`* @param {boolean|undefined} [opts.persistedOwnsPrWorkflow] - the legacy* `metadata.ownsPrWorkflow` boolean (#3733)@@ -639,7 +639,6 @@ export function resolvePrOpenedBy({*/export function resolvePrOwnership({task,- isTruthyMeta,persistedPrOpenedBy,persistedOwnsPrWorkflow,providerId = null,diff --git a/server/lib/slashdoInvocation.test.js b/server/lib/slashdoInvocation.test.jsindex 059a08f125..d75f0ce310 100644--- a/server/lib/slashdoInvocation.test.js+++ b/server/lib/slashdoInvocation.test.js@@ -489,7 +489,7 @@ describe('parseExplicitReviewWith', () => {describe('resolvePrOwnership', () => {const resolve = (overrides = {}) => resolvePrOwnership({- task: { metadata: { openPR: true } }, isTruthyMeta: Boolean,+ task: { metadata: { openPR: true } },providerId: 'codex', providerCommand: 'codex', ...overrides,});diff --git a/server/lib/taskRetryHold.js b/server/lib/taskRetryHold.jsindex 235a87d81a..d03017e2b6 100644--- a/server/lib/taskRetryHold.js+++ b/server/lib/taskRetryHold.js@@ -1,3 +1,4 @@+import { isTruthyMeta } from './metadataFlags.js';/*** Retry hold — the intermediate task state between a failed run's verdict and the* resume pointer its retry needs (#3373).@@ -80,7 +81,7 @@ export function clearedRetryHoldMetadata() {*/export function isRetryHeld(metadata) {const value = metadata?.[RETRY_HOLD_KEY];- if (value === true || value === 'true') return true;+ if (isTruthyMeta(value)) return true;return typeof value === 'string' && value !== '' && value !== 'false' && value !== 'null' && value !== 'undefined';}@@ -92,7 +93,7 @@ export function isRetryHeld(metadata) {export function isRetryHoldOwner(metadata, agentId) {if (!isRetryHeld(metadata)) return false;const value = metadata[RETRY_HOLD_KEY];- if (value === true || value === 'true') return true;+ if (isTruthyMeta(value)) return true;return !!agentId && value === agentId;}diff --git a/server/lib/taskTargetBranch.js b/server/lib/taskTargetBranch.jsindex 7dbe83be0b..b8786e3362 100644--- a/server/lib/taskTargetBranch.js+++ b/server/lib/taskTargetBranch.js@@ -1,3 +1,4 @@+import { isTruthyMeta } from './metadataFlags.js';/*** Task target-branch metadata — one reader and one terminal-strip rule.*@@ -8,7 +9,6 @@* the single canonical review-loop key.*/-const isTruthyMetadataFlag = (value) => value === true || value === 'true';/*** Resolve the branch a task must work on, or null when it should cut a fresh one.@@ -17,7 +17,7 @@ const isTruthyMetadataFlag = (value) => value === true || value === 'true';*/export function resolveTaskTargetBranch(metadata) {if (metadata?.existingBranch) return metadata.existingBranch;- if (isTruthyMetadataFlag(metadata?.reviewLoopFollowUp) && metadata?.reviewLoopPRBranch) {+ if (isTruthyMeta(metadata?.reviewLoopFollowUp) && metadata?.reviewLoopPRBranch) {return metadata.reviewLoopPRBranch;}return null;diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 9f62932ce3..a673754ef6 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -148,9 +148,7 @@ function resolveCliErrorAnalysis({ finalSuccess, task, model, rawStreamBuffer, o/*** Spawn agent directly (fallback when runner not available).- * `isTruthyMetaFn` is the lifecycle's shared metadata predicate, passed in by- * the caller and threaded on to `finalizeAgent`. Completion cleanup is not- * injected: `runSpawnerCompletionCleanup` is imported at top level, since+ * Completion cleanup is not injected: `runSpawnerCompletionCleanup` is imported at top level, since* nothing in its static closure reaches this module or agentLifecycle.js.*/export async function spawnDirectly({@@ -165,7 +163,6 @@ export async function spawnDirectly({agentDir,executionId,laneName,- isTruthyMetaFn,prOpenedBy,safetyProfile = null,}) {@@ -269,7 +266,6 @@ export async function spawnDirectly({duration: 0, outputBuffer: '', workspacePath, prExpected: false,error: message, completionReason: 'spawn-error',errorAnalysis: { category: 'actionable', error: message, suggestedFix: message },- isTruthyMetaFn,});cosEvents.emit('agent:error', { agentId, taskId: task.id, error: message });return null;@@ -778,7 +774,6 @@ export async function spawnDirectly({// `agentOpensOwnPr` are two predicates (#3358).const prOwnership = resolvePrOwnership({task,- isTruthyMeta: isTruthyMetaFn,persistedPrOpenedBy: prOpenedBy,providerId: provider?.id,providerCommand: provider?.command,@@ -809,7 +804,6 @@ export async function spawnDirectly({outputBuffer,errorAnalysis,terminatedByUser,- isTruthyMetaFn,error: finalError || undefined,completionReason: terminatedByUser ? 'user-terminated' : undefined,workspacePath: cwd,diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.jsindex b0e72e7197..88429bd604 100644--- a/server/services/agentCliSpawning.test.js+++ b/server/services/agentCliSpawning.test.js@@ -493,7 +493,6 @@ describe('stream error containment', () => {providerCommand: provider.command,leanMode: false,worktreeInfo: { branchName: 'agent/t', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMetaFn: (v) => v === true || v === 'true',});const minimalArgs = {@@ -513,7 +512,6 @@ describe('stream error containment', () => {agentDir: '/tmp',executionId: null,laneName: null,- isTruthyMetaFn: vi.fn().mockReturnValue(false),};// Re-import the mocked cosAgentLifecycle module reference once — mocking is module-scoped.@@ -1224,7 +1222,7 @@ describe('stream error containment', () => {metadata: { openPR: true, reviewers: ['codex', 'antigravity'], reviewStopMode: 'on-clean' },};- spawnDirectly({ ...minimalArgs, task, prOpenedBy: stampPrOpenedBy(task), isTruthyMetaFn: (v) => v === true });+ spawnDirectly({ ...minimalArgs, task, prOpenedBy: stampPrOpenedBy(task) });await new Promise((r) => setTimeout(r, 10));fakeProcess.stdout.emit('data', Buffer.from('{"type":"result","result":"ok"}\n'));await new Promise((r) => setTimeout(r, 50));@@ -1249,7 +1247,7 @@ describe('stream error containment', () => {it('hands a read-only CLI run to PortOS using the prompt ownership stamp', async () => {const task = { id: 'task-read-only', description: 'analyze the code', metadata: { openPR: true, readOnly: true } };- const spawnPromise = spawnDirectly({ ...minimalArgs, task, prOpenedBy: stampPrOpenedBy(task), isTruthyMetaFn: (v) => v === true });+ const spawnPromise = spawnDirectly({ ...minimalArgs, task, prOpenedBy: stampPrOpenedBy(task) });await vi.waitFor(() => expect(fakeProcess.listenerCount('close')).toBeGreaterThan(0));fakeProcess.emit('close', 0);await spawnPromise;@@ -1265,7 +1263,7 @@ describe('stream error containment', () => {// value would stamp resume pointers on every completed run, or on none.it('hands the dispatch the run verdict — failure on a non-zero exit, success on a clean one', async () => {const task = { id: 'task-rp', description: 'do stuff', metadata: {} };- spawnDirectly({ ...minimalArgs, task, isTruthyMetaFn: (v) => v === true });+ spawnDirectly({ ...minimalArgs, task });await new Promise((r) => setTimeout(r, 10));fakeProcess.emit('close', 1);await vi.waitFor(() => expect(runSpawnerCompletionCleanup).toHaveBeenCalledWith(@@ -1274,7 +1272,7 @@ describe('stream error containment', () => {runSpawnerCompletionCleanup.mockClear();fakeProcess = makeFakeProcess();- spawnDirectly({ ...minimalArgs, task: { id: 'task-rp-ok', description: 'do stuff', metadata: {} }, isTruthyMetaFn: (v) => v === true });+ spawnDirectly({ ...minimalArgs, task: { id: 'task-rp-ok', description: 'do stuff', metadata: {} } });await new Promise((r) => setTimeout(r, 10));fakeProcess.stdout.emit('data', Buffer.from('{"type":"result","result":"ok"}\n'));await new Promise((r) => setTimeout(r, 50));diff --git a/server/services/agentCompletionCleanup.test.js b/server/services/agentCompletionCleanup.test.jsindex e780994bc0..c8e79f838a 100644--- a/server/services/agentCompletionCleanup.test.js+++ b/server/services/agentCompletionCleanup.test.js@@ -272,7 +272,6 @@ describe('runAgentCompletionCleanup — agentOpensOwnPr mirrors the prompt gate'promptOpensOwnPr(task, {providerType, providerId, providerCommand, leanMode,worktreeInfo: worktree,- isTruthyMetaFn: (v) => v === true || v === 'true',});// `prClaimVerified` is the caller's answer to "did finalize's PR-claim checkdiff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsindex 577221be01..f104c71597 100644--- a/server/services/agentFinalization.js+++ b/server/services/agentFinalization.js@@ -62,6 +62,7 @@ import { extractSimplifySummaries } from './agentSummaryExtraction.js';import { usesCreativeDirectorScratchCwd, removeCreativeDirectorScratchCwd } from '../lib/spawnCwd.js';import { issueNumberFromRef } from './issueReconcile.js';+import { isTruthyMeta } from '../lib/metadataFlags.js';/*** Release the execution lane and complete tool-execution tracking for a* finishing agent. Pulled OUT of finalizeAgent so callers can fire it@@ -287,9 +288,8 @@ function hasIssuePartialTrailer(body, issueNumber) {}function isVerifiedNoChangeTask(task) {- const isPersistedTrue = (value) => value === true || value === 'true';- return (isPersistedTrue(task?.metadata?.autonomousJob) || isPersistedTrue(task?.metadata?.isInvestigation))- && isPersistedTrue(task?.metadata?.noChangeSuccess);+ return (isTruthyMeta(task?.metadata?.autonomousJob) || isTruthyMeta(task?.metadata?.isInvestigation))+ && isTruthyMeta(task?.metadata?.noChangeSuccess);}/**@@ -783,10 +783,9 @@ async function evaluateGoalFidelity({ task, workspacePath, startedAt }) {// Leave-open review follow-ups are the deliberate exception: their deliverable// IS the review-fix commits, while merge-shaped follow-ups were settled from// forge state immediately above.- const reviewLoopFollowUp = task.metadata?.reviewLoopFollowUp === true- || task.metadata?.reviewLoopFollowUp === 'true';+ const reviewLoopFollowUp = isTruthyMeta(task.metadata?.reviewLoopFollowUp);const reviewLoopLeaveOpen = reviewLoopFollowUp- && (task.metadata?.reviewLoopLeaveOpen === true || task.metadata?.reviewLoopLeaveOpen === 'true');+ && isTruthyMeta(task.metadata?.reviewLoopLeaveOpen);if (declaresNoCommitCriterion(task) && !reviewLoopLeaveOpen) return noFidelityVerdict();const claimFlow = isClaimFlowDispatch(task);const claimed = claimFlow@@ -1214,7 +1213,6 @@ export async function finalizeAgent({outputBuffer,errorAnalysis: reportedErrorAnalysis,terminatedByUser = false,- isTruthyMetaFn,error,completionReason,workspacePath = null,@@ -1441,8 +1439,8 @@ export async function finalizeAgent({cosEvents.emit(GOAL_FIDELITY_HOLD_EVENT, { agentId, taskId: task?.id, review: fidelity.review });}- if (verdict.success && isTruthyMetaFn) {- await persistSimplifySummaries(agentId, task, outputBuffer, isTruthyMetaFn);+ if (verdict.success) {+ await persistSimplifySummaries(agentId, task, outputBuffer);}const taskType = task?.taskType || 'user';@@ -1900,8 +1898,8 @@ async function dispatchTaskOutputHook({ agentId, task, success, workspacePath, a* Persist task/simplify summaries for agents that ran with /simplify.* Shared by handleAgentCompletion (runner mode) and spawnDirectly (direct mode).*/-export async function persistSimplifySummaries(agentId, task, outputBuffer, isTruthyMetaFn) {- if (!isTruthyMetaFn(task.metadata?.simplify)) return;+export async function persistSimplifySummaries(agentId, task, outputBuffer) {+ if (!isTruthyMeta(task.metadata?.simplify)) return;const summaries = extractSimplifySummaries(outputBuffer);if (!summaries) return;// Persist whenever *either* summary is present — e.g. if the /simplifydiff --git a/server/services/agentFinalization.providerBench.test.js b/server/services/agentFinalization.providerBench.test.jsindex 09069680ca..1e77852094 100644--- a/server/services/agentFinalization.providerBench.test.js+++ b/server/services/agentFinalization.providerBench.test.js@@ -103,7 +103,6 @@ const failedRun = (errorAnalysis, providerId = 'antigravity-tui') => finalizeAgeoutputBuffer: '',errorAnalysis,terminatedByUser: false,- isTruthyMetaFn: () => false,error: errorAnalysis?.message,completionReason: 'fallback-signal',workspacePath: '/w',@@ -291,7 +290,6 @@ describe('finalizeAgent provider sidelining', () => {outputBuffer: '',errorAnalysis: analysis,terminatedByUser: true,- isTruthyMetaFn: () => false,completionReason: 'terminated',workspacePath: '/w',prExpected: false,@@ -323,7 +321,6 @@ describe('finalizeAgent — Creative Director scratch cleanup (#4650)', () => {duration: 1000,outputBuffer: '',terminatedByUser: false,- isTruthyMetaFn: () => false,workspacePath: dir,prExpected: false,});diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex ec33a51286..61fbcba294 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -319,7 +319,6 @@ export async function spawnViaRunner(agentId, task, opts) {duration: 0,outputBuffer: '',errorAnalysis,- isTruthyMetaFn: isTruthyMeta,error: message,completionReason: 'spawn-rejected',workspacePath,@@ -660,7 +659,6 @@ export async function handleAgentCompletion(agentId, exitCode, success, durationduration,outputBuffer,errorAnalysis,- isTruthyMetaFn: isTruthyMeta,workspacePath: agent.workspacePath || null,prExpected: runnerPrClaimExpected,// The run window the commit criterion is evaluated against (#3637).diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.jsindex 0f4334b6fb..634f165313 100644--- a/server/services/agentLifecycle.test.js+++ b/server/services/agentLifecycle.test.js@@ -831,12 +831,12 @@ describe('runAgentSpawn source — instance provenance + claim ordering (#1563)'});it('records claimFlow separately from CoS-managed PR/worktree flags', () => {- expect(AGENT_REGISTRATION_SRC).toContain('configOpenPR: isTruthyMetaFn(task.metadata?.openPR)');+ expect(AGENT_REGISTRATION_SRC).toContain('configOpenPR: isTruthyMeta(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_SPAWN_DISPATCH_SRC).toContain('const claimFlowTask = isClaimFlowTask(task, isTruthyMeta);');+ expect(AGENT_SPAWN_DISPATCH_SRC).toContain('const claimFlowTask = isClaimFlowTask(task);');expect(AGENT_REGISTRATION_SRC).toContain('configClaimFlow: claimFlowTask');expect(AGENT_REGISTRATION_SRC.indexOf('configClaimFlow')).toBeGreaterThan(AGENT_REGISTRATION_SRC.indexOf('configOpenPR'));});@@ -1028,5 +1028,5 @@ describe('runAgentSpawn source — quota-burn provenance projection (#6406)', ()// Archive classification must survive the task-to-agent metadata projection.it('preserves the machine-local privacy marker in spawned agent metadata', () => {- expect(AGENT_REGISTRATION_SRC).toContain('machineLocal: isTruthyMetaFn(task.metadata?.machineLocal)');+ expect(AGENT_REGISTRATION_SRC).toContain('machineLocal: isTruthyMeta(task.metadata?.machineLocal)');});diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 4ebee682c1..fa99139e9d 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -10,6 +10,7 @@ import { join } from 'path';import { stat } from 'fs/promises';import { getMemorySection } from './memoryRetriever.js';import { getToolsSummaryForPrompt } from './tools.js';+import { isTruthyMeta } from '../lib/metadataFlags.js';import { PATHS, tryReadFile } from '../lib/fileUtils.js';import { loadSlashdoFile, loadSlashdoLib, writeResolvedSlashdoBody } from '../lib/slashdoLoader.js';import { DEFAULT_REVIEWER, DEFAULT_REVIEW_STOP_MODE, isToolFreeReviewer, isCliReviewer, hasRequiredReviewer, resolveReviewerConfig } from '../lib/validation.js';@@ -113,15 +114,14 @@ export function isUiAuditTask(task) {return UI_AUDIT_TASK_TYPE_SET.has(taskType);}-export function isClaimFlowTask(task, isTruthyMetaFn = (value) => value === true || value === 'true') {+export function isClaimFlowTask(task) {// Delegates to isClaimFlowDispatch (taskTypeHooks.js) so the prompt-side// claim posture and the finalization/learning-side exemption resolve the// SAME task shapes — that predicate reads the marker plus the full// analysisType → taskAnalysisType → taskType chain, covering an archived// projection or a bare taskType this narrower chain used to miss (the #6613- // writer/reader split, one shape over). The isTruthyMetaFn seam stays for- // the suites that inject it.- return isTruthyMetaFn(task?.metadata?.claimFlow)+ // writer/reader split, one shape over).+ return isTruthyMeta(task?.metadata?.claimFlow)|| isClaimFlowDispatch(task);}@@ -234,7 +234,7 @@ PortOS launched you autonomously. Nobody is watching this session and nothing ca/** Load and safely stage the review recipe shared by full and light prompts. */async function prepareReviewLoopRecipe(task, {- providerType, providerId, providerCommand, leanMode, worktreeInfo, isTruthyMetaFn,+ providerType, providerId, providerCommand, leanMode, worktreeInfo,codeReviewDefaults, defaultReviewers,}) {// Preload slashdo's local-agent review-loop recipe once for review-loop@@ -243,7 +243,7 @@ async function prepareReviewLoopRecipe(task, {// CLI-reviewer invocation. Cheap + cached; only read for follow-ups — and not// for a merge-only follow-up, which has no reviewer to invoke and renders a// section that ignores this body entirely.- const isFollowUpNeedingRecipes = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp)+ const isFollowUpNeedingRecipes = isTruthyMeta(task.metadata?.reviewLoopFollowUp)&& !isMergeOnlyFollowUp(task.metadata || {});// …and a slashdo-free harness driving its OWN review loop inline needs the// identical recipe (`buildInlineReviewLoopSection`). Same predicate the render@@ -255,7 +255,7 @@ async function prepareReviewLoopRecipe(task, {// would otherwise// read + `atomicWrite` 56KB and then render nothing from it.const isInlineNeedingRecipes = inlinePrLifecycleSection(task, {- providerType, providerId, providerCommand, leanMode, worktreeInfo, isTruthyMetaFn,+ providerType, providerId, providerCommand, leanMode, worktreeInfo,}) === 'review-loop'&& resolveReviewerConfig(task.metadata, codeReviewDefaults, defaultReviewers).reviewers.some(isCliReviewer);const localAgentLoopBody = (isFollowUpNeedingRecipes || isInlineNeedingRecipes)@@ -304,7 +304,6 @@ async function prepareReviewLoopRecipe(task, {* @param {Object} config - CoS configuration* @param {string} workspaceDir - Working directory (may be a worktree)* @param {Object|null} worktreeInfo - Worktree details if using a worktree- * @param {Function} isTruthyMetaFn - isTruthyMeta function (passed to avoid circular dep)* @param {Object} options* @param {string} [options.providerType='api'] - `'tui' | 'cli' | 'api'`* `providerId` + `providerCommand` + `leanMode` together decide whether the@@ -332,7 +331,7 @@ async function prepareReviewLoopRecipe(task, {* of a single string, for providers spawned with `--append-system-prompt-file`.* Ignored on the full/api path, which always returns a string.*/-export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo = null, isTruthyMetaFn = (v) => v === true || v === 'true', options = {}) {+export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo = null, options = {}) {// Undo the queue-path description/context split so a round-tripped generated// prompt (swarm, scheduled claim-work, other system tasks) renders once// instead of double-printing its first line under a `### Context` header.@@ -391,7 +390,7 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfoisFollowUpNeedingRecipes, localAgentLoopBody,localAgentLoopBodyForInline, localAgentLoopBodyPath,} = await prepareReviewLoopRecipe(task, {- providerType, providerId, providerCommand, leanMode, worktreeInfo, isTruthyMetaFn,+ providerType, providerId, providerCommand, leanMode, worktreeInfo,codeReviewDefaults, defaultReviewers,});@@ -399,8 +398,8 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfoconst forgeCli = await resolveManualForgeCli(workspaceDir, worktreeInfo, task);const lightOptions = { isTui, providerId, providerCommand, providerModel, leanMode, agentId, defaultReviewers, codeReviewDefaults, localAgentLoopBody: localAgentLoopBodyForInline, localAgentLoopBodyPath, forgeCli };return options.split === true- ? buildLightContextPromptParts(task, workspaceDir, worktreeInfo, isTruthyMetaFn, lightOptions)- : buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTruthyMetaFn, lightOptions);+ ? buildLightContextPromptParts(task, workspaceDir, worktreeInfo, lightOptions)+ : buildLightContextPrompt(task, workspaceDir, worktreeInfo, lightOptions);}// Creative Director tasks (scene evaluation, treatment/plan run via API) judge@@ -427,9 +426,9 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfoconst compactionSection = task.metadata?.compaction?.needed ? buildCompactionSection(task) : '';// Build worktree context section if applicable- const willOpenPR = isTruthyMetaFn(task.metadata?.openPR);+ const willOpenPR = isTruthyMeta(task.metadata?.openPR);const whenDone = task.metadata?.whenDone === 'commit-push' ? 'commit-push' : 'leave-uncommitted';- const claimFlow = isClaimFlowTask(task, isTruthyMetaFn);+ const claimFlow = isClaimFlowTask(task);// Worktree with no PR: PortOS merges the branch back on exit, so every// commit/push instruction below is commit-only (see portosMergesBranchOnExit).const portosMergesBranch = portosMergesBranchOnExit({ worktreeInfo, willOpenPR });@@ -437,13 +436,13 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo// A discard (reasoning-only) worktree: the agent reasons in it but it's thrown// away on exit with no commit/merge/PR (see agentWorktreeCleanup.js). Suppresses// all commit/push/PR completion guidance in favor of the sentinel-only contract.- const discardWorktree = isTruthyMetaFn(task.metadata?.discardWorktree);+ const discardWorktree = isTruthyMeta(task.metadata?.discardWorktree);// No-code / API-action task (e.g. Creative Director agents): deliverable is an// HTTP PATCH, not a commit — suppress the /do:push completion workflow. Also// derive from a CD task's own `creativeDirector` marker so tasks queued as// `pending` BEFORE this flag existed (persisted across an upgrade) are still// recognized without a metadata migration.- const noCodeOutput = isTruthyMetaFn(task.metadata?.noCodeOutput) || isCreativeDirectorTask;+ const noCodeOutput = isTruthyMeta(task.metadata?.noCodeOutput) || isCreativeDirectorTask;// A tool-free public-review stage has no sentinel, API, or command to reach// for: its reply IS the deliverable. Wins over every other completion contract.const toolFreeReasoning = isPublicReviewNoToolProfile(task.metadata?.executionProfile);@@ -451,12 +450,12 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo// is the JSON payload in the sentinel, not an API action — so it takes the// programmatic-output contract ahead of the no-code one.const sentinelPayloadOutput = isPublicReviewRestrictedProfile(task.metadata?.executionProfile) && !toolFreeReasoning;- const noChangeSuccess = isTruthyMetaFn(task.metadata?.noChangeSuccess);- const isReadOnly = isTruthyMetaFn(task.metadata?.readOnly);+ const noChangeSuccess = isTruthyMeta(task.metadata?.noChangeSuccess);+ const isReadOnly = isTruthyMeta(task.metadata?.readOnly);// The review-loop follow-up that addresses PR feedback and merges (spawned by// the previous agent's cleanup hook). Its own procedure section renders far// below; the flag is read up here because it is an input to the mode decision.- const isReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);+ const isReviewLoopFollowUp = isTruthyMeta(task.metadata?.reviewLoopFollowUp);const isWorktreeOnExistingBranch = isPrBranchWorktree(task, worktreeInfo);// Build pipeline context section if this is a pipeline stage@@ -471,7 +470,7 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo// only commit (not push) — keep this wording aligned with the worktree// section above. TUI agents own the full simplify+push+PR sequence in the// Completion Workflow section below, so this section is suppressed for TUI.- const simplifyEnabled = isTruthyMetaFn(task.metadata?.simplify);+ const simplifyEnabled = isTruthyMeta(task.metadata?.simplify);// `/simplify` is a Claude Code built-in slash command — only a Claude session// that loaded its commands can run it. Everyone else (API/CLI) gets the inline// equivalent describing the same reuse/quality/efficiency self-review so the@@ -506,7 +505,7 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo} = resolveReviewerConfig(task.metadata, codeReviewDefaults, defaultReviewers);const taskReviewStopMode = task.metadata?.reviewStopMode || codeReviewDefaults?.stopMode || DEFAULT_REVIEW_STOP_MODE;const configuredTaskReviewerApplies = task.metadata?.reviewerApplies !== undefined- ? isTruthyMetaFn(task.metadata?.reviewerApplies)+ ? isTruthyMeta(task.metadata?.reviewerApplies): (codeReviewDefaults?.reviewerApplies === true);// A PR/MR review consumes public contributor-controlled content. Its reviewer// must stay review-only; the orchestrating agent validates and applies fixes.@@ -890,8 +889,8 @@ Begin working on the task now.`;* Falls back gracefully when worktree/jira/pipeline metadata is absent — only* the present sections render.*/-export function buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTruthyMetaFn, options = {}) {- const { taskSections, contractSections } = buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMetaFn, options);+export function buildLightContextPrompt(task, workspaceDir, worktreeInfo, options = {}) {+ const { taskSections, contractSections } = buildLightContextSections(task, workspaceDir, worktreeInfo, options);return [...taskSections, ...contractSections, BEGIN_WORKING_LINE].join('\n\n') + '\n';}@@ -906,8 +905,8 @@ export function buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTrut** @returns {{ userPrompt: string, systemPrompt: string|null }}*/-export function buildLightContextPromptParts(task, workspaceDir, worktreeInfo, isTruthyMetaFn, options = {}) {- const { taskSections, contractSections } = buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMetaFn, options);+export function buildLightContextPromptParts(task, workspaceDir, worktreeInfo, options = {}) {+ const { taskSections, contractSections } = buildLightContextSections(task, workspaceDir, worktreeInfo, options);return {userPrompt: [...taskSections, BEGIN_WORKING_LINE].join('\n\n') + '\n',systemPrompt: contractSections.length ? contractSections.join('\n\n') + '\n' : null,@@ -916,29 +915,29 @@ export function buildLightContextPromptParts(task, workspaceDir, worktreeInfo, iconst BEGIN_WORKING_LINE = 'Begin working on the task now.';-function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMetaFn, { isTui = true, providerId = null, providerCommand = null, providerModel = null, leanMode = false, agentId = null, defaultReviewers, codeReviewDefaults, localAgentLoopBody = null, localAgentLoopBodyPath = null, forgeCli = null } = {}) {+function buildLightContextSections(task, workspaceDir, worktreeInfo, { isTui = true, providerId = null, providerCommand = null, providerModel = null, leanMode = false, agentId = null, defaultReviewers, codeReviewDefaults, localAgentLoopBody = null, localAgentLoopBodyPath = null, forgeCli = null } = {}) {// Idempotent with the reconcile in buildAgentPrompt; also protects the// directly-exported buildLightContextPrompt/Parts entry points.task = reconcileSplitContext(task);- const willOpenPR = isTruthyMetaFn(task.metadata?.openPR);- const claimFlow = isClaimFlowTask(task, isTruthyMetaFn);+ const willOpenPR = isTruthyMeta(task.metadata?.openPR);+ const claimFlow = isClaimFlowTask(task);// Worktree with no PR: PortOS merges the branch back on exit, so the commit// guidance and completion workflow are commit-only (portosMergesBranchOnExit).const portosMergesBranch = portosMergesBranchOnExit({ worktreeInfo, willOpenPR });const prCompletion = resolvePrCompletion(task.metadata);- const simplifyEnabled = isTruthyMetaFn(task.metadata?.simplify);- const isReadOnly = isTruthyMetaFn(task.metadata?.readOnly);- const discardWorktree = isTruthyMetaFn(task.metadata?.discardWorktree);+ const simplifyEnabled = isTruthyMeta(task.metadata?.simplify);+ const isReadOnly = isTruthyMeta(task.metadata?.readOnly);+ const discardWorktree = isTruthyMeta(task.metadata?.discardWorktree);// A no-code / API-action task (e.g. a Creative Director plan/treatment/evaluate// agent): its deliverable is an HTTP PATCH, not a commit — suppress the// /do:push completion workflow (see buildActionOutputCompletionSection). Also// derive from a CD task's `creativeDirector` marker so pre-upgrade `pending`// tasks (queued before this flag existed) are recognized without a migration.- const noCodeOutput = isTruthyMetaFn(task.metadata?.noCodeOutput) || !!task.metadata?.creativeDirector;+ const noCodeOutput = isTruthyMeta(task.metadata?.noCodeOutput) || !!task.metadata?.creativeDirector;const toolFreeReasoning = isPublicReviewNoToolProfile(task.metadata?.executionProfile);const sentinelPayloadOutput = isPublicReviewRestrictedProfile(task.metadata?.executionProfile) && !toolFreeReasoning;- const noChangeSuccess = isTruthyMetaFn(task.metadata?.noChangeSuccess);- const isReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);+ const noChangeSuccess = isTruthyMeta(task.metadata?.noChangeSuccess);+ const isReviewLoopFollowUp = isTruthyMeta(task.metadata?.reviewLoopFollowUp);const isWorktreeOnExistingBranch = isPrBranchWorktree(task, worktreeInfo);// Ordered reviewer list + flags for the Review Loop (task metadata wins; else// the install's configured Code Review Defaults threaded from buildAgentPrompt;@@ -956,7 +955,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet} = resolveReviewerConfig(task.metadata, codeReviewDefaults, defaultReviewers);const lightReviewStopMode = task.metadata?.reviewStopMode || codeReviewDefaults?.stopMode || DEFAULT_REVIEW_STOP_MODE;const configuredLightReviewerApplies = task.metadata?.reviewerApplies !== undefined- ? isTruthyMetaFn(task.metadata?.reviewerApplies)+ ? isTruthyMeta(task.metadata?.reviewerApplies): (codeReviewDefaults?.reviewerApplies === true);// Inline PR/MR lifecycles and review-loop follow-ups cross the public-forge// boundary. Preserve reviewer-applies only for non-public local review work.@@ -995,7 +994,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet// so the completion step's cross-reference can't name the wrong one.const inlineSection = claimFlow || [COMPLETION_MODES.RELEASE_FLOW, COMPLETION_MODES.AUDIT_FLOW, COMPLETION_MODES.RECONCILE_FLOW].includes(completionMode) ? null : inlinePrLifecycleSection(task, {providerType: isTui ? PROVIDER_TYPES.TUI : PROVIDER_TYPES.CLI,- providerId, providerCommand, leanMode, worktreeInfo, isTruthyMetaFn,+ providerId, providerCommand, leanMode, worktreeInfo,});const rendersInlinePrLifecycle = inlineSection !== null;// Slashdo already partitions reviewers. Plain-git completion prompts need thediff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex 31a9f249b8..77c9d22584 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -113,7 +113,6 @@ import { resolveCompletionMode } from '../lib/agentCompletionMode.js';import { buildLightContextPrompt, buildAgentPrompt, buildCompletionGuidelineBullet, reconcileSplitContext, buildReviewLoopFollowUpSection, getAppWorkspace, getAgentInstructionsContext, detectSkillTemplates, loadSkillTemplates, UI_AUDIT_RUNTIME_RULE, UI_AUDIT_TASK_TYPES, UNATTENDED_RUN_RULE } from './agentPromptBuilder.js';import { getCodeReviewDefaults } from './codeReview.js'; // mocked above — control the configured default-import { isTruthyMeta } from './agentState.js';import { getMemorySection } from './memoryRetriever.js';import { getDigitalTwinForPrompt } from './digital-twin.js';import { getToolsSummaryForPrompt } from './tools.js';@@ -249,7 +248,6 @@ describe('composable skill template routing', () => {task,'/workspace/example-app',null,- isTruthyMeta,{ providerId: 'codex-tui', providerCommand: 'codex' },);const apiPrompt = await buildAgentPrompt(@@ -257,7 +255,6 @@ describe('composable skill template routing', () => {{},'/workspace/example-app',null,- isTruthyMeta,{ providerType: 'api' },);@@ -347,7 +344,7 @@ describe('tool-free public-review stage completion', () => {});it('tells the model its reply is the deliverable and never mentions a sentinel or API action', () => {- const prompt = buildLightContextPrompt(gateTask(), '/repo', null, isTruthyMeta, {+ const prompt = buildLightContextPrompt(gateTask(), '/repo', null, {providerId: 'claude-ollama', providerCommand: 'claude',});expect(prompt).toMatch(/## Completion \(Tool-Free Reasoning\)/);@@ -365,7 +362,7 @@ describe('sandboxed public-review actions stage completion', () => {const task = makeTask({metadata: { noCodeOutput: true, discardWorktree: true, openPR: false, executionProfile: 'public-review-actions' },});- const prompt = buildLightContextPrompt(task, '/repo', null, isTruthyMeta, {+ const prompt = buildLightContextPrompt(task, '/repo', null, {providerId: 'codex-tui', providerCommand: 'codex',});expect(prompt).toMatch(/exact payload format described in your task instructions/);@@ -386,10 +383,10 @@ describe('sandboxed public-review actions stage completion', () => {});// Same provider record, spawned two ways — so the ONLY variable is the// spawn mode, which is exactly the thing that must not move the contract.- const headless = buildLightContextPrompt(task(), '/repo', null, isTruthyMeta, {+ const headless = buildLightContextPrompt(task(), '/repo', null, {providerType: 'cli', providerId: 'claude-code', providerCommand: 'claude',});- const tui = buildLightContextPrompt(task(), '/repo', null, isTruthyMeta, {+ const tui = buildLightContextPrompt(task(), '/repo', null, {providerType: 'tui', providerId: 'claude-code', providerCommand: 'claude',});expect(tui).toMatch(/exact payload format described in your task instructions/);@@ -411,7 +408,7 @@ describe('no-code / API-action task completion (CD agents must NOT be told to /d});it('a no-code TUI task gets the No-Code completion section, not the /do:push Completion Workflow', () => {- const prompt = buildLightContextPrompt(cdTask(), '/repo', null, isTruthyMeta, {+ const prompt = buildLightContextPrompt(cdTask(), '/repo', null, {providerId: 'claude-code-tui', providerCommand: 'claude',});expect(prompt).toMatch(/## Completion \(No Code Output\)/);@@ -428,7 +425,7 @@ describe('no-code / API-action task completion (CD agents must NOT be told to /dconst legacyCdTask = makeTask({metadata: { context: 'PATCH the plan', creativeDirector: { projectId: 'p', kind: 'plan' }, openPR: false },});- const prompt = buildLightContextPrompt(legacyCdTask, '/repo', null, isTruthyMeta, {+ const prompt = buildLightContextPrompt(legacyCdTask, '/repo', null, {providerId: 'claude-code-tui', providerCommand: 'claude',});expect(prompt).toMatch(/## Completion \(No Code Output\)/);@@ -437,7 +434,7 @@ describe('no-code / API-action task completion (CD agents must NOT be told to /dit('a normal code task on the same provider still gets the /do:push Completion Workflow', () => {const prompt = buildLightContextPrompt(- makeTask({ metadata: { openPR: false } }), '/repo', null, isTruthyMeta,+ makeTask({ metadata: { openPR: false } }), '/repo', null,{ providerId: 'claude-code-tui', providerCommand: 'claude' },);expect(prompt).toMatch(/## Completion Workflow/);@@ -450,8 +447,8 @@ describe('claim-flow completion handoff', () => {it.each([true, false])('honors leave-open on the %s light/full claim path', async (light) => {const task = makeTask({ metadata: { analysisType: 'claim-issue', claimFlow: true, useWorktree: false, openPR: false, prCompletion: 'leave-open' } });const prompt = light- ? buildLightContextPrompt(task, '/repo', null, isTruthyMeta, { isTui: true, providerId: 'codex-tui', providerCommand: 'codex' })- : await buildAgentPrompt(task, {}, '/repo', null, isTruthyMeta, { providerType: 'api' });+ ? buildLightContextPrompt(task, '/repo', null, { isTui: true, providerId: 'codex-tui', providerCommand: 'codex' })+ : await buildAgentPrompt(task, {}, '/repo', null, { providerType: 'api' });expect(prompt).toContain('PR completion policy: LEAVE OPEN');expect(prompt).toContain('Complete implementation, configured reviews, publication, and CI checks as usual');expect(prompt).toContain('preserve the claim markers, issue state, branch, and worktree');@@ -480,7 +477,6 @@ describe('claim-flow completion handoff', () => {existingBranch: true,claimResumeInPlace: true,},- isTruthyMeta,{ isTui: true, providerId: 'grok-tui', providerCommand: 'grok' },);@@ -497,7 +493,7 @@ describe('claim-flow completion handoff', () => {it('keeps self-managed claim work out of the generic false/false handoff', () => {const prompt = buildLightContextPrompt(makeTask({ metadata: { claimFlow: true, useWorktree: false, openPR: false, simplify: true } }),- '/repo', null, isTruthyMeta,+ '/repo', null,{ isTui: true, providerId: 'codex-tui', providerCommand: 'codex' },);@@ -513,7 +509,7 @@ describe('claim-flow completion handoff', () => {it('uses the claim handoff on the full API prompt path too', async () => {const prompt = await buildAgentPrompt(makeTask({ metadata: { claimFlow: true, useWorktree: false, openPR: false, simplify: true } }),- {}, '/repo', null, isTruthyMeta, { providerType: 'api' },+ {}, '/repo', null, { providerType: 'api' },);expect(prompt).toMatch(/## Claim Workflow Handoff/);@@ -525,7 +521,7 @@ describe('claim-flow completion handoff', () => {it('renders merge-on-green PR completion policy for claim flow on light and full prompt paths', async () => {const lightPrompt = buildLightContextPrompt(makeTask({ metadata: { claimFlow: true, useWorktree: false, openPR: false, prCompletion: 'merge-on-green' } }),- '/repo', null, isTruthyMeta,+ '/repo', null,{ isTui: true, providerId: 'codex-tui', providerCommand: 'codex' },);@@ -536,7 +532,7 @@ describe('claim-flow completion handoff', () => {const apiPrompt = await buildAgentPrompt(makeTask({ metadata: { claimFlow: true, useWorktree: false, openPR: false, prCompletion: 'merge-on-green' } }),- {}, '/repo', null, isTruthyMeta, { providerType: 'api' },+ {}, '/repo', null, { providerType: 'api' },);expect(apiPrompt).toMatch(/## Claim Workflow Handoff/);@@ -556,7 +552,6 @@ describe('claim-flow completion handoff', () => {} }),{}, '/repo',{ branchName: 'b', worktreePath: '/tmp/wt', baseBranch: 'origin/main' },- isTruthyMeta,{ providerType: 'api' },);@@ -570,7 +565,7 @@ describe('claim-flow completion handoff', () => {it('recognizes a queued legacy claim task by analysisType', () => {const prompt = buildLightContextPrompt(makeTask({ metadata: { analysisType: 'claim-issue', useWorktree: false, openPR: false } }),- '/repo', null, isTruthyMeta,+ '/repo', null,{ isTui: true, providerId: 'codex-tui', providerCommand: 'codex' },);@@ -587,7 +582,7 @@ describe('claim-flow completion handoff', () => {it('pins the reviewers the task persisted, exactly once', () => {const prompt = buildLightContextPrompt(makeTask({ metadata: claimMeta({ reviewers: ['codex', 'claude'], usernames: ['alice'] }) }),- '/repo', null, isTruthyMeta,+ '/repo', null,{ isTui: true, providerId: 'codex-tui', providerCommand: 'codex' },);@@ -610,7 +605,7 @@ describe('claim-flow completion handoff', () => {reviewerEfforts: { antigravity: 'medium' },}),}),- '/repo', null, isTruthyMeta,+ '/repo', null,{ isTui: true, providerId: 'codex-tui', providerCommand: 'codex' },);@@ -620,7 +615,7 @@ describe('claim-flow completion handoff', () => {it('emits the pin on the full API prompt path too', async () => {const prompt = await buildAgentPrompt(makeTask({ metadata: claimMeta({ reviewers: ['grok'], usernames: [] }) }),- {}, '/repo', null, isTruthyMeta, { providerType: 'api' },+ {}, '/repo', null, { providerType: 'api' },);expect(prompt).toContain('--review-with grok');@@ -633,7 +628,7 @@ describe('claim-flow completion handoff', () => {// resolver is what keeps an in-flight legacy task off the #2507 stall.vi.mocked(getCodeReviewDefaults).mockResolvedValueOnce({ reviewers: ['copilot'] });const prompt = await buildAgentPrompt(- makeTask({ metadata: claimMeta() }), {}, '/repo', null, isTruthyMeta, { providerType: 'api' },+ makeTask({ metadata: claimMeta() }), {}, '/repo', null, { providerType: 'api' },);expect(prompt).toContain('--review-with codex');@@ -643,7 +638,7 @@ describe('claim-flow completion handoff', () => {it('does not emit the pin for a non-claim task', () => {const prompt = buildLightContextPrompt(makeTask({ metadata: { openPR: false, reviewers: ['codex'] } }),- '/repo', null, isTruthyMeta,+ '/repo', null,{ isTui: true, providerId: 'codex-tui', providerCommand: 'codex' },);@@ -659,7 +654,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { analysisType } }),'/repo',null,- isTruthyMeta,);expect(prompt).toContain(UI_AUDIT_RUNTIME_RULE);@@ -697,7 +691,6 @@ describe('buildLightContextPrompt', () => {{},'/repo',null,- isTruthyMeta,{ providerType: 'api' },);@@ -709,7 +702,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { selfImprovementType: 'mobile-responsive' } }),'/repo',null,- isTruthyMeta,);expect(prompt).toContain(UI_AUDIT_RUNTIME_RULE);@@ -720,7 +712,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { analysisType: 'security' } }),'/repo',null,- isTruthyMeta,);expect(prompt).not.toContain('## UI Audit Runtime');@@ -729,12 +720,12 @@ describe('buildLightContextPrompt', () => {describe('what it omits', () => {it('does NOT include the obsolete "# Chief of Staff Agent Briefing" header', () => {- const prompt = buildLightContextPrompt(makeTask(), '/repo', null, isTruthyMeta);+ const prompt = buildLightContextPrompt(makeTask(), '/repo', null);expect(prompt).not.toMatch(/Chief of Staff Agent Briefing/);});it('does NOT inject the "You are an autonomous agent" role-play framing', () => {- const prompt = buildLightContextPrompt(makeTask(), '/repo', null, isTruthyMeta);+ const prompt = buildLightContextPrompt(makeTask(), '/repo', null);expect(prompt).not.toMatch(/You are an autonomous agent/);});@@ -743,7 +734,7 @@ describe('buildLightContextPrompt', () => {// checking the rendered output has no section headings for them.const prompt = buildLightContextPrompt(makeTask({metadata: { context: 'extra detail', app: 'comics' }- }), '/repo', null, isTruthyMeta);+ }), '/repo', null);expect(prompt).not.toMatch(/## CLAUDE\.md Instructions/);expect(prompt).not.toMatch(/## Relevant Memory/);expect(prompt).not.toMatch(/## Digital Twin/);@@ -759,7 +750,7 @@ describe('buildLightContextPrompt', () => {describe('what it includes', () => {it('includes the task description directly without a metadata header', () => {- const prompt = buildLightContextPrompt(makeTask(), '/workspaces/foo', null, isTruthyMeta);+ const prompt = buildLightContextPrompt(makeTask(), '/workspaces/foo', null);expect(prompt).toMatch(/Add a button to the dashboard/);// The agent's cwd is set by the spawner; the prompt doesn't repeat metadata.expect(prompt).not.toMatch(/task-test-1/);@@ -771,24 +762,24 @@ describe('buildLightContextPrompt', () => {it('shows Target App for a managed app', () => {const prompt = buildLightContextPrompt(makeTask({ metadata: { app: 'comics' } }),- '/r', null, isTruthyMeta);+ '/r', null);expect(prompt).toMatch(/\*\*Target App\*\*: comics/);});it('omits Target App for the PortOS default app (cwd already scopes it)', () => {const prompt = buildLightContextPrompt(makeTask({ metadata: { app: 'portos-default' } }),- '/r', null, isTruthyMeta);+ '/r', null);expect(prompt).not.toMatch(/\*\*Target App\*\*/);});it('renders attached context (multiline and single-line)', () => {const single = buildLightContextPrompt(- makeTask({ metadata: { context: 'one-liner' } }), '/r', null, isTruthyMeta);+ makeTask({ metadata: { context: 'one-liner' } }), '/r', null);expect(single).toMatch(/### Context\none-liner/);const multi = buildLightContextPrompt(- makeTask({ metadata: { context: 'line one\nline two' } }), '/r', null, isTruthyMeta);+ makeTask({ metadata: { context: 'line one\nline two' } }), '/r', null);expect(multi).toMatch(/### Context\n\nline one\nline two/);});@@ -796,11 +787,11 @@ describe('buildLightContextPrompt', () => {// `metadata.context` payload must keep rendering identically.it('renders metadata.prompt, and the note after it', () => {const promptOnly = buildLightContextPrompt(- makeTask({ metadata: { prompt: 'line one\nline two' } }), '/r', null, isTruthyMeta);+ makeTask({ metadata: { prompt: 'line one\nline two' } }), '/r', null);expect(promptOnly).toMatch(/### Context\n\nline one\nline two/);const both = buildLightContextPrompt(- makeTask({ metadata: { prompt: 'line one\nline two', context: 'a short note' } }), '/r', null, isTruthyMeta);+ makeTask({ metadata: { prompt: 'line one\nline two', context: 'a short note' } }), '/r', null);expect(both).toMatch(/### Context\n\nline one\nline two\n\na short note/);});@@ -811,7 +802,7 @@ describe('buildLightContextPrompt', () => {const body = '# ⚡ SWARM MODE — claim and ship up to 3 independent issues in parallel\n\n**This run operates in slashdo mode.** Do the work.';const prompt = buildLightContextPrompt(makeTask({ description: '# ⚡ SWARM MODE — claim and ship up to 3 independent issues in parallel', metadata: { context: body } }),- '/r', null, isTruthyMeta);+ '/r', null);// Header appears exactly once, and the redundant `### Context` wrapper is gone.expect(prompt.match(/# ⚡ SWARM MODE/g)).toHaveLength(1);expect(prompt).not.toMatch(/### Context/);@@ -821,7 +812,7 @@ describe('buildLightContextPrompt', () => {// Same task written by post-#4153 code: payload in `metadata.prompt`.const split = buildLightContextPrompt(makeTask({ description: '# ⚡ SWARM MODE — claim and ship up to 3 independent issues in parallel', metadata: { prompt: body } }),- '/r', null, isTruthyMeta);+ '/r', null);expect(split.match(/# ⚡ SWARM MODE/g)).toHaveLength(1);expect(split).not.toMatch(/### Context/);expect(split).toMatch(/\*\*This run operates in slashdo mode\.\*\* Do the work\./);@@ -830,7 +821,7 @@ describe('buildLightContextPrompt', () => {it('lists screenshot file paths so the agent can read them via its own tools', () => {const prompt = buildLightContextPrompt(makeTask({ metadata: { screenshots: ['/tmp/a.png', '/tmp/b.png'] } }),- '/r', null, isTruthyMeta);+ '/r', null);expect(prompt).toMatch(/### Screenshots/);expect(prompt).toMatch(/`\/tmp\/a\.png`/);expect(prompt).toMatch(/`\/tmp\/b\.png`/);@@ -842,7 +833,7 @@ describe('buildLightContextPrompt', () => {{ filename: 'a-123.png', originalName: 'photo-one.png', path: '/tmp/attachments/a-123.png' },{ filename: 'b-456.png', originalName: 'photo-two.png', path: '/tmp/attachments/b-456.png' },] } }),- '/r', null, isTruthyMeta);+ '/r', null);expect(prompt).toMatch(/### Attachments/);expect(prompt).toMatch(/`\/tmp\/attachments\/a-123\.png` \(photo-one\.png\)/);expect(prompt).toMatch(/`\/tmp\/attachments\/b-456\.png` \(photo-two\.png\)/);@@ -854,7 +845,7 @@ describe('buildLightContextPrompt', () => {// must map that back to an on-disk path for the agent's filesystem tools.const prompt = buildLightContextPrompt(makeTask({ metadata: { screenshots: ['/api/screenshots/abcd1234-shot.png'] } }),- '/r', null, isTruthyMeta);+ '/r', null);const abs = join(PATHS.screenshots, 'abcd1234-shot.png');expect(prompt).toContain(`\`${abs}\``);expect(prompt).not.toMatch(/`\/api\/screenshots\//);@@ -865,7 +856,7 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { attachments: [{ filename: 'a-123.png', originalName: 'photo-one.png', path: '/api/attachments/a-123.png' },] } }),- '/r', null, isTruthyMeta);+ '/r', null);const abs = join(PATHS.cosAttachments, 'a-123.png');expect(prompt).toContain(`\`${abs}\` (photo-one.png)`);expect(prompt).not.toMatch(/`\/api\/attachments\//);@@ -877,7 +868,7 @@ describe('buildLightContextPrompt', () => {worktreePath: '/tmp/wt',baseBranch: 'origin/main',};- const prompt = buildLightContextPrompt(makeTask(), '/r', wt, isTruthyMeta);+ const prompt = buildLightContextPrompt(makeTask(), '/r', wt);expect(prompt).toMatch(/## Git Worktree/);expect(prompt).toMatch(/`cos\/test-1`/);expect(prompt).toMatch(/`\/tmp\/wt`/);@@ -891,7 +882,7 @@ describe('buildLightContextPrompt', () => {jiraTicketUrl: 'https://j/PROJ-123',jiraBranch: 'jira/proj-123',}- }), '/r', null, isTruthyMeta);+ }), '/r', null);expect(prompt).toMatch(/## JIRA/);expect(prompt).toMatch(/PROJ-123/);expect(prompt).toMatch(/`jira\/proj-123`/);@@ -902,7 +893,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { simplify: true, openPR: true } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: true });expect(prompt).toMatch(/## Completion Workflow/);expect(prompt).toMatch(/`\/simplify`/);@@ -937,7 +927,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { simplify: true, openPR: true, analysisType: 'jira-sprint-manager' } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: true });expect(prompt).toMatch(/Leave the PR open — do NOT merge it/);expect(prompt).toMatch(/tracked in JIRA/);@@ -952,7 +941,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { simplify: true, openPR: true, prCompletion: 'leave-open', reviewLoop: true } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: true });expect(prompt).toMatch(/Leave the PR open — do NOT merge it/);expect(prompt).toMatch(/`\/do:pr --review-with none --no-merge`/);@@ -965,7 +953,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, jiraTicketId: 'PROJ-9' } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: false, providerId: 'claude-code' });// `--no-merge` is required: a saved slashdo `merge: true` default would// otherwise merge the PR before the "leave it open" step is ever reached.@@ -979,7 +966,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, analysisType: 'jira-sprint-manager' } }),'/r',{ branchName: 'claim/x', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{ isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode' });// A JIRA-tracked PR is a human's to land, so there is no merge section for// the agent to drive — and an agent told to open a PR it will never land@@ -1000,7 +986,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex'] } }),'/r',null,- isTruthyMeta,{ isTui: true, providerId: 'codex-tui', providerCommand: 'codex' });expect(prompt).not.toMatch(/gh pr create/);expect(prompt).not.toMatch(/git push -u origin/);@@ -1023,7 +1008,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{ isTui: true, providerId: 'codex-tui', providerCommand: 'codex' });expect(prompt).not.toMatch(/gh pr create/);expect(prompt).not.toMatch(/## Review Loop/);@@ -1043,8 +1027,7 @@ describe('buildLightContextPrompt', () => {sourceTaskId: 'task-src-6',}}),'/r',- { branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta);+ { branchName: 'b', worktreePath: '/tmp/wt' });expect(prompt).toMatch(/glab mr note 5 --message/);expect(prompt).not.toMatch(/gh pr comment/);});@@ -1061,8 +1044,7 @@ describe('buildLightContextPrompt', () => {sourceTaskId: 'task-src-5',}}),'/r',- { branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta);+ { branchName: 'b', worktreePath: '/tmp/wt' });expect(prompt).toMatch(/## Review-Loop Follow-up/);// The review still runs — only the merge is withheld.expect(prompt).toMatch(/codex/);@@ -1076,7 +1058,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { simplify: true, openPR: true } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: true, providerId: 'codex-tui' });expect(prompt).toMatch(/## Completion Workflow/);expect(prompt).not.toMatch(/`\/simplify`/);@@ -1088,7 +1069,7 @@ describe('buildLightContextPrompt', () => {// merges nothing on exit — so /do:push is the right completion step.const prompt = buildLightContextPrompt(makeTask({ metadata: { simplify: true, openPR: false } }),- '/r', null, isTruthyMeta, { isTui: true });+ '/r', null, { isTui: true });expect(prompt).toMatch(/`\/do:push`/);expect(prompt).not.toMatch(/`\/do:pr`/);// /do:push doesn't open a PR — no merge step should be emitted.@@ -1105,7 +1086,7 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { simplify: true, openPR: false } }),'/r',{ branchName: 'cos/task-1/agent-a', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta, { isTui: true });+ { isTui: true });expect(prompt).toMatch(/## Completion Workflow/);expect(prompt).toMatch(/^1\. `\/simplify`/m);expect(prompt).toMatch(/^2\. Stage only the files you changed \(never `git add -A` \/ `git add \.`\) and commit with a conventional message/m);@@ -1126,7 +1107,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { simplify: true, openPR: true, reviewLoop: true, reviewers: ['codex', 'copilot'] } }),'/r',{ branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{isTui: true,providerId: 'opencode-ollama-tui',@@ -1191,7 +1171,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex', 'copilot'], reviewStopMode } }),'/r',{ branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{ isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode', localAgentLoopBody: 'RECIPE' });expect(prompt).toContain(`\`${reviewStopMode}\` skips the PR-side reviewers only when the local phase actually satisfied that stop condition`);@@ -1208,7 +1187,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['copilot', 'codex'], reviewStopMode } }),'/r',{ branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{ isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode', localAgentLoopBody: 'RECIPE' });expect(prompt).toContain('Cross-phase stop-mode gate');@@ -1223,7 +1201,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex', 'copilot', 'ollama'], reviewStopMode } }),'/r',{ branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{ isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode', localAgentLoopBody: 'RECIPE' });expect(prompt).toContain('`ollama`=0, `codex`=1, `copilot`=2');@@ -1237,7 +1214,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex', 'copilot'], optionalReviewers: ['codex'] } }),'/r',{ branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{ isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode', localAgentLoopBody: 'RECIPE' });expect(prompt).toContain('All local reviewers are optional, so missing/inconclusive results');@@ -1259,7 +1235,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex'] } }),'/r',{ branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{isTui: true,providerId: 'opencode-ollama-tui',@@ -1292,7 +1267,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['claude', 'antigravity', 'grok'], reviewerApplies: true } }),'/r',{ branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{isTui: true,providerId: 'opencode-ollama-tui',@@ -1323,7 +1297,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex'] } }),'/r',{ branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{isTui: true,providerId: 'opencode-ollama-tui',@@ -1341,7 +1314,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex'], reviewerApplies: true } }),'/r',{ branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{ isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode', localAgentLoopBody: 'RECIPE' });const localStart = prompt.indexOf('### Local Review Before Opening the PR/MR');const prPush = prompt.indexOf('publish_reviewed_branch -u "$PUSH_REMOTE" "$BRANCH"');@@ -1357,7 +1329,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex'] } }),'/r',{ branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'release; echo bad' },- isTruthyMeta,{ isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode', localAgentLoopBody: 'RECIPE' });expect(prompt).toContain("git diff 'origin/release; echo bad'...HEAD");@@ -1369,7 +1340,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['ollama'], usernames: ['alice'] } }),'/r',{ branchName: 'claim/issue-4363', worktreePath: '/tmp/wt', baseBranch: 'main', forgeCli: 'glab' },- isTruthyMeta,{ isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode' });expect(prompt).toMatch(/### Local Review Before Opening the PR\/MR/);@@ -1395,7 +1365,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { simplify: true, openPR: true } }),'/r',{ branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{ isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode' });expect(prompt).toMatch(/gh pr create/);expect(prompt).toMatch(/## Merge Gate/);@@ -1410,7 +1379,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: false } }),'/r',{ branchName: 'claim/issue-2', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode' });expect(prompt).toMatch(/## Completion Workflow/);expect(prompt).not.toMatch(/`\/do:push`/);@@ -1426,7 +1394,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: false } }),'/r',{ branchName: 'weird;rm -rf', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode' });expect(prompt).not.toMatch(/git push/);expect(prompt).not.toMatch(/git .*weird;rm -rf/);@@ -1444,7 +1411,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['copilot'] } }),'/r',{ branchName: 'claim/x', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{ isTui: true, providerId: 'codex-tui', providerCommand: 'codex', defaultReviewers: ['copilot'] });expect(prompt).toMatch(/## Completion Workflow/);expect(prompt).toMatch(/does NOT have slashdo/);@@ -1464,7 +1430,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex'] } }),'/r',{ branchName: 'claim/x', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{ isTui: true, providerId: 'codex-tui', providerCommand: 'codex' });// A routine base conflict stays in this agent's lifecycle. Previously the@@ -1486,7 +1451,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['copilot'] } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{ isTui: true, providerId: 'antigravity-tui', providerCommand: 'agy' });expect(prompt).toMatch(/## Review Loop/);expect(prompt).not.toMatch(/## Review-Loop Follow-up/);@@ -1505,7 +1469,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex'] } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{ isTui: true, providerId: 'codex-tui', providerCommand: 'codex' });expect(prompt).toMatch(/write the completion sentinel — the run is not done until you have/);expect(prompt).not.toMatch(/The system will clean up your worktree on exit/);@@ -1516,7 +1479,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex'] } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{ isTui: false, providerId: 'codex', providerCommand: 'codex' });expect(prompt).toMatch(/### Local Review Before Opening the PR\/MR/);expect(prompt).toMatch(/## Merge Gate/);@@ -1537,7 +1499,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex'] } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{isTui: true, providerId: 'codex-tui', providerCommand: 'codex',localAgentLoopBody: 'RECIPE: codex --sandbox read-only review --base <base>',@@ -1555,7 +1516,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex'] } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{isTui: true, providerId: 'codex-tui', providerCommand: 'codex',localAgentLoopBody: body,@@ -1582,7 +1542,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true } }),'/r',{ branchName: 'weird;rm -rf /', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{ isTui: true, providerId: 'codex-tui', providerCommand: 'codex' });expect(prompt).toMatch(/BRANCH='weird;rm -rf \/'/);expect(prompt).toContain('publish_reviewed_branch -u "$PUSH_REMOTE" "$BRANCH"');@@ -1596,7 +1555,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true } }),'/r',{ branchName: 'cos/task-1/agent-2', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{ isTui: true, providerId: 'codex-tui', providerCommand: 'codex' });expect(readable).toMatch(/BRANCH=cos\/task-1\/agent-2/);expect(readable).toContain('publish_reviewed_branch -u "$PUSH_REMOTE" "$BRANCH"');@@ -1605,7 +1563,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: true, providerId: 'codex-tui', providerCommand: 'codex' });expect(noBase).toMatch(/git remote set-head origin --auto/);expect(noBase).toMatch(/BASE_BRANCH=\$\(git symbolic-ref --short refs\/remotes\/origin\/HEAD/);@@ -1620,7 +1577,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, simplify: true } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: false, providerId: 'my-custom-agent', providerCommand: '/opt/homebrew/bin/claude' });expect(prompt).toMatch(/^## Completion$/m);expect(prompt).toMatch(/`\/simplify`/);@@ -1633,7 +1589,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: false } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: true, providerId: 'antigravity-tui', providerCommand: 'agy' });expect(prompt).not.toMatch(/`\/do:push`/);expect(prompt).not.toMatch(/git push/);@@ -1646,7 +1601,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: true, providerId: 'claude-code-tui', providerCommand: 'claude' });expect(prompt).toMatch(/`\/do:pr --review-with none`/);expect(prompt).toMatch(/external review is disabled/i);@@ -1658,7 +1612,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: false, providerId: 'codex', providerCommand: 'codex' });expect(prompt).toMatch(/^## Completion$/m);expect(prompt).not.toMatch(/`\/do:pr`/);@@ -1678,7 +1631,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, simplify: true } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: false, providerId: 'antigravity-cli', providerCommand: 'agy' });expect(prompt).toMatch(/^## Completion$/m);expect(prompt).not.toMatch(/`\/simplify`/);@@ -1699,7 +1651,6 @@ describe('buildLightContextPrompt', () => {task,'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: false, providerId: 'codex', providerCommand: 'codex' });expect(prompt).toMatch(/no change is needed/i);expect(prompt).toMatch(/leave the worktree clean/i);@@ -1719,7 +1670,6 @@ describe('buildLightContextPrompt', () => {} }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: true, providerId: 'claude-code-tui', providerCommand: 'claude' },);@@ -1737,7 +1687,6 @@ describe('buildLightContextPrompt', () => {} }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: true, providerId: 'claude-ollama-tui', providerCommand: 'claude', leanMode: true },);@@ -1754,7 +1703,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, simplify: true } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: false });expect(prompt).toMatch(/`\/simplify`/);expect(prompt).toMatch(/`\/do:pr/);@@ -1765,7 +1713,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, simplify: true } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: false, providerId: 'claude-code' });expect(prompt).toMatch(/^## Completion$/m);expect(prompt).toMatch(/`\/simplify`/);@@ -1786,7 +1733,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, simplify: false } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: false, providerId: 'claude-code' });expect(prompt).toMatch(/`\/do:pr --review-with none`/);expect(prompt).toMatch(/external review disabled/i);@@ -1803,7 +1749,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, simplify: false } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: false, providerId: 'claude-code' });expect(prompt).toMatch(/`\/do:pr`/);expect(prompt).not.toMatch(/`\/simplify`/);@@ -1817,7 +1762,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: false, simplify: true } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{ isTui: false, providerId: 'claude-code' });expect(prompt).toMatch(/^\s*\d+\.\s+Stage only the files you changed \(never `git add -A` \/ `git add \.`\) and commit with a conventional message/m);expect(prompt).toMatch(/Do NOT push and do NOT open a PR: PortOS merges this branch into `main` in the source checkout after you exit and deletes it/);@@ -1829,7 +1773,7 @@ describe('buildLightContextPrompt', () => {it('suppresses the PR completion workflow but still writes a sentinel when readOnly + TUI', () => {const prompt = buildLightContextPrompt(makeTask({ metadata: { readOnly: true } }),- '/r', null, isTruthyMeta, { isTui: true });+ '/r', null, { isTui: true });expect(prompt).toMatch(/Read-Only Task/);expect(prompt).not.toMatch(/## Completion Workflow/);// A read-only TUI agent must still be told to write .agent-done — the@@ -1851,7 +1795,7 @@ describe('buildLightContextPrompt', () => {const completionPrompt = (metadata = {}) => buildLightContextPrompt(makeTask({ metadata }),- '/shared-checkout', null, isTruthyMeta,+ '/shared-checkout', null,{ isTui: true, agentId: 'agent-07ddbb85', providerId: 'opencode-mtplx-tui', providerCommand: 'opencode' });it('gives a worktree-less TUI completion run one canonical sentinel path, no read-only banner, and permission to write it', () => {@@ -1891,7 +1835,7 @@ describe('buildLightContextPrompt', () => {it('read-only on a non-TUI (CLI) provider gets the bare notice, no sentinel', () => {const prompt = buildLightContextPrompt(makeTask({ metadata: { readOnly: true } }),- '/r', null, isTruthyMeta, { isTui: false, providerId: 'claude-code' });+ '/r', null, { isTui: false, providerId: 'claude-code' });expect(prompt).toMatch(/Read-Only Task/);// CLI/API agents complete on process exit and never poll a sentinel.expect(prompt).not.toMatch(/\.agent-done/);@@ -1911,7 +1855,7 @@ describe('buildLightContextPrompt', () => {}}),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta, { defaultReviewers: ['copilot'] });+ { defaultReviewers: ['copilot'] });expect(prompt).toMatch(/## Review-Loop Follow-up/);expect(prompt).toMatch(/task-src-1/);expect(prompt).toMatch(/gh pr merge "https:\/\/github\.com\/o\/r\/pull\/9" --merge --delete-branch/);@@ -1949,8 +1893,7 @@ describe('buildLightContextPrompt', () => {sourceTaskId: 'task-src-2',}}),'/r',- { branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta);+ { branchName: 'b', worktreePath: '/tmp/wt' });expect(prompt).toMatch(/## Merge Follow-up/);expect(prompt).not.toMatch(/## Review-Loop Follow-up/);// CI is the gate, and the merge command matches the review-loop contract.@@ -1979,8 +1922,7 @@ describe('buildLightContextPrompt', () => {sourceTaskId: 'task-src-3',}}),'/r',- { branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta);+ { branchName: 'b', worktreePath: '/tmp/wt' });expect(prompt).toMatch(/## Merge Follow-up/);// Addressed by MR IID — `glab mr merge` does not accept a URL.expect(prompt).toMatch(/glab mr merge 5 --yes --remove-source-branch/);@@ -2004,8 +1946,7 @@ describe('buildLightContextPrompt', () => {sourceTaskId: 'task-src-4',}}),'/r',- { branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta);+ { branchName: 'b', worktreePath: '/tmp/wt' });expect(prompt).toMatch(/gh pr merge "https:\/\/github\.example\.com\/o\/r\/pull\/7" --merge --delete-branch/);expect(prompt).not.toMatch(/glab (?:issue|mr) /);});@@ -2023,8 +1964,7 @@ describe('buildLightContextPrompt', () => {sourceTaskId: 'task-src-2',}}),'/r',- { branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta);+ { branchName: 'b', worktreePath: '/tmp/wt' });expect(prompt).toMatch(/--review-with claude/);// The Copilot-specific pre-request wording must be replaced when no// Copilot reviewer leads the order (the agent invokes the reviewers itself).@@ -2044,8 +1984,7 @@ describe('buildLightContextPrompt', () => {sourceTaskId: 'task-src-3',}}),'/r',- { branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta);+ { branchName: 'b', worktreePath: '/tmp/wt' });expect(prompt).toMatch(/--review-with codex,antigravity,copilot/);expect(prompt).toMatch(/--review-stop-on-clean/);expect(prompt).not.toMatch(/--reviewer-applies/);@@ -2074,7 +2013,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: true, defaultReviewers: codeReviewDefaults.reviewers, codeReviewDefaults });expect(prompt).toMatch(/--review-with ollama~opt,codex,@alice --review-stop-on-findings/);expect(prompt).not.toMatch(/--reviewer-applies/);@@ -2099,7 +2037,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: true, defaultReviewers: codeReviewDefaults.reviewers, codeReviewDefaults });// The skip list is NOT relaxed — a surviving `inconclusive` still blocks.expect(prompt).toContain('skip the gate if the loop ended `timeout`, `error`, `inconclusive`, `review-blocked`, or `guardrail`');@@ -2114,7 +2051,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: true });expect(prompt).toContain('skip the gate if the loop ended `timeout`, `error`, `inconclusive`, `review-blocked`, or `guardrail`');expect(prompt).not.toContain('Every configured reviewer is optional (`~opt`)');@@ -2131,7 +2067,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: true, defaultReviewers: codeReviewDefaults.reviewers, codeReviewDefaults });expect(prompt).toMatch(/--review-with ollama~opt~max=1,codex~max=2/);});@@ -2141,7 +2076,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['ollama'], reviewerMaxRounds: { ollama: 0 } } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: true, defaultReviewers: ['ollama'], codeReviewDefaults: { reviewers: ['ollama'], reviewerMaxRounds: { ollama: 3 } } });// `0` = loop until clean, and it must not be mistaken for "no cap".expect(prompt).toMatch(/--review-with ollama~max=0/);@@ -2154,7 +2088,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true } }),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: true });expect(prompt).not.toMatch(/@alice/);expect(prompt).not.toMatch(/~opt/);@@ -2174,8 +2107,7 @@ describe('buildLightContextPrompt', () => {sourceTaskId: 'task-src-u',}}),'/r',- { branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta);+ { branchName: 'b', worktreePath: '/tmp/wt' });expect(prompt).toMatch(/--review-with copilot,@CodeReviewbot/);// The agent is told to request the username as a PR reviewer that gates merge.expect(prompt).toMatch(/--add-reviewer/);@@ -2195,8 +2127,7 @@ describe('buildLightContextPrompt', () => {sourceTaskId: 'task-src-uonly',}}),'/r',- { branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta);+ { branchName: 'b', worktreePath: '/tmp/wt' });expect(prompt).toMatch(/--review-with @CodeReviewbot/);// No copilot fallback re-introduced.expect(prompt).not.toMatch(/--review-with copilot/);@@ -2214,8 +2145,7 @@ describe('buildLightContextPrompt', () => {sourceTaskId: 'task-src-map',}}),'/r',- { branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta);+ { branchName: 'b', worktreePath: '/tmp/wt' });expect(prompt).toMatch(/codex --model gpt-5\.6-sol/);expect(prompt).toMatch(/claude --model qwen2\.5:7b/);});@@ -2233,8 +2163,7 @@ describe('buildLightContextPrompt', () => {sourceTaskId: 'task-src-effort',}}),'/r',- { branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta);+ { branchName: 'b', worktreePath: '/tmp/wt' });// codex takes a config pair; claude and agy take --effort. The model pin// and the effort ride the SAME command line when both are set.expect(prompt).toMatch(/codex --model gpt-5\.6-sol -c model_reasoning_effort=high/);@@ -2257,8 +2186,7 @@ describe('buildLightContextPrompt', () => {sourceTaskId: 'task-src-cursor-effort',}}),'/r',- { branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta);+ { branchName: 'b', worktreePath: '/tmp/wt' });// This is a literal command line the agent runs; `cursor-agent --effort max`// exits non-zero, so the level has to ride the model variant instead.expect(prompt).toMatch(/cursor-agent --model gpt-5\[effort=max\]/);@@ -2277,8 +2205,7 @@ describe('buildLightContextPrompt', () => {sourceTaskId: 'task-src-local-effort',}}),'/r',- { branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta);+ { branchName: 'b', worktreePath: '/tmp/wt' });expect(prompt).toContain('"effort": "high"');// The effort has no slashdo suffix, so it must NOT leak into the flag string.expect(prompt).not.toMatch(/--review-with[^\n]*effort/);@@ -2297,8 +2224,7 @@ describe('buildLightContextPrompt', () => {sourceTaskId: 'task-src-max',}}),'/r',- { branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta);+ { branchName: 'b', worktreePath: '/tmp/wt' });// This prompt drives the loop in prose, so the cap has to be stated —// the `equiv` flag string alone wouldn't bind the agent.expect(prompt).toMatch(/Round caps \(~max\)/);@@ -2321,8 +2247,7 @@ describe('buildLightContextPrompt', () => {sourceTaskId: 'task-src-nomax',}}),'/r',- { branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta);+ { branchName: 'b', worktreePath: '/tmp/wt' });expect(prompt).not.toMatch(/Round caps \(~max\)/);expect(prompt).toMatch(/--review-with ollama,codex/);});@@ -2339,8 +2264,7 @@ describe('buildLightContextPrompt', () => {sourceTaskId: 'task-src-cl',}}),'/r',- { branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta);+ { branchName: 'b', worktreePath: '/tmp/wt' });expect(prompt).toMatch(/claude --model qwen2\.5:7b/);});@@ -2363,8 +2287,7 @@ describe('buildLightContextPrompt', () => {sourceTaskId: 'task-src-verbatim',}}),'/r',- { branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta);+ { branchName: 'b', worktreePath: '/tmp/wt' });// Both ids appear exactly as configured — no Bedrock rewrite, no mangling.expect(prompt).toMatch(/claude --model us\.anthropic\.claude-opus-4-8/);expect(prompt).toMatch(/codex --model gpt-5\.6-sol/);@@ -2387,8 +2310,7 @@ describe('buildLightContextPrompt', () => {sourceTaskId: 'task-src-cx',}}),'/r',- { branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta);+ { branchName: 'b', worktreePath: '/tmp/wt' });expect(prompt).toMatch(/codex --model gpt-5\.6-sol/);});@@ -2406,8 +2328,7 @@ describe('buildLightContextPrompt', () => {sourceTaskId: 'task-src-noncx',}}),'/r',- { branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta);+ { branchName: 'b', worktreePath: '/tmp/wt' });expect(prompt).not.toMatch(/--model gpt-5\.6-sol/);});@@ -2422,8 +2343,7 @@ describe('buildLightContextPrompt', () => {sourceTaskId: 'task-src-llm',}}),'/r',- { branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta);+ { branchName: 'b', worktreePath: '/tmp/wt' });// The agent gets a copy-pasteable stdin bridge pipeline — no HTTP route,// no instance-password gate — without it the lmstudio/ollama reviewer// kinds have no way to actually run a review.@@ -2441,7 +2361,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, simplify: true, reviewers: ['antigravity'] } }),'/r',{ branchName: 'feat', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: true });expect(prompt).toMatch(/`\/do:pr --review-with antigravity`/);});@@ -2451,7 +2370,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex', 'antigravity'], reviewStopMode: 'on-clean' } }),'/r',{ branchName: 'feat', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: true });expect(prompt).toMatch(/--review-stop-on-clean/);// `partial` is a successful stop-mode short-circuit → mergeable.@@ -2463,7 +2381,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex', 'antigravity'] } }),'/r',{ branchName: 'feat', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: true });expect(prompt).toContain('reports `clean` (or `too-large`)');expect(prompt).not.toContain('reports `clean`, `partial`');@@ -2479,8 +2396,7 @@ describe('buildLightContextPrompt', () => {sourceTaskId: 'task-src-4',}}),'/r',- { branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta);+ { branchName: 'b', worktreePath: '/tmp/wt' });// Must instruct requesting Copilot at its turn — not claim a pre-request happened.expect(prompt).toMatch(/request a Copilot review when you reach its turn/);expect(prompt).not.toMatch(/already requested the initial Copilot/);@@ -2501,7 +2417,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, simplify: true, reviewLoopFollowUp: true } }),'/r',{ branchName: 'feat-x', worktreePath: '/tmp/wt', existingBranch: true },- isTruthyMeta,{ isTui: false, providerId: 'claude-code' });expect(prompt).toMatch(/## Git Worktree/);expect(prompt).toMatch(/\*\(pre-existing PR branch\)\*/);@@ -2521,7 +2436,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, simplify: true, resumedFromAgentId: 'agent-dead' } }),'/r',{ branchName: 'cos/task-1/agent-dead', worktreePath: '/tmp/wt', existingBranch: true },- isTruthyMeta,{ isTui: false, providerId: 'claude-code' });expect(prompt).toMatch(/## Resuming Unfinished Work/);expect(prompt).toMatch(/agent-dead/);@@ -2534,7 +2448,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: true, simplify: true } }),'/r',{ branchName: 'cos/task-1/agent-new', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{ isTui: false, providerId: 'claude-code' });expect(prompt).toMatch(/## Git Worktree/);expect(prompt).not.toMatch(/## Resuming Unfinished Work/);@@ -2547,7 +2460,6 @@ describe('buildLightContextPrompt', () => {makeTask({ metadata: { openPR: false, simplify: true } }),'/r',{ branchName: 'feat-x', worktreePath: '/tmp/wt' },- isTruthyMeta,{ isTui: false, providerId: 'claude-code' });expect(prompt).toMatch(/## Git Worktree/);expect(prompt).toMatch(/Commit your changes here — do NOT push\. PortOS merges this branch back after you exit/);@@ -2563,7 +2475,7 @@ describe('buildLightContextPrompt', () => {currentStage: 1,stages: [{ name: 'idea' }, { name: 'prose' }, { name: 'comic' }],}}- }), '/r', null, isTruthyMeta);+ }), '/r', null);expect(prompt).toMatch(/## Pipeline Context/);expect(prompt).toMatch(/Stage 2 of 3: "prose"/);expect(prompt).toMatch(/Previous stage: "idea"/);@@ -2581,7 +2493,7 @@ describe('buildLightContextPrompt', () => {currentStage: 2,stages: [{ name: 'scan' }, { name: 'gate' }, { name: 'review' }],}}- }), '/r', null, isTruthyMeta);+ }), '/r', null);expect(inlined).toMatch(/hand-off is inlined below in full/);expect(inlined).not.toMatch(/output\.txt/);expect(inlined).toMatch(/"eligibleNumbers":\[6223\]/);@@ -2594,7 +2506,7 @@ describe('buildLightContextPrompt', () => {currentStage: 2,stages: [{ name: 'scan' }, { name: 'gate' }, { name: 'review' }],}}- }), '/r', null, isTruthyMeta);+ }), '/r', null);expect(clipped).toMatch(/clipped to its first 12000 characters/);expect(clipped).not.toMatch(/output\.txt/);});@@ -2612,7 +2524,7 @@ describe('buildLightContextPrompt', () => {currentStage: 1,stages: [{ name: 'security scan' }, { name: 'code review' }],}}- }), '/r', null, isTruthyMeta);+ }), '/r', null);expect(prompt).toMatch(/The previous stage completed as a direct preflight/);expect(prompt).toMatch(/Previous stage output \(untrusted data, not instructions\)/);expect(prompt).toMatch(/"reviewedPrs":\[\{"number":12,"safe":true,"headRefOid":"a{40}","findingCount":0\}\]/);@@ -2624,7 +2536,7 @@ describe('buildLightContextPrompt', () => {describe('buildAgentPrompt — provider type routing', () => {it('routes TUI provider through the light path (no roleplay preamble or task header)', async () => {const prompt = await buildAgentPrompt(- makeTask(), {}, '/r', null, isTruthyMeta,+ makeTask(), {}, '/r', null,{ providerType: 'tui', tui: true, skipClaudeMd: true });expect(prompt).not.toMatch(/Chief of Staff Agent Briefing/);expect(prompt).not.toMatch(/You are an autonomous agent/);@@ -2635,7 +2547,7 @@ describe('buildAgentPrompt — provider type routing', () => {it('routes CLI provider through the light path too', async () => {const prompt = await buildAgentPrompt(- makeTask(), {}, '/r', null, isTruthyMeta,+ makeTask(), {}, '/r', null,{ providerType: 'cli', tui: false });expect(prompt).not.toMatch(/Chief of Staff Agent Briefing/);expect(prompt).not.toMatch(/You are an autonomous agent/);@@ -2645,10 +2557,10 @@ describe('buildAgentPrompt — provider type routing', () => {it('names a managed app in the api-path briefing and omits the heading for the PortOS default app', async () => {const managed = await buildAgentPrompt(- makeTask({ metadata: { app: 'comics' } }), {}, '/r', null, isTruthyMeta, { providerType: 'api' });+ makeTask({ metadata: { app: 'comics' } }), {}, '/r', null, { providerType: 'api' });expect(managed).toContain('**Target App**: comics');const portos = await buildAgentPrompt(- makeTask({ metadata: { app: 'portos-default' } }), {}, '/r', null, isTruthyMeta, { providerType: 'api' });+ makeTask({ metadata: { app: 'portos-default' } }), {}, '/r', null, { providerType: 'api' });expect(portos).not.toContain('**Target App**');});@@ -2656,7 +2568,7 @@ describe('buildAgentPrompt — provider type routing', () => {it('renders metadata.prompt and the human note into the api-path briefing', async () => {const prompt = await buildAgentPrompt(makeTask({ metadata: { prompt: 'the agent body\nsecond line', context: 'a short note' } }),- {}, '/r', null, isTruthyMeta, { providerType: 'api' });+ {}, '/r', null, { providerType: 'api' });expect(prompt).toContain('the agent body\nsecond line');expect(prompt).toContain('a short note');});@@ -2664,7 +2576,7 @@ describe('buildAgentPrompt — provider type routing', () => {it('renders a legacy context-only task unchanged', async () => {const prompt = await buildAgentPrompt(makeTask({ metadata: { context: 'legacy body\nsecond line' } }),- {}, '/r', null, isTruthyMeta, { providerType: 'api' });+ {}, '/r', null, { providerType: 'api' });expect(prompt).toContain('legacy body\nsecond line');});@@ -2683,14 +2595,14 @@ describe('buildAgentPrompt — provider type routing', () => {securityScan: { reports: [{ number: 42, findings: flaggedPayload }] },},}),- {}, '/r', null, isTruthyMeta, { providerType: 'api' });+ {}, '/r', null, { providerType: 'api' });expect(prompt).not.toContain(flaggedPayload);});// #8200 — there is no user-editable template on this path; the builder never// consults the prompt-stage system, so a stored stage cannot silently diverge.it('builds the api-path briefing without consulting a prompt stage', async () => {- const prompt = await buildAgentPrompt(makeTask(), {}, '/r', null, isTruthyMeta, { providerType: 'api' });+ const prompt = await buildAgentPrompt(makeTask(), {}, '/r', null, { providerType: 'api' });expect(prompt).toMatch(/^## Instructions$/m);expect(prompt).toMatch(/^## Git Hygiene/m);});@@ -2701,7 +2613,7 @@ describe('buildAgentPrompt — provider type routing', () => {it('returns { userPrompt, systemPrompt } with the task in user and the contract in system', async () => {const parts = await buildAgentPrompt(- splitTask(), {}, '/r', wt, isTruthyMeta,+ splitTask(), {}, '/r', wt,{ providerType: 'tui', providerId: 'claude-ollama-tui', providerCommand: 'claude', leanMode: true, split: true });expect(parts.userPrompt).toMatch(/Add a button to the dashboard/);expect(parts.userPrompt).toMatch(/Some context/);@@ -2714,8 +2626,8 @@ describe('buildAgentPrompt — provider type routing', () => {it('split parts carry exactly the combined prompt sections (no drift)', async () => {const opts = { providerType: 'tui', providerId: 'claude-ollama-tui', providerCommand: 'claude', leanMode: true };- const combined = await buildAgentPrompt(splitTask(), {}, '/r', wt, isTruthyMeta, opts);- const parts = await buildAgentPrompt(splitTask(), {}, '/r', wt, isTruthyMeta, { ...opts, split: true });+ const combined = await buildAgentPrompt(splitTask(), {}, '/r', wt, opts);+ const parts = await buildAgentPrompt(splitTask(), {}, '/r', wt, { ...opts, split: true });// Combined = task sections + contract sections + Begin line; the split// moves the contract out and keeps the Begin line with the user prompt.const reassembled = parts.userPrompt.replace(@@ -2727,7 +2639,7 @@ describe('buildAgentPrompt — provider type routing', () => {it('leanMode routes a claude TUI to the slashdo-free completion workflow', async () => {const prompt = await buildAgentPrompt(- splitTask(), {}, '/r', wt, isTruthyMeta,+ splitTask(), {}, '/r', wt,{ providerType: 'tui', providerId: 'claude-ollama-tui', providerCommand: 'claude', leanMode: true });expect(prompt).not.toMatch(/`\/do:push`/);expect(prompt).not.toMatch(/`\/do:pr`/);@@ -2741,7 +2653,7 @@ describe('buildAgentPrompt — provider type routing', () => {// session is told to run it.const task = splitTask();const prompt = await buildAgentPrompt(- { ...task, metadata: { ...task.metadata, simplify: true } }, {}, '/r', wt, isTruthyMeta,+ { ...task, metadata: { ...task.metadata, simplify: true } }, {}, '/r', wt,{ providerType: 'tui', providerId: 'claude-code-tui', providerCommand: 'claude' });expect(prompt).toMatch(/^1\. `\/simplify`/m);expect(prompt).not.toMatch(/does NOT have slashdo/);@@ -2751,7 +2663,7 @@ describe('buildAgentPrompt — provider type routing', () => {it('splits a STANDARD (non-lean) claude TUI too, keeping slashdo in the system prompt', async () => {const task = splitTask();const parts = await buildAgentPrompt(- { ...task, metadata: { ...task.metadata, simplify: true } }, {}, '/r', wt, isTruthyMeta,+ { ...task, metadata: { ...task.metadata, simplify: true } }, {}, '/r', wt,{ providerType: 'tui', providerId: 'claude-code-tui', providerCommand: 'claude', split: true });// Task in the user prompt, contract (with slashdo — NOT slashdo-free) in system.expect(parts.userPrompt).toMatch(/Add a button to the dashboard/);@@ -2763,8 +2675,8 @@ describe('buildAgentPrompt — provider type routing', () => {it('split parts carry exactly the combined prompt for a standard claude CLI (no drift)', async () => {const opts = { providerType: 'cli', providerId: 'claude-code', providerCommand: 'claude' };- const combined = await buildAgentPrompt(splitTask(), {}, '/r', wt, isTruthyMeta, opts);- const parts = await buildAgentPrompt(splitTask(), {}, '/r', wt, isTruthyMeta, { ...opts, split: true });+ const combined = await buildAgentPrompt(splitTask(), {}, '/r', wt, opts);+ const parts = await buildAgentPrompt(splitTask(), {}, '/r', wt, { ...opts, split: true });const reassembled = parts.userPrompt.replace(/\n\nBegin working on the task now\.\n$/,'\n\n' + parts.systemPrompt.replace(/\n$/, '') + '\n\nBegin working on the task now.\n'@@ -2793,7 +2705,6 @@ describe('buildAgentPrompt — provider type routing', () => {{},'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- isTruthyMeta,{ providerType: 'api' });expect(prompt).toMatch(/## Review-Loop Follow-up/);// Merge command must be present, exactly with --merge --delete-branch.@@ -2820,14 +2731,14 @@ describe('unattended-run rule reaches every prompt path', () => {const wt = { branchName: 'cos/t/a', worktreePath: '/tmp/wt', baseBranch: 'main' };it('rides in the light-context prompt', () => {- const prompt = buildLightContextPrompt(makeTask(), '/repo', null, isTruthyMeta);+ const prompt = buildLightContextPrompt(makeTask(), '/repo', null);expect(prompt).toMatch(RULE_HEADING);expect(prompt).toMatch(/Never ask the user to choose or approve/);});it('rides in the SYSTEM half of a split prompt, not the user half', async () => {const parts = await buildAgentPrompt(- makeTask(), {}, '/r', wt, isTruthyMeta,+ makeTask(), {}, '/r', wt,{ providerType: 'tui', providerId: 'claude-code-tui', providerCommand: 'claude', split: true });expect(parts.systemPrompt).toMatch(RULE_HEADING);expect(parts.userPrompt).not.toMatch(RULE_HEADING);@@ -2835,7 +2746,7 @@ describe('unattended-run rule reaches every prompt path', () => {it('rides in the full api-path prompt', async () => {const prompt = await buildAgentPrompt(- makeTask(), {}, '/r', null, isTruthyMeta, { providerType: 'api' });+ makeTask(), {}, '/r', null, { providerType: 'api' });expect(prompt).toMatch(RULE_HEADING);});@@ -2976,7 +2887,7 @@ describe('discardWorktree (reasoning-only) completion contract', () => {};it('light TUI path emits the sentinel-only completion, not the /do:push workflow', () => {- const prompt = buildLightContextPrompt(liTask(), '/r', wt, isTruthyMeta, { isTui: true });+ const prompt = buildLightContextPrompt(liTask(), '/r', wt, { isTui: true });assertReasoningOnly(prompt);// Worktree section carries the discard note, not commit/merge guidance.expect(prompt).toMatch(/discarded on exit/);@@ -2984,7 +2895,7 @@ describe('discardWorktree (reasoning-only) completion contract', () => {});it('light CLI (non-TUI) path emits the sentinel-only completion', () => {- const prompt = buildLightContextPrompt(liTask(), '/r', wt, isTruthyMeta, { isTui: false, providerId: 'codex' });+ const prompt = buildLightContextPrompt(liTask(), '/r', wt, { isTui: false, providerId: 'codex' });assertReasoningOnly(prompt);});@@ -3010,7 +2921,7 @@ describe('discardWorktree (reasoning-only) completion contract', () => {};it('light TUI path', () => {- const prompt = buildLightContextPrompt(auditTask(), '/r', wt, isTruthyMeta, { isTui: true });+ const prompt = buildLightContextPrompt(auditTask(), '/r', wt, { isTui: true });assertActionOutput(prompt);// The sentinel is still the done-signal for a TUI run — just not the// place the deliverable goes.@@ -3018,12 +2929,12 @@ describe('discardWorktree (reasoning-only) completion contract', () => {});it('light CLI (non-TUI) path', () => {- const prompt = buildLightContextPrompt(auditTask(), '/r', wt, isTruthyMeta, { isTui: false, providerId: 'codex' });+ const prompt = buildLightContextPrompt(auditTask(), '/r', wt, { isTui: false, providerId: 'codex' });assertActionOutput(prompt);});it('full (api) path', async () => {- const prompt = await buildAgentPrompt(auditTask(), {}, '/r', wt, isTruthyMeta, { providerType: 'api' });+ const prompt = await buildAgentPrompt(auditTask(), {}, '/r', wt, { providerType: 'api' });assertActionOutput(prompt);});@@ -3034,7 +2945,7 @@ describe('discardWorktree (reasoning-only) completion contract', () => {// aim a push straight at that branch — and for a task that changes no code,// whatever it swept up would be the user's own uncommitted work.const task = makeTask({ metadata: { noCodeOutput: true, useWorktree: false, openPR: false } });- const prompt = await buildAgentPrompt(task, {}, '/r', null, isTruthyMeta, { providerType: 'api' });+ const prompt = await buildAgentPrompt(task, {}, '/r', null, { providerType: 'api' });expect(prompt).toMatch(/## Completion \(No Code Output\)/);expect(prompt).toMatch(/Do NOT commit, push, or open a PR/);expect(prompt).not.toMatch(/Commit and push using/);@@ -3044,7 +2955,7 @@ describe('discardWorktree (reasoning-only) completion contract', () => {});it('full (api) path suppresses the commit/push instructions in Instructions + Git Hygiene', async () => {- const prompt = await buildAgentPrompt(liTask(), {}, '/r', wt, isTruthyMeta, { providerType: 'api' });+ const prompt = await buildAgentPrompt(liTask(), {}, '/r', wt, { providerType: 'api' });assertReasoningOnly(prompt);// Fallback-template step 4 must not tell the agent to commit/push.expect(prompt).toMatch(/Write your result to the completion sentinel/);@@ -3104,7 +3015,7 @@ describe('discardWorktree (reasoning-only) completion contract', () => {expect(claudeMdSection).toMatch(/gh pr merge/);expect(claudeMdSection).toMatch(/Commit and push your changes/);- const prompt = await buildAgentPrompt(liTask(), {}, '/r', wt, isTruthyMeta, { providerType: 'api' });+ const prompt = await buildAgentPrompt(liTask(), {}, '/r', wt, { providerType: 'api' });// The verbatim splice is the production contract — the builder passes the// user's own instructions through untouched.expect(prompt).toContain(claudeMdSection);@@ -3132,7 +3043,7 @@ describe('discardWorktree (reasoning-only) completion contract', () => {const cdTask = makeTask({metadata: { creativeDirector: { projectId: 'p', kind: 'evaluate' }, useWorktree: false, openPR: false },});- const prompt = await buildAgentPrompt(cdTask, {}, '/r', null, isTruthyMeta, { providerType: 'api' });+ const prompt = await buildAgentPrompt(cdTask, {}, '/r', null, { providerType: 'api' });expect(prompt).not.toMatch(/## CLAUDE\.md Instructions/);expect(prompt).not.toMatch(/Example Global Instructions/);});@@ -3147,7 +3058,7 @@ describe('discardWorktree (reasoning-only) completion contract', () => {const cdTask = makeTask({metadata: { creativeDirector: { projectId: 'p', kind: 'evaluate' }, useWorktree: false, openPR: false },});- const prompt = await buildAgentPrompt(cdTask, {}, '/r', null, isTruthyMeta, { providerType: 'api' });+ const prompt = await buildAgentPrompt(cdTask, {}, '/r', null, { providerType: 'api' });expect(getMemorySection).not.toHaveBeenCalled();expect(getDigitalTwinForPrompt).not.toHaveBeenCalled();expect(getToolsSummaryForPrompt).not.toHaveBeenCalled();@@ -3168,7 +3079,7 @@ describe('discardWorktree (reasoning-only) completion contract', () => {memory: { maxContextTokens: 0 },digitalTwin: { maxContextTokens: 0 },soul: { maxContextTokens: 1200 },- }, '/r', null, isTruthyMeta, { providerType: 'api' });+ }, '/r', null, { providerType: 'api' });expect(prompt).toContain('Example Global Instructions');expect(prompt).toMatch(/^## Instructions$/m);expect(getMemorySection).toHaveBeenLastCalledWith(expect.anything(), { maxTokens: 2000 });@@ -3184,7 +3095,7 @@ describe('discardWorktree (reasoning-only) completion contract', () => {vi.mocked(getMemorySection).mockClear().mockResolvedValue('## Memory Context\nNONCD_MEMORY_SENTINEL');vi.mocked(getDigitalTwinForPrompt).mockClear().mockResolvedValue('## Digital Twin\nNONCD_TWIN_SENTINEL');vi.mocked(getToolsSummaryForPrompt).mockClear().mockResolvedValue('## Available Tools\nNONCD_TOOLS_SENTINEL');- const prompt = await buildAgentPrompt(makeTask(), {}, '/r', null, isTruthyMeta, { providerType: 'api' });+ const prompt = await buildAgentPrompt(makeTask(), {}, '/r', null, { providerType: 'api' });expect(getMemorySection).toHaveBeenCalled();expect(getDigitalTwinForPrompt).toHaveBeenCalled();expect(getToolsSummaryForPrompt).toHaveBeenCalled();@@ -3220,7 +3131,7 @@ describe('discardWorktree (reasoning-only) completion contract', () => {// --delete-branch`. (The `openPR: false` sibling above never reaches that// line at all, which is why its /gh pr merge/ check can't carry this.)const prTask = makeTask({ metadata: { discardWorktree: true, useWorktree: true, openPR: true, simplify: true } });- const prompt = buildLightContextPrompt(prTask, '/r', wt, isTruthyMeta, { isTui: true });+ const prompt = buildLightContextPrompt(prTask, '/r', wt, { isTui: true });expect(prompt).not.toMatch(/gh pr merge/);expect(prompt).toMatch(/## Completion \(Reasoning-Only Task\)/);// The light path targets agentic CLIs that load CLAUDE.md natively, so the@@ -3253,7 +3164,7 @@ describe('full (api) path: step 4 and Git Hygiene agree on the completion contra// that is the exact shape whose step 4 had no matching arm.const prompt = await buildAgentPrompt(makeTask({ metadata: { executionProfile: 'public-review-gate', useWorktree: false, openPR: false } }),- {}, '/r', null, isTruthyMeta, { providerType: 'api' });+ {}, '/r', null, { providerType: 'api' });// The contract the other two sections already got right.expect(prompt).toMatch(/## Completion \(Tool-Free Reasoning\)/);@@ -3267,7 +3178,7 @@ describe('full (api) path: step 4 and Git Hygiene agree on the completion contrait('a read-only task is never told to commit — in step 4 or in Git Hygiene', async () => {const prompt = await buildAgentPrompt(makeTask({ metadata: { readOnly: true, useWorktree: false, openPR: false } }),- {}, '/r', null, isTruthyMeta, { providerType: 'api' });+ {}, '/r', null, { providerType: 'api' });// The Guidelines bullet already resolved this correctly.expect(prompt).toMatch(/\*\*This is a read-only task\.\*\*/);@@ -3292,7 +3203,7 @@ describe('buildAgentPrompt — reviewer resolution honors Code Review Defaults (it('threads a configured default reviewer list into --review-with when the task pins none', async () => {vi.mocked(getCodeReviewDefaults).mockResolvedValueOnce({ reviewers: ['claude', 'codex'] });- const prompt = await buildAgentPrompt(reviewLoopTask(), {}, '/r', { branchName: 'b', worktreePath: '/tmp/wt' }, isTruthyMeta, claudeCliOpts);+ const prompt = await buildAgentPrompt(reviewLoopTask(), {}, '/r', { branchName: 'b', worktreePath: '/tmp/wt' }, claudeCliOpts);expect(prompt).toMatch(/`\/do:pr --review-with claude,codex`/);// The stalling copilot default must not leak in.expect(prompt).not.toMatch(/--review-with copilot/);@@ -3300,7 +3211,7 @@ describe('buildAgentPrompt — reviewer resolution honors Code Review Defaults (it('keeps review opt-in when no default is configured', async () => {vi.mocked(getCodeReviewDefaults).mockResolvedValueOnce({ reviewers: [] });- const prompt = await buildAgentPrompt(reviewLoopTask(), {}, '/r', { branchName: 'b', worktreePath: '/tmp/wt' }, isTruthyMeta, claudeCliOpts);+ const prompt = await buildAgentPrompt(reviewLoopTask(), {}, '/r', { branchName: 'b', worktreePath: '/tmp/wt' }, claudeCliOpts);// An empty default is suppressed from --review-with, so /do:pr runs without// an explicit reviewer flag.expect(prompt).toMatch(/`\/do:pr`/);@@ -3310,14 +3221,14 @@ describe('buildAgentPrompt — reviewer resolution honors Code Review Defaults (it('a task-pinned reviewer list still wins over the configured default', async () => {vi.mocked(getCodeReviewDefaults).mockResolvedValueOnce({ reviewers: ['claude', 'codex'] });const task = makeTask({ metadata: { openPR: true, reviewLoop: true, simplify: false, reviewers: ['grok'] } });- const prompt = await buildAgentPrompt(task, {}, '/r', { branchName: 'b', worktreePath: '/tmp/wt' }, isTruthyMeta, claudeCliOpts);+ const prompt = await buildAgentPrompt(task, {}, '/r', { branchName: 'b', worktreePath: '/tmp/wt' }, claudeCliOpts);expect(prompt).toMatch(/`\/do:pr --review-with grok`/);expect(prompt).not.toMatch(/--review-with claude/);});it('keeps review opt-in when the settings read fails', async () => {vi.mocked(getCodeReviewDefaults).mockRejectedValueOnce(new Error('settings unavailable'));- const prompt = await buildAgentPrompt(reviewLoopTask(), {}, '/r', { branchName: 'b', worktreePath: '/tmp/wt' }, isTruthyMeta, claudeCliOpts);+ const prompt = await buildAgentPrompt(reviewLoopTask(), {}, '/r', { branchName: 'b', worktreePath: '/tmp/wt' }, claudeCliOpts);expect(prompt).toMatch(/`\/do:pr`/);expect(prompt).not.toMatch(/--review-with claude/);});@@ -3488,7 +3399,7 @@ describe('buildAgentPrompt — slashdo-backed tasks', () => {it('renders the Claude Code invocation for a claude-code provider', async () => {const prompt = await buildAgentPrompt(- slashdoTask(), {}, '/r', null, isTruthyMeta,+ slashdoTask(), {}, '/r', null,{ providerType: 'cli', providerId: 'claude-code' });expect(prompt).toContain('/do:plan-task');expect(prompt).toContain('Add rate limiting to the widget API');@@ -3496,7 +3407,7 @@ describe('buildAgentPrompt — slashdo-backed tasks', () => {it('renders the flat invocation for OpenCode', async () => {const prompt = await buildAgentPrompt(- slashdoTask(), {}, '/r', null, isTruthyMeta,+ slashdoTask(), {}, '/r', null,{ providerType: 'tui', providerId: 'opencode-tui', providerCommand: 'opencode' });expect(prompt).toContain('/do-plan-task');expect(prompt).not.toContain('/do:plan-task');@@ -3504,7 +3415,7 @@ describe('buildAgentPrompt — slashdo-backed tasks', () => {it('names the skill instead of a slash command for a skill-style CLI', async () => {const prompt = await buildAgentPrompt(- slashdoTask(), {}, '/r', null, isTruthyMeta,+ slashdoTask(), {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });expect(prompt).toContain('do-plan-task');expect(prompt).not.toContain('/do:plan-task');@@ -3517,7 +3428,7 @@ describe('buildAgentPrompt — slashdo-backed tasks', () => {it.each(['claude-code', 'opencode', 'codex'])('inlines the command body for %s', async (providerId) => {vi.mocked(loadSlashdoFile).mockResolvedValue('# Plan Task\n\nInvestigate, then file the issue.');const prompt = await buildAgentPrompt(- slashdoTask(), {}, '/r', null, isTruthyMeta,+ slashdoTask(), {}, '/r', null,{ providerType: 'cli', providerId });expect(prompt).toContain('Investigate, then file the issue.');// `skipIncludes: []` — nothing pruned, since this task pins no reviewers and@@ -3528,7 +3439,7 @@ describe('buildAgentPrompt — slashdo-backed tasks', () => {it('still emits the invocation when the body cannot be loaded', async () => {vi.mocked(loadSlashdoFile).mockResolvedValue(null);const prompt = await buildAgentPrompt(- slashdoTask(), {}, '/r', null, isTruthyMeta,+ slashdoTask(), {}, '/r', null,{ providerType: 'cli', providerId: 'claude-code' });expect(prompt).toContain('/do:plan-task');});@@ -3538,7 +3449,7 @@ describe('buildAgentPrompt — slashdo-backed tasks', () => {vi.mocked(loadSlashdoFile).mockResolvedValueOnce('# Release\n\nCanonical release procedure.');const prompt = await buildAgentPrompt(makeTask({ description: 'Run the release check', metadata: { slashdoCommand: 'release' } }),- {}, '/r', null, isTruthyMeta,+ {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });expect(prompt).toContain('do-release');@@ -3562,7 +3473,7 @@ describe('buildAgentPrompt — slashdo-backed tasks', () => {slashdoCommand: 'release', slashdoArgs: '--review-with codex[gpt-6-astra]~opt~max=1~effort=low'});const prompt = await buildAgentPrompt(- makeTask({ metadata: scheduledMetadata }), {}, '/r', null, isTruthyMeta,+ makeTask({ metadata: scheduledMetadata }), {}, '/r', null,{ providerType, providerId, providerCommand, agentId: 'release-test' });expect(prompt).toContain('Canonical release procedure.');expect(prompt).toContain('--review-with codex[gpt-6-astra]~opt~max=1~effort=low');@@ -3587,7 +3498,7 @@ describe('buildAgentPrompt — slashdo-backed tasks', () => {makeTask({ metadata: sanitizeTaskMetadata({useWorktree: false, openPR: false, simplify: true,worktreeChangesExpected: true, slashdoCommand: command,- }) }), {}, '/r', null, isTruthyMeta,+ }) }), {}, '/r', null,{ providerType, providerId, providerCommand, agentId: 'better-test' });expect(prompt).toContain('Canonical audit procedure.');expect(prompt).toContain('Better Workflow Handoff');@@ -3616,7 +3527,7 @@ describe('buildAgentPrompt — slashdo-backed tasks', () => {...sanitizeTaskMetadata({ useWorktree: false, openPR: false, worktreeChangesExpected: false, simplify: true }),...identity.metadata,},- }), {}, '/r', null, isTruthyMeta,+ }), {}, '/r', null,{ providerType, providerId: 'codex', providerCommand: 'codex', agentId: 'reconcile-test' });expect(prompt).toContain('Reconcile only claim/issue-42');expect(prompt).toContain('## Branch Reconciliation Handoff');@@ -3633,7 +3544,7 @@ describe('buildAgentPrompt — slashdo-backed tasks', () => {it('keeps explicit read-only reconciliation restricted', async () => {const prompt = await buildAgentPrompt(makeTask({metadata: { analysisType: 'branch-reconcile', readOnly: true, openPR: false },- }), {}, '/r', null, isTruthyMeta, { providerType: 'cli', providerId: 'codex' });+ }), {}, '/r', null, { providerType: 'cli', providerId: 'codex' });expect(prompt).toMatch(/read.only/i);expect(prompt).not.toContain('## Branch Reconciliation Handoff');});@@ -3642,7 +3553,7 @@ describe('buildAgentPrompt — slashdo-backed tasks', () => {vi.mocked(loadSlashdoFile).mockResolvedValue('# Release\n\nCanonical release procedure.');const prompt = await buildAgentPrompt(makeTask({ metadata: { analysisType: 'do-release', openPR: false } }),- {}, '/r', null, isTruthyMeta, { providerType: 'tui', providerId: 'codex-tui', providerCommand: 'codex' });+ {}, '/r', null, { providerType: 'tui', providerId: 'codex-tui', providerCommand: 'codex' });expect(prompt).toContain('Canonical release procedure.');expect(prompt).toContain('Release Workflow Handoff');expect(prompt).not.toContain('Do NOT push');@@ -3650,7 +3561,7 @@ describe('buildAgentPrompt — slashdo-backed tasks', () => {it('uses explicit slashdoArgs when present', async () => {const prompt = await buildAgentPrompt(- slashdoTask({ slashdoArgs: '--issues 42' }), {}, '/r', null, isTruthyMeta,+ slashdoTask({ slashdoArgs: '--issues 42' }), {}, '/r', null,{ providerType: 'cli', providerId: 'claude-code' });expect(prompt).toContain('/do:plan-task --issues 42');});@@ -3666,7 +3577,7 @@ describe('buildAgentPrompt — slashdo-backed tasks', () => {openPR: false,simplify: false,reviewLoop: false,- }), {}, '/r', null, isTruthyMeta,+ }), {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });expect(prompt).toContain('--yes');@@ -3679,20 +3590,20 @@ describe('buildAgentPrompt — slashdo-backed tasks', () => {});it('reaches the api-path briefing through task.description', async () => {- const prompt = await buildAgentPrompt(slashdoTask(), {}, '/r', null, isTruthyMeta, { providerType: 'api', providerId: 'claude-code' });+ const prompt = await buildAgentPrompt(slashdoTask(), {}, '/r', null, { providerType: 'api', providerId: 'claude-code' });expect(prompt).toContain('/do:plan-task');});it('leaves a task with no slashdoCommand untouched', async () => {const prompt = await buildAgentPrompt(- makeTask(), {}, '/r', null, isTruthyMeta,+ makeTask(), {}, '/r', null,{ providerType: 'cli', providerId: 'claude-code' });expect(prompt).not.toContain('Slashdo Workflow');});it('ignores an invalid command rather than joining it into a path', async () => {const prompt = await buildAgentPrompt(- slashdoTask({ slashdoCommand: '../../etc/passwd' }), {}, '/r', null, isTruthyMeta,+ slashdoTask({ slashdoCommand: '../../etc/passwd' }), {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });expect(prompt).not.toContain('Slashdo Workflow');expect(vi.mocked(loadSlashdoFile)).not.toHaveBeenCalledWith('../../etc/passwd', expect.anything());@@ -3729,7 +3640,7 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {it('hands a file-tools host a pointer instead of the body when over budget', async () => {const prompt = await buildAgentPrompt(- slashdoTask(), {}, '/r', null, isTruthyMeta,+ slashdoTask(), {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });expect(prompt).toContain('/install/data/cos/slashdo-resolved/review.md');expect(prompt).not.toContain(OVER);@@ -3742,7 +3653,7 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {const files = { 'audit.md': 'Audit procedure' };vi.mocked(loadSlashdoBundle).mockResolvedValueOnce({ body, files });const prompt = await buildAgentPrompt(- slashdoTask({ reviewers: ['codex'] }), {}, '/managed-app', null, isTruthyMeta,+ slashdoTask({ reviewers: ['codex'] }), {}, '/managed-app', null,{ providerType: 'cli', providerId: 'codex' });expect(writeResolvedSlashdoBody).toHaveBeenCalledWith('review', body, { files });expect(prompt).toContain('/install/data/cos/slashdo-resolved/review.md');@@ -3758,7 +3669,7 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {vi.mocked(loadSlashdoFile).mockResolvedValueOnce('Complete inline audit procedure');vi.mocked(writeResolvedSlashdoBody).mockRejectedValueOnce(new Error('EACCES'));const prompt = await buildAgentPrompt(- slashdoTask(), {}, '/managed-app', null, isTruthyMeta,+ slashdoTask(), {}, '/managed-app', null,{ providerType: 'cli', providerId: 'codex' });expect(prompt).toContain('Complete inline audit procedure');expect(prompt).not.toContain('Read lib/audit.md');@@ -3767,21 +3678,21 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {it('rejects a missing required procedure instead of dispatching an invocation alone', async () => {vi.mocked(loadSlashdoBundle).mockRejectedValueOnce(new Error('Missing required slashdo library: audit.md'));await expect(buildAgentPrompt(- slashdoTask(), {}, '/r', null, isTruthyMeta,+ slashdoTask(), {}, '/r', null,{ providerType: 'cli', providerId: 'codex' })).rejects.toThrow('Missing required slashdo library');});it('inlines the body when it is under budget, and stages no file', async () => {vi.mocked(loadSlashdoFile).mockResolvedValue(UNDER);const prompt = await buildAgentPrompt(- slashdoTask(), {}, '/r', null, isTruthyMeta,+ slashdoTask(), {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });expect(prompt).toContain('Step one.');expect(vi.mocked(writeResolvedSlashdoBody)).not.toHaveBeenCalled();});it('inlines for an api provider regardless of size — no file tools to read with', async () => {- const prompt = await buildAgentPrompt(slashdoTask(), {}, '/r', null, isTruthyMeta,+ const prompt = await buildAgentPrompt(slashdoTask(), {}, '/r', null,{ providerType: 'api', providerId: 'some-http-provider' });expect(prompt).toContain(OVER);expect(vi.mocked(writeResolvedSlashdoBody)).not.toHaveBeenCalled();@@ -3789,7 +3700,7 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {it('warns once, naming the command and size, when an api provider is handed an over-budget body', async () => {const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});- await buildAgentPrompt(slashdoTask(), {}, '/r', null, isTruthyMeta,+ await buildAgentPrompt(slashdoTask(), {}, '/r', null,{ providerType: 'api', providerId: 'some-http-provider' });expect(warn).toHaveBeenCalledTimes(1);expect(warn.mock.calls[0][0]).toContain('review');@@ -3801,7 +3712,7 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {vi.mocked(writeResolvedSlashdoBody).mockRejectedValue(new Error('EACCES'));const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});const prompt = await buildAgentPrompt(- slashdoTask(), {}, '/r', null, isTruthyMeta,+ slashdoTask(), {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });// A failed write must not silently drop the procedure.expect(prompt).toContain(OVER);@@ -3826,7 +3737,6 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex'] } }),{}, '/r',{ branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{ providerType: 'tui', providerId: 'opencode-tui', providerCommand: 'opencode' });const [, stagedBody] = vi.mocked(writeResolvedSlashdoBody).mock.calls.at(-1);@@ -3851,7 +3761,6 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex'] } }),{}, '/r',{ branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta,{ providerType: 'tui', providerId: 'opencode-tui', providerCommand: 'opencode' });expect(prompt).toContain('RECIPE FALLBACK HEADER');@@ -3868,7 +3777,7 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {it('carries a pinned reviewer effort on the --review-with token, not as prose', async () => {const prompt = await buildAgentPrompt(slashdoTask({ reviewers: ['codex'], reviewerEfforts: { codex: 'high' } }),- {}, '/r', null, isTruthyMeta,+ {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });expect(prompt).toContain('codex~effort=high');// Restating it would have the agent pass `-c model_reasoning_effort=high` a@@ -3885,7 +3794,7 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {usernames: ['octocat'],reviewerEfforts: { codex: 'high' },}),- {}, '/r', null, isTruthyMeta,+ {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });// (the note's own prose mentions the flag — assert on the pin line instead)expect(prompt).not.toContain('Run this workflow with');@@ -3898,7 +3807,7 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {// flag to a CLI it never invokes.const prompt = await buildAgentPrompt(slashdoTask({ reviewers: ['codex'], reviewerEfforts: { codex: 'high', claude: 'xhigh' } }),- {}, '/r', null, isTruthyMeta,+ {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });expect(prompt).toContain('codex~effort=high');expect(prompt).not.toContain('claude~effort=xhigh');@@ -3907,7 +3816,7 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {it('adds no effort sentence when no reviewer pins one', async () => {const prompt = await buildAgentPrompt(- slashdoTask({ reviewers: ['codex'] }), {}, '/r', null, isTruthyMeta,+ slashdoTask({ reviewers: ['codex'] }), {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });expect(prompt).not.toContain('pinned reasoning effort');});@@ -3916,7 +3825,7 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {it('prunes unreachable reviewer loops when the task pins its reviewers', async () => {await buildAgentPrompt(- slashdoTask({ reviewers: ['codex'] }), {}, '/r', null, isTruthyMeta,+ slashdoTask({ reviewers: ['codex'] }), {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });const skipped = skipArg();expect(skipped).toContain('copilot-review-loop');@@ -3925,7 +3834,7 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {it('pins --review-with alongside a pruned body so the run matches what it got', async () => {const prompt = await buildAgentPrompt(- slashdoTask({ reviewers: ['codex'] }), {}, '/r', null, isTruthyMeta,+ slashdoTask({ reviewers: ['codex'] }), {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });expect(prompt).toContain('--review-with codex');});@@ -3933,7 +3842,7 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {it('prunes from the install Code Review Defaults when the task pins nothing', async () => {vi.mocked(getCodeReviewDefaults).mockResolvedValue({ reviewers: ['ollama'] });await buildAgentPrompt(- slashdoTask(), {}, '/r', null, isTruthyMeta,+ slashdoTask(), {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });expect(skipArg()).not.toContain('ollama-review-loop');});@@ -3943,7 +3852,7 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {// install that has not opted into code review.vi.mocked(getCodeReviewDefaults).mockResolvedValue({ reviewers: [] });const prompt = await buildAgentPrompt(- slashdoTask(), {}, '/r', null, isTruthyMeta,+ slashdoTask(), {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });expect(skipArg()).toEqual([]);expect(prompt).not.toContain('--review-with');@@ -3955,7 +3864,7 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {it('honors the legacy single `reviewer` string, not just the reviewers array', async () => {vi.mocked(getCodeReviewDefaults).mockResolvedValue({ reviewers: ['ollama'] });const prompt = await buildAgentPrompt(- slashdoTask({ reviewer: 'codex' }), {}, '/r', null, isTruthyMeta,+ slashdoTask({ reviewer: 'codex' }), {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });// Legacy `reviewer` beats the defaults, so the CLI loop is kept and the// local-model loop (the default's) is what gets dropped.@@ -3970,7 +3879,7 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {reviewers: ['codex'], optionalReviewers: ['codex'],});const prompt = await buildAgentPrompt(- slashdoTask(), {}, '/r', null, isTruthyMeta,+ slashdoTask(), {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });// Pinning a non-blocking reviewer as blocking changes the merge gate.expect(prompt).toContain('--review-with codex~opt');@@ -3987,7 +3896,7 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {reviewers: ['copilot'], optionalReviewers: ['copilot'],});const prompt = await buildAgentPrompt(- slashdoTask(), {}, '/r', null, isTruthyMeta,+ slashdoTask(), {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });expect(prompt).toContain('--review-with copilot~opt');expect(skipArg()).not.toContain('copilot-review-loop');@@ -3996,14 +3905,14 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {it('prunes NOTHING when the defaults read fails', async () => {vi.mocked(getCodeReviewDefaults).mockRejectedValue(new Error('unreadable'));await buildAgentPrompt(- slashdoTask(), {}, '/r', null, isTruthyMeta,+ slashdoTask(), {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });expect(skipArg()).toEqual([]);});it('keeps the @login loop when a username reviewer gates the PR', async () => {await buildAgentPrompt(- slashdoTask({ reviewers: ['codex'], usernames: ['octocat'] }), {}, '/r', null, isTruthyMeta,+ slashdoTask({ reviewers: ['codex'], usernames: ['octocat'] }), {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });const skipped = skipArg();expect(skipped).not.toContain('github-reviewer-loop');@@ -4023,7 +3932,7 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {it('prunes for the explicit flag, not for the task metadata behind it', async () => {const prompt = await buildAgentPrompt(slashdoTask({ slashdoArgs: '--review-with ollama', reviewers: ['codex'] }),- {}, '/r', null, isTruthyMeta,+ {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });const skipped = skipArg();// The reviewer the run will actually invoke keeps its loop…@@ -4038,7 +3947,7 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {it('preserves an explicit `none` opt-out inherited from Code Review Defaults', async () => {vi.mocked(getCodeReviewDefaults).mockResolvedValue({ reviewers: ['codex'] });const prompt = await buildAgentPrompt(- slashdoTask({ slashdoArgs: '--review-with none' }), {}, '/r', null, isTruthyMeta,+ slashdoTask({ slashdoArgs: '--review-with none' }), {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });expect(prompt).toContain('--review-with none');// `none` sets REVIEW_AGENTS=[] with no fallback, so no loop is reachable.@@ -4055,7 +3964,7 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {// The metadata names a DIFFERENT loop variant, so a metadata-derived pin// would both prune away agy's loop and add a second set of suffixes.slashdoTask({ slashdoArgs: args, reviewers: ['ollama'], reviewerEfforts: { ollama: 'high' } }),- {}, '/r', null, isTruthyMeta,+ {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });expect(prompt).not.toContain('--review-with ollama');expect(skipArg()).not.toContain('local-agent-review-loop');@@ -4067,7 +3976,7 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {it('reads the equals form the same as the spaced one', async () => {const prompt = await buildAgentPrompt(slashdoTask({ slashdoArgs: '--review-with=ollama', reviewers: ['codex'] }),- {}, '/r', null, isTruthyMeta,+ {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });expect(skipArg()).not.toContain('ollama-review-loop');expect(skipArg()).toContain('local-agent-review-loop');@@ -4080,7 +3989,7 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {// A slug outside the grammar PortOS mirrors: guessing which loop it needs// is how the run loses the one it reaches.slashdoTask({ slashdoArgs: '--review-with some-future-reviewer' }),- {}, '/r', null, isTruthyMeta,+ {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });expect(skipArg()).toEqual([]);expect(prompt).toContain('--review-with some-future-reviewer');@@ -4090,7 +3999,7 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {it('leaves the metadata contract in charge when the args name no reviewer', async () => {const prompt = await buildAgentPrompt(slashdoTask({ slashdoArgs: '--issues 42', reviewers: ['codex'] }),- {}, '/r', null, isTruthyMeta,+ {}, '/r', null,{ providerType: 'cli', providerId: 'codex' });expect(prompt).toContain('--review-with codex');expect(skipArg()).toContain('copilot-review-loop');@@ -4342,7 +4251,7 @@ describe('TUI reviewLoopFollowUp completion instructions', () => {}};const worktreeInfo = { worktreePath: '/tmp/wt-1', branchName: 'cos/task-orig/agent-1' };- const prompt = await buildLightContextPrompt(task, '/repo', worktreeInfo, (v) => v === true || v === 'true', {+ const prompt = await buildLightContextPrompt(task, '/repo', worktreeInfo, {isTui: true,providerId: 'antigravity-tui',providerCommand: 'agy',@@ -4364,7 +4273,7 @@ describe('TUI reviewLoopFollowUp completion instructions', () => {metadata: { useWorktree: false, openPR: false, discardWorktree: true, providerId: 'claude-code-tui', providerCommand: 'claude' }});const build = (taskId, agentId) => buildLightContextPrompt(- worktreelessTask(taskId), '/repo', null, (v) => v === true || v === 'true',+ worktreelessTask(taskId), '/repo', null,{ isTui: true, providerId: 'claude-code-tui', providerCommand: 'claude', agentId });@@ -4387,7 +4296,7 @@ describe('TUI reviewLoopFollowUp completion instructions', () => {describe('planner attribution', () => {it('gives a light-path run the exact planner label for the model it resolved to', () => {const prompt = buildLightContextPrompt(- makeTask({ metadata: { openPR: false } }), '/repo', null, isTruthyMeta,+ makeTask({ metadata: { openPR: false } }), '/repo', null,{ providerId: 'claude-code-tui', providerCommand: 'claude', providerModel: 'claude-opus-5' },);expect(prompt).toMatch(/## Planner Attribution/);@@ -4397,7 +4306,7 @@ describe('planner attribution', () => {it('falls back to the provider id when the run pinned no model', () => {const prompt = buildLightContextPrompt(- makeTask({ metadata: { openPR: false } }), '/repo', null, isTruthyMeta,+ makeTask({ metadata: { openPR: false } }), '/repo', null,{ providerId: 'grok', providerCommand: 'grok' },);expect(prompt).toMatch(/--label planner:grok/);@@ -4408,7 +4317,7 @@ describe('planner attribution', () => {// an install's stored prompt template predates it and would silently drop it.it('reaches an api provider through the full path too', async () => {const prompt = await buildAgentPrompt(- makeTask({ metadata: { openPR: false } }), {}, '/repo', null, isTruthyMeta,+ makeTask({ metadata: { openPR: false } }), {}, '/repo', null,{ providerType: 'api', providerId: 'lmstudio', providerModel: 'claude-opus-5' },);const text = typeof prompt === 'string' ? prompt : prompt.userPrompt;@@ -4433,10 +4342,10 @@ describe('planner attribution', () => {};it.each([- ['light', (task) => buildLightContextPrompt(task, '/repo', null, isTruthyMeta,+ ['light', (task) => buildLightContextPrompt(task, '/repo', null,{ providerId: 'claude-code-tui', providerCommand: 'claude', providerModel: 'claude-opus-5' })],['api', async (task) => {- const prompt = await buildAgentPrompt(task, {}, '/repo', null, isTruthyMeta,+ const prompt = await buildAgentPrompt(task, {}, '/repo', null,{ providerType: 'api', providerId: 'lmstudio', providerModel: 'claude-opus-5' });return typeof prompt === 'string' ? prompt : prompt.userPrompt;}],@@ -4448,7 +4357,7 @@ describe('planner attribution', () => {it('recognizes the contract when a template re-indented it', () => {const indented = MANDATORY_DISPATCH_HINT_GUIDANCE.split('\n').join('\n ');- const text = buildLightContextPrompt(embedsContract(indented), '/repo', null, isTruthyMeta,+ const text = buildLightContextPrompt(embedsContract(indented), '/repo', null,{ providerId: 'claude-code-tui', providerCommand: 'claude', providerModel: 'claude-opus-5' });expectDeduped(text);});@@ -4456,7 +4365,7 @@ describe('planner attribution', () => {it('keeps the full contract for a task that paraphrased it', () => {const prompt = buildLightContextPrompt(makeTask({ description: 'File issues with model: and effort: labels.', metadata: { openPR: false } }),- '/repo', null, isTruthyMeta, { providerId: 'claude-code-tui', providerCommand: 'claude' },+ '/repo', null, { providerId: 'claude-code-tui', providerCommand: 'claude' },);expect(prompt).toContain('## Issue Filing Labels');expect(prompt.split(MANDATORY_DISPATCH_HINT_GUIDANCE).length - 1).toBe(1);@@ -4464,7 +4373,7 @@ describe('planner attribution', () => {it('still enforces filing labels when PortOS cannot attribute the run', () => {const prompt = buildLightContextPrompt(- makeTask({ metadata: { openPR: false } }), '/repo', null, isTruthyMeta, {},+ makeTask({ metadata: { openPR: false } }), '/repo', null, {},);expect(prompt).not.toMatch(/## Planner Attribution/);expect(prompt).toContain('## Issue Filing Labels');@@ -4485,7 +4394,7 @@ describe('auto-merge posture (worktree, no PR) is commit-only on every path', ()makeTask({ metadata: { openPR: false, simplify: true } }),{}, '/r',{ branchName: 'cos/task-1/agent-a', worktreePath: '/tmp/wt', baseBranch: 'main' },- isTruthyMeta, { providerType: 'api' });+ { providerType: 'api' });expect(prompt).toMatch(/Fix any issues found, then commit your changes \(do NOT push — PortOS merges this branch back into the source checkout after you exit/);expect(prompt).toMatch(/Commit your changes \(see Git Hygiene below\) — do NOT push, PortOS merges this branch back on exit/);expect(prompt).toMatch(/\*\*Commit only — do NOT push\.\*\* Stage specific files \(no `git add -A`\), use `feat:`\/`fix:`\/`breaking:` prefix in the commit message, no Co-Authored-By annotations\. PortOS merges this branch back into the source checkout after you exit and deletes it, so do NOT run `git push` or `\/do:push` yourself/);@@ -4498,7 +4407,7 @@ describe('auto-merge posture (worktree, no PR) is commit-only on every path', ()it('api path: the same task WITHOUT a worktree keeps commit-and-push', async () => {const prompt = await buildAgentPrompt(makeTask({ metadata: { openPR: false, simplify: true } }),- {}, '/r', null, isTruthyMeta, { providerType: 'api' });+ {}, '/r', null, { providerType: 'api' });expect(prompt).toMatch(/commit and push using `\/do:push`/);expect(prompt).toMatch(/Commit and push using `\/do:push`/);expect(prompt).not.toMatch(/PortOS merges this branch back/);diff --git a/server/services/agentSpawnDispatch.js b/server/services/agentSpawnDispatch.jsindex 66e36fae4e..b99311562c 100644--- a/server/services/agentSpawnDispatch.js+++ b/server/services/agentSpawnDispatch.js@@ -23,7 +23,7 @@ import { validatePublicReviewModel } from './modelAbuseGuard.js';import { loadPublicReviewSpawnInput } from './publicReviewSpawnInput.js';import { registerAgent } from './cosAgentLifecycle.js';import { createAgentRun } from './agentRunTracking.js';-import { isTruthyMeta, useRunner } from './agentState.js';+import { useRunner } from './agentState.js';import { cloudSwarmThreadCapacity, localEndpointOfProvider, providerBaseUrl } from './cosLocalEndpointSlots.js';import { describeLocalPromptBudget, planLocalPromptBudget } from '../lib/localPromptBudget.js';import { resolveAgentProviderAndModel } from './agentProviderResolution.js';@@ -116,7 +116,7 @@ export async function dispatchAgentRun(context, { spawnViaRunner } = {}) {const privatePrompt = privateSecurity? await import('./privateSecurityAssessment.js').then(({ preparePrivateSecurityAssessment }) => preparePrivateSecurityAssessment(task, provider, selectedModel)): null;- const promptResult = privateSecurity ? privatePrompt : await buildAgentPrompt(task, config, workspacePath, worktreeInfo, isTruthyMeta, {+ const promptResult = privateSecurity ? privatePrompt : await buildAgentPrompt(task, config, workspacePath, worktreeInfo, {providerType: provider.type,providerId: provider.id,providerCommand: provider.command,@@ -187,9 +187,8 @@ export async function dispatchAgentRun(context, { spawnViaRunner } = {}) {providerCommand: provider.command,leanMode,worktreeInfo,- isTruthyMetaFn: isTruthyMeta,});- const claimFlowTask = isClaimFlowTask(task, isTruthyMeta);+ const claimFlowTask = isClaimFlowTask(task);const [forgeTarget, primaryCheckoutBaseline] = await Promise.all([resolvedApp? resolveAppForgeTarget(resolvedApp, { repoPath: workspacePath }).then(r => r.target)@@ -220,7 +219,6 @@ export async function dispatchAgentRun(context, { spawnViaRunner } = {}) {executionMode,publicReviewPosture,resolvedAppName,- isTruthyMetaFn: isTruthyMeta,}));emitLog('info', `Agent ${agentId} initializing...${worktreeInfo ? ' (worktree)' : ''}${jiraBranchName ? ` (JIRA: ${jiraTicket?.ticketId})` : ''}`, { agentId, taskId: task.id });@@ -281,7 +279,6 @@ export async function dispatchAgentRun(context, { spawnViaRunner } = {}) {agentDir,executionId: toolExecution.id,laneName,- isTruthyMetaFn: isTruthyMeta,leanMode,prOpenedBy,useDurableRunner: dispatchUseRunner,@@ -303,7 +300,6 @@ export async function dispatchAgentRun(context, { spawnViaRunner } = {}) {agentDir,executionId: toolExecution.id,laneName,- isTruthyMetaFn: isTruthyMeta,prOpenedBy,safetyProfile,});diff --git a/server/services/agentState.js b/server/services/agentState.jsindex 3192431640..3ea84857c0 100644--- a/server/services/agentState.js+++ b/server/services/agentState.js@@ -177,8 +177,7 @@ export const hasActiveTaskOwner = (taskId, agents = {}) => {};// Metadata booleans may arrive as true/'true' or false/'false' (JSON vs TASKS.md string round-trip)-export const isTruthyMeta = (value) => value === true || value === 'true';-export const isFalsyMeta = (value) => value === false || value === 'false';+export { isTruthyMeta, isFalsyMeta } from '../lib/metadataFlags.js';// Metadata strings may be absent, empty, or non-string (objects/numbers leak past `||` checks).// Returns `value` only when it's a non-empty string, otherwise `fallback`.diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex b7e91f846d..9a9a658643 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -267,7 +267,6 @@ export async function spawnTuiAgent({agentDir,executionId,laneName,- isTruthyMetaFn,prOpenedBy,leanMode = false,useDurableRunner = false,@@ -320,7 +319,6 @@ export async function spawnTuiAgent({// off to read the same answer.const prOwnership = resolvePrOwnership({task,- isTruthyMeta: isTruthyMetaFn,persistedPrOpenedBy: prOpenedBy,providerId: provider?.id,providerCommand: provider?.command,@@ -363,7 +361,6 @@ export async function spawnTuiAgent({rawFile,executionId,laneName,- isTruthyMetaFn,directLaunch,prOwnership,mergeGateIsOwed,diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex c364d651b1..a6efce9930 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -702,7 +702,6 @@ describe('spawnTuiAgent runtime', () => {providerCommand: provider?.command ?? null,leanMode: overrides.leanMode ?? false,worktreeInfo: overrides.worktreeInfo ?? { branchName: 'agent/t', worktreePath: '/tmp/ws', baseBranch: 'main' },- isTruthyMetaFn: (v) => v === true || v === 'true',});}@@ -718,7 +717,7 @@ describe('spawnTuiAgent runtime', () => {const agentDir = overrides.agentDir ?? '/tmp/agentdir';const executionId = overrides.executionId ?? null;const laneName = overrides.laneName ?? null;- const helpers = overrides.helpers ?? { isTruthyMetaFn: (v) => !!v };+ const helpers = overrides.helpers ?? {};return spawnTuiAgent({agentId,task,@@ -1050,7 +1049,6 @@ describe('spawnTuiAgent runtime', () => {const spawnPromise = runSpawn({provider: { id: 'codex-tui', name: 'Codex TUI', type: 'tui', command: 'codex', envVars: {} },task,- helpers: { isTruthyMetaFn: (value) => value === true || value === 'true' },});await flushMicrotasks();@@ -1081,7 +1079,6 @@ describe('spawnTuiAgent runtime', () => {description: 'do the thing',metadata: { openPR: true, prCompletion: 'review-then-merge' },},- helpers: { isTruthyMetaFn: (value) => value === true || value === 'true' },});await flushMicrotasks();@@ -1125,7 +1122,6 @@ describe('spawnTuiAgent runtime', () => {description: 'do the thing',metadata: { openPR: true, prCompletion: 'review-then-merge' },},- helpers: { isTruthyMetaFn: (value) => value === true || value === 'true' },});await flushMicrotasks();diff --git a/server/services/agentTuiSpawning/sessionController.js b/server/services/agentTuiSpawning/sessionController.jsindex 8aecf83d89..4a27c0f530 100644--- a/server/services/agentTuiSpawning/sessionController.js+++ b/server/services/agentTuiSpawning/sessionController.js@@ -472,7 +472,6 @@ export function createTuiSessionController({rawFile,executionId,laneName,- isTruthyMetaFn,directLaunch,prOwnership,mergeGateIsOwed,@@ -1100,7 +1099,6 @@ export function createTuiSessionController({outputBuffer: getOutputBuffer(),errorAnalysis,terminatedByUser,- isTruthyMetaFn,error: finalError || undefined,completionReason: reason,workspacePath: cwd,diff --git a/server/services/agentTuiSpawning/sessionController.test.js b/server/services/agentTuiSpawning/sessionController.test.jsindex 224a1955b3..565b1c7562 100644--- a/server/services/agentTuiSpawning/sessionController.test.js+++ b/server/services/agentTuiSpawning/sessionController.test.js@@ -78,7 +78,6 @@ function makeController({rawFile: '/tmp/workspace/raw.txt',executionId: 'exec-1',laneName: 'lane-1',- isTruthyMetaFn: () => false,directLaunch: true,prOwnership: { prOpenedBy: 'agent-inline', prClaimExpected: true, taskOpenPR: true },mergeGateIsOwed,diff --git a/server/services/cosTaskGenerator.auditMode.test.js b/server/services/cosTaskGenerator.auditMode.test.jsindex f29cd98abd..c11e933de7 100644--- a/server/services/cosTaskGenerator.auditMode.test.js+++ b/server/services/cosTaskGenerator.auditMode.test.js@@ -104,7 +104,6 @@ import { generateManagedAppImprovementTaskForType } from './cosTaskGenerator.js'import { generateTaskFromJob } from './autonomousJobs/skillTemplates.js';import { buildLightContextPrompt } from './agentPromptBuilder.js';import { declaresNoCommitCriterion } from './taskTypeHooks.js';-import { isTruthyMeta } from './agentState.js';import {AUDIT_TASK_TYPES,FILE_ISSUES_DELIVERY_SETTINGS,@@ -141,7 +140,7 @@ const generate = (taskType, options = {}) =>* enforcement at all.*/const renderPrompt = (task) =>- `${task.description}\n\n${buildLightContextPrompt(task, WORKSPACE, null, isTruthyMeta, { isTui: true })}`;+ `${task.description}\n\n${buildLightContextPrompt(task, WORKSPACE, null, { isTui: true })}`;/*** Affirmative code-delivery directives. Matched as numbered workflow STEPS and@@ -254,7 +253,7 @@ describe('issues-only audit dispatch never acquires code-shipping instructions (it('requires a persisted report for CLI audits that normally finish by exiting', async () => {const task = await generate('better-complexity');- const prompt = buildLightContextPrompt(task, WORKSPACE, null, isTruthyMeta, { isTui: false });+ const prompt = buildLightContextPrompt(task, WORKSPACE, null, { isTui: false });expect(prompt).toContain('## Required audit assessment handoff');expect(prompt).toContain('including agents that normally finish by exiting');expect(prompt).toContain('.agent-done');@@ -376,7 +375,7 @@ describe('mode is honored identically from schedule, manual run, and quota burn'expect(task.metadata).toMatchObject({ fileIssues: false, useWorktree: true, openPR: true });const prompt = buildLightContextPrompt(task, WORKSPACE, {branch: 'cos/example', worktreePath: WORKSPACE,- }, isTruthyMeta, { isTui: true, providerId: 'codex-tui', providerCommand: 'codex' });+ }, { isTui: true, providerId: 'codex-tui', providerCommand: 'codex' });expect(prompt).toContain('gh pr create');expect(prompt).toContain('## Merge Gate');expect(prompt).toContain('--merge --delete-branch');diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex d5db68532b..a02c9bf2a3 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -108,6 +108,7 @@ import {} from './cosTaskPreStepBlocks.js';import { detectIdleLeftoverBranches, formatUserActionDetectorBlock } from './userActionDetectors.js';+import { isTruthyMeta } from '../lib/metadataFlags.js';// Back-compat shim — these five were public here before the pre-step layer moved// to its own module, so a deep import of this file keeps resolving them.export {@@ -193,7 +194,7 @@ export function isCooldownExemptTask(task) {const meta = task?.metadata;if (!meta) return false;return meta.pipeline?.currentStage > 0- || meta.perpetual === true || meta.perpetual === 'true'+ || isTruthyMeta(meta.perpetual)|| hasQuotaBurnProvenance(meta);}@@ -1961,7 +1962,7 @@ export function applyAppWorktreeDefault(metadata, app) {metadata.useWorktree = true; // openPR implies useWorktree} else if (app.defaultOpenPR === false || taskTypeDisabledWorktree) {metadata.openPR = false;- } else if ((app.defaultUseWorktree === true || metadata.useWorktree === true || metadata.useWorktree === 'true') && app.defaultOpenPR !== false) {+ } else if ((app.defaultUseWorktree === true || isTruthyMeta(metadata.useWorktree)) && app.defaultOpenPR !== false) {metadata.openPR = true;metadata.useWorktree = true;}@@ -1970,7 +1971,7 @@ export function applyAppWorktreeDefault(metadata, app) {// Apply defaultUseWorktree (only if not already set by task-type or openPR above)if (metadata.useWorktree === undefined) {// openPR implies useWorktree — don't let app default override explicit openPR: true- const explicitOpenPR = metadata.openPR === true || metadata.openPR === 'true';+ const explicitOpenPR = isTruthyMeta(metadata.openPR);if (explicitOpenPR) {metadata.useWorktree = true;} else if (app.defaultUseWorktree === true) {@@ -1981,7 +1982,7 @@ export function applyAppWorktreeDefault(metadata, app) {}// Final invariant: openPR implies useWorktree (normalize in both directions)- const finalOpenPR = metadata.openPR === true || metadata.openPR === 'true';+ const finalOpenPR = isTruthyMeta(metadata.openPR);const finalWorktreeOff = metadata.useWorktree === false || metadata.useWorktree === 'false';if (finalOpenPR && finalWorktreeOff) {// openPR wins — force useWorktree ondiff --git a/server/services/ollamaAgentContext.js b/server/services/ollamaAgentContext.jsindex 4c219b73c6..9029c77d35 100644--- a/server/services/ollamaAgentContext.js+++ b/server/services/ollamaAgentContext.js@@ -1,3 +1,4 @@+import { isTruthyMeta } from '../lib/metadataFlags.js';/*** Pre-spawn context-window preparation for Ollama-backed *agent harnesses** (`claude-ollama`, `claude-ollama-tui`, `opencode-ollama`, …).@@ -135,7 +136,7 @@ export async function dropUnsupportedOllamaThinking(provider, model, effort = nuconst keep = { provider, effort, dropped: false }const wantsThinking = !!effort|| (typeof provider?.effort === 'string' && provider.effort.trim() !== '')- || provider?.thinking === true || provider?.thinking === 'true'+ || isTruthyMeta(provider?.thinking)if (!wantsThinking) return keepif (!await ollamaModelRejectsThinking(provider, model)) return keepdiff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.jsindex 790a39c1b3..3ec969b0a9 100644--- a/server/services/promptSections/completion.js+++ b/server/services/promptSections/completion.js@@ -13,6 +13,7 @@ import { PR_COMPLETIONS, leavesPrForHuman, resolvePrCompletion } from '../../libimport { LIGHT_CONTEXT_PROVIDER_TYPES, SIMPLIFY_INLINE_REVIEW } from './constants.js';import { buildCiMergeGateSteps, buildReviewLoopFollowUpSection, LEAVE_PR_OPEN_STEP } from './reviewLifecycle.js';+import { isTruthyMeta } from '../../lib/metadataFlags.js';export const NO_CHANGE_AUDIT_GUIDANCE = 'This audit may legitimately conclude that no change is needed. First verify the data this audit owns against authoritative sources. If the audited data is current, leave the worktree clean and do not run the commit, push, PR, or review steps below; write the completion sentinel when this provider uses one, or exit without committing when it does not. If a change is needed, continue through the normal workflow below.';function withNoChangeAuditGuidance(guidance, noChangeSuccess) {@@ -869,7 +870,6 @@ export function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLE*//** Same coercion the callers pass in; a default so external callers needn't. */-const isTruthyMetaDefault = (v) => v === true || v === 'true';/*** A git ref rendered into a shell command line in the prompt, or `fallback` when@@ -1083,7 +1083,7 @@ function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLET** @returns {string} a `PR_OPENED_BY` value*/-export function promptOpensOwnPr(task, { providerType, providerId, providerCommand, leanMode, worktreeInfo, isTruthyMetaFn = isTruthyMetaDefault }) {+export function promptOpensOwnPr(task, { providerType, providerId, providerCommand, leanMode, worktreeInfo }) {if (!LIGHT_CONTEXT_PROVIDER_TYPES.has(providerType)) return PR_OPENED_BY.PORTOS;if (!agentOwnsPrWorkflow({ providerType, leanMode })) return PR_OPENED_BY.PORTOS;// No worktree ⇒ no branch to name in `git push -u origin <branch>`, and the@@ -1095,12 +1095,12 @@ export function promptOpensOwnPr(task, { providerType, providerId, providerCommaif (!worktreeInfo) return PR_OPENED_BY.PORTOS;const metadata = task?.metadata || {};- if (!isTruthyMetaFn(metadata.openPR)) return PR_OPENED_BY.PORTOS;+ if (!isTruthyMeta(metadata.openPR)) return PR_OPENED_BY.PORTOS;// The completion branches that hand back a contract which never opens a PR.- if (isTruthyMetaFn(metadata.noCodeOutput) || metadata.creativeDirector) return PR_OPENED_BY.PORTOS;- if (isTruthyMetaFn(metadata.discardWorktree)) return PR_OPENED_BY.PORTOS;- if (isTruthyMetaFn(metadata.readOnly)) return PR_OPENED_BY.PORTOS;- if (isTruthyMetaFn(metadata.reviewLoopFollowUp)) return PR_OPENED_BY.PORTOS;+ if (isTruthyMeta(metadata.noCodeOutput) || metadata.creativeDirector) return PR_OPENED_BY.PORTOS;+ if (isTruthyMeta(metadata.discardWorktree)) return PR_OPENED_BY.PORTOS;+ if (isTruthyMeta(metadata.readOnly)) return PR_OPENED_BY.PORTOS;+ if (isTruthyMeta(metadata.reviewLoopFollowUp)) return PR_OPENED_BY.PORTOS;// A PR a human lands gets neither a review loop nor a merge gate.if (resolvePrCompletion(metadata) === PR_COMPLETIONS.LEAVE_OPEN || leavesPrForHuman(task)) return PR_OPENED_BY.PORTOS;diff --git a/server/services/promptSections/reviewLifecycle.js b/server/services/promptSections/reviewLifecycle.jsindex e5d8b2cab1..ce68f124be 100644--- a/server/services/promptSections/reviewLifecycle.js+++ b/server/services/promptSections/reviewLifecycle.js@@ -13,6 +13,7 @@ import { INLINE_REVIEW_LOOP_STEP } from './constants.js';import { normalizeForgeCli } from './forge.js';import { buildCliReviewerOutcomeInstructions } from './reviewerOutcome.js';+import { isTruthyMeta } from '../../lib/metadataFlags.js';// A large model reviewing a large diff should not be cut off at the HTTP// route's 600000ms cap (`server/routes/codeReview.js`) — the bridge spreads// this straight into `runLocalCodeReview`'s own `timeoutMs`, so there is no@@ -29,7 +30,7 @@ const LOCAL_LLM_REVIEW_TIMEOUT_MS = 1_800_000;* slashdo bodies (`/do:rpr`, the local-agent review loop) that section ignores.*/export function isMergeOnlyFollowUp(metadata = {}) {- return metadata?.reviewLoopMergeOnly === true || metadata?.reviewLoopMergeOnly === 'true';+ return isTruthyMeta(metadata?.reviewLoopMergeOnly);}/**@@ -44,7 +45,7 @@ export function isMergeOnlyFollowUp(metadata = {}) {*/export function isSelfReviewFollowUp(metadata = {}) {return isMergeOnlyFollowUp(metadata)- && (metadata?.reviewLoopSelfReview === true || metadata?.reviewLoopSelfReview === 'true');+ && (isTruthyMeta(metadata?.reviewLoopSelfReview));}/**@@ -743,7 +744,7 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,// nothing here can transition it), so that run reviews and stops. Derived here// beside `inline` because it selects phase text, and a flag read 400 lines// below the one it pairs with is how the two ladders drifted apart.- const leaveOpen = metadata.reviewLoopLeaveOpen === true || metadata.reviewLoopLeaveOpen === 'true';+ const leaveOpen = isTruthyMeta(metadata.reviewLoopLeaveOpen);const prUrl = metadata.reviewLoopPRUrl || '';const prBranch = metadata.reviewLoopPRBranch || '';const prNumber = metadata.reviewLoopPRNumber ?? '';diff --git a/server/services/promptSections/slashdo.js b/server/services/promptSections/slashdo.jsindex f0d38f942b..de5335e79d 100644--- a/server/services/promptSections/slashdo.js+++ b/server/services/promptSections/slashdo.js@@ -7,6 +7,7 @@ import { resolveSlashdoInvocation, buildSlashdoSection, unreachableReviewerIncluimport { currentTaskTypeName } from '../../lib/scheduledTaskTypes.js';import { DEFAULT_REVIEWER, resolveReviewerConfig, buildReviewerEffortNote, buildReviewersCsv } from '../../lib/validation.js';+import { isTruthyMeta } from '../../lib/metadataFlags.js';/*** The ONE reviewer contract a slashdo invocation runs under — resolved before the* body is pruned, before a `--review-with` is pinned, and before any per-reviewer@@ -194,7 +195,7 @@ export async function applySlashdoInvocation(task, {// Plan-only supplies destination/approval flags as slashdo args, so preserve// the task description bridge that those flags would otherwise suppress.- const includeTaskContext = task.metadata?.planOnly === true || task.metadata?.planOnly === 'true';+ const includeTaskContext = isTruthyMeta(task.metadata?.planOnly);const section = buildSlashdoSection(resolved, body, {bodyPath,reviewWith,diff --git a/server/services/taskTypeHooks.js b/server/services/taskTypeHooks.jsindex 4af6abed6a..199132ef62 100644--- a/server/services/taskTypeHooks.js+++ b/server/services/taskTypeHooks.js@@ -203,8 +203,8 @@ export const NON_COMMITTING_COORDINATOR_TASK_TYPES = new Set([* clean by construction even on the run that fixed and merged the PR.*/export function isNonCommittingCoordinatorTask(task) {- if (task?.metadata?.reviewLoopFollowUp === true || task?.metadata?.reviewLoopFollowUp === 'true') return true;- if (task?.metadata?.prRemediationFollowUp === true || task?.metadata?.prRemediationFollowUp === 'true') return true;+ if (isTruthyMeta(task?.metadata?.reviewLoopFollowUp)) return true;+ if (isTruthyMeta(task?.metadata?.prRemediationFollowUp)) return true;const type = task?.metadata?.analysisType || task?.metadata?.taskAnalysisType || task?.taskType || null;return NON_COMMITTING_COORDINATOR_TASK_TYPES.has(type);}diff --git a/server/services/videoGen/minimaxH3Controls.js b/server/services/videoGen/minimaxH3Controls.jsindex eb2a374046..74199808d2 100644--- a/server/services/videoGen/minimaxH3Controls.js+++ b/server/services/videoGen/minimaxH3Controls.js@@ -25,6 +25,7 @@import { ServerError } from '../../lib/errorHandler.js';+import { isTruthyMeta } from '../../lib/metadataFlags.js';const h3Error = (message, code) => new ServerError(message, { status: 400, code });// The canonical coercion, matching `routes/videoGen.js`. The route's schema@@ -33,7 +34,6 @@ const h3Error = (message, code) => new ServerError(message, { status: 400, code// 'false' | undefined` is the whole input space — and `'false'` is why a plain// truthiness check is wrong (`Boolean('false')` is true, which would read an// explicit opt-OUT as an opt-in).-const isRequestedTrue = (value) => value === true || value === 'true';/*** @param {object} opts@@ -52,7 +52,7 @@ export const minimaxH3ControlError = ({ model, negativePrompt, disableAudio, til'MINIMAX_H3_NEGATIVE_PROMPT_UNSUPPORTED',);}- if (isRequestedTrue(disableAudio)) {+ if (isTruthyMeta(disableAudio)) {return h3Error('MiniMax H3 jointly generates video and audio; its audio track cannot be disabled.','MINIMAX_H3_AUDIO_REQUIRED',diff --git a/server/services/videoGen/submitJob.js b/server/services/videoGen/submitJob.jsindex ca9c3c5a84..cfcd7215e3 100644--- a/server/services/videoGen/submitJob.js+++ b/server/services/videoGen/submitJob.js@@ -31,6 +31,7 @@ import {} from './prepareParams.js';import { VIDEO_GEN_LOCAL_ONLY_FIELD_NAMES } from './requestFields.js';+import { isTruthyMeta } from '../../lib/metadataFlags.js';const submitValidatedVideoGenJob = async (body, uploads) => {let fableLoomRenderSettings = null;if (body.fableLoom) {@@ -266,11 +267,11 @@ const submitValidatedVideoGenJob = async (body, uploads) => {...(isDefaultSpeedProfile(body.speedProfileId) ? {} : { speedProfileId: body.speedProfileId }),...(isFullDecode(body.draftDecode) ? {} : { draftDecode: body.draftDecode }),...(isDefaultVideoStreamingMode(body.streamingMode) ? {} : { streamingMode: body.streamingMode }),- disableAudio: body.disableAudio === true || body.disableAudio === 'true',+ disableAudio: isTruthyMeta(body.disableAudio),// Absent means "use the settings.videoGen.displaySleep default" — only// forward it when the form actually sent an explicit choice....(body.displaySleep !== undefined- ? { displaySleep: body.displaySleep === true || body.displaySleep === 'true' }+ ? { displaySleep: isTruthyMeta(body.displaySleep) }: {}),sourceImagePath,audioFilePath,@@ -291,7 +292,7 @@ const submitValidatedVideoGenJob = async (body, uploads) => {icReferencePaths,icStrength: body.icStrength,icAttentionStrength: body.icAttentionStrength,- icSkipStage2: body.icSkipStage2 === true || body.icSkipStage2 === 'true',+ icSkipStage2: isTruthyMeta(body.icSkipStage2),...(body.musicVideo ? { musicVideo: body.musicVideo } : {}),...(body.fableLoom ? { fableLoom: body.fableLoom } : {}),...(body.visualConditioning ? { visualConditioning: body.visualConditioning } : {}),diff --git a/server/services/voice/proactiveTriggers.js b/server/services/voice/proactiveTriggers.jsindex a2ea1dbeb4..8b1cc3904d 100644--- a/server/services/voice/proactiveTriggers.js+++ b/server/services/voice/proactiveTriggers.js@@ -40,6 +40,7 @@ import { speakProactive as defaultSpeak } from './proactiveSpeech.js';import { getVoiceConfig } from './config.js';import { TIMED_COOLDOWN_BLOCKED_CATEGORIES } from '../../lib/taskBlockCategories.js';+import { isTruthyMeta } from '../../lib/metadataFlags.js';// Per-source minimum interval between spoken lines (ms). Tuned for an opt-in// assistant: critical errors are rare so a wide spacing is fine; tasks and// notifications can cluster, so a one-minute floor keeps them from chattering.@@ -177,7 +178,6 @@ export const formatEscalationOpeningLine = (notification) => {// Truthy check mirroring isTruthyMeta — task metadata round-trips through// TASKS.md, so `voiceDispatch: true` comes back as the STRING 'true'. Kept// inline so this module stays decoupled from the agent-state helpers.-const isMetaTrue = (v) => v === true || v === 'true';// Completion of a voice-dispatched coding task, keyed off the task's TERMINAL// status (completed / blocked) rather than per-agent-attempt — so a task that@@ -356,7 +356,7 @@ export const wireProactiveTriggers = ({const task = evt.task;const status = task?.status;if (status !== 'completed' && status !== 'blocked') return;- if (!isMetaTrue(task.metadata?.voiceDispatch)) return;+ if (!isTruthyMeta(task.metadata?.voiceDispatch)) return;if (status === 'blocked' && task.metadata?.blockedCategory === 'user-terminated') return;// A TIMED cooldown is not a terminal outcome — the sweeper flips it back to// `pending` in minutes. Announcing it would be wrong AND would burn the