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: carve agent prompt sections into modules (#4896)
Adam Eivyf8bdea6695ec
diff --git a/scripts/agent-instructions-files.test.js b/scripts/agent-instructions-files.test.jsindex 7dc9ac2734..9a8bf8ac5e 100644--- a/scripts/agent-instructions-files.test.js+++ b/scripts/agent-instructions-files.test.js@@ -55,8 +55,8 @@ const EXCLUDED_PREFIXES = [// and this test. Everywhere else, a bare `CLAUDE.md` must be paired with// `AGENTS.md` on the same line.const DUAL_NAME_IMPLEMENTATION = [- 'server/services/agentPromptBuilder.js','server/services/agentPromptBuilder.test.js',+ 'server/services/promptSections/instructions.js','server/lib/agentInstructionsFile.js','server/lib/agentInstructionsFile.test.js','scripts/agent-instructions-files.test.js',@@ -118,6 +118,6 @@ describe('agent-instructions files (#4852)', () => {.filter((file) => !EXCLUDED_PREFIXES.some((prefix) => file.startsWith(prefix)));expect(scanned).toContain('AGENTS.md');- expect(scanned).toContain('server/services/agentPromptBuilder.js');+ expect(scanned).toContain('server/services/promptSections/instructions.js');});});diff --git a/server/services/agentImportCycles.test.js b/server/services/agentImportCycles.test.jsindex f1e7f90b93..d1221732e0 100644--- a/server/services/agentImportCycles.test.js+++ b/server/services/agentImportCycles.test.js@@ -190,6 +190,17 @@ describe('agent lifecycle cluster — no static import cycles (#2837)', () => {}});+ it('keeps prompt section modules as leaves under agentPromptBuilder (#4896)', () => {+ const sections = [...graph.keys()].filter(file => file.startsWith('promptSections/'));+ expect(sections.length, 'prompt section extraction is missing').toBeGreaterThan(5);++ const backEdges = sections.filter(file => (graph.get(file) || []).includes('agentPromptBuilder.js'));+ expect(backEdges, `prompt sections must not import agentPromptBuilder.js: ${backEdges.join(', ')}`).toEqual([]);++ const sectionCycles = findCycles(graph).filter(cycle => sections.some(file => cycle.split(' -> ').includes(file)));+ expect(sectionCycles, `prompt section cycle(s) introduced:\n${sectionCycles.join('\n')}`).toEqual([]);+ });+it('keeps the agentOrchestrator facade outside the graph it fronts (#3450)', () => {// The facade only stays a facade while its edges point one way: it imports// the cluster, the cluster never imports it back.diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 19eba68028..fea8413962 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -6,35 +6,67 @@* Also handles JIRA ticket creation and app workspace resolution.*/-import { join, basename } from 'path';-import { readdir, stat } from 'fs/promises';-import { homedir } from 'os';+import { join } from 'path';+import { stat } from 'fs/promises';import { getMemorySection } from './memoryRetriever.js';import { getDigitalTwinForPrompt } from './digital-twin.js';import { buildPrompt } from './promptService.js';import { getToolsSummaryForPrompt } from './tools.js';-import { getActiveProvider } from './providers.js';-import { runPromptThroughProvider } from '../lib/promptRunner.js';-import { readJSONFile, PATHS, tryReadFile, expandHome } from '../lib/fileUtils.js';+import { PATHS, tryReadFile } from '../lib/fileUtils.js';import { loadSlashdoFile, loadSlashdoLib, writeResolvedSlashdoBody } from '../lib/slashdoLoader.js';-import { AGENT_INSTRUCTIONS_FILENAME, CLAUDE_BRIDGE_FILENAME } from '../lib/agentInstructionsFile.js';-import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, LOCAL_LLM_REVIEWERS, MODEL_CAPABLE_CLI_REVIEWERS, describeReviewerCli, isCliReviewer, reviewerCliBinary, normalizeReviewUsernames, normalizeOptionalReviewers, normalizeReviewerMaxRounds, resolveReviewerConfig, resolveClaimReviewerConfig, buildReviewerPinNote, reviewerEffortArgs, reviewerModelArg, buildReviewerEffortNote, resolveKeyedReviewers, buildReviewWithArgs, buildReviewersCsv } from '../lib/validation.js';+import { DEFAULT_REVIEWER, DEFAULT_REVIEW_STOP_MODE, isCliReviewer, resolveReviewerConfig } from '../lib/validation.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';-import { doneSentinelName, PROGRAMMATIC_OUTPUT_COMPLETION_HEADING } from '../lib/agentSentinel.js';-import { canTypeSlashCommands, agentOwnsPrWorkflow, resolveSlashdoInvocation, buildSlashdoSection, oversizedBodyPointer, unreachableReviewerIncludes, SLASHDO_INLINE_BUDGET_CHARS } from '../lib/slashdoInvocation.js';-import { shellQuote } from '../lib/shellQuote.js';-import { TASK_PROMPT_KEY, TASK_CONTEXT_KEY, taskContextBlock } from '../lib/cosTaskPrompt.js';-import { detectForgeCli } from '../lib/gitForge.js';-import { forgeCliForTracker, resolveRepoForgeTarget } from '../lib/workTracker.js';+import { doneSentinelName } from '../lib/agentSentinel.js';+import { canTypeSlashCommands, SLASHDO_INLINE_BUDGET_CHARS } from '../lib/slashdoInvocation.js';+import { TASK_CONTEXT_KEY, taskContextBlock } from '../lib/cosTaskPrompt.js';import { PR_COMPLETIONS, leavesPrForHuman, resolvePrCompletion } from '../lib/prDisposition.js';-import * as jiraService from './jira.js';-import { emitLog } from './cosEvents.js';import { PORTOS_APP_ID } from './apps.js';import { getCodeReviewDefaults } from './codeReview.js';+import { LIGHT_CONTEXT_PROVIDER_TYPES, SIMPLIFY_INLINE_REVIEW } from './promptSections/constants.js';+import { detectSkillTemplates, getAgentInstructionsContext, loadSkillTemplates } from './promptSections/instructions.js';+import { buildCompactionSection, buildTaskBlock, reconcileSplitContext } from './promptSections/taskContext.js';+import { applySlashdoInvocation } from './promptSections/slashdo.js';+import { manualForgeCli, resolveManualForgeCli } from './promptSections/forge.js';+import {+ DISCARD_WORKTREE_NOTE,+ buildActionOutputCompletionSection,+ buildClaimFlowCompletionSection,+ buildCliCompletionSection,+ buildCompletionGuidelineBullet,+ buildInlineReviewLoopSection,+ buildProgrammaticOutputCompletionSection,+ buildReadOnlyCompletionSection,+ buildResumeSection,+ buildSentinelWriteSteps,+ buildTuiCompletionSection,+ claimReviewersCsv,+ inlinePrLifecycleSection,+ isPrBranchWorktree,+ worktreeCommitGuidance,+} from './promptSections/completion.js';+import { buildReviewLoopFollowUpSection, isMergeOnlyFollowUp } from './promptSections/reviewLifecycle.js';++export {+ detectDomainSkillTemplate,+ detectSkillTemplate,+ detectSkillTemplates,+ getAgentInstructionsContext,+ loadSkillTemplate,+ loadSkillTemplates,+} from './promptSections/instructions.js';+export { buildCompactionSection, buildTaskBlock, reconcileSplitContext } from './promptSections/taskContext.js';+export {+ buildActionOutputCompletionSection,+ buildCompletionGuidelineBullet,+ buildProgrammaticOutputCompletionSection,+ buildReadOnlyCompletionSection,+ buildResumeSection,+ inlinePrLifecycleSection,+} from './promptSections/completion.js';+export { buildReviewLoopFollowUpSection } from './promptSections/reviewLifecycle.js';+export { createJiraTicketForTask, generateJiraTitle, getAppDataForTask, getAppWorkspace } from './promptSections/appContext.js';-const ROOT_DIR = PATHS.root;const AGENTS_DIR = PATHS.cosAgents;-const SKILLS_DIR = join(ROOT_DIR, 'data/prompts/skills');// Scheduled claim tasks created before the explicit marker was introduced still// carry their task kind in analysisType. Keep those persisted queue records on@@ -58,29 +90,6 @@ function resolveSentinelPath(worktreeInfo, workspaceDir, agentId) {return `${worktreeInfo?.worktreePath || workspaceDir}/${doneSentinelName(agentId)}`;}-function normalizeForgeCli(value) {- if (value === 'glab' || value === 'gitlab') return 'glab';- if (value === 'gh' || value === 'github') return 'gh';- return null;-}--function manualForgeCli(forgeCli, worktreeInfo) {- return normalizeForgeCli(forgeCli)- || normalizeForgeCli(worktreeInfo?.forgeCli)- || forgeCliForTracker(worktreeInfo?.forge)- || 'gh';-}--async function resolveManualForgeCli(workspaceDir, worktreeInfo, task) {- const explicit = manualForgeCli(null, worktreeInfo);- if (explicit !== 'gh') return explicit;- const preferredForge = normalizeForgeCli(task?.metadata?.workTracker);- const target = await resolveRepoForgeTarget(worktreeInfo?.worktreePath || workspaceDir, {- preferredForge: preferredForge === 'glab' ? 'gitlab' : preferredForge === 'gh' ? 'github' : null,- }).catch(() => null);- return forgeCliForTracker(target?.forge) || explicit;-}-// Appended to every agent briefing. PortOS shares ONE pm2 daemon across many// apps; an agent restarting "the server" once ran `pm2 kill` and took the whole// machine (incl. PortOS) down. A PATH shim (server/lib/agentGuard) hard-blocks@@ -104,1497 +113,6 @@ PortOS launched you autonomously. Nobody is watching this session and nothing ca- **Ambiguous task?** Pick the most reasonable reading, do the work, and note the alternatives you rejected in your completion summary.- **Genuinely blocked** (missing credential, contradictory requirements)? Write why to the completion sentinel and stop. Do NOT wait for a reply.`;-/**- * Skill template keyword matchers.- * Each entry maps a skill template filename to its trigger keywords.- * Order matters — first match wins, so more specific patterns come first.- */-const SKILL_MATCHERS = [- {- skill: 'data-safety',- keywords: ['data-safety', 'upgrade-safety', 'schema parity', 'schemaversion', 'seed file', 'data.reference']- },- {- skill: 'simplify',- keywords: ['dead code', 'unused export', 'duplication', 'copy-paste', 'unreferenced']- },- {- skill: 'security-audit',- keywords: ['security', 'audit', 'vulnerability', 'xss', 'injection', 'owasp', 'cve', 'penetration', 'hardening', 'sanitize', 'authorization']- },- {- skill: 'mobile-responsive',- keywords: ['mobile', 'responsive', 'tablet', 'breakpoint', 'viewport', 'touch', 'swipe', 'small screen', 'media query', 'mobile-friendly', 'adaptive']- },- {- skill: 'bug-fix',- keywords: ['fix', 'bug', 'broken', 'error', 'crash', 'issue', 'not working', 'fails', 'regression', 'defect']- },- {- skill: 'refactor',- keywords: ['refactor', 'reorganize', 'restructure', 'clean up', 'simplify', 'extract', 'consolidate', 'decouple', 'modularize']- },- {- skill: 'documentation',- keywords: ['document', 'documentation', 'docs', 'readme', 'jsdoc', 'api docs', 'guide', 'tutorial', 'changelog']- },- {- skill: 'feature',- keywords: ['add', 'create', 'implement', 'build', 'new', 'feature', 'support', 'enable', 'integrate', 'endpoint', 'page', 'component']- }-];--// Domain templates complement (rather than replace) the lifecycle template-// selected above. Keep this list narrow: broad graphics terms would add prompt-// weight to tasks that do not involve scene construction or rendering.-const DOMAIN_SKILL_MATCHERS = [- {- skill: 'threejs-visual',- patterns: [- /\bthree(?:\.?js)\b/,- /\breact[-\s]?three[-\s]?fiber\b/,- /\br3f\b/,- /\bwebgl\s+scene\b/,- ],- },-];--/**- * Detect the best matching skill template for a task based on description keywords.- * @param {Object} task - Task object with description- * @returns {string|null} Skill template name or null if no match- */-export function detectSkillTemplate(task) {- const desc = (task?.description || '').toLowerCase();- for (const matcher of SKILL_MATCHERS) {- if (matcher.keywords.some(kw => desc.includes(kw))) {- return matcher.skill;- }- }- return null;-}--/**- * Detect one optional domain template to append after the primary lifecycle- * template. Domain routing is deliberately independent so, for example, a- * Three.js security audit keeps its security guidance.- * @param {Object} task - Task object with description- * @returns {string|null} Domain skill template name or null- */-export function detectDomainSkillTemplate(task) {- const desc = (task?.description || '').toLowerCase();- for (const matcher of DOMAIN_SKILL_MATCHERS) {- if (matcher.patterns.some((pattern) => pattern.test(desc))) {- return matcher.skill;- }- }- return null;-}--/**- * Resolve the primary lifecycle template and at most one domain guide.- * @param {Object} task - Task object with description- * @returns {string[]} Ordered template names- */-export function detectSkillTemplates(task) {- return [detectSkillTemplate(task), detectDomainSkillTemplate(task)].filter(Boolean);-}--/**- * Load a skill template from disk if it exists.- * @param {string} skillName - Name of the skill template file (without .md)- * @returns {Promise<string|null>} Template content or null- */-export async function loadSkillTemplate(skillName) {- const content = await tryReadFile(join(SKILLS_DIR, `${skillName}.md`));- if (content) console.log(`🎯 Loaded skill template: ${skillName}`);- return content;-}--/**- * Load ordered templates as one prompt section, retaining the primary guidance- * even when an optional domain template is unavailable on an older install.- * @param {string[]} skillNames - Ordered skill template names- * @param {(skillName: string) => Promise<string|null>} loadTemplate - Loader seam for tests- * @returns {Promise<string|null>} Joined template content or null- */-export async function loadSkillTemplates(skillNames, loadTemplate = loadSkillTemplate) {- const templates = await Promise.all(skillNames.map((skillName) => (- Promise.resolve(loadTemplate(skillName)).catch((err) => {- console.log(`⚠️ Skill template load failed for ${skillName}: ${err.message}`);- return null;- })- )));- return templates.filter(Boolean).join('\n\n') || null;-}--// Nested agent-instruction discovery bounds (#3866). On-demand nested memory-// files are a Claude Code feature — an API-provider agent reads nothing-// natively, so PortOS has to splice them in itself or a subtree rule (including-// a data-loss guard) never reaches that class of agent. The walk is bounded on-// three axes so a repo that grows nested files can't silently balloon every-// agent prompt or turn one prompt build into a full-tree crawl.-const NESTED_AGENT_MD_MAX_DEPTH = 5;-const NESTED_AGENT_MD_MAX_FILES = 10;-const NESTED_AGENT_MD_MAX_DIRS = 2000;-// Dot-directories are skipped wholesale (covers `.git`), so these are the-// non-dot trees that are either vendored, generated, or runtime state. The list-// is deliberately polyglot: an agent workspace is any app PortOS manages, not-// just this repo, so a Rust `target/` or a Go `vendor/` would otherwise burn the-// directory budget on generated files.-const NESTED_AGENT_MD_SKIP_DIRS = new Set([- 'node_modules', 'data', 'data.reference', 'dist', 'build', 'coverage',- 'out', 'obj', 'bin', 'target', 'vendor', 'tmp', 'venv', 'Pods', '__pycache__',-]);--// Instruction filenames in preference order (#4852). `AGENTS.md` is the-// cross-vendor standard PortOS now ships; `CLAUDE.md` stays discoverable because-// a managed app may still carry only that name, and a plain rename would-// silently drop its context. A directory holding both contributes exactly ONE-// entry — otherwise this repo's four nested pairs would count as eight against-// NESTED_AGENT_MD_MAX_FILES and the budget would overflow without a signal.-const AGENT_INSTRUCTION_FILENAMES = [AGENT_INSTRUCTIONS_FILENAME, CLAUDE_BRIDGE_FILENAME];--/**- * True for a bridge `CLAUDE.md` whose entire body is an `@AGENTS.md` import —- * how PortOS and its scaffolders keep Claude Code (which has no configurable- * memory filename) reading the shared file. It carries no content of its own, so- * splicing it would add a useless one-line section to every agent prompt and- * burn a slot against the file cap.- * @param {string} content- */-const isImportOnlyInstructionFile = (content) => {- const lines = String(content)- .replace(/<!--[\s\S]*?-->/g, '')- .split('\n')- .map((line) => line.trim())- .filter(Boolean);- if (lines.length === 0) return false;- if (!lines.every((line) => /^@\S+$/.test(line))) return false;- return lines.some((line) => basename(line.slice(1)).toLowerCase() === 'agents.md');-};--/**- * Read one instruction file, collapsing "absent", "empty", and "import-only- * bridge" to the same null so callers can fall through to the next candidate.- * @param {string} path- * @returns {Promise<string|null>} trimmed content, or null- */-const readInstructionFile = async (path) => {- const content = await tryReadFile(path);- if (!content?.trim()) return null;- if (basename(path) === CLAUDE_BRIDGE_FILENAME && isImportOnlyInstructionFile(content)) return null;- return content.trim();-};--/**- * Collect nested per-directory instruction files (the workspace root is excluded- * — its caller reads it separately and must keep it first). Depth-first in- * lexicographic order, so the result is deterministic and prompt caching stays- * stable across builds.- * @param {string} workspaceDir- * @returns {Promise<Array<{ rel: string, content: string }>>} e.g. `[{ rel: 'server/AGENTS.md', … }]`- */-async function findNestedAgentInstructionFiles(workspaceDir) {- const found = [];- let dirsVisited = 0;-- const walk = async (dir, relDir, depth) => {- if (found.length >= NESTED_AGENT_MD_MAX_FILES) return;- if (depth > NESTED_AGENT_MD_MAX_DEPTH) return;- if (dirsVisited >= NESTED_AGENT_MD_MAX_DIRS) return;- dirsVisited += 1;-- const entries = await readdir(dir, { withFileTypes: true }).catch(() => null);- if (!entries) return;- // A nested directory carrying its own `.git` is a submodule or vendored- // checkout (`lib/slashdo` here) — its instructions are that project's, not- // this workspace's. Detected structurally rather than by an allowlist of- // paths, which would silently stop matching the moment the workspace root is- // something other than this repo's root.- if (depth > 0 && entries.some((entry) => entry.name === '.git')) return;- const sorted = [...entries].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));-- const subdirs = [];- const instructionNames = new Set();- for (const entry of sorted) {- const rel = relDir ? `${relDir}/${entry.name}` : entry.name;- if (entry.isDirectory()) {- if (entry.name.startsWith('.')) continue;- if (NESTED_AGENT_MD_SKIP_DIRS.has(entry.name)) continue;- subdirs.push({ path: join(dir, entry.name), rel });- // Symlinked directories are deliberately NOT followed — a link back up- // the tree would loop, and the depth cap alone wouldn't make the result- // meaningful. A symlinked instruction *file* is still read (below).- } else if (AGENT_INSTRUCTION_FILENAMES.includes(entry.name)) {- instructionNames.add(entry.name);- }- }-- // One entry per directory. Content is read here rather than by the caller so- // an import-only bridge can be dropped before it consumes a slot against the- // file cap — filtering after the walk would let a directory of bridges push- // real instructions out of the budget.- if (relDir) {- for (const name of AGENT_INSTRUCTION_FILENAMES) {- if (!instructionNames.has(name)) continue;- const content = await readInstructionFile(join(dir, name));- if (!content) continue;- found.push({ rel: `${relDir}/${name}`, content });- break;- }- if (found.length >= NESTED_AGENT_MD_MAX_FILES) return;- }-- for (const sub of subdirs) {- if (found.length >= NESTED_AGENT_MD_MAX_FILES) return;- await walk(sub.path, sub.rel, depth + 1);- }- };-- await walk(workspaceDir, '', 0);- return found;-}--/**- * Read agent-instruction files for agent context.- * Reads the global (`~/.claude/CLAUDE.md`), the workspace-root `AGENTS.md` (or- * `CLAUDE.md`), and every nested instruction file under the workspace (#3866) —- * nested last, each as its own labeled section, so precedence still reads- * root-then-specific.- */-export async function getAgentInstructionsContext(workspaceDir) {- const contexts = [];-- // Claude Code's own global memory location — a user-level path, not a repo- // convention, so it keeps the CLAUDE.md name (#4852).- const globalPath = join(homedir(), '.claude', 'CLAUDE.md');- const globalContent = await tryReadFile(globalPath);- if (globalContent?.trim()) {- contexts.push({ type: 'Global Instructions', path: globalPath, content: globalContent.trim() });- }-- // Workspace-root instructions, `AGENTS.md` preferred.- for (const name of AGENT_INSTRUCTION_FILENAMES) {- const projectPath = join(workspaceDir, name);- const projectContent = await readInstructionFile(projectPath);- if (projectContent) {- contexts.push({ type: 'Project Instructions', path: projectPath, content: projectContent });- break;- }- }-- // Nested per-directory instructions, appended after the root file.- for (const { rel, content } of await findNestedAgentInstructionFiles(workspaceDir)) {- contexts.push({ type: `Project Instructions (${rel})`, path: join(workspaceDir, rel), content });- }-- if (contexts.length === 0) {- return null;- }-- let section = '## Agent Instructions\n\n';- section += 'The following instructions must be followed when working on this task:\n\n';-- for (const ctx of contexts) {- section += `### ${ctx.type}\n`;- section += `Source: \`${ctx.path}\`\n\n`;- section += ctx.content + '\n\n';- }-- return section;-}-/**- * Build a compaction instruction section for retries after context-limit failures.- * Provides explicit guidance to the agent on reducing output verbosity.- */-export function buildCompactionSection(task) {- const compaction = task.metadata?.compaction;- if (!compaction?.needed) return '';-- const hints = compaction.retryHints || [];- const reason = compaction.reason === 'output-limit' ? 'output length limit' : 'context window limit';- const prevOutputKB = compaction.outputSize ? Math.round(compaction.outputSize / 1024) : 'unknown';-- return `-## Context Compaction Required--**WARNING**: A previous attempt at this task failed because the agent exceeded the ${reason}.-Previous output size: ~${prevOutputKB} KB. You MUST keep your output compact to avoid the same failure.--**Mandatory output constraints**:-${hints.map(h => `- ${h}`).join('\n')}-- Do NOT reproduce entire file contents in your output-- Reference files by path and line number instead of quoting them-- Limit exploratory reads — plan your approach first, then make targeted changes-`;-}--/**- * Provider types that get the **light** prompt: agentic CLIs with native- * filesystem tools and agent-instruction loading (Claude Code, Codex, Antigravity —- * whether running interactively as `tui` or one-shot as `cli`). Everything- * else (`api`: LM Studio, raw OpenAI/Anthropic) needs the full pasted-in- * context because it has no native filesystem access.- */-const LIGHT_CONTEXT_PROVIDER_TYPES = new Set([PROVIDER_TYPES.TUI, PROVIDER_TYPES.CLI]);--// Inline reuse/quality/efficiency self-review wording for agents that can't run-// the Claude Code `/simplify` built-in (API providers + codex/antigravity CLIs).-// Shared by both prompt paths so the two phrasings can't drift apart.-const SIMPLIFY_INLINE_REVIEW = 'review your changed code for reuse, quality, and efficiency (DRY, dead code, naming, simpler equivalents, missed edge cases)';--/**- * Render a file-list task field (screenshots, attachments, …) either as a- * `### Header` + bulleted-path list (light path) or a single inline- * `**Header**: a, b` line (full path). Shared by every file-list field in- * `buildTaskBlock` so a wording tweak or a new field can't drift between them.- *- * @param {string} header - Section heading / inline label (e.g. "Screenshots").- * @param {Array} items - Task-metadata array; anything else renders as ''.- * @param {(item: any) => string} formatItem - Renders one item for the bulleted list.- * @param {(item: any) => string} formatInline - Renders one item for the inline join.- * @param {boolean} asList - Bulleted-list style vs. inline style.- * @returns {string}- */-function renderFileListField(header, items, formatItem, formatInline, asList) {- if (!Array.isArray(items) || items.length === 0) return '';- return asList- ? `### ${header}\nUse your filesystem tools to inspect each path:\n` +- items.map(i => `- ${formatItem(i)}`).join('\n')- : `**${header}**: ${items.map(formatInline).join(', ')}`;-}--/**- * Build the shared task block — the description plus optional `**Target App**`,- * `**Screenshots**`, and `**Attachments**` fields. Used by BOTH the light and- * full prompt paths so a new task-metadata field gets surfaced in both without- * drift.- *- * Returns pre-rendered slots (`description`, `targetApp`, `screenshots`,- * `attachments`). Absent fields come back as empty strings so the full path's- * template literal can interpolate them in fixed positions and preserve- * byte-identical line spacing. The light path filters out the empty strings- * and joins what remains.- *- * @param {Object} task- * @param {Object} [opts]- * @param {boolean} [opts.screenshotsAsList=false] - When true, render screenshots- * and attachments as a header followed by a bulleted list of paths (light- * path style). When false, render as a single inline `**Field**: a, b`- * line (full path style).- * @returns {{ description: string, targetApp: string, screenshots: string, attachments: string }}- */-export function buildTaskBlock(task, { screenshotsAsList = false } = {}) {- const description = task.description;- // Only surface **Target App** for MANAGED apps — it scopes cross-repo work the- // agent's cwd wouldn't otherwise reveal. For the PortOS default app the agent- // already runs in the PortOS directory, so the line is redundant noise.- const app = task.metadata?.app;- const targetApp = app && app !== PORTOS_APP_ID ? `**Target App**: ${app}` : '';- const screenshots = renderFileListField(- 'Screenshots', task.metadata?.screenshots,- (s) => `\`${resolveTaskFileRef(s)}\``, (s) => resolveTaskFileRef(s), screenshotsAsList- );- const label = (f) => (f?.originalName || f?.filename || f?.path || '').toString();- const path = (f) => resolveTaskFileRef((f?.path || '').toString());- const attachments = renderFileListField(- 'Attachments', task.metadata?.attachments,- (f) => `\`${path(f)}\` (${label(f)})`, (f) => `${label(f)} (${path(f)})`, screenshotsAsList- );- return { description, targetApp, screenshots, attachments };-}--// Map for API-relative upload URLs → the on-disk root the agent should read.-const TASK_REF_ROOTS = {- '/api/screenshots/': PATHS.screenshots,- '/api/attachments/': PATHS.cosAttachments,- '/api/uploads/': PATHS.uploads,-};--/**- * Resolve a stored screenshot/attachment reference to an absolute filesystem- * path the CoS agent can open with its filesystem tools.- *- * Uploads now return API-relative URLs (`/api/screenshots/<file>`) instead of- * absolute paths (issue #2518 — absolute paths leaked the install layout in the- * HTTP response), so tasks created after that change store the relative URL.- * Convert those back to an absolute path here, at prompt-build time, where the- * absolute path is local-only and never persisted or published. Legacy tasks- * that stored an absolute path (or any non-`/api/` value) are passed through- * unchanged so existing queues keep rendering the same path.- */-function resolveTaskFileRef(ref) {- if (typeof ref !== 'string' || !ref) return ref;- for (const [prefix, root] of Object.entries(TASK_REF_ROOTS)) {- if (ref.startsWith(prefix)) {- return join(root, basename(decodeURIComponent(ref)));- }- }- return ref;-}--/**- * Undo the COS-TASKS.md round-trip split before rendering. The queue path in- * `cosTaskGenerator.js` persists a generated multi-line prompt by moving the- * full body into `metadata.prompt` (`metadata.context` before the #4153 split)- * and keeping only its first line as- * `description`, so the markdown stays one-line-per-task. Coming back out, the- * payload therefore *leads with a verbatim copy* of `description` — and every- * render path emits both (the task block, then the full body again under a- * `### Context` header). For a swarm task that surfaces as the reported- * double `# ⚡ SWARM MODE …` header; the same duplication hits any other- * generated/scheduled/system task that round-trips through the queue.- *- * When the split signature is present (the payload's first non-empty line- * equals `description`), fold it back into `description` so the prompt renders- * once, as one clean body with no spurious header. The split `prompt` key stays- * available to customized briefing templates; the legacy `context` payload key- * is dropped because it is already represented by `description`. A genuinely-- * separate user-supplied note (first line differs from `description`) is left- * untouched.- *- * Pure and idempotent: returns the same task when nothing matched, otherwise a- * shallow clone (never mutates the caller's task, so the stored task keeps its- * one-line `description` for the task-list UI).- */-export function reconcileSplitContext(task) {- if (typeof task?.description !== 'string') return task;- const description = task.description.trim();- // `prompt` first: that is where the payload lives on a task written by- // current code (#4153). `context` stays in the loop so a task written before- // the split — or synced from a peer still on the old code — reconciles too.- // Keep the new prompt key available to customized templates. Drop only the- // legacy context key, whose payload is already represented by description.- for (const key of [TASK_PROMPT_KEY, TASK_CONTEXT_KEY]) {- const payload = task.metadata?.[key];- if (typeof payload !== 'string') continue;- // Mirror firstLine() in cosTaskStore.js: first non-empty, trimmed line.- const firstNonEmpty = payload.split('\n').map(l => l.trim()).find(Boolean) || '';- if (firstNonEmpty !== description) continue;- if (key === TASK_PROMPT_KEY) return { ...task, description: payload };- const { [key]: _dropped, ...restMeta } = task.metadata;- return { ...task, description: payload, metadata: restMeta };- }- return task;-}--/**- * Fold a slashdo-backed task's invocation + procedure into its description (#3089).- *- * A task that names a bundled workflow persists only the BARE command- * (`metadata.slashdoCommand`) because the form's provider select defaults to- * "Auto" — the concrete shape (`/do:x`, `/do-x`, or an Agent Skill selected by- * name) is only knowable here, once the scheduler has picked a provider.- *- * The command body travels with the prompt for every provider, not just the- * skill-style ones: PortOS ships slashdo as a submodule and only surfaces it as- * slash commands via the repo-local `.claude/commands/do/` symlinks, which don't- * exist in the managed-app workspaces most CoS tasks run in.- *- * **Size control (#3110).** Expanded bodies run 38KB–317KB. Two independent- * reductions apply, in this order:- *- * 1. **Prune unreachable reviewer variants.** `review`/`better`/`pr` each paste- * all five of slashdo's reviewer loops though one run drives one of them.- * Pruning to a single CLI reviewer measured -23% on `review` (258,260 →- * 198,997 chars), -27% on `pr`, and -28% on `depfree`. (slashdo's- * orchestration wrapper is never pruned — it dispatches even a single-entry- * reviewer list — which is ~37KB of the theoretical ceiling.)- * 2. **Point at a resolved copy on disk when still over budget** — but only for a- * host with file tools (`cli`/`tui`; an HTTP `api` provider has none and- * inlines with a warning). On its own this is roughly token-NEUTRAL for an- * agent that reads the whole procedure; it pays off when the host can invoke- * slashdo natively or needs only part of the body.- *- * Pruning is only sound if the run then uses the reviewers we pruned FOR, so the- * section emits an explicit `--review-with` pin alongside a pruned body —- * otherwise the agent could resolve a different reviewer from slashdo's own saved- * defaults and find that loop missing. No explicit pin ⇒ no prune.- *- * The reviewers, usernames, and optional-reviewers are resolved through the SAME- * three helpers as the inline `/do:pr` completion path further down- * (`normalizeReviewers` / `resolveReviewUsernames` / `resolveOptionalReviewers`),- * so what we prune for is exactly what the rest of the prompt resolves — legacy- * single-`reviewer` tasks and defaults-inherited `optionalReviewers` included.- *- * The one case that does NOT authorize pruning is a resolved lone `copilot` that- * nothing named explicitly (no task pin, no username reviewers, not marked- * optional): `pickCodeReviewDefaults` and `normalizeReviewers` both fall back to- * `['copilot']`, so that value can't be told apart from an unconfigured install —- * and pinning `--review-with copilot` where Copilot review isn't enabled is the- * #2507 stall. This mirrors `buildReviewWithArgs`'s lone-default suppression,- * including its exemption for an explicitly-optional copilot.- *- * Applied to the description (on a COPY — the stored task is untouched) rather- * than emitted as its own template slot, because the briefing template renders- * `{{task.description}}`: a new `{{slashdoSection}}` placeholder would be- * silently dropped by every install whose customized template predates it.- *- * @returns {Promise<Object>} the task, or a copy carrying the invocation- */-async function applySlashdoInvocation(task, {- providerId = null, providerCommand = null, leanMode = false, hasFileTools = false,- defaultReviewers = null, codeReviewDefaults = null,-} = {}) {- const command = task.metadata?.slashdoCommand;- const resolved = resolveSlashdoInvocation({- command,- args: task.metadata?.slashdoArgs || '',- providerId,- providerCommand,- leanMode,- });- if (!resolved) return task;-- // Resolved through the SAME three helpers the inline `/do:pr` completion path- // uses below (`taskReviewers` / `taskReviewerUsernames` / `taskOptionalReviewers`),- // so the reviewers we prune for are exactly the ones the rest of the prompt- // resolves. Hand-rolling `metadata.reviewers` here instead dropped the legacy- // single `reviewer` string and the defaults' `optionalReviewers` — pruning for- // one reviewer while the run resolved another, and pinning an optional reviewer- // as blocking.- const {- reviewers: resolvedReviewers,- usernames: resolvedUsernames,- optionalReviewers: resolvedOptional,- reviewerMaxRounds: resolvedMaxRounds,- reviewerModels: resolvedModels,- reviewerEfforts: resolvedEfforts- } = resolveReviewerConfig(task.metadata, codeReviewDefaults, defaultReviewers);-- // A resolved lone `copilot` with no usernames is ambiguous: it's what an- // unconfigured install produces (`pickCodeReviewDefaults` and- // `normalizeReviewers` both fall back to `['copilot']`), so it can't be told- // apart from a real choice UNLESS something names it explicitly. Absent that,- // treat it as unconfigured and prune nothing — pinning `--review-with copilot`- // where Copilot review isn't enabled is the #2507 stall.- //- // Marking copilot OPTIONAL — or giving it a `~max=<n>` round cap — is such an- // explicit naming: nothing defaults to either suffix, so both are deliberate- // choices, and dropping one would silently turn a non-blocking review blocking- // or spend an unbudgeted number of rounds. `buildReviewWithArgs` makes the same- // exemption for its lone-default suppression — keep the two in step. It carries a- // third clause for a copilot `~effort=`; there is deliberately none here, because- // copilot has no effort ladder at all (`REVIEWER_EFFORT_LEVELS` is keyed off- // `reviewerCliBinary`, and copilot names no binary), so `normalizeReviewerEfforts`- // drops the pin long before either function sees it.- const taskPinnedReviewer = (Array.isArray(task.metadata?.reviewers) && task.metadata.reviewers.length > 0)- || (typeof task.metadata?.reviewer === 'string' && !!task.metadata.reviewer);- const optionalDefaultReviewer = resolvedOptional.some(t => t.toLowerCase() === DEFAULT_REVIEWER);- const cappedDefaultReviewer = Object.keys(resolvedMaxRounds)- .some(t => t.toLowerCase() === DEFAULT_REVIEWER);- const isBareDefault = resolvedReviewers.length === 1- && resolvedReviewers[0] === DEFAULT_REVIEWER- && !resolvedUsernames.length- && !taskPinnedReviewer- && !optionalDefaultReviewer- && !cappedDefaultReviewer;- const skipIncludes = isBareDefault- ? []- : unreachableReviewerIncludes({ reviewers: resolvedReviewers, usernames: resolvedUsernames });-- const body = await loadSlashdoFile(command, { stripFrontmatter: true, skipIncludes }).catch(() => null);- if (!body) console.log(`⚠️ Slashdo command body unavailable, sending invocation only: ${command}`);- const overBudget = !!body && body.length > SLASHDO_INLINE_BUDGET_CHARS;- // An HTTP `api` provider can't read a file, so an over-budget body is pasted- // whole. Surface the cost rather than paying it silently.- if (overBudget && !hasFileTools) {- console.warn(`⚠️ Inlining ${Math.round(body.length / 1000)}KB slashdo body for API provider (no file tools): ${command}`);- }- // Only spend the write when the pointer will actually be used.- const bodyPath = (overBudget && hasFileTools)- ? await writeResolvedSlashdoBody(command, body, { skipIncludes }).catch((err) => {- console.warn(`⚠️ Could not stage slashdo body for ${command}, inlining instead: ${err.message}`);- return null;- })- : null;-- const reviewWith = skipIncludes.length- ? buildReviewersCsv(resolvedReviewers, resolvedUsernames, resolvedOptional, resolvedMaxRounds, resolvedModels, resolvedEfforts)- : '';- // Gated on the PIN, not on pruning. When `reviewWith` is emitted, each token- // carries `~effort=<level>` and slashdo's loop applies it — the note would only- // have the agent pass the flag twice. When nothing is pinned, the workflow- // resolves reviewers itself and the note is the pin's only route to the CLI it- // spawns (the `/do:pr` completion step further down is a different invocation- // entirely, and for a slashdo-backed task usually isn't reached).- const reviewerEffortNote = buildReviewerEffortNote(resolvedReviewers, resolvedEfforts, { reviewWith, reviewerModels: resolvedModels });- const section = buildSlashdoSection(resolved, body, { bodyPath, reviewWith, reviewerEffortNote });- return { ...task, description: `${task.description}\n\n${section}` };-}--/**- * True when a follow-up task is a **merge-only** run: it has a PR to land but no- * reviewer to run (Review Loop off, or every configured reviewer was stripped —- * e.g. copilot on a GitLab MR). Tolerates the string `'true'` because task- * metadata round-trips through JSON/forms like every other CoS flag.- *- * Used both to pick the prompt section and to skip preloading the reviewer-only- * slashdo bodies (`/do:rpr`, the local-agent review loop) that section ignores.- */-function isMergeOnlyFollowUp(metadata = {}) {- return metadata?.reviewLoopMergeOnly === true || metadata?.reviewLoopMergeOnly === 'true';-}--/**- * Build the **review-loop follow-up** section — the instructions for the- * agent spawned by `spawnReviewLoopFollowUp` to drive Copilot's review-and-fix- * loop until the PR merges. Same 7-step procedure, same merge command, same- * MERGED-state verification, same 10-iteration cap in BOTH the light and full- * paths — extracted so the two can't drift independently.- *- * I/O (the slashdo `/do:rpr` body) is intentionally pulled outside this helper- * and threaded in via `rprBody` so the function stays pure and synchronous.- *- * @param {Object} metadata - task.metadata (reviewLoopPR* fields, sourceTaskId)- * @param {Object} [opts]- * @param {boolean} [opts.verbose=false] - When true, emit the verbose prose- * variant the full (api) path uses, with PR Details list and an inlined- * `/do:rpr` reference. When false, emit the compact list the light path uses.- * @param {string|null} [opts.rprBody=null] - The loaded `/do:rpr` slashdo body.- * Only appended in verbose mode; ignored in compact mode.- * @param {string|null} [opts.localAgentLoopBody=null] - The loaded slashdo- * `lib/local-agent-review-loop.md` body (conditionals resolved to the- * subprocess/`else` branch). Inlined when a spawnable CLI reviewer- * (codex/antigravity/claude/grok) is in the list so the agent gets the exact- * headless invocation and review-only contract instead of improvising it.- * @param {string|null} [opts.localAgentLoopBodyPath=null] - Path to a staged copy- * of that body. When set and the body is over `SLASHDO_INLINE_BUDGET_CHARS`,- * the section points at the file instead of pasting it. Only the inline caller- * passes this; a follow-up agent, whose whole job is the loop, still inlines.- * @param {boolean} [opts.inline=false] - Emit the SAME loop for an agent that- * opened the PR itself moments ago, rather than for a follow-up agent handed- * someone else's PR (`buildInlineReviewLoopSection`). Only the framing differs:- * the heading and opening sentence, and the fact that nothing pre-requested a- * Copilot review. The loop body, notes, merge command, and MERGED verification- * stay byte-identical so the two callers can't drift.- * @returns {string}- */-export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false, rprBody = null, localAgentLoopBody = null, localAgentLoopBodyPath = null, inlineExitStep = null, forgeCli = null } = {}) {- // One parameter, not two: an `inline` boolean alongside it could disagree with- // it, and the disagreement renders silently — `inline` with a blank exit step- // emits a bare "6." and a truncated merge-gate hand-back.- const inline = inlineExitStep !== null;- const prUrl = metadata.reviewLoopPRUrl || '';- const prBranch = metadata.reviewLoopPRBranch || '';- const prNumber = metadata.reviewLoopPRNumber ?? '';- const prOwner = metadata.reviewLoopPROwner ?? '';- const prRepo = metadata.reviewLoopPRRepo ?? '';- const sourceTaskId = metadata.sourceTaskId || 'unknown';- const reviewForgeCli = normalizeForgeCli(forgeCli)- || (detectForgeCli(metadata.reviewLoopPRHost) === 'glab' ? 'glab' : 'gh');- // Merge-only follow-up (Review Loop off): no reviewer to wait on or invoke —- // the whole job is CI-gate → fix → merge. Branch before any reviewer defaulting- // below, which would otherwise resolve the empty list back to `[copilot]`.- if (isMergeOnlyFollowUp(metadata)) {- return buildMergeFollowUpSection({- prUrl, prBranch, prNumber, prOwner, prRepo, sourceTaskId, verbose, inlineExitStep,- prHost: metadata.reviewLoopPRHost ?? '',- forgeCli: reviewForgeCli,- });- }- // Arbitrary GitHub reviewer usernames (gate-only PR reviewers), appended to- // the review flow after the keyed reviewers.- const usernames = normalizeReviewUsernames(metadata.reviewLoopReviewerUsernames);- // Ordered keyed reviewer list (back-compat: legacy single `reviewLoopReviewer`).- // `reviewLoopReviewers` from spawnReviewLoopFollowUp is authoritative (copilot- // already stripped on non-GitHub forges); resolveKeyedReviewers keeps an- // explicit empty list empty when usernames carry the review (username-only).- const reviewerSource = Array.isArray(metadata.reviewLoopReviewers)- ? metadata.reviewLoopReviewers- : (metadata.reviewLoopReviewer ? [metadata.reviewLoopReviewer] : undefined);- const reviewers = resolveKeyedReviewers(reviewerSource, usernames.length > 0);- // Reviewer identities marked non-blocking — emitted with slashdo's `~opt`.- const optionalReviewers = normalizeOptionalReviewers(metadata.reviewLoopOptionalReviewers) || [];- // Per-reviewer `~max=<n>` iteration caps, keyed by emitted token. An absent key- // leaves slashdo's built-in per-loop default; `0` means "loop until clean".- const reviewerMaxRounds = normalizeReviewerMaxRounds(metadata.reviewLoopReviewerMaxRounds) || {};- const stopMode = metadata.reviewLoopStopMode || DEFAULT_REVIEW_STOP_MODE;- const reviewerApplies = metadata.reviewLoopReviewerApplies === true;- const hasCopilot = reviewers.includes(DEFAULT_REVIEWER);- const hasLocalLlm = reviewers.some(r => LOCAL_LLM_REVIEWERS.includes(r));- // Spawnable-CLI reviewers, in configured order.- const cliReviewers = reviewers.filter(isCliReviewer);- const hasCli = cliReviewers.length > 0;- const hasGithubUser = usernames.length > 0;- // Optional per-reviewer model pins (Code Review Defaults panel, or the task's own- // ReviewerPicker row), threaded as a reviewer-keyed map. A model-capable CLI- // reviewer in this loop's list gets a `<reviewer> --model <id>` note; a local-LLM- // reviewer's pin goes into its `/api/code-review/local` request body instead- // (below). Absent = let that reviewer use its own default. For an Ollama-backed- // `claude` reviewer the id is the local Ollama model. Falls back to the legacy- // codex-scalar metadata key so a follow-up task persisted by an older install- // still threads its codex model.- const reviewerModelMap = (metadata.reviewLoopReviewerModels && typeof metadata.reviewLoopReviewerModels === 'object')- ? metadata.reviewLoopReviewerModels- : (typeof metadata.reviewLoopCodexModel === 'string' && metadata.reviewLoopCodexModel- ? { codex: metadata.reviewLoopCodexModel }- : {});- // Optional per-reviewer reasoning-effort pins, same two sources as the models.- // A CLI reviewer's effort becomes a flag on the command line the agent runs- // (`--effort high` for claude/agy, `-c model_reasoning_effort=high` for codex —- // `reviewerEffortArgs` owns that shape, and returns nothing for cursor, whose- // level is folded into `--model` by `reviewerModelArg`); a local-LLM reviewer's becomes the- // `reasoning_effort` field of its `/api/code-review/local` body (below). There is- // no slashdo `--review-with` suffix for effort, which is why it rides the- // invocation rather than `equivArgs`.- const reviewerEffortMap = (metadata.reviewLoopReviewerEfforts && typeof metadata.reviewLoopReviewerEfforts === 'object')- ? metadata.reviewLoopReviewerEfforts- : {};- // One entry per CLI reviewer carrying a pinned model and/or effort, rendered as- // the literal command line the agent must run. Reviewers are listed rather than- // filtered to MODEL_CAPABLE_CLI_REVIEWERS up front because a CLI reviewer may- // carry only one of the two pins (and `grok` carries neither). The per-flag- // gates below decide what each entry renders; an entry with no flags drops out.- const reviewerPinEntries = cliReviewers- .map((r) => {- const flags = [];- // Thread each configured model id VERBATIM. We deliberately don't env-map it- // here (e.g. bare Claude tier → Bedrock form): this is a text-template layer- // with only a providerId, not the merged spawn env (process.env + settings.json- // + provider.envVars) the CLI argv builder normalizes against — and the nested- // reviewer CLI is spawned by the agent, not PortOS, so the argv chokepoint never- // runs. The Code Review Defaults model field is free-text for exactly this- // reason: the user configures the id their environment needs (a Bedrock-form id- // on a Bedrock box, an installed Ollama model for an Ollama-backed `claude`).- if (MODEL_CAPABLE_CLI_REVIEWERS.includes(r) && typeof reviewerModelMap[r] === 'string' && reviewerModelMap[r]) {- // `reviewerModelArg` (not the raw id) because cursor carries its- // reasoning effort INSIDE the model id — `gpt-5[effort=max]` — so the- // pinned pair must render as ONE `--model`, never a `--effort` cursor- // rejects. Every other reviewer gets the id back verbatim.- flags.push(`--model ${reviewerModelArg(r, reviewerModelMap[r], reviewerEffortMap[r])}`);- }- const effortArgs = reviewerEffortArgs(r, reviewerEffortMap[r]);- if (effortArgs.length) flags.push(effortArgs.join(' '));- // Binary, not slug: this renders a literal command line, and the- // `antigravity` slug names no executable.- return flags.length ? `\`${reviewerCliBinary(r) || r} ${flags.join(' ')} …\`` : null;- })- .filter(Boolean);- const reviewerPinNote = reviewerPinEntries.length- ? ` When invoking a reviewer with a pinned model or reasoning effort, pass it: ${reviewerPinEntries.join(', ')}.`- : '';- // When the slashdo local-agent review loop is inlined below (a spawnable CLI- // reviewer is in the list), point the invocation step at it so the agent runs- // the exact headless recipe instead of probing the CLI's flags / hand-rolling- // an invocation — the failure mode that had a codex CoS agent burn a dozen- // exploratory `claude --help` / `claude -p 'hello'` / `--tools ''` probes- // before it stumbled into a working review call.- const cliProcedurePointer = (hasCli && localAgentLoopBody)- ? ' Follow the **CLI Reviewer Procedure** section below for the exact headless invocation and review-only contract — do NOT probe the CLI or guess flags.'- : '';- // Each configured CLI reviewer paired with the command the agent must actually- // run. Resolved ONCE — the slug-vs-binary distinction is the whole point of- // this block, so every string below reads it from here rather than restating- // the `|| slug` fallback. Unmapped slug ⇒ falls back to itself.- const cliBinaries = cliReviewers.map(slug => ({ slug, binary: reviewerCliBinary(slug) || slug }));- // `**codex / agy / claude**` — the CLI reviewers THIS loop configured, named by- // the binary. Previously a fixed "codex / antigravity / claude / grok" string,- // which both listed reviewers that weren't configured and named `antigravity`,- // a command that exists on no PATH.- const cliReviewerHeading = cliBinaries.map(c => c.binary).join(' / ');- // Spell out slug → binary for any reviewer whose command differs from its- // slug, so the agent can reconcile the configured list / `--review-with` token- // with the executable named in the invocation table.- const cliBinaryAliases = cliBinaries- .filter(c => c.binary !== c.slug)- .map(c => `the \`${c.slug}\` reviewer runs the \`${c.binary}\` binary (there is no \`${c.slug}\` command)`);- const cliBinaryNote = cliBinaryAliases.length- ? ` Reviewer slug → command: ${cliBinaryAliases.join('; ')}.`- : '';- // A configured reviewer that cannot run is NOT a clean review. Without this,- // an agent whose reviewer binary was missing self-reviewed and merged anyway- // — the exact regression this note blocks.- const missingCliNote = hasCli- ? `**Missing reviewer CLI:** verify each reviewer's binary is on PATH (${cliBinaries.map(c => `\`command -v ${c.binary}\``).join(' / ')}) before concluding it is unavailable. If a configured reviewer's binary genuinely is not installed, that reviewer is UNSATISFIED — do NOT substitute your own self-review and do NOT merge. Post a PR comment naming the missing command and exit.`- : '';- // "multi" reflects the TOTAL number of review sources (keyed reviewers +- // username reviewers) so the ordered per-reviewer loop wording kicks in as- // soon as there's more than one thing to satisfy.- const multi = (reviewers.length + usernames.length) > 1;- // The system pre-requests the initial Copilot review only when copilot LEADS the- // order; otherwise the agent must request it at copilot's turn (so Copilot reviews- // the post-CLI-fix state, not a stale diff). An INLINE loop opened its own PR- // moments ago and nothing pre-requested anything, so it always requests.- const copilotIsFirst = !inline && reviewers[0] === DEFAULT_REVIEWER;- const reviewerLabel = [- ...reviewers.map(r => `\`${r}\``),- ...usernames.map(u => `\`@${u}\``),- ].join(' → ');- const equivArgs = buildReviewWithArgs(reviewers, { stopMode, reviewerApplies, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels: reviewerModelMap });- const equiv = equivArgs ? ` (equivalent to \`/do:pr ${equivArgs}\`)` : '';-- // First step: how to obtain a review. For a single copilot/CLI reviewer keep the- // focused wording; for a list, dispatch each reviewer in order. Only emit the- // per-reviewer-kind bullet that actually applies to the configured list.- // `lmstudio`/`ollama` don't have CLIs the agent can spawn — PortOS exposes- // `POST /api/code-review/local` which runs the configured local model against- // the diff and returns findings text. The agent always reaches it via- // `http://localhost:5555` (the canonical loopback API port).- // A pinned local-LLM model can't ride the endpoint's server-side default: that- // reads the GLOBAL settings scalar and has never seen this task. So when the- // user pinned one on the reviewer's row, name it in the request body — `model`- // in the POST body overrides the configured default (see routes/codeReview.js).- // Absent pin ⇒ omit the key entirely rather than sending `""`, which would be a- // model id the backend can't resolve.- // The pinned reasoning effort rides the same body as `effort` — the endpoint- // forwards it as the backend's OpenAI-compatible `reasoning_effort`. Same- // absent-vs-empty contract as the model: no pin ⇒ the key is omitted, not blank.- // Which body keys this run actually pins, accumulated across the local-LLM- // reviewers in the list. The jq example below is built from THIS set rather than- // naming both keys unconditionally: an effort-only run that was shown a- // `model: "…"` placeholder would have the agent send the literal ellipsis, and- // the route's `body.model || configured` prefers that truthy junk over the- // install default — turning a pinned-effort review into a model-not-found error.- const pinnedString = (map, r) => (typeof map[r] === 'string' && map[r] ? map[r] : null);- const localLlmPins = LOCAL_LLM_REVIEWERS- .filter(r => reviewers.includes(r))- .map(r => ({ reviewer: r, model: pinnedString(reviewerModelMap, r), effort: pinnedString(reviewerEffortMap, r) }))- .filter(p => p.model || p.effort);- const localLlmPinNote = localLlmPins.map(({ reviewer, model, effort }) => {- const keys = [- ...(model ? [`"model": "${model}"`] : []),- ...(effort ? [`"effort": "${effort}"`] : [])- ];- return `\`${reviewer}\` → \`${keys.join(', ')}\``;- });- // Both strings derive from the same `localLlmPins` array rather than the jq line- // reading a Set the note's `.map` filled as a side effect — that coupling meant- // hoisting one line above the other silently emptied the key list.- const localLlmPinJq = [- 'backend: "…"',- ...(localLlmPins.some(p => p.model) ? ['model: "…"'] : []),- ...(localLlmPins.some(p => p.effort) ? ['effort: "…"'] : []),- 'diff: .'- ].join(', ');- const diffCommand = reviewForgeCli === 'glab'- ? `glab mr diff ${prNumber || '<MR_NUMBER>'}`- : `gh pr diff ${prNumber || '<PR_NUMBER>'}`;- const localLlmInvocation = `POST the diff to PortOS's local reviewer endpoint and extract its review text before evaluating it. Substitute the active reviewer name for \`<lmstudio|ollama>\`:-\`\`\`bash-REVIEW_RESPONSE=$(mktemp)-${diffCommand} | jq -Rs '{ backend: "<lmstudio|ollama>", diff: . }' | curl -sS -X POST http://localhost:5555/api/code-review/local -H 'Content-Type: application/json' -d @- > "$REVIEW_RESPONSE"-if ! jq -er '.findings | select(type == "string" and length > 0)' "$REVIEW_RESPONSE" > "\${REVIEW_RESPONSE}.findings"; then- echo "Local reviewer failed: $(jq -r '.error // "missing .findings in reviewer response"' "$REVIEW_RESPONSE")" >&2- STATUS=cli-error # Never treat an absent or malformed response as clean.- exit 1-else- cat "\${REVIEW_RESPONSE}.findings"-fi-\`\`\`-Only a successfully extracted \`.findings\` value is the review text; treat it like any other reviewer's findings.${localLlmPinNote.length- ? ` This run pins settings for ${localLlmPinNote.join(', ')} — add those keys to the JSON body (\`jq -Rs '{ ${localLlmPinJq} }'\`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk.`- : ''}`;- // Instruct the agent to request each username reviewer as a PR reviewer and- // gate the merge on their approval. `gh pr edit --add-reviewer` takes the bare- // login, so strip the `@`.- const githubUsersInvocation = reviewForgeCli === 'glab'- ? `request ${usernames.map(u => `\`@${u}\``).join(', ')} as MR reviewer${usernames.length > 1 ? 's' : ''} using the GitLab project UI or API, then inspect \`glab mr view ${prNumber || '<MR_NUMBER>'}\` for their review and address any findings; their approval gates the merge.`- : `request ${usernames.map(u => `\`@${u}\``).join(', ')} as PR reviewer${usernames.length > 1 ? 's' : ''} (\`gh pr edit ${prNumber || '<PR_NUMBER>'} --add-reviewer <user>\`, drop the \`@\`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.`;- const multiBullets = [- hasCopilot ? `**copilot**: ${copilotIsFirst- ? 'wait for the initial Copilot review the system already pre-requested (Copilot leads the list)'- : 'request a Copilot review when you reach its turn'} (poll every 5–15s, max 5 min/round), then re-request on later rounds.` : null,- hasCli ? `**${cliReviewerHeading}**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or \`git diff <base-branch>...HEAD\`; on GitHub \`gh pr diff ${prNumber || ''}\` also works).${cliBinaryNote}${reviewerPinNote}${cliProcedurePointer}` : null,- hasLocalLlm ? `**lmstudio / ollama**: ${localLlmInvocation}` : null,- hasGithubUser ? `**@github reviewers**: ${githubUsersInvocation}` : null,- ].filter(Boolean).join(' ');- // Name the BINARY, not the slug: `Invoke the \`antigravity\` CLI` sent a- // follow-up agent hunting for a command that does not exist.- const singleCliInvocation = `Invoke ${describeReviewerCli(cliReviewers[0])} to review this branch's diff against its base (use the CLI's own base-diff mode or \`git diff <base-branch>...HEAD\`; on GitHub \`gh pr diff ${prNumber || ''}\` also works). Capture its findings as concrete issues to address.${reviewerPinNote}${cliProcedurePointer}`;- // Resolved sequentially so a future reviewer kind only adds one branch- // instead of deepening the nested ternary.- let waitOrInvokeStep;- if (multi) waitOrInvokeStep = `For EACH reviewer in order — ${reviewerLabel} — run a full review-and-fix sub-loop before advancing to the next. ${multiBullets}`;- else if (hasCopilot) waitOrInvokeStep = 'Wait for the latest Copilot review to complete (poll every 5–15s, max 5 minutes per round); the system already requested the initial review.';- else if (hasLocalLlm) waitOrInvokeStep = localLlmInvocation;- else if (hasCli) waitOrInvokeStep = singleCliInvocation;- else waitOrInvokeStep = `To obtain a review, ${githubUsersInvocation}`;-- const stopModeNote = stopMode === 'on-findings'- ? '**Stop mode (on-findings):** stop after the FIRST reviewer whose findings you actually fixed and committed; skip the remaining reviewers.'- : stopMode === 'on-clean'- ? '**Stop mode (on-clean):** stop after the FIRST reviewer that reports zero findings; skip the remaining reviewers.'- : (multi ? '**Stop mode (all):** run every reviewer in the list, in order, before merging.' : '');-- const applyNote = hasCli- ? (reviewerApplies- ? '**Reviewer applies:** let each CLI reviewer apply its own fixes to the working tree, then verify, run tests, and push.'- : "**Reviewer applies (off):** read each CLI reviewer's findings and apply the fixes yourself (default).")- : '';-- // Inline runs opened the PR seconds ago inside their own completion workflow,- // so nothing pre-requested anything — claiming otherwise would have the agent- // poll forever for a Copilot review no one asked for.- const initialReviewState = inline- ? 'Nothing has reviewed this PR yet — you must request/invoke each configured reviewer yourself against its diff.'- : (hasCopilot && copilotIsFirst)- ? 'The system has already requested the initial Copilot code review (Copilot leads the order).'- : hasCopilot- ? 'Copilot is configured after another reviewer, so the system did NOT pre-request it — request the Copilot review yourself when you reach its turn (after the earlier reviewers’ fixes are pushed), and invoke the other reviewers yourself.'- : 'The system did NOT pre-request a reviewer because no Copilot review leads the order — you must request/invoke each configured reviewer yourself against the PR diff.';- const repeatedCommentsNote = '**Repeated comments:** If a fresh review round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on.';- // Challenge protocol (#2471): auto-invoke the bounded worker↔reviewer dispute- // from the review loop. When a reviewer's BLOCKING finding is a false positive,- // the agent disputes it once via POST /challenge instead of silently complying- // or accepting a false block, then RE-CHECKS (re-run reviewer) to overturn or- // escalate. One challenge per task, also bounded by the task's retry budget —- // a second dispute or an out-of-retries task returns 409.- const challengeProtocolNote = [- '**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:',- '```bash',- `curl -sS -X POST http://localhost:5555/api/cos/tasks/${sourceTaskId}/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'`,- '```',- 'A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can\'t dispute — then fix the finding or, if genuinely blocked, post a PR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user.' + (hasLocalLlm ? ' For a local reviewer you may instead POST `{"recheck":{"backend":"<lmstudio|ollama>","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.' : ''),- ].join('\n');- // Per-reviewer round caps. This prompt drives the loop in PROSE (it isn't- // slashdo parsing a `~max=<n>` suffix), so a configured cap only binds if it's- // spelled out here — the `equiv` flag string alone documents intent without- // constraining the agent. `0` is slashdo's "loop until clean", so it's rendered- // as such rather than as a zero-round budget.- const maxRoundsEntries = Object.entries(reviewerMaxRounds)- .filter(([token]) => reviewers.includes(token) || usernames.some(u => `@${u}`.toLowerCase() === token.toLowerCase()))- .map(([token, max]) => `\`${token}\` → ${max === 0 ? 'loop until clean (no cap)' : `${max} round${max === 1 ? '' : 's'}`}`);- const maxRoundsNote = maxRoundsEntries.length- ? `**Round caps (~max):** stop these reviewers after their budget even if findings remain, then advance: ${maxRoundsEntries.join(', ')}. Spending a configured budget is a SUCCESS, not a failure — do not block the merge on it. Reviewers not listed keep the default cap below.`- : '';-- const extraNotes = [stopModeNote, applyNote, maxRoundsNote, missingCliNote].filter(Boolean);-- // Inline slashdo's local-agent review loop verbatim when a spawnable CLI- // reviewer is configured. This is the maintained, precise recipe — exact- // per-CLI headless invocation (`claude -p "$LOCAL_PROMPT" --dangerously-skip-permissions`,- // `codex --sandbox read-only review --base …`, etc.), the review-only /- // no-sub-agent-fan-out `$LOCAL_PROMPT` contract, and the parse-and-apply- // handling. Without it the agent only sees "invoke that CLI" and reverse-- // engineers the invocation, wasting calls. The inlined body AGREES with- // cliBinaryNote rather than contradicting the "follow it verbatim" order —- // slashdo's per-CLI invocation table names `agy` and normalizes the- // `gemini`/`antigravity` slugs onto it, so the note is a pointer into that- // table, not a correction layered over it. Conditionals were resolved to the- // subprocess (`else`) branch by loadSlashdoLib, so no in-process-Agent-tool- // branch leaks in to confuse a non-Claude-Code host.- //- // Over budget WITH a staged copy on disk (`localAgentLoopBodyPath`, only ever- // passed for an inline loop — see buildAgentPrompt) the agent is pointed at the- // file instead. Same trade `buildSlashdoSection` makes: an initial run is- // already carrying the real task, and pasting 40KB of reviewer recipe up front- // to be read at step 4 is the wrong place to spend that context.- const cliProcedureHeader = `\n### CLI Reviewer Procedure (${cliReviewerHeading})\n\nDrive each spawnable CLI reviewer EXACTLY as the slashdo local-agent review loop specifies — use its per-CLI invocation and review-only prompt contract verbatim; do NOT probe the CLI's \`--help\`, test it with throwaway prompts, or hand-roll flags. Run the reviewer once per round, capture its findings, and (unless reviewer-applies is set) apply the fixes yourself.\n\n`;- //- // The path IS the decision — it is non-null only when the caller already- // measured the body over budget and staged it. Re-testing the length here- // would give the two sites a way to disagree, and the disagreement is silent:- // the file gets written AND the 40KB still gets pasted.- const cliReviewerProcedure = (hasCli && localAgentLoopBody)- ? (localAgentLoopBodyPath- ? `${cliProcedureHeader}${oversizedBodyPointer(localAgentLoopBodyPath, localAgentLoopBody)}\n`- : `${cliProcedureHeader}${localAgentLoopBody}\n`)- : '';-- // A JIRA-tracked PR is a human's to land (its ticket is already "In Review" and- // nothing here can transition it), so this follow-up reviews and stops. Emitted- // as the same steps 4-6 so the loop body above stays identical either way.- const leaveOpen = metadata.reviewLoopLeaveOpen === true || metadata.reviewLoopLeaveOpen === 'true';- const objective = leaveOpen- ? '**Your job is to drive the review-and-fix loop to completion. Do NOT merge — this PR is tracked in JIRA and a human lands it.**'- : '**Your job is to drive the review-and-fix loop to completion and merge the PR.**';- // Where the loop hands control back. A follow-up agent's whole task WAS the- // loop, so it exits; an inline loop is one step of a larger completion- // workflow that still owes the run its `.agent-done` sentinel — telling it to- // "exit" here leaves a finished merge without the sentinel that records it.- const exitStep = inline- ? `6. ${inlineExitStep}`- : `6. Exit. Do **not** run \`/do:push\` or open a new PR${leaveOpen ? '' : ' — the merge handles everything'}. The system will clean up your worktree on exit.`;- const closingSteps = leaveOpen- ? [- '4. When the reviewer list is exhausted (or the stop mode triggers), **leave the PR open** — do NOT merge it, and do NOT delete the branch. Its JIRA ticket is sitting in review and a human lands both together; merging here would leave the work merged and the ticket stuck in review.',- // Forge-aware: `gh pr comment` fails outright on a GitLab MR URL.- `5. Post a short comment on the ${detectForgeCli(metadata.reviewLoopPRHost) === 'glab' ? 'MR' : 'PR'} summarising what the reviewers raised and what you fixed, so the human landing it knows the state: ${detectForgeCli(metadata.reviewLoopPRHost) === 'glab' ? `\`glab mr note ${prNumber !== '' ? prNumber : '<MR_NUMBER>'} --message "<summary>"\`` : `\`gh pr comment "${prUrl}" --body "<summary>"\``}.`,- exitStep,- ]- : [- `4. When the reviewer list is exhausted (or the stop mode triggers), merge the PR **immediately** with this exact command (flags: \`--merge --delete-branch\`, nothing else — a true merge commit keeps the branch tip in main's history so automated worktree cleanup can prove the branch is merged):`,- ' ```bash',- reviewForgeCli === 'glab'- ? ` glab mr merge "${prNumber || '<MR_NUMBER>'}" --yes --remove-source-branch`- : ` gh pr merge "${prUrl}" --merge --delete-branch`,- ' ```',- reviewForgeCli === 'glab'- ? null- : (prOwner && prRepo && prNumber ? ` (Equivalent: \`gh pr merge ${prNumber} --repo ${prOwner}/${prRepo} --merge --delete-branch\`.)` : null),- ' You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.',- reviewForgeCli === 'glab'- ? `5. Confirm the MR is actually merged before exiting: \`glab mr view "${prNumber || '<MR_NUMBER>'}"\` must show it merged. If it is still open or was closed unmerged, investigate (a check is failing, a thread is still unresolved, or branch protection is blocking) — fix and retry the merge. Do NOT exit until it is merged.`- : `5. Confirm the PR is actually merged before exiting: \`gh pr view "${prUrl}" --json state -q .state\` must return \`MERGED\`. If it returns \`OPEN\` or \`CLOSED\`, investigate (a check is failing, a thread is still unresolved, or branch protection is blocking) — fix and retry the merge. Do NOT exit until state is \`MERGED\`.`,- exitStep,- ].filter(Boolean);-- // Framing only — everything below it is identical for both callers.- const heading = inline ? '## Review Loop' : '## Review-Loop Follow-up (PRIMARY OBJECTIVE)';- const opening = inline- ? `This runs as **step ${INLINE_REVIEW_LOOP_STEP} of the Completion Workflow above**, against the PR you just opened on \`${prBranch}\` (\`${prUrl}\` / \`${prNumber}\` are the shell variables you captured there). ${initialReviewState} ${objective}`- : `A previous agent finished implementing the work for source task **${sourceTaskId}** and opened **PR ${prUrl}** on branch \`${prBranch}\`. ${initialReviewState} ${objective}`;-- if (verbose) {- return `-${heading}-${opening}--**Reviewers (in order)**: ${reviewerLabel}${equiv}.-${extraNotes.length ? '\n' + extraNotes.join('\n') + '\n' : ''}-**Run this loop UNTIL all configured reviewers are satisfied (or the stop mode triggers), capped at 10 iterations per reviewer:**--1. ${waitOrInvokeStep}-2. If there are unresolved review findings, fix them in this worktree, run the project's tests, commit (\`feat:\`/\`fix:\` prefix, no Co-Authored-By), push, and (for Copilot) resolve the addressed threads.-3. Re-review with the same reviewer until it reports clean, then advance to the next reviewer in the list.-${closingSteps.join('\n')}--**Hard stop:** if a reviewer's loop hasn't converged after 10 iterations, post a PR comment summarising the unresolved blockers and exit. Do not loop indefinitely.--${repeatedCommentsNote}--${challengeProtocolNote}--PR Details:-- **URL**: ${prUrl}-- **Branch**: \`${prBranch}\`-${prNumber !== '' ? `- **Number**: ${prNumber}` : ''}-${prOwner && prRepo ? `- **Repo**: ${prOwner}/${prRepo}` : ''}-- **Source task**: ${sourceTaskId}-- **Reviewers**: ${reviewerLabel}-${cliReviewerProcedure}${(rprBody && (hasCopilot || hasGithubUser)) ? `\n### /do:rpr Reference — Copilot / @github reviewers (full procedure)\n\nThis is the PR-comment review loop for the **copilot** and **@github** reviewers only (request a review on the PR, poll for comments, resolve threads).${cliReviewerProcedure ? ' It does NOT apply to the local CLI reviewers — for those, follow the **CLI Reviewer Procedure** above instead.' : ''}\n\n${rprBody}\n` : ''}`;- }-- // Compact light-path variant.- const compactOpening = inline- ? opening- : `A previous agent finished task **${sourceTaskId}** and opened **PR ${prUrl}** on \`${prBranch}\`. ${initialReviewState} ${leaveOpen ? 'Drive the review-and-fix loop to completion — do NOT merge (JIRA-tracked; a human lands it).' : 'Drive the review-and-fix loop to completion and merge.'}`;- return [- heading,- compactOpening,- `**Reviewers (in order)**: ${reviewerLabel}${equiv}.`,- ...extraNotes,- '',- '**Loop UNTIL all reviewers are satisfied (or the stop mode triggers), capped at 10 iterations per reviewer:**',- `1. ${waitOrInvokeStep}`,- '2. If unresolved findings: fix in this worktree, run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push' + (hasCopilot ? ', and (for Copilot) resolve the addressed threads.' : '.'),- '3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.',- ...closingSteps,- '',- '**Hard stop:** if a reviewer is not converged after 10 rounds, post a PR comment summarising blockers and exit.',- repeatedCommentsNote,- '',- challengeProtocolNote,- cliReviewerProcedure- ].filter(Boolean).join('\n');-}--/**- * The step that replaces the merge steps when a PR is a human's to land — a- * JIRA-tracked task whose ticket is already "In Review" (see- * `lib/prDisposition.js`). Merging would land the work while the board still- * shows it in review, and no completion path here can transition the ticket.- */-const LEAVE_PR_OPEN_STEP = (step, jiraTracked = false) => `${step}. **Leave the PR open — do NOT merge it.** ${jiraTracked- ? 'This task is tracked in JIRA: its ticket is in review and a human lands the PR and the ticket together.'- : 'This task is configured to stop after opening the PR so a human can inspect and land it.'} Report the PR URL in your summary and stop.`;--/**- * The CI-gated merge procedure, in numbered steps starting at `startStep`.- *- * This is the single definition of "no reviewer is configured, so CI is the- * merge gate" — shared by every flow that reaches it: the agent's own completion- * workflow (slashdo TUI + Claude Code CLI via `buildPostPRMergeSteps`) and the- * merge follow-up agent PortOS spawns when it opened the PR itself. They differ- * only in how the PR is addressed and whether GitLab commands are offered, so- * those are parameters rather than hand-written copies that drift.- *- * Ends on the same merge command + MERGED verification as the review-loop- * contract (`buildReviewLoopFollowUpSection`): a true merge commit keeps the- * branch tip in the base branch's history, which is what lets automated worktree- * cleanup prove the branch landed.- *- * @param {number} startStep - number of the first emitted step.- * @param {Object} opts- * @param {string} opts.prRef - how to address the PR in `gh` commands, already- * quoted: the `"<PR_URL>"` placeholder before the PR exists, or the real URL.- * @param {string} [opts.mrRef] - how to address the MR in `glab` commands.- * **`glab mr merge` selects by MR IID or source branch — NOT by URL**, so this- * is the number (or a `<MR_NUMBER>` placeholder), never `prRef`.- * @param {'github'|'gitlab'|'unknown'} [opts.forge] - which CLI to name. PortOS- * opens GitLab MRs too (`git.createPR` falls back to `glab`), so a follow-up- * whose PR host is a GitLab instance must not be handed `gh` commands it can't- * run. Callers derive this with `detectForgeCli` — a GitHub Enterprise host is- * `github`, not "not github.com". `unknown` (the agent's own completion- * workflow, which runs before the PR exists) emits both, commented.- * @returns {{lines: string[], nextStep: number}}- */-function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>', forge = 'github', alreadyMergedHint = ' (a saved `/do:pr` default can merge it for you)' }) {- const gh = forge !== 'gitlab';- const glab = forge !== 'github';- const both = gh && glab;- const checksCmd = gh- ? `\`gh pr checks ${prRef} --watch --fail-fast --interval 30\`${glab ? ' (GitLab: `glab ci status`)' : ''}`- : '`glab ci status`';- const mergeableCmd = gh- ? `\`gh pr view ${prRef} --json mergeable -q .mergeable\` reports \`CONFLICTING\`${glab ? ' (GitLab: `glab mr view ' + mrRef + '` shows a conflict)' : ''}`- : `\`glab mr view ${mrRef}\` shows a conflict with the target branch`;- const stateCmd = gh- ? `\`gh pr view ${prRef} --json state -q .state\` must return \`MERGED\`${glab ? ' (GitLab: `glab mr view ' + mrRef + '` must show it merged)' : ''}`- : `\`glab mr view ${mrRef}\` must show it merged`;- const lines = [- `${startStep}. **Wait for CI to finish**: ${checksCmd}. "No checks reported" is AMBIGUOUS — a just-opened PR reports it while checks are still attaching, and merging on it races the CI this gate exists to wait for. Treat it as green ONLY when the repo genuinely has no CI (${gh ? '`gh workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check is configured' : 'no `.gitlab-ci.yml` and no pipeline is configured'}). If CI IS expected, wait 30s and re-check for up to 5 minutes — and if it still hasn't attached, **leave the PR open and say so**; never merge on checks that were expected but never appeared.`,- `${startStep + 1}. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (${gh ? `\`gh run view --log-failed\`${glab ? ' on GitHub, `glab ci trace` on GitLab' : ''}` : '`glab ci trace`'}), fix the cause here, run the project's tests, commit (\`fix:\` prefix, no Co-Authored-By), push, and go back to the previous step — cap this at 5 rounds. If ${mergeableCmd}, \`git fetch origin\`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, re-run the tests, \`git push --force-with-lease\`, and re-check.`,- `${startStep + 2}. **Merge** with exactly these flags, nothing else — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, and any merge-deferral flag leaves the PR open after you exit. If it is already merged${alreadyMergedHint}, skip to the next step:`,- ' ```bash',- gh ? ` ${both ? '# GitHub: ' : ''}gh pr merge ${prRef} --merge --delete-branch` : null,- // `glab mr merge` takes an MR IID or source branch — a URL is not accepted.- glab ? ` ${both ? '# GitLab: ' : ''}glab mr merge ${mrRef} --yes --remove-source-branch` : null,- ' ```',- // Not every repo allows merge commits; a repo restricted to squash/rebase- // rejects `--merge` outright, which would leave the PR open forever.- gh ? ` If that is rejected because this repo disallows merge commits, re-check what it allows (\`gh repo view --json mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed\`) and merge with an allowed method instead — \`--squash\` first, else \`--rebase\` — keeping \`--delete-branch\`.` : null,- `${startStep + 3}. **Confirm the merge before exiting**: ${stateCmd}. If it is still open or was closed unmerged, investigate (failing check, merge conflict, branch protection), fix, and retry. Leave it open — saying so explicitly in your completion summary — if CI stays red after a genuine fix attempt, a conflict needs a human decision, expected checks never attached, or a branch protection you cannot satisfy blocks the merge (a required approving review, a required check only a human can trigger). Hand those to a human rather than retrying until you time out.`,- ].filter(Boolean);- return { lines, nextStep: startStep + 4 };-}--/**- * Build the **merge follow-up** section — the instructions for the agent- * `spawnReviewLoopFollowUp` spawns when no reviewer survived resolution (Review- * Loop off, or copilot-only on a non-GitHub forge). Nothing else will touch the- * PR, so the merge gate is CI alone (`buildCiMergeGateSteps`).- *- * @param {Object} opts - PR coordinates + `verbose` (full/api path) vs compact.- * @returns {string}- */-function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = '', prRepo = '', prHost = '', sourceTaskId = 'unknown', verbose = false, inlineExitStep = null, forgeCli = null }) {- const inline = inlineExitStep !== null;- // PortOS opens GitLab MRs via `glab` too, so a GitLab host must not be handed- // `gh` commands (the host is persisted by spawnReviewLoopFollowUp). Classify- // with the shared detector — a GitHub Enterprise host is still `gh`, which a- // bare `host !== 'github.com'` test would get wrong.- //- // An INLINE gate has no persisted host to classify — its PR does not exist yet- // — so the caller supplies the forge already selected for the create step.- // Falling back to GitHub preserves the historical manual workflow when no- // remote metadata is available.- const gate = buildCiMergeGateSteps(1, {- prRef: `"${prUrl}"`,- mrRef: prNumber !== '' ? `${prNumber}` : '<MR_NUMBER>',- forge: inline- ? (normalizeForgeCli(forgeCli) === 'glab' ? 'gitlab' : 'github')- : (detectForgeCli(prHost) === 'glab' ? 'gitlab' : 'github'),- // An inline run reached this gate through plain `git`/`gh` — it never ran- // `/do:pr`, so a saved slashdo merge default can't have landed the PR for it.- alreadyMergedHint: inline ? '' : undefined,- });- const steps = [- ...gate.lines,- inline- ? `${gate.nextStep}. ${inlineExitStep} Do NOT start a code review — none is configured for this task.`- : `${gate.nextStep}. Exit. Do NOT run \`/do:push\`, do NOT open a new PR, and do NOT start a code review — landing this PR is the whole job.`,- ];- const prDetails = verbose ? [- '',- 'PR Details:',- `- **URL**: ${prUrl}`,- `- **Branch**: \`${prBranch}\``,- prNumber !== '' ? `- **Number**: ${prNumber}` : null,- prOwner && prRepo ? `- **Repo**: ${prOwner}/${prRepo}` : null,- `- **Source task**: ${sourceTaskId}`,- ].filter(Boolean) : [];-- return [- inline ? '## Merge Gate' : '## Merge Follow-up (PRIMARY OBJECTIVE)',- inline- ? `This runs as **step ${INLINE_REVIEW_LOOP_STEP} of the Completion Workflow above**, against the PR you just opened on \`${prBranch}\` (\`${prUrl}\` / \`${prNumber}\` are the shell variables you captured there). **No code review was requested for this task, so nothing else will merge this PR — land it yourself once CI is green.**`- : `A previous agent finished the work for source task **${sourceTaskId}** and opened **PR ${prUrl}** on \`${prBranch}\`. **No code review was requested for this task, so nothing else will merge this PR — your job is to land it once CI is green.**`,- '',- ...steps,- '',- '**Hard stop:** if CI is still red after 5 fix rounds, or a conflict needs a product decision you can\'t make, post a PR comment summarising exactly what is blocking the merge and exit with the PR left open. Do not force a merge over red CI.',- ...prDetails,- ].join('\n');-}--/**- * Build the single "## Guidelines" completion-handoff bullet for the full- * (api) prompt path. Mirrors the helper pattern the light path already uses- * (`worktreeCommitGuidance`, `buildTuiCompletionSection`) — same 4-branch- * decision tree (read-only / TUI / worktree+PR / worktree-only / default) but- * flattened into a function so reading is linear instead of a nested ternary.- *- * Returns the bullet body WITHOUT the leading `- ` marker (caller prepends),- * or `null` when the branch produces no text (the legacy empty-string tail).- *- * @param {Object} opts- * @param {boolean} opts.isReadOnly- * @param {boolean} opts.isTui- * @param {string} opts.tuiCompletionCommand - `/do:pr` or `/do:push`- * @param {boolean} [opts.slashdoFree] - TUI without slashdo: the bullet points- * at the manual commit + system-handoff workflow instead of a `/do:*` command.- * @param {Object|null} opts.worktreeInfo- * @param {boolean} opts.willOpenPR- * @param {'review-then-merge'|'merge-on-green'|'leave-open'} opts.prCompletion- * @returns {string|null}- */-export function buildCompletionGuidelineBullet({- isReadOnly, isTui, tuiCompletionCommand, slashdoFree = false,- worktreeInfo, willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, discardWorktree = false, noCodeOutput = false,- leavePrOpen = false, isPrFollowUp = false, claimFlow = false,-}) {- // A PR follow-up (review-loop or merge-only) already carries its own PRIMARY- // OBJECTIVE section with the full procedure, and its cleanup runs with- // `skipMerge`. The generic "your branch is merged back automatically" bullet- // would contradict both — and a merge-only run legitimately makes no commit.- if (isPrFollowUp && !discardWorktree && !noCodeOutput && !isReadOnly) {- return 'Follow the follow-up section above — it is the whole task. Commit and push only fixes you actually make; the deliverable is the PR\'s final state, not a commit. Do NOT open a new PR, and do NOT expect this branch to be merged back for you.';- }- // `noCodeOutput` is checked FIRST because the two flags answer different- // questions: `discardWorktree` decides what happens to the checkout, while- // `noCodeOutput` decides where the deliverable goes. A task that sets both —- // "do your work through an API/CLI action during the run, and never land- // code" — must be told its output channel is that action, NOT the sentinel.- // Telling it "write your result to the sentinel" is how a run files nothing- // and reports its findings into a file that gets thrown away (PLAN.md records- // this exact hazard from the 2026-07-16 codex review). No pre-existing task- // sets both, so this ordering changes nothing that shipped before it.- if (noCodeOutput) {- return '**This task produces no code output.** Its result is the API request or command your instructions describe (a PortOS endpoint call, a filed tracker issue, …) — do NOT run `/do:push`, `/do:pr`, `/simplify`, `git commit`, `git push`, or open a PR. Write the completion sentinel (see the Completion section) and stop.';- }- if (discardWorktree) {- return '**This is a reasoning-only task.** The worktree is discarded on exit — do NOT commit, push, merge, or open a PR. Write your result to the completion sentinel (see the Completion section) and stop.';- }- if (claimFlow) {- return '**This is a self-managed claim flow.** Follow the claim prompt above through its phase-specific worktree, PR/MR, review, merge or human-handoff, and cleanup steps. Do NOT stop after committing or hand the lifecycle back to PortOS.';- }- if (isReadOnly) {- return '**This is a read-only task.** Do NOT commit, push, or modify any files in the repository. Only read data and generate reports.';- }- if (isTui) {- // NOTE: in production this branch is only reachable from the full/api prompt- // path, where `isTui` is currently always false (TUI providers route through- // buildLightContextPrompt, which emits the live TUI completion via- // buildTuiCompletionSection — not this bullet). It's kept provider-aware and- // directly unit-tested so the guideline stays correct if that routing changes.- const howTo = slashdoFree- ? 'the Completion Workflow above (plain `git` commit + PortOS handoff — this provider has no slashdo commands)'- : `the Completion Workflow above (\`${tuiCompletionCommand}\`)`;- return `On successful completion, YOU run ${howTo}, then write the sentinel and stop — PortOS closes the session once it sees the sentinel; do NOT run \`/quit\`.`;- }- if (worktreeInfo && willOpenPR) {- const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;- const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;- const reviewSuffix = policyLeavesOpen- ? ' This task is configured to leave the PR OPEN for you to inspect — no follow-up agent will review or merge it automatically.'- : leavePrOpen- ? ' This task is tracked in JIRA, so the PR is left OPEN for a human to land alongside the ticket — nothing merges it automatically.' + (runsReviewLoop ? ' A follow-up agent still runs the configured reviewers against it.' : '')- : runsReviewLoop- ? ' For GitHub PRs, a Copilot code review will also be requested automatically (skipped on GitLab and other non-GitHub forges) — do NOT run `/do:rpr` or attempt to address review comments yourself; you will have already exited.'- : ' No review was requested for this task, so a follow-up agent merges the PR once CI is green — do NOT try to merge it yourself; you will have already exited.';- return `On successful completion, the system will push your branch and open a pull request — do NOT open a PR manually. (If the task fails, no PR is opened; the worktree is then cleaned up unless a safety check preserves it for manual recovery.)${reviewSuffix}`;- }- if (worktreeInfo) {- return 'Your worktree branch will be automatically merged back to the source branch when your task completes — do NOT open a PR.';- }- return null;-}--// One-line worktree note for a discard (reasoning-only) task, replacing the-// "commit / push / auto-merge" guidance the normal worktree section emits. The-// worktree exists only so the reasoner can make scratch edits without touching-// the real tree — cleanup discards it with no commit/merge/PR (see-// `discardWorktree` in agentWorktreeCleanup.js).-const DISCARD_WORKTREE_NOTE = 'Do NOT commit, push, or open a PR — this worktree is discarded on exit. Make any scratch edits that help you reason; only the completion sentinel is kept.';--/**- * Is this worktree attached to a branch a PR already points at — i.e. the- * review-loop follow-up, whose guidance is "push review fixes here, the PR- * points at this branch"?- *- * Identified POSITIVELY, off the follow-up's own `reviewLoopFollowUp` marker,- * rather than as "any `existingBranch` worktree". `existingBranch` means only- * "attach to this branch" and now has two producers: the follow-up, and a retry- * resuming a dead agent's branch (`resumedFromAgentId`), which follows the task's- * ordinary push/PR flow and may have no PR at all. Keying on the marker means a- * THIRD producer defaults to the ordinary flow instead of silently inheriting- * review-fix instructions for a PR that doesn't exist.- */-function isPrBranchWorktree(task, worktreeInfo) {- return worktreeInfo?.existingBranch === true && !!task?.metadata?.reviewLoopFollowUp;-}--/**- * Is this worktree a RESUME of a previous failed agent's branch? Keyed on- * `resumedFromAgentId`, which only the resume path stamps (see- * agentCompletionCleanup.js).- */-function isResumedWorktree(task, worktreeInfo) {- return worktreeInfo?.existingBranch === true && !!task?.metadata?.resumedFromAgentId;-}--/**- * Resume banner for a retry picking up what a PREVIOUS unfinished agent left- * behind (`metadata.existingBranch` + `resumedFromAgentId`, stamped by- * `recordTaskResumePointer` when a dead run's branch — or whole worktree —- * survived cleanup).- *- * Without this the retry sees an ordinary worktree that just happens to have- * work in it and redoes what is already done — the failure mode the- * agent-d2ae0352 incident exposed (reaped 30s after its PR merged; the- * replacement agent started the shipped work over). Telling it to read the log- * FIRST is the whole point: the prior run may have gone as far as opening or even- * merging a PR, in which case there is nothing left to build.- *- * An ADOPTED worktree (`worktreeInfo.adopted` — the shape a server restart leaves,- * killed mid-edit before committing) additionally carries the dead run's- * uncommitted edits and untracked files, so the banner points at `git status`- * as the primary record rather than the commit log.- *- * Returns '' when this isn't a resume, so callers can interpolate unconditionally.- */-export function buildResumeSection(task, worktreeInfo) {- if (!isResumedWorktree(task, worktreeInfo)) return '';- const priorAgentId = task.metadata.resumedFromAgentId;- const carriedWork = worktreeInfo.adopted- ? `**You are in its actual working directory** — its commits are on your branch \`${worktreeInfo.branchName}\`-AND any edits it had not committed yet are still in your working tree, exactly as it left them.`- : `**Its commits are already on your branch** \`${worktreeInfo.branchName}\` — you are-continuing its run, not starting over.`;- return `-## Resuming Unfinished Work — Read This First-A previous agent (\`${priorAgentId}\`) worked this same task and did NOT finish cleanly-(it hung, timed out, or was terminated — a server restart kills runs mid-edit).-${carriedWork}--Before you write any code, establish what is already done:-1. \`git status\` — anything it left uncommitted. Treat these as YOUR in-progress- changes: review them, finish them, and commit them. Do not discard them wholesale.-2. \`git log --oneline ${worktreeInfo.baseBranch || 'origin/HEAD'}..HEAD\` — the commits it already made.-3. Check whether it already shipped: look for an open or merged PR for this branch- — \`gh pr list --head ${worktreeInfo.branchName} --state all\` on GitHub,- \`glab mr list --source-branch ${worktreeInfo.branchName}\` on GitLab.--Then do only what remains. If a PR is already **merged**, the work is done — go-straight to your completion step and report that. If a PR is already **open**,-finish/land that PR rather than opening a second one. Do NOT redo completed work,-and do NOT revert its commits unless they are actually wrong.-`;-}--/**- * Completion block for a **programmatic-output** (throwaway-worktree) task: the- * agent reasons in a worktree that is discarded on exit, so it must NOT commit,- * push, merge, or open a PR. Its only channel out is the `.agent-done` sentinel,- * whose exact payload shape is specified by the task instructions (a task-type- * output hook — see `taskTypeHooks.js` / `layeredIntelligenceHooks.js`). This- * replaces the normal `/do:push`+markdown-sentinel completion workflow, which- * would tell the agent to push code (defeating the discard guarantee) and write- * a markdown summary (breaking the hook's structured-JSON sentinel contract).- */-export function buildProgrammaticOutputCompletionSection(sentinelPath) {- return [- // Shared constant: a pre-spawn task-type hook's prompt points here BY NAME.- `## ${PROGRAMMATIC_OUTPUT_COMPLETION_HEADING}`,- 'This is a reasoning task, not a code change. The worktree you are in is **discarded on exit** — any commits, pushes, or PRs are thrown away and have no effect. Do NOT run `/do:push`, `/do:pr`, `git commit`, `git push`, or open a pull request.',- '',- `When you have finished reasoning, write your result to \`${sentinelPath}\` in the exact payload format described in your task instructions, then stop. PortOS watches this sentinel and finalizes the run shortly after it appears — do NOT run \`/quit\` and do NOT wait for anything after writing the sentinel.`- ].join('\n');-}--/**- * Completion block for a **read-only** task (e.g. reference-watch, pr-reviewer's- * scan stage). The agent must NOT commit/push/modify source; its real output is- * recorded elsewhere DURING the run (a tracker issue, PLAN.md, a report).- *- * A TUI agent still needs a `.agent-done` sentinel to signal completion — the- * sentinel watcher in `spawnTuiAgent` is the primary finalize path and the channel- * that ingests the run summary. Without it a read-only TUI run relies on shell- * exit, so the resolution summary is not captured cleanly (the bug this- * repairs). CLI/API read-only agents complete on process exit and never poll a- * sentinel, so they get the bare notice only.- */-export function buildReadOnlyCompletionSection({ isTui = false, sentinelPath = null } = {}) {- const notice = '## Read-Only Task\nDo NOT commit, push, or modify any files. Read data and report findings only.';- if (!isTui || !sentinelPath) return notice;- return [- notice,- '',- `When you have finished, write a short markdown summary of what you found (and where you recorded it) to \`${sentinelPath}\`, then stop. PortOS watches this sentinel and finalizes the run shortly after it appears — do NOT run \`/quit\` and do NOT wait for anything after writing the sentinel.`- ].join('\n');-}--/**- * Completion block for a **no-code / API-action** task (e.g. a Creative Director- * plan/treatment/evaluate agent). The agent's deliverable is the HTTP request its- * task instructions already describe (a PATCH to a PortOS endpoint), NOT a code- * change — so the normal `/do:push`+PR completion workflow is wrong: there is- * nothing to commit or push, and telling the agent to run `/do:push` just makes it- * load that skill for no reason (and can contradict the task prompt's own- * "on a 200 your task is complete"). A TUI agent still writes a `.agent-done`- * sentinel so the watcher finalizes it promptly instead of waiting for a runtime- * reaper.- */-export function buildActionOutputCompletionSection({ isTui = false, sentinelPath = null } = {}) {- const notice = '## Completion (No Code Output)\nThis task produces **no code change** — its result is delivered DURING the run by the API request or command your instructions describe (a PATCH to a PortOS endpoint, a filed tracker issue, …), not by a commit and not by this sentinel. Do NOT run `/do:push`, `/do:pr`, `/simplify`, `git commit`, `git push`, or open a pull request; there is nothing to push.';- if (!isTui || !sentinelPath) return notice;- return [- notice,- '',- `Your task is complete once that request succeeds. Then write a one-line summary to \`${sentinelPath}\` and stop — PortOS watches this sentinel and finalizes the run shortly after it appears. Do NOT run \`/quit\` and do NOT wait for anything after writing the sentinel.`- ].join('\n');-}--/**- * The `--review-with` token list a claim task's prompt names, read back off the- * task record. The claim generators persist the bundle they rendered into- * `{reviewers}` (`reviewerConfigMetadata`), so this reproduces that CSV exactly.- *- * A claim task queued before #4770 carries no reviewer metadata, so this falls- * through to the install's Code Review Defaults — routed through the claim- * resolver so an in-flight legacy task can't be pinned to a bare `copilot`,- * which a claim agent has no CLI to invoke (#2507).- */-function claimReviewersCsv(task, codeReviewDefaults, defaultReviewers) {- return resolveClaimReviewerConfig(task?.metadata, codeReviewDefaults, defaultReviewers).csv;-}--/**- * Completion handoff for claim prompts that create their own worktree and own- * the forge lifecycle. `openPR: false` must remain the CoS provisioning posture,- * so claimFlow is the explicit signal that keeps these prompts out of the- * generic commit-only handoff.- *- * This is also the ONE emitter of the reviewer pin (#4770). Every claim- * generator persists the reviewer bundle it rendered into `{reviewers}` onto the- * task, so `resolveClaimReviewerConfig(task.metadata, …)` here reproduces that- * exact CSV — which means the pin covers all five claim task types from one call- * site, instead of three prose appends in `cosTaskGenerator.js` that a new claim- * generator could forget.- *- * @param {string} [reviewersCsv] - the emitted `--review-with` token list to pin;- * empty suppresses the block (`buildReviewerPinNote` returns '').- */-function buildClaimFlowCompletionSection({ isTui = false, sentinelPath = null, reviewersCsv = '' } = {}) {- const pin = buildReviewerPinNote(reviewersCsv);- const lines = [- ...(pin ? [pin, ''] : []),- '## Claim Workflow Handoff',- 'This is a self-managed claim flow. The claim prompt above owns its claim worktree, branch, PR/MR, review, merge or human-handoff, and cleanup. Follow its phase-specific exit conditions — do NOT stop after a code commit or hand the lifecycle back to PortOS.',- '',- 'For a successful claim, signal completion only after the prompt\'s prescribed PR/MR and cleanup steps are complete. For a clean no-work, blocked, or review-stuck exit, follow the prompt\'s prescribed leave-open/cleanup path first.'- ];- if (isTui && sentinelPath) {- lines.push('', 'When that path is complete, write the completion sentinel and stop:', '', ...buildSentinelWriteSteps(1, sentinelPath, ' ## PR/MR\n <PR or MR URL, or explain the clean exit>'));- } else {- lines.push('', 'After the prompt\'s prescribed final step, exit so PortOS can record the completed claim.');- }- return lines.join('\n');-}-/*** Build the agent prompt.*@@ -2400,629 +918,3 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMetreturn { taskSections, contractSections };}--/**- * Worktree commit-guidance helper for the light prompt. Picks the right- * single-sentence instruction based on whether the agent will run its own- * push workflow (TUI or Claude Code CLI with slashdo), reuse an existing PR- * branch (review fixes), or hand off to PortOS's post-exit push.- */-function worktreeCommitGuidance({ isTui, hasSlashdo, ownsPrWorkflow = false, isWorktreeOnExistingBranch, willOpenPR, discardWorktree, claimFlow = false }) {- if (discardWorktree) return DISCARD_WORKTREE_NOTE;- if (claimFlow) return 'The claim workflow in the Completion section owns the push, PR/MR, review, merge or human-handoff, and cleanup steps.';- if (isTui) return 'Commit your changes to this branch — see **Completion Workflow** below.';- if (isWorktreeOnExistingBranch) {- return 'Commit and **push** any review-fix commits to this branch (the PR points at it). Use `git pull --rebase` before pushing if needed.';- }- if (hasSlashdo && willOpenPR) {- return 'Commit your changes here — the **Completion** section below drives the push and PR.';- }- if (hasSlashdo) {- return 'Commit your changes here — the **Completion** section below drives the push.';- }- if (ownsPrWorkflow && willOpenPR) {- return 'Commit your changes here — the **Completion** section below drives the push, the PR, the review loop, and the merge.';- }- if (willOpenPR) {- return 'Commit your changes here. The system will push and open a PR after you exit — do NOT push or open a PR yourself.';- }- return 'Commit your changes here. Your branch will be merged back automatically when the task completes.';-}--/**- * Build the merge-and-verify steps that follow `/do:pr` in completion blocks.- * Returns `{ lines, nextStep }` — append `lines` to the workflow array and- * assign `nextStep` back to the caller's step counter so any subsequent- * numbered steps stay continuous.- *- * The agent must drive the merge itself — `/do:pr` runs the review loop but- * exits without merging, so without this step the PR sits open and the branch- * leaks. Mirrors the merge contract in the review-loop follow-up section so- * both agent flows converge on the same final state. `reviewers` only colors- * the wording — the merge step itself is reviewer-agnostic.- *- * `prCompletion` selects the review gate or CI-only merge gate. Leave-open- * callers do not invoke this helper.- */-function buildPostPRMergeSteps(startStep, { prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, reviewers = DEFAULT_REVIEWERS, usernames = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE } = {}) {- // No review loop → CI is the whole gate, so emit the shared CI procedure that- // the manual-TUI workflow and the merge follow-up agent also use. The PR URL- // isn't known when this prompt is written, hence the placeholder.- if (prCompletion === PR_COMPLETIONS.MERGE_ON_GREEN) {- const gate = buildCiMergeGateSteps(startStep, { prRef: '"<PR_URL>"', forge: 'unknown' });- return {- lines: [- ' **No review loop is configured for this task, so nothing and nobody else will merge this PR** — `/do:pr` opens it and exits. Capture the PR URL it printed, then:',- ...gate.lines,- ],- nextStep: gate.nextStep- };- }- // Trailing space when present so the sentence reads "the Copilot review loop"- // (lone copilot, no usernames) or "the review loop" (multi/CLI/username) —- // never "the the review loop".- const reviewerLabel = (reviewers.length === 1 && reviewers[0] === DEFAULT_REVIEWER && usernames.length === 0) ? 'Copilot ' : '';- // Under an explicit stop-mode, the multi-reviewer loop can exit `partial` (later- // reviewers intentionally skipped after the short-circuit) — that's a successful- // outcome the user opted into, so merge on it too. Match the known stop-modes- // explicitly so an unknown/invalid value falls through to the safe default- // (only `clean`/`too-large` mergeable).- const explicitStopMode = reviewStopMode === 'on-findings' || reviewStopMode === 'on-clean';- const mergeStatuses = explicitStopMode- ? '`clean`, `partial` (a stop-mode short-circuit you opted into), or `too-large`'- : '`clean` (or `too-large`)';- const lines = [- `${startStep}. **Merge the PR immediately when the ${reviewerLabel}review loop reports ${mergeStatuses}** — \`/do:pr\` opens the PR and runs the review loop but does NOT merge. Capture the PR URL printed by \`/do:pr\` and run the exact command below (flags: \`--merge --delete-branch\`, nothing else — a true merge commit keeps the branch tip in main's history so automated worktree cleanup can prove the branch is merged; any merge-deferral flag leaves the PR open after you exit). Skip the merge if the loop ended \`timeout\`, \`error\`, \`inconclusive\`, or \`guardrail\`; leave the PR open for human follow-up.`,- ' ```bash',- ' gh pr merge "<PR_URL>" --merge --delete-branch',- ' ```',- `${startStep + 1}. Confirm the merge before exiting: \`gh pr view "<PR_URL>" --json state -q .state\` must return \`MERGED\`. If it returns \`OPEN\` or \`CLOSED\`, investigate (failing check, unresolved thread, branch protection), fix, and retry. Do NOT exit until state is \`MERGED\` (or you have explicitly decided not to merge per the rule above).`- ];- return { lines, nextStep: startStep + 2 };-}--/**- * Resolve the review-loop invocation shared by buildTuiCompletionSection and- * buildCliCompletionSection: the normalized reviewer usernames, the- * `--review-with ...` argument text, and the effort-pin note. Both callers- * used to re-derive this identical trio from the same 8-field reviewer-config- * bundle independently.- */-function resolveReviewInvocation({ willOpenPR, runsReviewLoop, reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies }) {- const reviewUsernames = normalizeReviewUsernames(usernames);- const reviewArgs = willOpenPR- ? (runsReviewLoop ? buildReviewWithArgs(reviewers, { stopMode: reviewStopMode, reviewerApplies, usernames: reviewUsernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts }) : '--review-with none')- : '';- // Effort pins ride the emitted `--review-with` tokens as `~effort=<level>`, so- // the prose note is suppressed whenever that suffix is present — it only speaks- // for an invocation that pins no reviewer list (see buildReviewerEffortNote).- const effortNote = willOpenPR && runsReviewLoop- ? buildReviewerEffortNote(reviewers, reviewerEfforts, { reviewWith: reviewArgs, reviewerModels })- : '';- return { reviewUsernames, reviewArgs, effortNote };-}--/**- * The `.agent-done` sentinel-write instruction block shared by- * buildTuiCompletionSection and buildManualTuiCompletionSection: the "write a- * short summary, then stop" instruction plus the fenced heredoc template.- * Returns the lines to splice into the caller's own line array — output must- * stay byte-identical since this is agent-facing prompt text.- */-function buildSentinelWriteSteps(stepNumber, sentinelPath, sentinelTail) {- return [- `${stepNumber}. Write a short markdown summary (~5–15 lines) to the completion sentinel, then stop — this sentinel is the done signal. PortOS watches it and finalizes the run shortly after it appears. Do NOT run \`/quit\` (it's a UI command, not something you can invoke) and do NOT wait for anything after writing the sentinel.`,- '',- ' ```bash',- ` cat > "${sentinelPath}" <<'EOF'`,- ' ## Summary',- ' <one-sentence statement of what was accomplished>',- '',- ' ## Changes',- ' - <key file or area>: <what changed and why>',- '',- sentinelTail,- ' EOF',- ' ```'- ];-}--/**- * TUI completion-workflow block. The TUI owns its own commit → push → PR- * pipeline via slashdo commands and signals "done" with a sentinel file.- *- * When `slashdoFree` is set — any TUI that does NOT load Claude Code slash- * commands: OpenCode, codex/antigravity/grok/kimi, or a lean `--bare` Claude- * session — the agent can't run `/do:pr` / `/do:push`, so it delegates to the- * plain-git/`gh` variant below (same sentinel handshake, no slashdo). The caller- * resolves that flag once via `canTypeSlashCommands` (#3114); past the early- * return this IS a Claude session, so `/simplify` and `/do:pr` are both safe to- * emit without a second provider check.- */-function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, simplifyEnabled, sentinelPath, slashdoFree = false, ownsPrWorkflow = false, branchName = null, baseBranch = null, leavePrOpen = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewerModels = {}, reviewerEfforts = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, forgeCli = 'gh' }) {- const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;- const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;- if (slashdoFree) {- // Plain `git`/`gh` instead of `/do:pr` — but still the whole lifecycle when- // the session is a real coding harness (`ownsPrWorkflow`); the reviewer- // procedure it needs is inlined in the Review Loop section that follows.- return buildManualTuiCompletionSection({ willOpenPR, prCompletion, simplifyEnabled, sentinelPath, branchName, baseBranch, leavePrOpen, ownsPrWorkflow, forgeCli });- }- const cmd = willOpenPR ? '/do:pr' : '/do:push';- // `/do:pr` may inherit a saved `review-with` default. Explicitly opt out- // when the task's Review Loop control is off so that default cannot start a- // Copilot (or other external) review unexpectedly.- const { reviewUsernames, reviewArgs, effortNote } = resolveReviewInvocation({ willOpenPR, runsReviewLoop, reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies });- // A saved slashdo `merge: true` default would otherwise merge a PR that must- // stay open — dropping our own merge steps isn't enough, `/do:pr` has to be- // told not to merge (see lib/prDisposition.js).- const mergeArg = (willOpenPR && (leavePrOpen || policyLeavesOpen)) ? ' --no-merge' : '';- const reviewerArg = (reviewArgs ? ` ${reviewArgs}` : '') + mergeArg;- const copilotOnly = reviewers.length === 1 && reviewers[0] === DEFAULT_REVIEWER && reviewUsernames.length === 0;- const reviewerListLabel = [...reviewers, ...reviewUsernames.map(u => `@${u}`)].join(', ');- // Ordering matters to the agent: `/do:pr` partitions the list and runs every- // local reviewer BEFORE it creates the PR, so the PR opens against an- // already-review-clean branch and only the cloud-side reviewers (Copilot,- // `@login`) plus CI remain. Saying "after the PR opens" of the whole list had- // agents expecting — and sometimes hand-rolling — a post-PR local pass.- const reviewSuffix = willOpenPR && runsReviewLoop- ? (copilotOnly- ? ' — `/do:pr` runs the Copilot review loop after the PR opens.'- : ` — \`/do:pr\` runs the review loop for ${reviewerListLabel} in order: local reviewers before it opens the PR, then the PR-side reviewers (Copilot / \`@login\`) once it is open.`)- : (willOpenPR ? ' — external review is disabled for this task.' : '');- // Reached only for a Claude TUI (a non-Claude one took the slashdoFree branch- // above), so `/simplify` — a Claude Code built-in — is invokable here.- const simplifyStep = simplifyEnabled ? '1. `/simplify`' : '1. (simplify disabled — skip)';- const sentinelTail = willOpenPR ? ' ## PR\n <PR URL>' : ' ## Branch\n <branch name>';- // A PR gets merge steps — gated on the review verdict when a loop runs, on CI- // alone when it doesn't (nothing else merges a no-review-loop PR). The one- // exception is a PR a human lands (JIRA-tracked; see lib/prDisposition.js).- const merge = (willOpenPR && !leavePrOpen && !policyLeavesOpen)- ? buildPostPRMergeSteps(3, { prCompletion, reviewers, usernames: reviewUsernames, reviewStopMode })- : { lines: (leavePrOpen || policyLeavesOpen) && willOpenPR ? [LEAVE_PR_OPEN_STEP(3, leavePrOpen)] : [], nextStep: (leavePrOpen || policyLeavesOpen) && willOpenPR ? 4 : 3 };- const sentinelStep = merge.nextStep;-- return [- '## Completion Workflow',- 'When the task is complete, run these in order:',- '',- simplifyStep,- `2. \`${cmd}${reviewerArg}\`${reviewSuffix}`,- ...(effortNote ? [` ${effortNote}`] : []),- ...merge.lines,- ...buildSentinelWriteSteps(sentinelStep, sentinelPath, sentinelTail)- ].join('\n');-}--/**- * Which numbered step of the manual completion workflow the inline review-loop /- * merge-gate section is. The manual workflow always emits step 1 (simplify, or- * an explicit "disabled — skip" placeholder) and step 2 (commit) before the PR- * steps, so the number is stable and the two sections can cross-reference each- * other without threading a counter between them.- */-const INLINE_REVIEW_LOOP_STEP = 4;--/** 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- * there is no ref to render. Branch names are usually PortOS's own, but a- * JIRA-derived one is external input and this text is pasted straight into an- * agent's terminal — so it goes through `shellQuote`, which leaves a bare-safe- * ref readable and single-quotes anything else into inertness.- */-function promptRef(ref, fallback) {- return (typeof ref === 'string' && ref) ? shellQuote(ref) : fallback;-}--/**- * The push + open-a-PR steps of the manual (slashdo-free) completion workflow.- *- * `$PR_URL` / `$PR_NUMBER` are captured into shell variables here because the- * inline review-loop and merge-gate sections address the PR by those names —- * they are rendered before the PR exists, so a literal URL is impossible.- */-function buildManualPrCreateStep(step, { branchName, baseBranch, forgeCli = 'gh' }) {- const branch = promptRef(branchName, '<branch>');- const base = promptRef(baseBranch, '<base-branch>');- const gitlab = forgeCli === 'glab';- return [- `${step}. Push the branch and open the pull request yourself, capturing its URL and number — the section below addresses the PR by these shell variables:`,- '',- ' ```bash',- ` git push -u origin ${branch}`,- gitlab- ? ` PR_URL=$(glab mr create --source-branch ${branch} --target-branch ${base} --title "<conventional title>" --description "<description>" | grep -Eo 'https?://[^[:space:]]+' | tail -n 1)`- : ` PR_URL=$(gh pr create --base ${base} --head ${branch} --title "<conventional title>" --body "<description>")`,- gitlab- ? ' PR_NUMBER=$(glab mr view "$PR_URL" --output json | jq -r .iid)'- : ' PR_NUMBER=$(gh pr view "$PR_URL" --json number -q .number)',- ' ```',- // `--fill` on a one-line commit produces an empty description; PortOS used- // to generate the body server-side, so spell out what it must contain now- // that the agent writes it.- gitlab- ? ' Write a real `--description`: a **Summary** section and a **Test plan** section, with no AI-attribution footer. If `glab` reports the merge request already exists, adopt its URL and IID before continuing.'- : ' Write a real `--body`: a **Summary** section and a **Test plan** section, no AI-attribution footer. Do NOT use `--fill`. If `gh` reports the pull request already exists, adopt it instead of failing: `PR_URL=$(gh pr view --json url -q .url)`.',- gitlab- ? ' The GitLab MR URL and IID are captured in `$PR_URL` and `$PR_NUMBER`; use those variables for every review, merge, and verification command below.'- : ` On a GitLab remote use \`glab mr create --source-branch ${branch} --target-branch ${base} --title "…" --description "…"\` and read the MR URL/IID back with \`glab mr view\`.`,- ];-}--/**- * Manual (slashdo-free) completion-workflow block — every provider that can't- * type `/do:pr` (codex, grok/agy, OpenCode, a lean `--bare` Claude session).- *- * When `ownsPrWorkflow` is set the agent drives the WHOLE lifecycle in one- * session: commit → push → open the PR → run the inline review loop → merge.- * That is the point of the flag — see `agentOwnsPrWorkflow`. Not typing a slash- * command never meant "can't run `gh`", but this block used to conclude exactly- * that, so every agy/grok/codex task ended in a commit and PortOS bought a- * second cold agent (`sys-rl-*`) just to review and land the PR.- *- * `ownsPrWorkflow: false` (lean mode) keeps the original handoff: commit and- * stop, PortOS owns the post-exit push / PR / review / merge lifecycle.- */-function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, simplifyEnabled, sentinelPath, branchName = null, baseBranch = null, leavePrOpen = false, ownsPrWorkflow = false, forgeCli = 'gh' }) {- const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;- const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;- // `ownsPrWorkflow` already folds in `willOpenPR`, the worktree, and the- // leave-open exclusions — it is `inlinePrLifecycleSection() !== null` (see the- // caller). Re-testing any of them here is how the two drifted apart before.- const drivesOwnPr = ownsPrWorkflow;- const simplifyStep = simplifyEnabled- ? `1. Before committing, ${SIMPLIFY_INLINE_REVIEW} and fix any findings.`- : '1. (simplify disabled — skip)';- const sentinelTail = drivesOwnPr ? ' ## PR\n <PR URL>' : ' ## Branch\n <branch name>';-- const lines = [- '## Completion Workflow',- drivesOwnPr- ? `This provider does NOT have slashdo (\`/do:*\`) commands, so drive the handoff with plain \`git\` and \`${forgeCli}\`. **You own this ${forgeCli === 'glab' ? 'MR' : 'PR'} end to end — nothing else will open, review, or merge it.** Run these in order:`- : 'This provider does NOT have slashdo (`/do:*`) commands, so finish the handoff with plain `git`. Run these in order:',- '',- simplifyStep,- '2. Stage only the files you changed (never `git add -A` / `git add .`) and commit with a conventional message (`feat:`/`fix:`/`breaking:` prefix, no Co-Authored-By annotations):',- '',- ' ```bash',- ' git add <file> [<file> ...]',- ' git commit -m "feat: <description>"',- ' ```',- ];-- let step = 3;- if (drivesOwnPr) {- lines.push(...buildManualPrCreateStep(step++, { branchName, baseBranch, forgeCli }));- lines.push(`${step++}. Work through the **${runsReviewLoop ? 'Review Loop' : 'Merge Gate'}** section below in full — it ends by merging the PR. Come back here when it is done.`);- } else if (willOpenPR) {- const handoff = policyLeavesOpen- ? 'PortOS will push the branch, create a pull request with your completion summary as its description, and leave it open for inspection.'- : leavePrOpen- ? 'PortOS will push the branch and create a pull request for the JIRA-linked human handoff.'- : runsReviewLoop- ? 'PortOS will push the branch, create a pull request with your completion summary as its description, run the configured reviewer follow-up, and merge only after review and CI pass.'- : 'PortOS will push the branch, create a pull request with your completion summary as its description, and merge it once CI is green.';- lines.push(`${step++}. Do NOT push, open, or merge a pull request yourself. ${handoff}`);- } else {- lines.push(`${step++}. Do NOT push this worktree branch yourself. PortOS will merge it back after completion.`);- }-- lines.push(...buildSentinelWriteSteps(step, sentinelPath, sentinelTail));-- return lines.join('\n');-}--/**- * Which inline PR-lifecycle section — if any — a run gets after its manual- * completion workflow: `'review-loop'`, `'merge-gate'` (no reviewer configured,- * so CI is the whole gate), or `null`.- *- * ONE definition, used by both the prompt assembly that renders the section and- * the `buildAgentPrompt` preload that decides whether to read + stage the ~56KB- * CLI-reviewer recipe for it. They were two conditions at opposite ends of the- * file, and the loose one paid for a 56KB read and an `atomicWrite` on every- * read-only / leave-open / merge-gate run whose section never rendered — while- * the strict one restated four branches of the completion if/else chain by hand,- * 130 lines away from the chain it mirrored.- *- * @returns {'review-loop'|'merge-gate'|null}- */-export function inlinePrLifecycleSection(task, { providerType, providerId, providerCommand, leanMode, worktreeInfo, isTruthyMetaFn = isTruthyMetaDefault }) {- if (!LIGHT_CONTEXT_PROVIDER_TYPES.has(providerType)) return null;- if (!agentOwnsPrWorkflow({ providerType, leanMode })) return null;- // A slashdo-capable session drives all of this through `/do:pr` instead.- if (canTypeSlashCommands({ providerId, providerCommand, leanMode })) return null;- // No worktree ⇒ no branch to name in `git push -u origin <branch>`, and the- // one production shape here is a JIRA-ticket run (agentWorkspacePrep skips- // worktree creation when a jiraBranch is set). Its PR is PortOS's to open and- // a human's to land; telling the agent to open one too yields a PR opened- // against a branch it had to guess at, and then a second `gh pr create` from- // cleanup that fails "a pull request already exists".- if (!worktreeInfo) return null;-- const metadata = task?.metadata || {};- if (!isTruthyMetaFn(metadata.openPR)) return null;- // The completion branches that hand back a contract which never opens a PR.- if (isTruthyMetaFn(metadata.noCodeOutput) || metadata.creativeDirector) return null;- if (isTruthyMetaFn(metadata.discardWorktree)) return null;- if (isTruthyMetaFn(metadata.readOnly)) return null;- if (isTruthyMetaFn(metadata.reviewLoopFollowUp)) return null;- // A PR a human lands gets neither a review loop nor a merge gate.- const prCompletion = resolvePrCompletion(metadata);- if (prCompletion === PR_COMPLETIONS.LEAVE_OPEN || leavesPrForHuman(task)) return null;-- return prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE ? 'review-loop' : 'merge-gate';-}--/**- * The inline review-loop (or, with no reviewer configured, merge-gate) section- * for an agent that opened its own PR under the manual completion workflow.- *- * Deliberately the SAME builder the `sys-rl-*` follow-up agent gets, driven off- * a synthesized `reviewLoop*` metadata shape: the procedure a follow-up runs and- * the procedure an inline run needs are the same procedure, and the whole- * regression this fixes came from having two of them. The PR coordinates are the- * shell variables `buildManualPrCreateStep` captured, because the section is- * rendered before the PR exists.- */-function buildInlineReviewLoopSection({- taskId, branchName, runsReviewLoop, leaveOpen, localAgentLoopBody, localAgentLoopBodyPath = null, writesSentinel = false,- reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies, forgeCli = 'gh',-}) {- // Where control goes after the merge. A TUI run still owes PortOS its- // `.agent-done` sentinel — telling it to "exit" here is how a finished merge- // can otherwise sit without recording completion — while a CLI run signals completion by exiting.- const inlineExitStep = writesSentinel- ? 'Return to the **Completion Workflow** above and write the completion sentinel — the run is not done until you have. Do NOT open a second PR.'- : 'You are done — exit. Do NOT open a second PR or push anything further.';- return buildReviewLoopFollowUpSection({- reviewLoopPRUrl: '$PR_URL',- reviewLoopPRNumber: '$PR_NUMBER',- reviewLoopPRBranch: branchName || '<branch>',- reviewLoopReviewers: reviewers,- reviewLoopReviewerUsernames: usernames,- reviewLoopOptionalReviewers: optionalReviewers,- reviewLoopReviewerMaxRounds: reviewerMaxRounds,- reviewLoopReviewerModels: reviewerModels,- reviewLoopReviewerEfforts: reviewerEfforts,- reviewLoopStopMode: reviewStopMode,- reviewLoopReviewerApplies: reviewerApplies,- reviewLoopLeaveOpen: leaveOpen,- // No reviewer configured ⇒ the merge-gate variant (CI is the whole gate),- // exactly as the merge-only follow-up gets.- reviewLoopMergeOnly: !runsReviewLoop,- sourceTaskId: taskId || 'unknown',- }, { verbose: false, localAgentLoopBody, localAgentLoopBodyPath, inlineExitStep, forgeCli });-}--/**- * CLI (non-TUI) completion block.- *- * Claude Code CLI agents have slashdo commands available (the submodule- * mounts them as project-level slash commands), so when `hasSlashdo` is- * true and a PR is expected, the agent owns the full `/simplify` → `/do:pr`- * sequence and PortOS skips its post-exit push+PR. Codex/Antigravity and other- * CLI providers fall through to the legacy commit-only block where PortOS- * handles push+PR on exit.- */-function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, hasSlashdo = false, ownsPrWorkflow = false, simplifyEnabled = false, leavePrOpen = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewerModels = {}, reviewerEfforts = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, forgeCli = 'gh' }) {- const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;- const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;- if (hasSlashdo && worktreeInfo && willOpenPR) {- const lines = ['## Completion', 'When finished, run these in order:'];- let step = 1;- if (simplifyEnabled) {- lines.push(`${step++}. \`/simplify\` — review the changed code for reuse, quality, and efficiency, and fix any findings.`);- }- const { reviewUsernames, reviewArgs, effortNote } = resolveReviewInvocation({ willOpenPR, runsReviewLoop, reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies });- // `--no-merge` overrides a saved slashdo `merge: true` default, which would- // otherwise merge a PR this task must leave open (see lib/prDisposition.js).- const reviewerArg = (reviewArgs ? ` ${reviewArgs}` : '') + ((leavePrOpen || policyLeavesOpen) ? ' --no-merge' : '');- const completionNote = runsReviewLoop- ? ((reviewers.length === 1 && reviewers[0] === DEFAULT_REVIEWER && reviewUsernames.length === 0)- ? 'and drives the Copilot review loop until clean.'- : `and drives the review loop for ${[...reviewers, ...reviewUsernames.map(u => `@${u}`)].join(', ')} in order until clean.`)- : 'with external review disabled.';- lines.push(`${step++}. \`/do:pr${reviewerArg}\` — commits your changes, pushes the branch, and opens a pull request against the default branch ${completionNote}`);- // Empty whenever the emitted `--review-with` already carries `~effort=<level>`- // (see buildReviewerEffortNote) — this speaks only for an unpinned invocation.- if (effortNote) lines.push(` ${effortNote}`);- // Merge steps follow — review-gated with a loop, CI-gated without one — unless- // this PR is a human's to land (JIRA-tracked; see lib/prDisposition.js).- if (leavePrOpen || policyLeavesOpen) {- lines.push(LEAVE_PR_OPEN_STEP(step, leavePrOpen));- } else {- const merge = buildPostPRMergeSteps(step, { prCompletion, reviewers, usernames: reviewUsernames, reviewStopMode });- lines.push(...merge.lines);- }- return lines.join('\n');- }- if (hasSlashdo && worktreeInfo) {- const lines = ['## Completion', 'When finished, run these in order:'];- let step = 1;- if (simplifyEnabled) {- lines.push(`${step++}. \`/simplify\` — review the changed code for reuse, quality, and efficiency, and fix any findings.`);- }- lines.push(`${step++}. \`/do:push\` — commits your changes and pushes the branch.`);- return lines.join('\n');- }- // Non-slashdo CLI that IS a real coding harness (codex, grok/agy, OpenCode):- // it can't type `/do:pr`, but it can run `git push` / `gh pr create` and drive- // the reviewer CLIs — so it owns the same end-to-end lifecycle the TUI manual- // path does, with the reviewer procedure inlined in the section that follows.- // `ownsPrWorkflow` already folds in `willOpenPR`, the worktree, and the- // leave-open exclusions (it is `inlinePrLifecycleSection() !== null`).- if (ownsPrWorkflow) {- const lines = ['## Completion', '**You own this PR end to end — nothing else will open, review, or merge it.** When finished, run these in order:'];- let step = 1;- lines.push(simplifyEnabled- ? `${step++}. Before committing, ${SIMPLIFY_INLINE_REVIEW} and fix any findings.`- : `${step++}. (simplify disabled — skip)`);- lines.push(`${step++}. Stage only the files you changed (never \`git add -A\` / \`git add .\`) and commit with a conventional message (\`feat:\`/\`fix:\`/\`breaking:\` prefix, no Co-Authored-By annotations).`);- lines.push(...buildManualPrCreateStep(step++, {- branchName: worktreeInfo?.branchName || null,- baseBranch: worktreeInfo?.baseBranch || null,- forgeCli,- }));- lines.push(`${step}. Work through the **${runsReviewLoop ? 'Review Loop' : 'Merge Gate'}** section below in full — it ends by merging the PR.`);- return lines.join('\n');- }- let body;- if (worktreeInfo && willOpenPR) {- body = 'Commit your changes (stage specific files, `feat:`/`fix:` prefix, no Co-Authored-By). Do NOT push — PortOS will push and open the PR after you exit.';- } else if (worktreeInfo) {- body = 'Commit your changes to this branch. PortOS will merge it back when the task completes.';- } else {- body = 'Commit and push your changes (`git pull --rebase && git push`, conventional commit prefix, no `git add -A`).';- }- // Non-slashdo CLIs (codex/antigravity) have no `/simplify` command; when the task- // enabled simplify, inline the equivalent self-review so the quality pass still- // runs before they commit.- const simplifyLine = simplifyEnabled- ? `Before committing, ${SIMPLIFY_INLINE_REVIEW} and fix any findings. `- : '';- return `## Completion\n${simplifyLine}${body}`;-}--/**- * Get the workspace path for an app, or `null` when it can't be resolved.- *- * This used to substitute the PortOS repo root for every failure — registry- * missing, app not found, app carrying no `repoPath` — which made an- * unresolvable app indistinguishable from a working one: the agent quietly- * wrote its files into the PortOS checkout and nothing said otherwise- * (issue #3180). A downstream existence check can't recover that case either,- * because the substituted root is a real directory.- *- * So this returns an explicit `null` sentinel and lets each caller decide- * whether "no workspace" is legal for it (per the sentinel-and-validate rule in- * AGENTS.md — absent must not collapse into a valid-looking value). The reason- * is logged here, where it's known.- *- * @returns {Promise<string|null>} the app's repoPath, or null if unresolvable- */-export async function getAppWorkspace(appName) {- const appsFile = join(ROOT_DIR, 'data/apps.json');- const unresolved = (why) => { console.warn(`⚠️ ${why} — no agent workspace resolved`); return null; };-- const data = await readJSONFile(appsFile, null);- if (!data) return unresolved(`No apps registry at ${appsFile}`);-- // Handle both object format { apps: { id: {...} } } and array format [...]- const apps = data.apps || data;-- const app = Array.isArray(apps)- ? apps.find(a => a.name === appName || a.id === appName)- // Object format - keys are app IDs- : (apps[appName] || Object.values(apps).find(a => a.name === appName));-- if (!app) return unresolved(`App '${appName}' not found in apps registry`);- if (!app.repoPath) return unresolved(`App '${appName}' has no repoPath`);- // Expand here, not just at the spawn boundary. Callers do more with this than- // spawn into it: agentLifecycle persists it as an agent's `sourceWorkspace`,- // and the worktree cleanup/merge paths later hand that value to a child- // process as its cwd. Node never shell-expands `~`, so returning the raw- // tilde form would let a task start (the spawn path expands) and then strand- // its worktree and branch when cleanup runs against a path that doesn't exist.- return expandHome(app.repoPath);-}--/**- * Get full app data for a task (including jira config).- * Returns the app object or null if not found.- */-export async function getAppDataForTask(task) {- const appName = task?.metadata?.app;- if (!appName) return null;-- const appsFile = join(ROOT_DIR, 'data/apps.json');- const data = await readJSONFile(appsFile, null);- if (!data) return null;-- const apps = data.apps || data;-- if (Array.isArray(apps)) {- return apps.find(a => a.name === appName || a.id === appName) || null;- }-- return apps[appName] || Object.values(apps).find(a => a.name === appName) || null;-}--/**- * Generate a concise JIRA ticket title from a task description using AI.- * Falls back to truncated description on failure.- */-export async function generateJiraTitle(description) {- const fallback = `[CoS] ${(description || 'Automated task').substring(0, 120)}`;-- const provider = await getActiveProvider().catch(() => null);- if (!provider) return fallback;-- const model = provider.defaultModel || provider.models?.[0];- if (!model) return fallback;-- const prompt = `Generate a concise JIRA ticket title (max 80 chars) for this task. Output ONLY the title text, nothing else.\n\nTask: ${description}`;-- // Best-effort title — failures are non-fatal (the task still gets the- // truncated-description fallback). 30s is the legacy cap; titles should- // be near-instant, and a slow model shouldn't block task creation.- const result = await runPromptThroughProvider({- provider, prompt, source: 'jira-title', model, timeout: 30000,- }).catch(err => {- console.warn(`⚠️ JIRA title generation failed: ${err.message}`);- return null;- });- if (!result) return fallback;-- const title = (result.text || '').trim().replace(/^["']|["']$/g, '');- return title || fallback;-}--/**- * Create a JIRA ticket for a task if the app has JIRA integration enabled.- * Non-blocking — returns null on failure.- * @returns {Promise<{ticketId: string, ticketUrl: string, summary: string}|null>}- */-export async function createJiraTicketForTask(task, app) {- const jira = app?.jira;- if (!jira?.enabled || !jira.instanceId || !jira.projectKey) return null;-- const summary = await generateJiraTitle(task.description);- const description = [- `Automated task created by PortOS Chief of Staff.`,- ``,- `*Task ID:* ${task.id}`,- `*Priority:* ${task.priority || 'MEDIUM'}`,- `*App:* ${app.name || task.metadata?.app || 'unknown'}`,- ``,- `{quote}`,- task.description || '',- `{quote}`- ].join('\n');-- const result = await jiraService.createTicket(jira.instanceId, {- projectKey: jira.projectKey,- summary,- description,- issueType: jira.issueType || 'Task',- labels: jira.labels || [],- assignee: jira.assignee,- epicKey: jira.epicKey- }).catch(err => {- emitLog('warn', `Failed to create JIRA ticket: ${err.message}`, { taskId: task.id, app: app.name });- return null;- });-- if (!result?.ticketId) return null;-- emitLog('success', `Created JIRA ticket ${result.ticketId}`, {- taskId: task.id,- ticketId: result.ticketId,- ticketUrl: result.url- });-- return { ticketId: result.ticketId, ticketUrl: result.url, summary };-}diff --git a/server/services/promptSections/README.md b/server/services/promptSections/README.mdnew file mode 100644index 0000000000..4add30ca07--- /dev/null+++ b/server/services/promptSections/README.md@@ -0,0 +1,14 @@+# Agent prompt sections++Leaf modules used by `agentPromptBuilder.js`. The builder remains the public facade and owns only full/light prompt orchestration; section-specific behavior lives here.++| Module | Responsibility |+| --- | --- |+| `appContext.js` | Managed-app workspace lookup and JIRA ticket helpers. |+| `completion.js` | Worktree, completion-workflow, and sentinel sections. |+| `constants.js` | Constants shared across full and light prompt paths. |+| `forge.js` | Forge CLI selection for generated workflow text. |+| `instructions.js` | Skill-template routing and bounded instruction-file discovery. |+| `reviewLifecycle.js` | Reviewer, CI-gate, and merge sections. |+| `slashdo.js` | Slashdo invocation and procedure expansion. |+| `taskContext.js` | Task, attachment, split-context, and compaction sections. |diff --git a/server/services/promptSections/appContext.js b/server/services/promptSections/appContext.jsnew file mode 100644index 0000000000..b43177ebd2--- /dev/null+++ b/server/services/promptSections/appContext.js@@ -0,0 +1,152 @@+/**+ * Managed-app workspace lookup and JIRA ticket prompt support.+ */++import { join } from 'path';+import { PATHS, readJSONFile, expandHome } from '../../lib/fileUtils.js';+import { runPromptThroughProvider } from '../../lib/promptRunner.js';+import { getActiveProvider } from '../providers.js';+import * as jiraService from '../jira.js';+import { emitLog } from '../cosEvents.js';++const ROOT_DIR = PATHS.root;++/**+ * Get the workspace path for an app, or `null` when it can't be resolved.+ *+ * This used to substitute the PortOS repo root for every failure — registry+ * missing, app not found, app carrying no `repoPath` — which made an+ * unresolvable app indistinguishable from a working one: the agent quietly+ * wrote its files into the PortOS checkout and nothing said otherwise+ * (issue #3180). A downstream existence check can't recover that case either,+ * because the substituted root is a real directory.+ *+ * So this returns an explicit `null` sentinel and lets each caller decide+ * whether "no workspace" is legal for it (per the sentinel-and-validate rule in+ * AGENTS.md — absent must not collapse into a valid-looking value). The reason+ * is logged here, where it's known.+ *+ * @returns {Promise<string|null>} the app's repoPath, or null if unresolvable+ */+export async function getAppWorkspace(appName) {+ const appsFile = join(ROOT_DIR, 'data/apps.json');+ const unresolved = (why) => { console.warn(`⚠️ ${why} — no agent workspace resolved`); return null; };++ const data = await readJSONFile(appsFile, null);+ if (!data) return unresolved(`No apps registry at ${appsFile}`);++ // Handle both object format { apps: { id: {...} } } and array format [...]+ const apps = data.apps || data;++ const app = Array.isArray(apps)+ ? apps.find(a => a.name === appName || a.id === appName)+ // Object format - keys are app IDs+ : (apps[appName] || Object.values(apps).find(a => a.name === appName));++ if (!app) return unresolved(`App '${appName}' not found in apps registry`);+ if (!app.repoPath) return unresolved(`App '${appName}' has no repoPath`);+ // Expand here, not just at the spawn boundary. Callers do more with this than+ // spawn into it: agentLifecycle persists it as an agent's `sourceWorkspace`,+ // and the worktree cleanup/merge paths later hand that value to a child+ // process as its cwd. Node never shell-expands `~`, so returning the raw+ // tilde form would let a task start (the spawn path expands) and then strand+ // its worktree and branch when cleanup runs against a path that doesn't exist.+ return expandHome(app.repoPath);+}++/**+ * Get full app data for a task (including jira config).+ * Returns the app object or null if not found.+ */+export async function getAppDataForTask(task) {+ const appName = task?.metadata?.app;+ if (!appName) return null;++ const appsFile = join(ROOT_DIR, 'data/apps.json');+ const data = await readJSONFile(appsFile, null);+ if (!data) return null;++ const apps = data.apps || data;++ if (Array.isArray(apps)) {+ return apps.find(a => a.name === appName || a.id === appName) || null;+ }++ return apps[appName] || Object.values(apps).find(a => a.name === appName) || null;+}++/**+ * Generate a concise JIRA ticket title from a task description using AI.+ * Falls back to truncated description on failure.+ */+export async function generateJiraTitle(description) {+ const fallback = `[CoS] ${(description || 'Automated task').substring(0, 120)}`;++ const provider = await getActiveProvider().catch(() => null);+ if (!provider) return fallback;++ const model = provider.defaultModel || provider.models?.[0];+ if (!model) return fallback;++ const prompt = `Generate a concise JIRA ticket title (max 80 chars) for this task. Output ONLY the title text, nothing else.\n\nTask: ${description}`;++ // Best-effort title — failures are non-fatal (the task still gets the+ // truncated-description fallback). 30s is the legacy cap; titles should+ // be near-instant, and a slow model shouldn't block task creation.+ const result = await runPromptThroughProvider({+ provider, prompt, source: 'jira-title', model, timeout: 30000,+ }).catch(err => {+ console.warn(`⚠️ JIRA title generation failed: ${err.message}`);+ return null;+ });+ if (!result) return fallback;++ const title = (result.text || '').trim().replace(/^["']|["']$/g, '');+ return title || fallback;+}++/**+ * Create a JIRA ticket for a task if the app has JIRA integration enabled.+ * Non-blocking — returns null on failure.+ * @returns {Promise<{ticketId: string, ticketUrl: string, summary: string}|null>}+ */+export async function createJiraTicketForTask(task, app) {+ const jira = app?.jira;+ if (!jira?.enabled || !jira.instanceId || !jira.projectKey) return null;++ const summary = await generateJiraTitle(task.description);+ const description = [+ `Automated task created by PortOS Chief of Staff.`,+ ``,+ `*Task ID:* ${task.id}`,+ `*Priority:* ${task.priority || 'MEDIUM'}`,+ `*App:* ${app.name || task.metadata?.app || 'unknown'}`,+ ``,+ `{quote}`,+ task.description || '',+ `{quote}`+ ].join('\n');++ const result = await jiraService.createTicket(jira.instanceId, {+ projectKey: jira.projectKey,+ summary,+ description,+ issueType: jira.issueType || 'Task',+ labels: jira.labels || [],+ assignee: jira.assignee,+ epicKey: jira.epicKey+ }).catch(err => {+ emitLog('warn', `Failed to create JIRA ticket: ${err.message}`, { taskId: task.id, app: app.name });+ return null;+ });++ if (!result?.ticketId) return null;++ emitLog('success', `Created JIRA ticket ${result.ticketId}`, {+ taskId: task.id,+ ticketId: result.ticketId,+ ticketUrl: result.url+ });++ return { ticketId: result.ticketId, ticketUrl: result.url, summary };+}diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.jsnew file mode 100644index 0000000000..cce62cf3d6--- /dev/null+++ b/server/services/promptSections/completion.js@@ -0,0 +1,771 @@+/**+ * Completion workflow, worktree, and sentinel prompt sections.+ */++import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, normalizeReviewUsernames, resolveClaimReviewerConfig, buildReviewerPinNote, buildReviewerEffortNote, buildReviewWithArgs } from '../../lib/validation.js';+import { PROGRAMMATIC_OUTPUT_COMPLETION_HEADING } from '../../lib/agentSentinel.js';+import { canTypeSlashCommands, agentOwnsPrWorkflow } from '../../lib/slashdoInvocation.js';+import { shellQuote } from '../../lib/shellQuote.js';+import { PR_COMPLETIONS, leavesPrForHuman, resolvePrCompletion } from '../../lib/prDisposition.js';+import { LIGHT_CONTEXT_PROVIDER_TYPES, SIMPLIFY_INLINE_REVIEW } from './constants.js';+import { buildCiMergeGateSteps, buildReviewLoopFollowUpSection, LEAVE_PR_OPEN_STEP } from './reviewLifecycle.js';++/**+ * Build the single "## Guidelines" completion-handoff bullet for the full+ * (api) prompt path. Mirrors the helper pattern the light path already uses+ * (`worktreeCommitGuidance`, `buildTuiCompletionSection`) — same 4-branch+ * decision tree (read-only / TUI / worktree+PR / worktree-only / default) but+ * flattened into a function so reading is linear instead of a nested ternary.+ *+ * Returns the bullet body WITHOUT the leading `- ` marker (caller prepends),+ * or `null` when the branch produces no text (the legacy empty-string tail).+ *+ * @param {Object} opts+ * @param {boolean} opts.isReadOnly+ * @param {boolean} opts.isTui+ * @param {string} opts.tuiCompletionCommand - `/do:pr` or `/do:push`+ * @param {boolean} [opts.slashdoFree] - TUI without slashdo: the bullet points+ * at the manual commit + system-handoff workflow instead of a `/do:*` command.+ * @param {Object|null} opts.worktreeInfo+ * @param {boolean} opts.willOpenPR+ * @param {'review-then-merge'|'merge-on-green'|'leave-open'} opts.prCompletion+ * @returns {string|null}+ */+export function buildCompletionGuidelineBullet({+ isReadOnly, isTui, tuiCompletionCommand, slashdoFree = false,+ worktreeInfo, willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, discardWorktree = false, noCodeOutput = false,+ leavePrOpen = false, isPrFollowUp = false, claimFlow = false,+}) {+ // A PR follow-up (review-loop or merge-only) already carries its own PRIMARY+ // OBJECTIVE section with the full procedure, and its cleanup runs with+ // `skipMerge`. The generic "your branch is merged back automatically" bullet+ // would contradict both — and a merge-only run legitimately makes no commit.+ if (isPrFollowUp && !discardWorktree && !noCodeOutput && !isReadOnly) {+ return 'Follow the follow-up section above — it is the whole task. Commit and push only fixes you actually make; the deliverable is the PR\'s final state, not a commit. Do NOT open a new PR, and do NOT expect this branch to be merged back for you.';+ }+ // `noCodeOutput` is checked FIRST because the two flags answer different+ // questions: `discardWorktree` decides what happens to the checkout, while+ // `noCodeOutput` decides where the deliverable goes. A task that sets both —+ // "do your work through an API/CLI action during the run, and never land+ // code" — must be told its output channel is that action, NOT the sentinel.+ // Telling it "write your result to the sentinel" is how a run files nothing+ // and reports its findings into a file that gets thrown away (PLAN.md records+ // this exact hazard from the 2026-07-16 codex review). No pre-existing task+ // sets both, so this ordering changes nothing that shipped before it.+ if (noCodeOutput) {+ return '**This task produces no code output.** Its result is the API request or command your instructions describe (a PortOS endpoint call, a filed tracker issue, …) — do NOT run `/do:push`, `/do:pr`, `/simplify`, `git commit`, `git push`, or open a PR. Write the completion sentinel (see the Completion section) and stop.';+ }+ if (discardWorktree) {+ return '**This is a reasoning-only task.** The worktree is discarded on exit — do NOT commit, push, merge, or open a PR. Write your result to the completion sentinel (see the Completion section) and stop.';+ }+ if (claimFlow) {+ return '**This is a self-managed claim flow.** Follow the claim prompt above through its phase-specific worktree, PR/MR, review, merge or human-handoff, and cleanup steps. Do NOT stop after committing or hand the lifecycle back to PortOS.';+ }+ if (isReadOnly) {+ return '**This is a read-only task.** Do NOT commit, push, or modify any files in the repository. Only read data and generate reports.';+ }+ if (isTui) {+ // NOTE: in production this branch is only reachable from the full/api prompt+ // path, where `isTui` is currently always false (TUI providers route through+ // buildLightContextPrompt, which emits the live TUI completion via+ // buildTuiCompletionSection — not this bullet). It's kept provider-aware and+ // directly unit-tested so the guideline stays correct if that routing changes.+ const howTo = slashdoFree+ ? 'the Completion Workflow above (plain `git` commit + PortOS handoff — this provider has no slashdo commands)'+ : `the Completion Workflow above (\`${tuiCompletionCommand}\`)`;+ return `On successful completion, YOU run ${howTo}, then write the sentinel and stop — PortOS closes the session once it sees the sentinel; do NOT run \`/quit\`.`;+ }+ if (worktreeInfo && willOpenPR) {+ const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;+ const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;+ const reviewSuffix = policyLeavesOpen+ ? ' This task is configured to leave the PR OPEN for you to inspect — no follow-up agent will review or merge it automatically.'+ : leavePrOpen+ ? ' This task is tracked in JIRA, so the PR is left OPEN for a human to land alongside the ticket — nothing merges it automatically.' + (runsReviewLoop ? ' A follow-up agent still runs the configured reviewers against it.' : '')+ : runsReviewLoop+ ? ' For GitHub PRs, a Copilot code review will also be requested automatically (skipped on GitLab and other non-GitHub forges) — do NOT run `/do:rpr` or attempt to address review comments yourself; you will have already exited.'+ : ' No review was requested for this task, so a follow-up agent merges the PR once CI is green — do NOT try to merge it yourself; you will have already exited.';+ return `On successful completion, the system will push your branch and open a pull request — do NOT open a PR manually. (If the task fails, no PR is opened; the worktree is then cleaned up unless a safety check preserves it for manual recovery.)${reviewSuffix}`;+ }+ if (worktreeInfo) {+ return 'Your worktree branch will be automatically merged back to the source branch when your task completes — do NOT open a PR.';+ }+ return null;+}++// One-line worktree note for a discard (reasoning-only) task, replacing the+// "commit / push / auto-merge" guidance the normal worktree section emits. The+// worktree exists only so the reasoner can make scratch edits without touching+// the real tree — cleanup discards it with no commit/merge/PR (see+// `discardWorktree` in agentWorktreeCleanup.js).+export const DISCARD_WORKTREE_NOTE = 'Do NOT commit, push, or open a PR — this worktree is discarded on exit. Make any scratch edits that help you reason; only the completion sentinel is kept.';++/**+ * Is this worktree attached to a branch a PR already points at — i.e. the+ * review-loop follow-up, whose guidance is "push review fixes here, the PR+ * points at this branch"?+ *+ * Identified POSITIVELY, off the follow-up's own `reviewLoopFollowUp` marker,+ * rather than as "any `existingBranch` worktree". `existingBranch` means only+ * "attach to this branch" and now has two producers: the follow-up, and a retry+ * resuming a dead agent's branch (`resumedFromAgentId`), which follows the task's+ * ordinary push/PR flow and may have no PR at all. Keying on the marker means a+ * THIRD producer defaults to the ordinary flow instead of silently inheriting+ * review-fix instructions for a PR that doesn't exist.+ */+export function isPrBranchWorktree(task, worktreeInfo) {+ return worktreeInfo?.existingBranch === true && !!task?.metadata?.reviewLoopFollowUp;+}++/**+ * Is this worktree a RESUME of a previous failed agent's branch? Keyed on+ * `resumedFromAgentId`, which only the resume path stamps (see+ * agentCompletionCleanup.js).+ */+function isResumedWorktree(task, worktreeInfo) {+ return worktreeInfo?.existingBranch === true && !!task?.metadata?.resumedFromAgentId;+}++/**+ * Resume banner for a retry picking up what a PREVIOUS unfinished agent left+ * behind (`metadata.existingBranch` + `resumedFromAgentId`, stamped by+ * `recordTaskResumePointer` when a dead run's branch — or whole worktree —+ * survived cleanup).+ *+ * Without this the retry sees an ordinary worktree that just happens to have+ * work in it and redoes what is already done — the failure mode the+ * agent-d2ae0352 incident exposed (reaped 30s after its PR merged; the+ * replacement agent started the shipped work over). Telling it to read the log+ * FIRST is the whole point: the prior run may have gone as far as opening or even+ * merging a PR, in which case there is nothing left to build.+ *+ * An ADOPTED worktree (`worktreeInfo.adopted` — the shape a server restart leaves,+ * killed mid-edit before committing) additionally carries the dead run's+ * uncommitted edits and untracked files, so the banner points at `git status`+ * as the primary record rather than the commit log.+ *+ * Returns '' when this isn't a resume, so callers can interpolate unconditionally.+ */+export function buildResumeSection(task, worktreeInfo) {+ if (!isResumedWorktree(task, worktreeInfo)) return '';+ const priorAgentId = task.metadata.resumedFromAgentId;+ const carriedWork = worktreeInfo.adopted+ ? `**You are in its actual working directory** — its commits are on your branch \`${worktreeInfo.branchName}\`+AND any edits it had not committed yet are still in your working tree, exactly as it left them.`+ : `**Its commits are already on your branch** \`${worktreeInfo.branchName}\` — you are+continuing its run, not starting over.`;+ return `+## Resuming Unfinished Work — Read This First+A previous agent (\`${priorAgentId}\`) worked this same task and did NOT finish cleanly+(it hung, timed out, or was terminated — a server restart kills runs mid-edit).+${carriedWork}++Before you write any code, establish what is already done:+1. \`git status\` — anything it left uncommitted. Treat these as YOUR in-progress+ changes: review them, finish them, and commit them. Do not discard them wholesale.+2. \`git log --oneline ${worktreeInfo.baseBranch || 'origin/HEAD'}..HEAD\` — the commits it already made.+3. Check whether it already shipped: look for an open or merged PR for this branch+ — \`gh pr list --head ${worktreeInfo.branchName} --state all\` on GitHub,+ \`glab mr list --source-branch ${worktreeInfo.branchName}\` on GitLab.++Then do only what remains. If a PR is already **merged**, the work is done — go+straight to your completion step and report that. If a PR is already **open**,+finish/land that PR rather than opening a second one. Do NOT redo completed work,+and do NOT revert its commits unless they are actually wrong.+`;+}++/**+ * Completion block for a **programmatic-output** (throwaway-worktree) task: the+ * agent reasons in a worktree that is discarded on exit, so it must NOT commit,+ * push, merge, or open a PR. Its only channel out is the `.agent-done` sentinel,+ * whose exact payload shape is specified by the task instructions (a task-type+ * output hook — see `taskTypeHooks.js` / `layeredIntelligenceHooks.js`). This+ * replaces the normal `/do:push`+markdown-sentinel completion workflow, which+ * would tell the agent to push code (defeating the discard guarantee) and write+ * a markdown summary (breaking the hook's structured-JSON sentinel contract).+ */+export function buildProgrammaticOutputCompletionSection(sentinelPath) {+ return [+ // Shared constant: a pre-spawn task-type hook's prompt points here BY NAME.+ `## ${PROGRAMMATIC_OUTPUT_COMPLETION_HEADING}`,+ 'This is a reasoning task, not a code change. The worktree you are in is **discarded on exit** — any commits, pushes, or PRs are thrown away and have no effect. Do NOT run `/do:push`, `/do:pr`, `git commit`, `git push`, or open a pull request.',+ '',+ `When you have finished reasoning, write your result to \`${sentinelPath}\` in the exact payload format described in your task instructions, then stop. PortOS watches this sentinel and finalizes the run shortly after it appears — do NOT run \`/quit\` and do NOT wait for anything after writing the sentinel.`+ ].join('\n');+}++/**+ * Completion block for a **read-only** task (e.g. reference-watch, pr-reviewer's+ * scan stage). The agent must NOT commit/push/modify source; its real output is+ * recorded elsewhere DURING the run (a tracker issue, PLAN.md, a report).+ *+ * A TUI agent still needs a `.agent-done` sentinel to signal completion — the+ * sentinel watcher in `spawnTuiAgent` is the primary finalize path and the channel+ * that ingests the run summary. Without it a read-only TUI run relies on shell+ * exit, so the resolution summary is not captured cleanly (the bug this+ * repairs). CLI/API read-only agents complete on process exit and never poll a+ * sentinel, so they get the bare notice only.+ */+export function buildReadOnlyCompletionSection({ isTui = false, sentinelPath = null } = {}) {+ const notice = '## Read-Only Task\nDo NOT commit, push, or modify any files. Read data and report findings only.';+ if (!isTui || !sentinelPath) return notice;+ return [+ notice,+ '',+ `When you have finished, write a short markdown summary of what you found (and where you recorded it) to \`${sentinelPath}\`, then stop. PortOS watches this sentinel and finalizes the run shortly after it appears — do NOT run \`/quit\` and do NOT wait for anything after writing the sentinel.`+ ].join('\n');+}++/**+ * Completion block for a **no-code / API-action** task (e.g. a Creative Director+ * plan/treatment/evaluate agent). The agent's deliverable is the HTTP request its+ * task instructions already describe (a PATCH to a PortOS endpoint), NOT a code+ * change — so the normal `/do:push`+PR completion workflow is wrong: there is+ * nothing to commit or push, and telling the agent to run `/do:push` just makes it+ * load that skill for no reason (and can contradict the task prompt's own+ * "on a 200 your task is complete"). A TUI agent still writes a `.agent-done`+ * sentinel so the watcher finalizes it promptly instead of waiting for a runtime+ * reaper.+ */+export function buildActionOutputCompletionSection({ isTui = false, sentinelPath = null } = {}) {+ const notice = '## Completion (No Code Output)\nThis task produces **no code change** — its result is delivered DURING the run by the API request or command your instructions describe (a PATCH to a PortOS endpoint, a filed tracker issue, …), not by a commit and not by this sentinel. Do NOT run `/do:push`, `/do:pr`, `/simplify`, `git commit`, `git push`, or open a pull request; there is nothing to push.';+ if (!isTui || !sentinelPath) return notice;+ return [+ notice,+ '',+ `Your task is complete once that request succeeds. Then write a one-line summary to \`${sentinelPath}\` and stop — PortOS watches this sentinel and finalizes the run shortly after it appears. Do NOT run \`/quit\` and do NOT wait for anything after writing the sentinel.`+ ].join('\n');+}++/**+ * The `--review-with` token list a claim task's prompt names, read back off the+ * task record. The claim generators persist the bundle they rendered into+ * `{reviewers}` (`reviewerConfigMetadata`), so this reproduces that CSV exactly.+ *+ * A claim task queued before #4770 carries no reviewer metadata, so this falls+ * through to the install's Code Review Defaults — routed through the claim+ * resolver so an in-flight legacy task can't be pinned to a bare `copilot`,+ * which a claim agent has no CLI to invoke (#2507).+ */+export function claimReviewersCsv(task, codeReviewDefaults, defaultReviewers) {+ return resolveClaimReviewerConfig(task?.metadata, codeReviewDefaults, defaultReviewers).csv;+}++/**+ * Completion handoff for claim prompts that create their own worktree and own+ * the forge lifecycle. `openPR: false` must remain the CoS provisioning posture,+ * so claimFlow is the explicit signal that keeps these prompts out of the+ * generic commit-only handoff.+ *+ * This is also the ONE emitter of the reviewer pin (#4770). Every claim+ * generator persists the reviewer bundle it rendered into `{reviewers}` onto the+ * task, so `resolveClaimReviewerConfig(task.metadata, …)` here reproduces that+ * exact CSV — which means the pin covers all five claim task types from one call+ * site, instead of three prose appends in `cosTaskGenerator.js` that a new claim+ * generator could forget.+ *+ * @param {string} [reviewersCsv] - the emitted `--review-with` token list to pin;+ * empty suppresses the block (`buildReviewerPinNote` returns '').+ */+export function buildClaimFlowCompletionSection({ isTui = false, sentinelPath = null, reviewersCsv = '' } = {}) {+ const pin = buildReviewerPinNote(reviewersCsv);+ const lines = [+ ...(pin ? [pin, ''] : []),+ '## Claim Workflow Handoff',+ 'This is a self-managed claim flow. The claim prompt above owns its claim worktree, branch, PR/MR, review, merge or human-handoff, and cleanup. Follow its phase-specific exit conditions — do NOT stop after a code commit or hand the lifecycle back to PortOS.',+ '',+ 'For a successful claim, signal completion only after the prompt\'s prescribed PR/MR and cleanup steps are complete. For a clean no-work, blocked, or review-stuck exit, follow the prompt\'s prescribed leave-open/cleanup path first.'+ ];+ if (isTui && sentinelPath) {+ lines.push('', 'When that path is complete, write the completion sentinel and stop:', '', ...buildSentinelWriteSteps(1, sentinelPath, ' ## PR/MR\n <PR or MR URL, or explain the clean exit>'));+ } else {+ lines.push('', 'After the prompt\'s prescribed final step, exit so PortOS can record the completed claim.');+ }+ return lines.join('\n');+}++/**+ * Worktree commit-guidance helper for the light prompt. Picks the right+ * single-sentence instruction based on whether the agent will run its own+ * push workflow (TUI or Claude Code CLI with slashdo), reuse an existing PR+ * branch (review fixes), or hand off to PortOS's post-exit push.+ */+export function worktreeCommitGuidance({ isTui, hasSlashdo, ownsPrWorkflow = false, isWorktreeOnExistingBranch, willOpenPR, discardWorktree, claimFlow = false }) {+ if (discardWorktree) return DISCARD_WORKTREE_NOTE;+ if (claimFlow) return 'The claim workflow in the Completion section owns the push, PR/MR, review, merge or human-handoff, and cleanup steps.';+ if (isTui) return 'Commit your changes to this branch — see **Completion Workflow** below.';+ if (isWorktreeOnExistingBranch) {+ return 'Commit and **push** any review-fix commits to this branch (the PR points at it). Use `git pull --rebase` before pushing if needed.';+ }+ if (hasSlashdo && willOpenPR) {+ return 'Commit your changes here — the **Completion** section below drives the push and PR.';+ }+ if (hasSlashdo) {+ return 'Commit your changes here — the **Completion** section below drives the push.';+ }+ if (ownsPrWorkflow && willOpenPR) {+ return 'Commit your changes here — the **Completion** section below drives the push, the PR, the review loop, and the merge.';+ }+ if (willOpenPR) {+ return 'Commit your changes here. The system will push and open a PR after you exit — do NOT push or open a PR yourself.';+ }+ return 'Commit your changes here. Your branch will be merged back automatically when the task completes.';+}++/**+ * Build the merge-and-verify steps that follow `/do:pr` in completion blocks.+ * Returns `{ lines, nextStep }` — append `lines` to the workflow array and+ * assign `nextStep` back to the caller's step counter so any subsequent+ * numbered steps stay continuous.+ *+ * The agent must drive the merge itself — `/do:pr` runs the review loop but+ * exits without merging, so without this step the PR sits open and the branch+ * leaks. Mirrors the merge contract in the review-loop follow-up section so+ * both agent flows converge on the same final state. `reviewers` only colors+ * the wording — the merge step itself is reviewer-agnostic.+ *+ * `prCompletion` selects the review gate or CI-only merge gate. Leave-open+ * callers do not invoke this helper.+ */+function buildPostPRMergeSteps(startStep, { prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, reviewers = DEFAULT_REVIEWERS, usernames = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE } = {}) {+ // No review loop → CI is the whole gate, so emit the shared CI procedure that+ // the manual-TUI workflow and the merge follow-up agent also use. The PR URL+ // isn't known when this prompt is written, hence the placeholder.+ if (prCompletion === PR_COMPLETIONS.MERGE_ON_GREEN) {+ const gate = buildCiMergeGateSteps(startStep, { prRef: '"<PR_URL>"', forge: 'unknown' });+ return {+ lines: [+ ' **No review loop is configured for this task, so nothing and nobody else will merge this PR** — `/do:pr` opens it and exits. Capture the PR URL it printed, then:',+ ...gate.lines,+ ],+ nextStep: gate.nextStep+ };+ }+ // Trailing space when present so the sentence reads "the Copilot review loop"+ // (lone copilot, no usernames) or "the review loop" (multi/CLI/username) —+ // never "the the review loop".+ const reviewerLabel = (reviewers.length === 1 && reviewers[0] === DEFAULT_REVIEWER && usernames.length === 0) ? 'Copilot ' : '';+ // Under an explicit stop-mode, the multi-reviewer loop can exit `partial` (later+ // reviewers intentionally skipped after the short-circuit) — that's a successful+ // outcome the user opted into, so merge on it too. Match the known stop-modes+ // explicitly so an unknown/invalid value falls through to the safe default+ // (only `clean`/`too-large` mergeable).+ const explicitStopMode = reviewStopMode === 'on-findings' || reviewStopMode === 'on-clean';+ const mergeStatuses = explicitStopMode+ ? '`clean`, `partial` (a stop-mode short-circuit you opted into), or `too-large`'+ : '`clean` (or `too-large`)';+ const lines = [+ `${startStep}. **Merge the PR immediately when the ${reviewerLabel}review loop reports ${mergeStatuses}** — \`/do:pr\` opens the PR and runs the review loop but does NOT merge. Capture the PR URL printed by \`/do:pr\` and run the exact command below (flags: \`--merge --delete-branch\`, nothing else — a true merge commit keeps the branch tip in main's history so automated worktree cleanup can prove the branch is merged; any merge-deferral flag leaves the PR open after you exit). Skip the merge if the loop ended \`timeout\`, \`error\`, \`inconclusive\`, or \`guardrail\`; leave the PR open for human follow-up.`,+ ' ```bash',+ ' gh pr merge "<PR_URL>" --merge --delete-branch',+ ' ```',+ `${startStep + 1}. Confirm the merge before exiting: \`gh pr view "<PR_URL>" --json state -q .state\` must return \`MERGED\`. If it returns \`OPEN\` or \`CLOSED\`, investigate (failing check, unresolved thread, branch protection), fix, and retry. Do NOT exit until state is \`MERGED\` (or you have explicitly decided not to merge per the rule above).`+ ];+ return { lines, nextStep: startStep + 2 };+}++/**+ * Resolve the review-loop invocation shared by buildTuiCompletionSection and+ * buildCliCompletionSection: the normalized reviewer usernames, the+ * `--review-with ...` argument text, and the effort-pin note. Both callers+ * used to re-derive this identical trio from the same 8-field reviewer-config+ * bundle independently.+ */+function resolveReviewInvocation({ willOpenPR, runsReviewLoop, reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies }) {+ const reviewUsernames = normalizeReviewUsernames(usernames);+ const reviewArgs = willOpenPR+ ? (runsReviewLoop ? buildReviewWithArgs(reviewers, { stopMode: reviewStopMode, reviewerApplies, usernames: reviewUsernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts }) : '--review-with none')+ : '';+ // Effort pins ride the emitted `--review-with` tokens as `~effort=<level>`, so+ // the prose note is suppressed whenever that suffix is present — it only speaks+ // for an invocation that pins no reviewer list (see buildReviewerEffortNote).+ const effortNote = willOpenPR && runsReviewLoop+ ? buildReviewerEffortNote(reviewers, reviewerEfforts, { reviewWith: reviewArgs, reviewerModels })+ : '';+ return { reviewUsernames, reviewArgs, effortNote };+}++/**+ * The `.agent-done` sentinel-write instruction block shared by+ * buildTuiCompletionSection and buildManualTuiCompletionSection: the "write a+ * short summary, then stop" instruction plus the fenced heredoc template.+ * Returns the lines to splice into the caller's own line array — output must+ * stay byte-identical since this is agent-facing prompt text.+ */+export function buildSentinelWriteSteps(stepNumber, sentinelPath, sentinelTail) {+ return [+ `${stepNumber}. Write a short markdown summary (~5–15 lines) to the completion sentinel, then stop — this sentinel is the done signal. PortOS watches it and finalizes the run shortly after it appears. Do NOT run \`/quit\` (it's a UI command, not something you can invoke) and do NOT wait for anything after writing the sentinel.`,+ '',+ ' ```bash',+ ` cat > "${sentinelPath}" <<'EOF'`,+ ' ## Summary',+ ' <one-sentence statement of what was accomplished>',+ '',+ ' ## Changes',+ ' - <key file or area>: <what changed and why>',+ '',+ sentinelTail,+ ' EOF',+ ' ```'+ ];+}++/**+ * TUI completion-workflow block. The TUI owns its own commit → push → PR+ * pipeline via slashdo commands and signals "done" with a sentinel file.+ *+ * When `slashdoFree` is set — any TUI that does NOT load Claude Code slash+ * commands: OpenCode, codex/antigravity/grok/kimi, or a lean `--bare` Claude+ * session — the agent can't run `/do:pr` / `/do:push`, so it delegates to the+ * plain-git/`gh` variant below (same sentinel handshake, no slashdo). The caller+ * resolves that flag once via `canTypeSlashCommands` (#3114); past the early+ * return this IS a Claude session, so `/simplify` and `/do:pr` are both safe to+ * emit without a second provider check.+ */+export function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, simplifyEnabled, sentinelPath, slashdoFree = false, ownsPrWorkflow = false, branchName = null, baseBranch = null, leavePrOpen = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewerModels = {}, reviewerEfforts = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, forgeCli = 'gh' }) {+ const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;+ const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;+ if (slashdoFree) {+ // Plain `git`/`gh` instead of `/do:pr` — but still the whole lifecycle when+ // the session is a real coding harness (`ownsPrWorkflow`); the reviewer+ // procedure it needs is inlined in the Review Loop section that follows.+ return buildManualTuiCompletionSection({ willOpenPR, prCompletion, simplifyEnabled, sentinelPath, branchName, baseBranch, leavePrOpen, ownsPrWorkflow, forgeCli });+ }+ const cmd = willOpenPR ? '/do:pr' : '/do:push';+ // `/do:pr` may inherit a saved `review-with` default. Explicitly opt out+ // when the task's Review Loop control is off so that default cannot start a+ // Copilot (or other external) review unexpectedly.+ const { reviewUsernames, reviewArgs, effortNote } = resolveReviewInvocation({ willOpenPR, runsReviewLoop, reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies });+ // A saved slashdo `merge: true` default would otherwise merge a PR that must+ // stay open — dropping our own merge steps isn't enough, `/do:pr` has to be+ // told not to merge (see lib/prDisposition.js).+ const mergeArg = (willOpenPR && (leavePrOpen || policyLeavesOpen)) ? ' --no-merge' : '';+ const reviewerArg = (reviewArgs ? ` ${reviewArgs}` : '') + mergeArg;+ const copilotOnly = reviewers.length === 1 && reviewers[0] === DEFAULT_REVIEWER && reviewUsernames.length === 0;+ const reviewerListLabel = [...reviewers, ...reviewUsernames.map(u => `@${u}`)].join(', ');+ // Ordering matters to the agent: `/do:pr` partitions the list and runs every+ // local reviewer BEFORE it creates the PR, so the PR opens against an+ // already-review-clean branch and only the cloud-side reviewers (Copilot,+ // `@login`) plus CI remain. Saying "after the PR opens" of the whole list had+ // agents expecting — and sometimes hand-rolling — a post-PR local pass.+ const reviewSuffix = willOpenPR && runsReviewLoop+ ? (copilotOnly+ ? ' — `/do:pr` runs the Copilot review loop after the PR opens.'+ : ` — \`/do:pr\` runs the review loop for ${reviewerListLabel} in order: local reviewers before it opens the PR, then the PR-side reviewers (Copilot / \`@login\`) once it is open.`)+ : (willOpenPR ? ' — external review is disabled for this task.' : '');+ // Reached only for a Claude TUI (a non-Claude one took the slashdoFree branch+ // above), so `/simplify` — a Claude Code built-in — is invokable here.+ const simplifyStep = simplifyEnabled ? '1. `/simplify`' : '1. (simplify disabled — skip)';+ const sentinelTail = willOpenPR ? ' ## PR\n <PR URL>' : ' ## Branch\n <branch name>';+ // A PR gets merge steps — gated on the review verdict when a loop runs, on CI+ // alone when it doesn't (nothing else merges a no-review-loop PR). The one+ // exception is a PR a human lands (JIRA-tracked; see lib/prDisposition.js).+ const merge = (willOpenPR && !leavePrOpen && !policyLeavesOpen)+ ? buildPostPRMergeSteps(3, { prCompletion, reviewers, usernames: reviewUsernames, reviewStopMode })+ : { lines: (leavePrOpen || policyLeavesOpen) && willOpenPR ? [LEAVE_PR_OPEN_STEP(3, leavePrOpen)] : [], nextStep: (leavePrOpen || policyLeavesOpen) && willOpenPR ? 4 : 3 };+ const sentinelStep = merge.nextStep;++ return [+ '## Completion Workflow',+ 'When the task is complete, run these in order:',+ '',+ simplifyStep,+ `2. \`${cmd}${reviewerArg}\`${reviewSuffix}`,+ ...(effortNote ? [` ${effortNote}`] : []),+ ...merge.lines,+ ...buildSentinelWriteSteps(sentinelStep, sentinelPath, sentinelTail)+ ].join('\n');+}++/**+ * Which numbered step of the manual completion workflow the inline review-loop /+ * merge-gate section is. The manual workflow always emits step 1 (simplify, or+ * an explicit "disabled — skip" placeholder) and step 2 (commit) before the PR+ * steps, so the number is stable and the two sections can cross-reference each+ * other without threading a counter between them.+ */++/** 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+ * there is no ref to render. Branch names are usually PortOS's own, but a+ * JIRA-derived one is external input and this text is pasted straight into an+ * agent's terminal — so it goes through `shellQuote`, which leaves a bare-safe+ * ref readable and single-quotes anything else into inertness.+ */+function promptRef(ref, fallback) {+ return (typeof ref === 'string' && ref) ? shellQuote(ref) : fallback;+}++/**+ * The push + open-a-PR steps of the manual (slashdo-free) completion workflow.+ *+ * `$PR_URL` / `$PR_NUMBER` are captured into shell variables here because the+ * inline review-loop and merge-gate sections address the PR by those names —+ * they are rendered before the PR exists, so a literal URL is impossible.+ */+function buildManualPrCreateStep(step, { branchName, baseBranch, forgeCli = 'gh' }) {+ const branch = promptRef(branchName, '<branch>');+ const base = promptRef(baseBranch, '<base-branch>');+ const gitlab = forgeCli === 'glab';+ return [+ `${step}. Push the branch and open the pull request yourself, capturing its URL and number — the section below addresses the PR by these shell variables:`,+ '',+ ' ```bash',+ ` git push -u origin ${branch}`,+ gitlab+ ? ` PR_URL=$(glab mr create --source-branch ${branch} --target-branch ${base} --title "<conventional title>" --description "<description>" | grep -Eo 'https?://[^[:space:]]+' | tail -n 1)`+ : ` PR_URL=$(gh pr create --base ${base} --head ${branch} --title "<conventional title>" --body "<description>")`,+ gitlab+ ? ' PR_NUMBER=$(glab mr view "$PR_URL" --output json | jq -r .iid)'+ : ' PR_NUMBER=$(gh pr view "$PR_URL" --json number -q .number)',+ ' ```',+ // `--fill` on a one-line commit produces an empty description; PortOS used+ // to generate the body server-side, so spell out what it must contain now+ // that the agent writes it.+ gitlab+ ? ' Write a real `--description`: a **Summary** section and a **Test plan** section, with no AI-attribution footer. If `glab` reports the merge request already exists, adopt its URL and IID before continuing.'+ : ' Write a real `--body`: a **Summary** section and a **Test plan** section, no AI-attribution footer. Do NOT use `--fill`. If `gh` reports the pull request already exists, adopt it instead of failing: `PR_URL=$(gh pr view --json url -q .url)`.',+ gitlab+ ? ' The GitLab MR URL and IID are captured in `$PR_URL` and `$PR_NUMBER`; use those variables for every review, merge, and verification command below.'+ : ` On a GitLab remote use \`glab mr create --source-branch ${branch} --target-branch ${base} --title "…" --description "…"\` and read the MR URL/IID back with \`glab mr view\`.`,+ ];+}++/**+ * Manual (slashdo-free) completion-workflow block — every provider that can't+ * type `/do:pr` (codex, grok/agy, OpenCode, a lean `--bare` Claude session).+ *+ * When `ownsPrWorkflow` is set the agent drives the WHOLE lifecycle in one+ * session: commit → push → open the PR → run the inline review loop → merge.+ * That is the point of the flag — see `agentOwnsPrWorkflow`. Not typing a slash+ * command never meant "can't run `gh`", but this block used to conclude exactly+ * that, so every agy/grok/codex task ended in a commit and PortOS bought a+ * second cold agent (`sys-rl-*`) just to review and land the PR.+ *+ * `ownsPrWorkflow: false` (lean mode) keeps the original handoff: commit and+ * stop, PortOS owns the post-exit push / PR / review / merge lifecycle.+ */+function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, simplifyEnabled, sentinelPath, branchName = null, baseBranch = null, leavePrOpen = false, ownsPrWorkflow = false, forgeCli = 'gh' }) {+ const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;+ const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;+ // `ownsPrWorkflow` already folds in `willOpenPR`, the worktree, and the+ // leave-open exclusions — it is `inlinePrLifecycleSection() !== null` (see the+ // caller). Re-testing any of them here is how the two drifted apart before.+ const drivesOwnPr = ownsPrWorkflow;+ const simplifyStep = simplifyEnabled+ ? `1. Before committing, ${SIMPLIFY_INLINE_REVIEW} and fix any findings.`+ : '1. (simplify disabled — skip)';+ const sentinelTail = drivesOwnPr ? ' ## PR\n <PR URL>' : ' ## Branch\n <branch name>';++ const lines = [+ '## Completion Workflow',+ drivesOwnPr+ ? `This provider does NOT have slashdo (\`/do:*\`) commands, so drive the handoff with plain \`git\` and \`${forgeCli}\`. **You own this ${forgeCli === 'glab' ? 'MR' : 'PR'} end to end — nothing else will open, review, or merge it.** Run these in order:`+ : 'This provider does NOT have slashdo (`/do:*`) commands, so finish the handoff with plain `git`. Run these in order:',+ '',+ simplifyStep,+ '2. Stage only the files you changed (never `git add -A` / `git add .`) and commit with a conventional message (`feat:`/`fix:`/`breaking:` prefix, no Co-Authored-By annotations):',+ '',+ ' ```bash',+ ' git add <file> [<file> ...]',+ ' git commit -m "feat: <description>"',+ ' ```',+ ];++ let step = 3;+ if (drivesOwnPr) {+ lines.push(...buildManualPrCreateStep(step++, { branchName, baseBranch, forgeCli }));+ lines.push(`${step++}. Work through the **${runsReviewLoop ? 'Review Loop' : 'Merge Gate'}** section below in full — it ends by merging the PR. Come back here when it is done.`);+ } else if (willOpenPR) {+ const handoff = policyLeavesOpen+ ? 'PortOS will push the branch, create a pull request with your completion summary as its description, and leave it open for inspection.'+ : leavePrOpen+ ? 'PortOS will push the branch and create a pull request for the JIRA-linked human handoff.'+ : runsReviewLoop+ ? 'PortOS will push the branch, create a pull request with your completion summary as its description, run the configured reviewer follow-up, and merge only after review and CI pass.'+ : 'PortOS will push the branch, create a pull request with your completion summary as its description, and merge it once CI is green.';+ lines.push(`${step++}. Do NOT push, open, or merge a pull request yourself. ${handoff}`);+ } else {+ lines.push(`${step++}. Do NOT push this worktree branch yourself. PortOS will merge it back after completion.`);+ }++ lines.push(...buildSentinelWriteSteps(step, sentinelPath, sentinelTail));++ return lines.join('\n');+}++/**+ * Which inline PR-lifecycle section — if any — a run gets after its manual+ * completion workflow: `'review-loop'`, `'merge-gate'` (no reviewer configured,+ * so CI is the whole gate), or `null`.+ *+ * ONE definition, used by both the prompt assembly that renders the section and+ * the `buildAgentPrompt` preload that decides whether to read + stage the ~56KB+ * CLI-reviewer recipe for it. They were two conditions at opposite ends of the+ * file, and the loose one paid for a 56KB read and an `atomicWrite` on every+ * read-only / leave-open / merge-gate run whose section never rendered — while+ * the strict one restated four branches of the completion if/else chain by hand,+ * 130 lines away from the chain it mirrored.+ *+ * @returns {'review-loop'|'merge-gate'|null}+ */+export function inlinePrLifecycleSection(task, { providerType, providerId, providerCommand, leanMode, worktreeInfo, isTruthyMetaFn = isTruthyMetaDefault }) {+ if (!LIGHT_CONTEXT_PROVIDER_TYPES.has(providerType)) return null;+ if (!agentOwnsPrWorkflow({ providerType, leanMode })) return null;+ // A slashdo-capable session drives all of this through `/do:pr` instead.+ if (canTypeSlashCommands({ providerId, providerCommand, leanMode })) return null;+ // No worktree ⇒ no branch to name in `git push -u origin <branch>`, and the+ // one production shape here is a JIRA-ticket run (agentWorkspacePrep skips+ // worktree creation when a jiraBranch is set). Its PR is PortOS's to open and+ // a human's to land; telling the agent to open one too yields a PR opened+ // against a branch it had to guess at, and then a second `gh pr create` from+ // cleanup that fails "a pull request already exists".+ if (!worktreeInfo) return null;++ const metadata = task?.metadata || {};+ if (!isTruthyMetaFn(metadata.openPR)) return null;+ // The completion branches that hand back a contract which never opens a PR.+ if (isTruthyMetaFn(metadata.noCodeOutput) || metadata.creativeDirector) return null;+ if (isTruthyMetaFn(metadata.discardWorktree)) return null;+ if (isTruthyMetaFn(metadata.readOnly)) return null;+ if (isTruthyMetaFn(metadata.reviewLoopFollowUp)) return null;+ // A PR a human lands gets neither a review loop nor a merge gate.+ const prCompletion = resolvePrCompletion(metadata);+ if (prCompletion === PR_COMPLETIONS.LEAVE_OPEN || leavesPrForHuman(task)) return null;++ return prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE ? 'review-loop' : 'merge-gate';+}++/**+ * The inline review-loop (or, with no reviewer configured, merge-gate) section+ * for an agent that opened its own PR under the manual completion workflow.+ *+ * Deliberately the SAME builder the `sys-rl-*` follow-up agent gets, driven off+ * a synthesized `reviewLoop*` metadata shape: the procedure a follow-up runs and+ * the procedure an inline run needs are the same procedure, and the whole+ * regression this fixes came from having two of them. The PR coordinates are the+ * shell variables `buildManualPrCreateStep` captured, because the section is+ * rendered before the PR exists.+ */+export function buildInlineReviewLoopSection({+ taskId, branchName, runsReviewLoop, leaveOpen, localAgentLoopBody, localAgentLoopBodyPath = null, writesSentinel = false,+ reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies, forgeCli = 'gh',+}) {+ // Where control goes after the merge. A TUI run still owes PortOS its+ // `.agent-done` sentinel — telling it to "exit" here is how a finished merge+ // can otherwise sit without recording completion — while a CLI run signals completion by exiting.+ const inlineExitStep = writesSentinel+ ? 'Return to the **Completion Workflow** above and write the completion sentinel — the run is not done until you have. Do NOT open a second PR.'+ : 'You are done — exit. Do NOT open a second PR or push anything further.';+ return buildReviewLoopFollowUpSection({+ reviewLoopPRUrl: '$PR_URL',+ reviewLoopPRNumber: '$PR_NUMBER',+ reviewLoopPRBranch: branchName || '<branch>',+ reviewLoopReviewers: reviewers,+ reviewLoopReviewerUsernames: usernames,+ reviewLoopOptionalReviewers: optionalReviewers,+ reviewLoopReviewerMaxRounds: reviewerMaxRounds,+ reviewLoopReviewerModels: reviewerModels,+ reviewLoopReviewerEfforts: reviewerEfforts,+ reviewLoopStopMode: reviewStopMode,+ reviewLoopReviewerApplies: reviewerApplies,+ reviewLoopLeaveOpen: leaveOpen,+ // No reviewer configured ⇒ the merge-gate variant (CI is the whole gate),+ // exactly as the merge-only follow-up gets.+ reviewLoopMergeOnly: !runsReviewLoop,+ sourceTaskId: taskId || 'unknown',+ }, { verbose: false, localAgentLoopBody, localAgentLoopBodyPath, inlineExitStep, forgeCli });+}++/**+ * CLI (non-TUI) completion block.+ *+ * Claude Code CLI agents have slashdo commands available (the submodule+ * mounts them as project-level slash commands), so when `hasSlashdo` is+ * true and a PR is expected, the agent owns the full `/simplify` → `/do:pr`+ * sequence and PortOS skips its post-exit push+PR. Codex/Antigravity and other+ * CLI providers fall through to the legacy commit-only block where PortOS+ * handles push+PR on exit.+ */+export function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, hasSlashdo = false, ownsPrWorkflow = false, simplifyEnabled = false, leavePrOpen = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewerModels = {}, reviewerEfforts = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, forgeCli = 'gh' }) {+ const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;+ const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;+ if (hasSlashdo && worktreeInfo && willOpenPR) {+ const lines = ['## Completion', 'When finished, run these in order:'];+ let step = 1;+ if (simplifyEnabled) {+ lines.push(`${step++}. \`/simplify\` — review the changed code for reuse, quality, and efficiency, and fix any findings.`);+ }+ const { reviewUsernames, reviewArgs, effortNote } = resolveReviewInvocation({ willOpenPR, runsReviewLoop, reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies });+ // `--no-merge` overrides a saved slashdo `merge: true` default, which would+ // otherwise merge a PR this task must leave open (see lib/prDisposition.js).+ const reviewerArg = (reviewArgs ? ` ${reviewArgs}` : '') + ((leavePrOpen || policyLeavesOpen) ? ' --no-merge' : '');+ const completionNote = runsReviewLoop+ ? ((reviewers.length === 1 && reviewers[0] === DEFAULT_REVIEWER && reviewUsernames.length === 0)+ ? 'and drives the Copilot review loop until clean.'+ : `and drives the review loop for ${[...reviewers, ...reviewUsernames.map(u => `@${u}`)].join(', ')} in order until clean.`)+ : 'with external review disabled.';+ lines.push(`${step++}. \`/do:pr${reviewerArg}\` — commits your changes, pushes the branch, and opens a pull request against the default branch ${completionNote}`);+ // Empty whenever the emitted `--review-with` already carries `~effort=<level>`+ // (see buildReviewerEffortNote) — this speaks only for an unpinned invocation.+ if (effortNote) lines.push(` ${effortNote}`);+ // Merge steps follow — review-gated with a loop, CI-gated without one — unless+ // this PR is a human's to land (JIRA-tracked; see lib/prDisposition.js).+ if (leavePrOpen || policyLeavesOpen) {+ lines.push(LEAVE_PR_OPEN_STEP(step, leavePrOpen));+ } else {+ const merge = buildPostPRMergeSteps(step, { prCompletion, reviewers, usernames: reviewUsernames, reviewStopMode });+ lines.push(...merge.lines);+ }+ return lines.join('\n');+ }+ if (hasSlashdo && worktreeInfo) {+ const lines = ['## Completion', 'When finished, run these in order:'];+ let step = 1;+ if (simplifyEnabled) {+ lines.push(`${step++}. \`/simplify\` — review the changed code for reuse, quality, and efficiency, and fix any findings.`);+ }+ lines.push(`${step++}. \`/do:push\` — commits your changes and pushes the branch.`);+ return lines.join('\n');+ }+ // Non-slashdo CLI that IS a real coding harness (codex, grok/agy, OpenCode):+ // it can't type `/do:pr`, but it can run `git push` / `gh pr create` and drive+ // the reviewer CLIs — so it owns the same end-to-end lifecycle the TUI manual+ // path does, with the reviewer procedure inlined in the section that follows.+ // `ownsPrWorkflow` already folds in `willOpenPR`, the worktree, and the+ // leave-open exclusions (it is `inlinePrLifecycleSection() !== null`).+ if (ownsPrWorkflow) {+ const lines = ['## Completion', '**You own this PR end to end — nothing else will open, review, or merge it.** When finished, run these in order:'];+ let step = 1;+ lines.push(simplifyEnabled+ ? `${step++}. Before committing, ${SIMPLIFY_INLINE_REVIEW} and fix any findings.`+ : `${step++}. (simplify disabled — skip)`);+ lines.push(`${step++}. Stage only the files you changed (never \`git add -A\` / \`git add .\`) and commit with a conventional message (\`feat:\`/\`fix:\`/\`breaking:\` prefix, no Co-Authored-By annotations).`);+ lines.push(...buildManualPrCreateStep(step++, {+ branchName: worktreeInfo?.branchName || null,+ baseBranch: worktreeInfo?.baseBranch || null,+ forgeCli,+ }));+ lines.push(`${step}. Work through the **${runsReviewLoop ? 'Review Loop' : 'Merge Gate'}** section below in full — it ends by merging the PR.`);+ return lines.join('\n');+ }+ let body;+ if (worktreeInfo && willOpenPR) {+ body = 'Commit your changes (stage specific files, `feat:`/`fix:` prefix, no Co-Authored-By). Do NOT push — PortOS will push and open the PR after you exit.';+ } else if (worktreeInfo) {+ body = 'Commit your changes to this branch. PortOS will merge it back when the task completes.';+ } else {+ body = 'Commit and push your changes (`git pull --rebase && git push`, conventional commit prefix, no `git add -A`).';+ }+ // Non-slashdo CLIs (codex/antigravity) have no `/simplify` command; when the task+ // enabled simplify, inline the equivalent self-review so the quality pass still+ // runs before they commit.+ const simplifyLine = simplifyEnabled+ ? `Before committing, ${SIMPLIFY_INLINE_REVIEW} and fix any findings. `+ : '';+ return `## Completion\n${simplifyLine}${body}`;+}diff --git a/server/services/promptSections/constants.js b/server/services/promptSections/constants.jsnew file mode 100644index 0000000000..e58e492513--- /dev/null+++ b/server/services/promptSections/constants.js@@ -0,0 +1,11 @@+/**+ * Prompt-section constants shared by the full and light orchestrators.+ */++import { PROVIDER_TYPES } from '../../lib/aiToolkit/constants.js';++export const LIGHT_CONTEXT_PROVIDER_TYPES = new Set([PROVIDER_TYPES.TUI, PROVIDER_TYPES.CLI]);++export const SIMPLIFY_INLINE_REVIEW = 'review your changed code for reuse, quality, and efficiency (DRY, dead code, naming, simpler equivalents, missed edge cases)';++export const INLINE_REVIEW_LOOP_STEP = 4;diff --git a/server/services/promptSections/forge.js b/server/services/promptSections/forge.jsnew file mode 100644index 0000000000..59be211d82--- /dev/null+++ b/server/services/promptSections/forge.js@@ -0,0 +1,28 @@+/**+ * Forge selection helpers shared by prompt sections.+ */++import { forgeCliForTracker, resolveRepoForgeTarget } from '../../lib/workTracker.js';++export function normalizeForgeCli(value) {+ if (value === 'glab' || value === 'gitlab') return 'glab';+ if (value === 'gh' || value === 'github') return 'gh';+ return null;+}++export function manualForgeCli(forgeCli, worktreeInfo) {+ return normalizeForgeCli(forgeCli)+ || normalizeForgeCli(worktreeInfo?.forgeCli)+ || forgeCliForTracker(worktreeInfo?.forge)+ || 'gh';+}++export async function resolveManualForgeCli(workspaceDir, worktreeInfo, task) {+ const explicit = manualForgeCli(null, worktreeInfo);+ if (explicit !== 'gh') return explicit;+ const preferredForge = normalizeForgeCli(task?.metadata?.workTracker);+ const target = await resolveRepoForgeTarget(worktreeInfo?.worktreePath || workspaceDir, {+ preferredForge: preferredForge === 'glab' ? 'gitlab' : preferredForge === 'gh' ? 'github' : null,+ }).catch(() => null);+ return forgeCliForTracker(target?.forge) || explicit;+}diff --git a/server/services/promptSections/index.js b/server/services/promptSections/index.jsnew file mode 100644index 0000000000..eedc32de4e--- /dev/null+++ b/server/services/promptSections/index.js@@ -0,0 +1,8 @@+export * from './appContext.js';+export * from './completion.js';+export * from './constants.js';+export * from './forge.js';+export * from './instructions.js';+export * from './reviewLifecycle.js';+export * from './slashdo.js';+export * from './taskContext.js';diff --git a/server/services/promptSections/instructions.js b/server/services/promptSections/instructions.jsnew file mode 100644index 0000000000..ca7bacb08b--- /dev/null+++ b/server/services/promptSections/instructions.js@@ -0,0 +1,312 @@+/**+ * Skill-template routing and bounded AGENTS.md / CLAUDE.md discovery.+ */++import { join, basename } from 'path';+import { readdir } from 'fs/promises';+import { homedir } from 'os';+import { PATHS, tryReadFile } from '../../lib/fileUtils.js';+import { AGENT_INSTRUCTIONS_FILENAME, CLAUDE_BRIDGE_FILENAME } from '../../lib/agentInstructionsFile.js';++const SKILLS_DIR = join(PATHS.root, 'data/prompts/skills');++/**+ * Skill template keyword matchers.+ * Each entry maps a skill template filename to its trigger keywords.+ * Order matters — first match wins, so more specific patterns come first.+ */+const SKILL_MATCHERS = [+ {+ skill: 'data-safety',+ keywords: ['data-safety', 'upgrade-safety', 'schema parity', 'schemaversion', 'seed file', 'data.reference']+ },+ {+ skill: 'simplify',+ keywords: ['dead code', 'unused export', 'duplication', 'copy-paste', 'unreferenced']+ },+ {+ skill: 'security-audit',+ keywords: ['security', 'audit', 'vulnerability', 'xss', 'injection', 'owasp', 'cve', 'penetration', 'hardening', 'sanitize', 'authorization']+ },+ {+ skill: 'mobile-responsive',+ keywords: ['mobile', 'responsive', 'tablet', 'breakpoint', 'viewport', 'touch', 'swipe', 'small screen', 'media query', 'mobile-friendly', 'adaptive']+ },+ {+ skill: 'bug-fix',+ keywords: ['fix', 'bug', 'broken', 'error', 'crash', 'issue', 'not working', 'fails', 'regression', 'defect']+ },+ {+ skill: 'refactor',+ keywords: ['refactor', 'reorganize', 'restructure', 'clean up', 'simplify', 'extract', 'consolidate', 'decouple', 'modularize']+ },+ {+ skill: 'documentation',+ keywords: ['document', 'documentation', 'docs', 'readme', 'jsdoc', 'api docs', 'guide', 'tutorial', 'changelog']+ },+ {+ skill: 'feature',+ keywords: ['add', 'create', 'implement', 'build', 'new', 'feature', 'support', 'enable', 'integrate', 'endpoint', 'page', 'component']+ }+];++// Domain templates complement (rather than replace) the lifecycle template+// selected above. Keep this list narrow: broad graphics terms would add prompt+// weight to tasks that do not involve scene construction or rendering.+const DOMAIN_SKILL_MATCHERS = [+ {+ skill: 'threejs-visual',+ patterns: [+ /\bthree(?:\.?js)\b/,+ /\breact[-\s]?three[-\s]?fiber\b/,+ /\br3f\b/,+ /\bwebgl\s+scene\b/,+ ],+ },+];++/**+ * Detect the best matching skill template for a task based on description keywords.+ * @param {Object} task - Task object with description+ * @returns {string|null} Skill template name or null if no match+ */+export function detectSkillTemplate(task) {+ const desc = (task?.description || '').toLowerCase();+ for (const matcher of SKILL_MATCHERS) {+ if (matcher.keywords.some(kw => desc.includes(kw))) {+ return matcher.skill;+ }+ }+ return null;+}++/**+ * Detect one optional domain template to append after the primary lifecycle+ * template. Domain routing is deliberately independent so, for example, a+ * Three.js security audit keeps its security guidance.+ * @param {Object} task - Task object with description+ * @returns {string|null} Domain skill template name or null+ */+export function detectDomainSkillTemplate(task) {+ const desc = (task?.description || '').toLowerCase();+ for (const matcher of DOMAIN_SKILL_MATCHERS) {+ if (matcher.patterns.some((pattern) => pattern.test(desc))) {+ return matcher.skill;+ }+ }+ return null;+}++/**+ * Resolve the primary lifecycle template and at most one domain guide.+ * @param {Object} task - Task object with description+ * @returns {string[]} Ordered template names+ */+export function detectSkillTemplates(task) {+ return [detectSkillTemplate(task), detectDomainSkillTemplate(task)].filter(Boolean);+}++/**+ * Load a skill template from disk if it exists.+ * @param {string} skillName - Name of the skill template file (without .md)+ * @returns {Promise<string|null>} Template content or null+ */+export async function loadSkillTemplate(skillName) {+ const content = await tryReadFile(join(SKILLS_DIR, `${skillName}.md`));+ if (content) console.log(`🎯 Loaded skill template: ${skillName}`);+ return content;+}++/**+ * Load ordered templates as one prompt section, retaining the primary guidance+ * even when an optional domain template is unavailable on an older install.+ * @param {string[]} skillNames - Ordered skill template names+ * @param {(skillName: string) => Promise<string|null>} loadTemplate - Loader seam for tests+ * @returns {Promise<string|null>} Joined template content or null+ */+export async function loadSkillTemplates(skillNames, loadTemplate = loadSkillTemplate) {+ const templates = await Promise.all(skillNames.map((skillName) => (+ Promise.resolve(loadTemplate(skillName)).catch((err) => {+ console.log(`⚠️ Skill template load failed for ${skillName}: ${err.message}`);+ return null;+ })+ )));+ return templates.filter(Boolean).join('\n\n') || null;+}++// Nested agent-instruction discovery bounds (#3866). On-demand nested memory+// files are a Claude Code feature — an API-provider agent reads nothing+// natively, so PortOS has to splice them in itself or a subtree rule (including+// a data-loss guard) never reaches that class of agent. The walk is bounded on+// three axes so a repo that grows nested files can't silently balloon every+// agent prompt or turn one prompt build into a full-tree crawl.+const NESTED_AGENT_MD_MAX_DEPTH = 5;+const NESTED_AGENT_MD_MAX_FILES = 10;+const NESTED_AGENT_MD_MAX_DIRS = 2000;+// Dot-directories are skipped wholesale (covers `.git`), so these are the+// non-dot trees that are either vendored, generated, or runtime state. The list+// is deliberately polyglot: an agent workspace is any app PortOS manages, not+// just this repo, so a Rust `target/` or a Go `vendor/` would otherwise burn the+// directory budget on generated files.+const NESTED_AGENT_MD_SKIP_DIRS = new Set([+ 'node_modules', 'data', 'data.reference', 'dist', 'build', 'coverage',+ 'out', 'obj', 'bin', 'target', 'vendor', 'tmp', 'venv', 'Pods', '__pycache__',+]);++// Instruction filenames in preference order (#4852). `AGENTS.md` is the+// cross-vendor standard PortOS now ships; `CLAUDE.md` stays discoverable because+// a managed app may still carry only that name, and a plain rename would+// silently drop its context. A directory holding both contributes exactly ONE+// entry — otherwise this repo's four nested pairs would count as eight against+// NESTED_AGENT_MD_MAX_FILES and the budget would overflow without a signal.+const AGENT_INSTRUCTION_FILENAMES = [AGENT_INSTRUCTIONS_FILENAME, CLAUDE_BRIDGE_FILENAME];++/**+ * True for a bridge `CLAUDE.md` whose entire body is an `@AGENTS.md` import —+ * how PortOS and its scaffolders keep Claude Code (which has no configurable+ * memory filename) reading the shared file. It carries no content of its own, so+ * splicing it would add a useless one-line section to every agent prompt and+ * burn a slot against the file cap.+ * @param {string} content+ */+const isImportOnlyInstructionFile = (content) => {+ const lines = String(content)+ .replace(/<!--[\s\S]*?-->/g, '')+ .split('\n')+ .map((line) => line.trim())+ .filter(Boolean);+ if (lines.length === 0) return false;+ if (!lines.every((line) => /^@\S+$/.test(line))) return false;+ return lines.some((line) => basename(line.slice(1)).toLowerCase() === 'agents.md');+};++/**+ * Read one instruction file, collapsing "absent", "empty", and "import-only+ * bridge" to the same null so callers can fall through to the next candidate.+ * @param {string} path+ * @returns {Promise<string|null>} trimmed content, or null+ */+const readInstructionFile = async (path) => {+ const content = await tryReadFile(path);+ if (!content?.trim()) return null;+ if (basename(path) === CLAUDE_BRIDGE_FILENAME && isImportOnlyInstructionFile(content)) return null;+ return content.trim();+};++/**+ * Collect nested per-directory instruction files (the workspace root is excluded+ * — its caller reads it separately and must keep it first). Depth-first in+ * lexicographic order, so the result is deterministic and prompt caching stays+ * stable across builds.+ * @param {string} workspaceDir+ * @returns {Promise<Array<{ rel: string, content: string }>>} e.g. `[{ rel: 'server/AGENTS.md', … }]`+ */+async function findNestedAgentInstructionFiles(workspaceDir) {+ const found = [];+ let dirsVisited = 0;++ const walk = async (dir, relDir, depth) => {+ if (found.length >= NESTED_AGENT_MD_MAX_FILES) return;+ if (depth > NESTED_AGENT_MD_MAX_DEPTH) return;+ if (dirsVisited >= NESTED_AGENT_MD_MAX_DIRS) return;+ dirsVisited += 1;++ const entries = await readdir(dir, { withFileTypes: true }).catch(() => null);+ if (!entries) return;+ // A nested directory carrying its own `.git` is a submodule or vendored+ // checkout (`lib/slashdo` here) — its instructions are that project's, not+ // this workspace's. Detected structurally rather than by an allowlist of+ // paths, which would silently stop matching the moment the workspace root is+ // something other than this repo's root.+ if (depth > 0 && entries.some((entry) => entry.name === '.git')) return;+ const sorted = [...entries].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));++ const subdirs = [];+ const instructionNames = new Set();+ for (const entry of sorted) {+ const rel = relDir ? `${relDir}/${entry.name}` : entry.name;+ if (entry.isDirectory()) {+ if (entry.name.startsWith('.')) continue;+ if (NESTED_AGENT_MD_SKIP_DIRS.has(entry.name)) continue;+ subdirs.push({ path: join(dir, entry.name), rel });+ // Symlinked directories are deliberately NOT followed — a link back up+ // the tree would loop, and the depth cap alone wouldn't make the result+ // meaningful. A symlinked instruction *file* is still read (below).+ } else if (AGENT_INSTRUCTION_FILENAMES.includes(entry.name)) {+ instructionNames.add(entry.name);+ }+ }++ // One entry per directory. Content is read here rather than by the caller so+ // an import-only bridge can be dropped before it consumes a slot against the+ // file cap — filtering after the walk would let a directory of bridges push+ // real instructions out of the budget.+ if (relDir) {+ for (const name of AGENT_INSTRUCTION_FILENAMES) {+ if (!instructionNames.has(name)) continue;+ const content = await readInstructionFile(join(dir, name));+ if (!content) continue;+ found.push({ rel: `${relDir}/${name}`, content });+ break;+ }+ if (found.length >= NESTED_AGENT_MD_MAX_FILES) return;+ }++ for (const sub of subdirs) {+ if (found.length >= NESTED_AGENT_MD_MAX_FILES) return;+ await walk(sub.path, sub.rel, depth + 1);+ }+ };++ await walk(workspaceDir, '', 0);+ return found;+}++/**+ * Read agent-instruction files for agent context.+ * Reads the global (`~/.claude/CLAUDE.md`), the workspace-root `AGENTS.md` (or+ * `CLAUDE.md`), and every nested instruction file under the workspace (#3866) —+ * nested last, each as its own labeled section, so precedence still reads+ * root-then-specific.+ */+export async function getAgentInstructionsContext(workspaceDir) {+ const contexts = [];++ // Claude Code's own global memory location — a user-level path, not a repo+ // convention, so it keeps the CLAUDE.md name (#4852).+ const globalPath = join(homedir(), '.claude', 'CLAUDE.md');+ const globalContent = await tryReadFile(globalPath);+ if (globalContent?.trim()) {+ contexts.push({ type: 'Global Instructions', path: globalPath, content: globalContent.trim() });+ }++ // Workspace-root instructions, `AGENTS.md` preferred.+ for (const name of AGENT_INSTRUCTION_FILENAMES) {+ const projectPath = join(workspaceDir, name);+ const projectContent = await readInstructionFile(projectPath);+ if (projectContent) {+ contexts.push({ type: 'Project Instructions', path: projectPath, content: projectContent });+ break;+ }+ }++ // Nested per-directory instructions, appended after the root file.+ for (const { rel, content } of await findNestedAgentInstructionFiles(workspaceDir)) {+ contexts.push({ type: `Project Instructions (${rel})`, path: join(workspaceDir, rel), content });+ }++ if (contexts.length === 0) {+ return null;+ }++ let section = '## Agent Instructions\n\n';+ section += 'The following instructions must be followed when working on this task:\n\n';++ for (const ctx of contexts) {+ section += `### ${ctx.type}\n`;+ section += `Source: \`${ctx.path}\`\n\n`;+ section += ctx.content + '\n\n';+ }++ return section;+}diff --git a/server/services/promptSections/reviewLifecycle.js b/server/services/promptSections/reviewLifecycle.jsnew file mode 100644index 0000000000..aa62ce121d--- /dev/null+++ b/server/services/promptSections/reviewLifecycle.js@@ -0,0 +1,605 @@+/**+ * Review-loop, CI-gate, and merge prompt sections.+ */++import { DEFAULT_REVIEWER, DEFAULT_REVIEW_STOP_MODE, LOCAL_LLM_REVIEWERS, MODEL_CAPABLE_CLI_REVIEWERS, describeReviewerCli, isCliReviewer, reviewerCliBinary, normalizeReviewUsernames, normalizeOptionalReviewers, normalizeReviewerMaxRounds, reviewerEffortArgs, reviewerModelArg, resolveKeyedReviewers, buildReviewWithArgs } from '../../lib/validation.js';+import { oversizedBodyPointer } from '../../lib/slashdoInvocation.js';+import { detectForgeCli } from '../../lib/gitForge.js';+import { INLINE_REVIEW_LOOP_STEP } from './constants.js';+import { normalizeForgeCli } from './forge.js';++/**+ * True when a follow-up task is a **merge-only** run: it has a PR to land but no+ * reviewer to run (Review Loop off, or every configured reviewer was stripped —+ * e.g. copilot on a GitLab MR). Tolerates the string `'true'` because task+ * metadata round-trips through JSON/forms like every other CoS flag.+ *+ * Used both to pick the prompt section and to skip preloading the reviewer-only+ * slashdo bodies (`/do:rpr`, the local-agent review loop) that section ignores.+ */+export function isMergeOnlyFollowUp(metadata = {}) {+ return metadata?.reviewLoopMergeOnly === true || metadata?.reviewLoopMergeOnly === 'true';+}++/**+ * Build the **review-loop follow-up** section — the instructions for the+ * agent spawned by `spawnReviewLoopFollowUp` to drive Copilot's review-and-fix+ * loop until the PR merges. Same 7-step procedure, same merge command, same+ * MERGED-state verification, same 10-iteration cap in BOTH the light and full+ * paths — extracted so the two can't drift independently.+ *+ * I/O (the slashdo `/do:rpr` body) is intentionally pulled outside this helper+ * and threaded in via `rprBody` so the function stays pure and synchronous.+ *+ * @param {Object} metadata - task.metadata (reviewLoopPR* fields, sourceTaskId)+ * @param {Object} [opts]+ * @param {boolean} [opts.verbose=false] - When true, emit the verbose prose+ * variant the full (api) path uses, with PR Details list and an inlined+ * `/do:rpr` reference. When false, emit the compact list the light path uses.+ * @param {string|null} [opts.rprBody=null] - The loaded `/do:rpr` slashdo body.+ * Only appended in verbose mode; ignored in compact mode.+ * @param {string|null} [opts.localAgentLoopBody=null] - The loaded slashdo+ * `lib/local-agent-review-loop.md` body (conditionals resolved to the+ * subprocess/`else` branch). Inlined when a spawnable CLI reviewer+ * (codex/antigravity/claude/grok) is in the list so the agent gets the exact+ * headless invocation and review-only contract instead of improvising it.+ * @param {string|null} [opts.localAgentLoopBodyPath=null] - Path to a staged copy+ * of that body. When set and the body is over `SLASHDO_INLINE_BUDGET_CHARS`,+ * the section points at the file instead of pasting it. Only the inline caller+ * passes this; a follow-up agent, whose whole job is the loop, still inlines.+ * @param {boolean} [opts.inline=false] - Emit the SAME loop for an agent that+ * opened the PR itself moments ago, rather than for a follow-up agent handed+ * someone else's PR (`buildInlineReviewLoopSection`). Only the framing differs:+ * the heading and opening sentence, and the fact that nothing pre-requested a+ * Copilot review. The loop body, notes, merge command, and MERGED verification+ * stay byte-identical so the two callers can't drift.+ * @returns {string}+ */+export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false, rprBody = null, localAgentLoopBody = null, localAgentLoopBodyPath = null, inlineExitStep = null, forgeCli = null } = {}) {+ // One parameter, not two: an `inline` boolean alongside it could disagree with+ // it, and the disagreement renders silently — `inline` with a blank exit step+ // emits a bare "6." and a truncated merge-gate hand-back.+ const inline = inlineExitStep !== null;+ const prUrl = metadata.reviewLoopPRUrl || '';+ const prBranch = metadata.reviewLoopPRBranch || '';+ const prNumber = metadata.reviewLoopPRNumber ?? '';+ const prOwner = metadata.reviewLoopPROwner ?? '';+ const prRepo = metadata.reviewLoopPRRepo ?? '';+ const sourceTaskId = metadata.sourceTaskId || 'unknown';+ const reviewForgeCli = normalizeForgeCli(forgeCli)+ || (detectForgeCli(metadata.reviewLoopPRHost) === 'glab' ? 'glab' : 'gh');+ // Merge-only follow-up (Review Loop off): no reviewer to wait on or invoke —+ // the whole job is CI-gate → fix → merge. Branch before any reviewer defaulting+ // below, which would otherwise resolve the empty list back to `[copilot]`.+ if (isMergeOnlyFollowUp(metadata)) {+ return buildMergeFollowUpSection({+ prUrl, prBranch, prNumber, prOwner, prRepo, sourceTaskId, verbose, inlineExitStep,+ prHost: metadata.reviewLoopPRHost ?? '',+ forgeCli: reviewForgeCli,+ });+ }+ // Arbitrary GitHub reviewer usernames (gate-only PR reviewers), appended to+ // the review flow after the keyed reviewers.+ const usernames = normalizeReviewUsernames(metadata.reviewLoopReviewerUsernames);+ // Ordered keyed reviewer list (back-compat: legacy single `reviewLoopReviewer`).+ // `reviewLoopReviewers` from spawnReviewLoopFollowUp is authoritative (copilot+ // already stripped on non-GitHub forges); resolveKeyedReviewers keeps an+ // explicit empty list empty when usernames carry the review (username-only).+ const reviewerSource = Array.isArray(metadata.reviewLoopReviewers)+ ? metadata.reviewLoopReviewers+ : (metadata.reviewLoopReviewer ? [metadata.reviewLoopReviewer] : undefined);+ const reviewers = resolveKeyedReviewers(reviewerSource, usernames.length > 0);+ // Reviewer identities marked non-blocking — emitted with slashdo's `~opt`.+ const optionalReviewers = normalizeOptionalReviewers(metadata.reviewLoopOptionalReviewers) || [];+ // Per-reviewer `~max=<n>` iteration caps, keyed by emitted token. An absent key+ // leaves slashdo's built-in per-loop default; `0` means "loop until clean".+ const reviewerMaxRounds = normalizeReviewerMaxRounds(metadata.reviewLoopReviewerMaxRounds) || {};+ const stopMode = metadata.reviewLoopStopMode || DEFAULT_REVIEW_STOP_MODE;+ const reviewerApplies = metadata.reviewLoopReviewerApplies === true;+ const hasCopilot = reviewers.includes(DEFAULT_REVIEWER);+ const hasLocalLlm = reviewers.some(r => LOCAL_LLM_REVIEWERS.includes(r));+ // Spawnable-CLI reviewers, in configured order.+ const cliReviewers = reviewers.filter(isCliReviewer);+ const hasCli = cliReviewers.length > 0;+ const hasGithubUser = usernames.length > 0;+ // Optional per-reviewer model pins (Code Review Defaults panel, or the task's own+ // ReviewerPicker row), threaded as a reviewer-keyed map. A model-capable CLI+ // reviewer in this loop's list gets a `<reviewer> --model <id>` note; a local-LLM+ // reviewer's pin goes into its `/api/code-review/local` request body instead+ // (below). Absent = let that reviewer use its own default. For an Ollama-backed+ // `claude` reviewer the id is the local Ollama model. Falls back to the legacy+ // codex-scalar metadata key so a follow-up task persisted by an older install+ // still threads its codex model.+ const reviewerModelMap = (metadata.reviewLoopReviewerModels && typeof metadata.reviewLoopReviewerModels === 'object')+ ? metadata.reviewLoopReviewerModels+ : (typeof metadata.reviewLoopCodexModel === 'string' && metadata.reviewLoopCodexModel+ ? { codex: metadata.reviewLoopCodexModel }+ : {});+ // Optional per-reviewer reasoning-effort pins, same two sources as the models.+ // A CLI reviewer's effort becomes a flag on the command line the agent runs+ // (`--effort high` for claude/agy, `-c model_reasoning_effort=high` for codex —+ // `reviewerEffortArgs` owns that shape, and returns nothing for cursor, whose+ // level is folded into `--model` by `reviewerModelArg`); a local-LLM reviewer's becomes the+ // `reasoning_effort` field of its `/api/code-review/local` body (below). There is+ // no slashdo `--review-with` suffix for effort, which is why it rides the+ // invocation rather than `equivArgs`.+ const reviewerEffortMap = (metadata.reviewLoopReviewerEfforts && typeof metadata.reviewLoopReviewerEfforts === 'object')+ ? metadata.reviewLoopReviewerEfforts+ : {};+ // One entry per CLI reviewer carrying a pinned model and/or effort, rendered as+ // the literal command line the agent must run. Reviewers are listed rather than+ // filtered to MODEL_CAPABLE_CLI_REVIEWERS up front because a CLI reviewer may+ // carry only one of the two pins (and `grok` carries neither). The per-flag+ // gates below decide what each entry renders; an entry with no flags drops out.+ const reviewerPinEntries = cliReviewers+ .map((r) => {+ const flags = [];+ // Thread each configured model id VERBATIM. We deliberately don't env-map it+ // here (e.g. bare Claude tier → Bedrock form): this is a text-template layer+ // with only a providerId, not the merged spawn env (process.env + settings.json+ // + provider.envVars) the CLI argv builder normalizes against — and the nested+ // reviewer CLI is spawned by the agent, not PortOS, so the argv chokepoint never+ // runs. The Code Review Defaults model field is free-text for exactly this+ // reason: the user configures the id their environment needs (a Bedrock-form id+ // on a Bedrock box, an installed Ollama model for an Ollama-backed `claude`).+ if (MODEL_CAPABLE_CLI_REVIEWERS.includes(r) && typeof reviewerModelMap[r] === 'string' && reviewerModelMap[r]) {+ // `reviewerModelArg` (not the raw id) because cursor carries its+ // reasoning effort INSIDE the model id — `gpt-5[effort=max]` — so the+ // pinned pair must render as ONE `--model`, never a `--effort` cursor+ // rejects. Every other reviewer gets the id back verbatim.+ flags.push(`--model ${reviewerModelArg(r, reviewerModelMap[r], reviewerEffortMap[r])}`);+ }+ const effortArgs = reviewerEffortArgs(r, reviewerEffortMap[r]);+ if (effortArgs.length) flags.push(effortArgs.join(' '));+ // Binary, not slug: this renders a literal command line, and the+ // `antigravity` slug names no executable.+ return flags.length ? `\`${reviewerCliBinary(r) || r} ${flags.join(' ')} …\`` : null;+ })+ .filter(Boolean);+ const reviewerPinNote = reviewerPinEntries.length+ ? ` When invoking a reviewer with a pinned model or reasoning effort, pass it: ${reviewerPinEntries.join(', ')}.`+ : '';+ // When the slashdo local-agent review loop is inlined below (a spawnable CLI+ // reviewer is in the list), point the invocation step at it so the agent runs+ // the exact headless recipe instead of probing the CLI's flags / hand-rolling+ // an invocation — the failure mode that had a codex CoS agent burn a dozen+ // exploratory `claude --help` / `claude -p 'hello'` / `--tools ''` probes+ // before it stumbled into a working review call.+ const cliProcedurePointer = (hasCli && localAgentLoopBody)+ ? ' Follow the **CLI Reviewer Procedure** section below for the exact headless invocation and review-only contract — do NOT probe the CLI or guess flags.'+ : '';+ // Each configured CLI reviewer paired with the command the agent must actually+ // run. Resolved ONCE — the slug-vs-binary distinction is the whole point of+ // this block, so every string below reads it from here rather than restating+ // the `|| slug` fallback. Unmapped slug ⇒ falls back to itself.+ const cliBinaries = cliReviewers.map(slug => ({ slug, binary: reviewerCliBinary(slug) || slug }));+ // `**codex / agy / claude**` — the CLI reviewers THIS loop configured, named by+ // the binary. Previously a fixed "codex / antigravity / claude / grok" string,+ // which both listed reviewers that weren't configured and named `antigravity`,+ // a command that exists on no PATH.+ const cliReviewerHeading = cliBinaries.map(c => c.binary).join(' / ');+ // Spell out slug → binary for any reviewer whose command differs from its+ // slug, so the agent can reconcile the configured list / `--review-with` token+ // with the executable named in the invocation table.+ const cliBinaryAliases = cliBinaries+ .filter(c => c.binary !== c.slug)+ .map(c => `the \`${c.slug}\` reviewer runs the \`${c.binary}\` binary (there is no \`${c.slug}\` command)`);+ const cliBinaryNote = cliBinaryAliases.length+ ? ` Reviewer slug → command: ${cliBinaryAliases.join('; ')}.`+ : '';+ // A configured reviewer that cannot run is NOT a clean review. Without this,+ // an agent whose reviewer binary was missing self-reviewed and merged anyway+ // — the exact regression this note blocks.+ const missingCliNote = hasCli+ ? `**Missing reviewer CLI:** verify each reviewer's binary is on PATH (${cliBinaries.map(c => `\`command -v ${c.binary}\``).join(' / ')}) before concluding it is unavailable. If a configured reviewer's binary genuinely is not installed, that reviewer is UNSATISFIED — do NOT substitute your own self-review and do NOT merge. Post a PR comment naming the missing command and exit.`+ : '';+ // "multi" reflects the TOTAL number of review sources (keyed reviewers ++ // username reviewers) so the ordered per-reviewer loop wording kicks in as+ // soon as there's more than one thing to satisfy.+ const multi = (reviewers.length + usernames.length) > 1;+ // The system pre-requests the initial Copilot review only when copilot LEADS the+ // order; otherwise the agent must request it at copilot's turn (so Copilot reviews+ // the post-CLI-fix state, not a stale diff). An INLINE loop opened its own PR+ // moments ago and nothing pre-requested anything, so it always requests.+ const copilotIsFirst = !inline && reviewers[0] === DEFAULT_REVIEWER;+ const reviewerLabel = [+ ...reviewers.map(r => `\`${r}\``),+ ...usernames.map(u => `\`@${u}\``),+ ].join(' → ');+ const equivArgs = buildReviewWithArgs(reviewers, { stopMode, reviewerApplies, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels: reviewerModelMap });+ const equiv = equivArgs ? ` (equivalent to \`/do:pr ${equivArgs}\`)` : '';++ // First step: how to obtain a review. For a single copilot/CLI reviewer keep the+ // focused wording; for a list, dispatch each reviewer in order. Only emit the+ // per-reviewer-kind bullet that actually applies to the configured list.+ // `lmstudio`/`ollama` don't have CLIs the agent can spawn — PortOS exposes+ // `POST /api/code-review/local` which runs the configured local model against+ // the diff and returns findings text. The agent always reaches it via+ // `http://localhost:5555` (the canonical loopback API port).+ // A pinned local-LLM model can't ride the endpoint's server-side default: that+ // reads the GLOBAL settings scalar and has never seen this task. So when the+ // user pinned one on the reviewer's row, name it in the request body — `model`+ // in the POST body overrides the configured default (see routes/codeReview.js).+ // Absent pin ⇒ omit the key entirely rather than sending `""`, which would be a+ // model id the backend can't resolve.+ // The pinned reasoning effort rides the same body as `effort` — the endpoint+ // forwards it as the backend's OpenAI-compatible `reasoning_effort`. Same+ // absent-vs-empty contract as the model: no pin ⇒ the key is omitted, not blank.+ // Which body keys this run actually pins, accumulated across the local-LLM+ // reviewers in the list. The jq example below is built from THIS set rather than+ // naming both keys unconditionally: an effort-only run that was shown a+ // `model: "…"` placeholder would have the agent send the literal ellipsis, and+ // the route's `body.model || configured` prefers that truthy junk over the+ // install default — turning a pinned-effort review into a model-not-found error.+ const pinnedString = (map, r) => (typeof map[r] === 'string' && map[r] ? map[r] : null);+ const localLlmPins = LOCAL_LLM_REVIEWERS+ .filter(r => reviewers.includes(r))+ .map(r => ({ reviewer: r, model: pinnedString(reviewerModelMap, r), effort: pinnedString(reviewerEffortMap, r) }))+ .filter(p => p.model || p.effort);+ const localLlmPinNote = localLlmPins.map(({ reviewer, model, effort }) => {+ const keys = [+ ...(model ? [`"model": "${model}"`] : []),+ ...(effort ? [`"effort": "${effort}"`] : [])+ ];+ return `\`${reviewer}\` → \`${keys.join(', ')}\``;+ });+ // Both strings derive from the same `localLlmPins` array rather than the jq line+ // reading a Set the note's `.map` filled as a side effect — that coupling meant+ // hoisting one line above the other silently emptied the key list.+ const localLlmPinJq = [+ 'backend: "…"',+ ...(localLlmPins.some(p => p.model) ? ['model: "…"'] : []),+ ...(localLlmPins.some(p => p.effort) ? ['effort: "…"'] : []),+ 'diff: .'+ ].join(', ');+ const diffCommand = reviewForgeCli === 'glab'+ ? `glab mr diff ${prNumber || '<MR_NUMBER>'}`+ : `gh pr diff ${prNumber || '<PR_NUMBER>'}`;+ const localLlmInvocation = `POST the diff to PortOS's local reviewer endpoint and extract its review text before evaluating it. Substitute the active reviewer name for \`<lmstudio|ollama>\`:+\`\`\`bash+REVIEW_RESPONSE=$(mktemp)+${diffCommand} | jq -Rs '{ backend: "<lmstudio|ollama>", diff: . }' | curl -sS -X POST http://localhost:5555/api/code-review/local -H 'Content-Type: application/json' -d @- > "$REVIEW_RESPONSE"+if ! jq -er '.findings | select(type == "string" and length > 0)' "$REVIEW_RESPONSE" > "\${REVIEW_RESPONSE}.findings"; then+ echo "Local reviewer failed: $(jq -r '.error // "missing .findings in reviewer response"' "$REVIEW_RESPONSE")" >&2+ STATUS=cli-error # Never treat an absent or malformed response as clean.+ exit 1+else+ cat "\${REVIEW_RESPONSE}.findings"+fi+\`\`\`+Only a successfully extracted \`.findings\` value is the review text; treat it like any other reviewer's findings.${localLlmPinNote.length+ ? ` This run pins settings for ${localLlmPinNote.join(', ')} — add those keys to the JSON body (\`jq -Rs '{ ${localLlmPinJq} }'\`) so the review runs with them instead of the install defaults. Send ONLY the keys named above; a key with no pinned value overrides the install default with junk.`+ : ''}`;+ // Instruct the agent to request each username reviewer as a PR reviewer and+ // gate the merge on their approval. `gh pr edit --add-reviewer` takes the bare+ // login, so strip the `@`.+ const githubUsersInvocation = reviewForgeCli === 'glab'+ ? `request ${usernames.map(u => `\`@${u}\``).join(', ')} as MR reviewer${usernames.length > 1 ? 's' : ''} using the GitLab project UI or API, then inspect \`glab mr view ${prNumber || '<MR_NUMBER>'}\` for their review and address any findings; their approval gates the merge.`+ : `request ${usernames.map(u => `\`@${u}\``).join(', ')} as PR reviewer${usernames.length > 1 ? 's' : ''} (\`gh pr edit ${prNumber || '<PR_NUMBER>'} --add-reviewer <user>\`, drop the \`@\`), then wait for their review (poll every 5–15s) and address any findings; their approval gates the merge.`;+ const multiBullets = [+ hasCopilot ? `**copilot**: ${copilotIsFirst+ ? 'wait for the initial Copilot review the system already pre-requested (Copilot leads the list)'+ : 'request a Copilot review when you reach its turn'} (poll every 5–15s, max 5 min/round), then re-request on later rounds.` : null,+ hasCli ? `**${cliReviewerHeading}**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or \`git diff <base-branch>...HEAD\`; on GitHub \`gh pr diff ${prNumber || ''}\` also works).${cliBinaryNote}${reviewerPinNote}${cliProcedurePointer}` : null,+ hasLocalLlm ? `**lmstudio / ollama**: ${localLlmInvocation}` : null,+ hasGithubUser ? `**@github reviewers**: ${githubUsersInvocation}` : null,+ ].filter(Boolean).join(' ');+ // Name the BINARY, not the slug: `Invoke the \`antigravity\` CLI` sent a+ // follow-up agent hunting for a command that does not exist.+ const singleCliInvocation = `Invoke ${describeReviewerCli(cliReviewers[0])} to review this branch's diff against its base (use the CLI's own base-diff mode or \`git diff <base-branch>...HEAD\`; on GitHub \`gh pr diff ${prNumber || ''}\` also works). Capture its findings as concrete issues to address.${reviewerPinNote}${cliProcedurePointer}`;+ // Resolved sequentially so a future reviewer kind only adds one branch+ // instead of deepening the nested ternary.+ let waitOrInvokeStep;+ if (multi) waitOrInvokeStep = `For EACH reviewer in order — ${reviewerLabel} — run a full review-and-fix sub-loop before advancing to the next. ${multiBullets}`;+ else if (hasCopilot) waitOrInvokeStep = 'Wait for the latest Copilot review to complete (poll every 5–15s, max 5 minutes per round); the system already requested the initial review.';+ else if (hasLocalLlm) waitOrInvokeStep = localLlmInvocation;+ else if (hasCli) waitOrInvokeStep = singleCliInvocation;+ else waitOrInvokeStep = `To obtain a review, ${githubUsersInvocation}`;++ const stopModeNote = stopMode === 'on-findings'+ ? '**Stop mode (on-findings):** stop after the FIRST reviewer whose findings you actually fixed and committed; skip the remaining reviewers.'+ : stopMode === 'on-clean'+ ? '**Stop mode (on-clean):** stop after the FIRST reviewer that reports zero findings; skip the remaining reviewers.'+ : (multi ? '**Stop mode (all):** run every reviewer in the list, in order, before merging.' : '');++ const applyNote = hasCli+ ? (reviewerApplies+ ? '**Reviewer applies:** let each CLI reviewer apply its own fixes to the working tree, then verify, run tests, and push.'+ : "**Reviewer applies (off):** read each CLI reviewer's findings and apply the fixes yourself (default).")+ : '';++ // Inline runs opened the PR seconds ago inside their own completion workflow,+ // so nothing pre-requested anything — claiming otherwise would have the agent+ // poll forever for a Copilot review no one asked for.+ const initialReviewState = inline+ ? 'Nothing has reviewed this PR yet — you must request/invoke each configured reviewer yourself against its diff.'+ : (hasCopilot && copilotIsFirst)+ ? 'The system has already requested the initial Copilot code review (Copilot leads the order).'+ : hasCopilot+ ? 'Copilot is configured after another reviewer, so the system did NOT pre-request it — request the Copilot review yourself when you reach its turn (after the earlier reviewers’ fixes are pushed), and invoke the other reviewers yourself.'+ : 'The system did NOT pre-request a reviewer because no Copilot review leads the order — you must request/invoke each configured reviewer yourself against the PR diff.';+ const repeatedCommentsNote = '**Repeated comments:** If a fresh review round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on.';+ // Challenge protocol (#2471): auto-invoke the bounded worker↔reviewer dispute+ // from the review loop. When a reviewer's BLOCKING finding is a false positive,+ // the agent disputes it once via POST /challenge instead of silently complying+ // or accepting a false block, then RE-CHECKS (re-run reviewer) to overturn or+ // escalate. One challenge per task, also bounded by the task's retry budget —+ // a second dispute or an out-of-retries task returns 409.+ const challengeProtocolNote = [+ '**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:',+ '```bash',+ `curl -sS -X POST http://localhost:5555/api/cos/tasks/${sourceTaskId}/challenge -H 'Content-Type: application/json' -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'`,+ '```',+ 'A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can\'t dispute — then fix the finding or, if genuinely blocked, post a PR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user.' + (hasLocalLlm ? ' For a local reviewer you may instead POST `{"recheck":{"backend":"<lmstudio|ollama>","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.' : ''),+ ].join('\n');+ // Per-reviewer round caps. This prompt drives the loop in PROSE (it isn't+ // slashdo parsing a `~max=<n>` suffix), so a configured cap only binds if it's+ // spelled out here — the `equiv` flag string alone documents intent without+ // constraining the agent. `0` is slashdo's "loop until clean", so it's rendered+ // as such rather than as a zero-round budget.+ const maxRoundsEntries = Object.entries(reviewerMaxRounds)+ .filter(([token]) => reviewers.includes(token) || usernames.some(u => `@${u}`.toLowerCase() === token.toLowerCase()))+ .map(([token, max]) => `\`${token}\` → ${max === 0 ? 'loop until clean (no cap)' : `${max} round${max === 1 ? '' : 's'}`}`);+ const maxRoundsNote = maxRoundsEntries.length+ ? `**Round caps (~max):** stop these reviewers after their budget even if findings remain, then advance: ${maxRoundsEntries.join(', ')}. Spending a configured budget is a SUCCESS, not a failure — do not block the merge on it. Reviewers not listed keep the default cap below.`+ : '';++ const extraNotes = [stopModeNote, applyNote, maxRoundsNote, missingCliNote].filter(Boolean);++ // Inline slashdo's local-agent review loop verbatim when a spawnable CLI+ // reviewer is configured. This is the maintained, precise recipe — exact+ // per-CLI headless invocation (`claude -p "$LOCAL_PROMPT" --dangerously-skip-permissions`,+ // `codex --sandbox read-only review --base …`, etc.), the review-only /+ // no-sub-agent-fan-out `$LOCAL_PROMPT` contract, and the parse-and-apply+ // handling. Without it the agent only sees "invoke that CLI" and reverse-+ // engineers the invocation, wasting calls. The inlined body AGREES with+ // cliBinaryNote rather than contradicting the "follow it verbatim" order —+ // slashdo's per-CLI invocation table names `agy` and normalizes the+ // `gemini`/`antigravity` slugs onto it, so the note is a pointer into that+ // table, not a correction layered over it. Conditionals were resolved to the+ // subprocess (`else`) branch by loadSlashdoLib, so no in-process-Agent-tool+ // branch leaks in to confuse a non-Claude-Code host.+ //+ // Over budget WITH a staged copy on disk (`localAgentLoopBodyPath`, only ever+ // passed for an inline loop — see buildAgentPrompt) the agent is pointed at the+ // file instead. Same trade `buildSlashdoSection` makes: an initial run is+ // already carrying the real task, and pasting 40KB of reviewer recipe up front+ // to be read at step 4 is the wrong place to spend that context.+ const cliProcedureHeader = `\n### CLI Reviewer Procedure (${cliReviewerHeading})\n\nDrive each spawnable CLI reviewer EXACTLY as the slashdo local-agent review loop specifies — use its per-CLI invocation and review-only prompt contract verbatim; do NOT probe the CLI's \`--help\`, test it with throwaway prompts, or hand-roll flags. Run the reviewer once per round, capture its findings, and (unless reviewer-applies is set) apply the fixes yourself.\n\n`;+ //+ // The path IS the decision — it is non-null only when the caller already+ // measured the body over budget and staged it. Re-testing the length here+ // would give the two sites a way to disagree, and the disagreement is silent:+ // the file gets written AND the 40KB still gets pasted.+ const cliReviewerProcedure = (hasCli && localAgentLoopBody)+ ? (localAgentLoopBodyPath+ ? `${cliProcedureHeader}${oversizedBodyPointer(localAgentLoopBodyPath, localAgentLoopBody)}\n`+ : `${cliProcedureHeader}${localAgentLoopBody}\n`)+ : '';++ // A JIRA-tracked PR is a human's to land (its ticket is already "In Review" and+ // nothing here can transition it), so this follow-up reviews and stops. Emitted+ // as the same steps 4-6 so the loop body above stays identical either way.+ const leaveOpen = metadata.reviewLoopLeaveOpen === true || metadata.reviewLoopLeaveOpen === 'true';+ const objective = leaveOpen+ ? '**Your job is to drive the review-and-fix loop to completion. Do NOT merge — this PR is tracked in JIRA and a human lands it.**'+ : '**Your job is to drive the review-and-fix loop to completion and merge the PR.**';+ // Where the loop hands control back. A follow-up agent's whole task WAS the+ // loop, so it exits; an inline loop is one step of a larger completion+ // workflow that still owes the run its `.agent-done` sentinel — telling it to+ // "exit" here leaves a finished merge without the sentinel that records it.+ const exitStep = inline+ ? `6. ${inlineExitStep}`+ : `6. Exit. Do **not** run \`/do:push\` or open a new PR${leaveOpen ? '' : ' — the merge handles everything'}. The system will clean up your worktree on exit.`;+ const closingSteps = leaveOpen+ ? [+ '4. When the reviewer list is exhausted (or the stop mode triggers), **leave the PR open** — do NOT merge it, and do NOT delete the branch. Its JIRA ticket is sitting in review and a human lands both together; merging here would leave the work merged and the ticket stuck in review.',+ // Forge-aware: `gh pr comment` fails outright on a GitLab MR URL.+ `5. Post a short comment on the ${detectForgeCli(metadata.reviewLoopPRHost) === 'glab' ? 'MR' : 'PR'} summarising what the reviewers raised and what you fixed, so the human landing it knows the state: ${detectForgeCli(metadata.reviewLoopPRHost) === 'glab' ? `\`glab mr note ${prNumber !== '' ? prNumber : '<MR_NUMBER>'} --message "<summary>"\`` : `\`gh pr comment "${prUrl}" --body "<summary>"\``}.`,+ exitStep,+ ]+ : [+ `4. When the reviewer list is exhausted (or the stop mode triggers), merge the PR **immediately** with this exact command (flags: \`--merge --delete-branch\`, nothing else — a true merge commit keeps the branch tip in main's history so automated worktree cleanup can prove the branch is merged):`,+ ' ```bash',+ reviewForgeCli === 'glab'+ ? ` glab mr merge "${prNumber || '<MR_NUMBER>'}" --yes --remove-source-branch`+ : ` gh pr merge "${prUrl}" --merge --delete-branch`,+ ' ```',+ reviewForgeCli === 'glab'+ ? null+ : (prOwner && prRepo && prNumber ? ` (Equivalent: \`gh pr merge ${prNumber} --repo ${prOwner}/${prRepo} --merge --delete-branch\`.)` : null),+ ' You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.',+ reviewForgeCli === 'glab'+ ? `5. Confirm the MR is actually merged before exiting: \`glab mr view "${prNumber || '<MR_NUMBER>'}"\` must show it merged. If it is still open or was closed unmerged, investigate (a check is failing, a thread is still unresolved, or branch protection is blocking) — fix and retry the merge. Do NOT exit until it is merged.`+ : `5. Confirm the PR is actually merged before exiting: \`gh pr view "${prUrl}" --json state -q .state\` must return \`MERGED\`. If it returns \`OPEN\` or \`CLOSED\`, investigate (a check is failing, a thread is still unresolved, or branch protection is blocking) — fix and retry the merge. Do NOT exit until state is \`MERGED\`.`,+ exitStep,+ ].filter(Boolean);++ // Framing only — everything below it is identical for both callers.+ const heading = inline ? '## Review Loop' : '## Review-Loop Follow-up (PRIMARY OBJECTIVE)';+ const opening = inline+ ? `This runs as **step ${INLINE_REVIEW_LOOP_STEP} of the Completion Workflow above**, against the PR you just opened on \`${prBranch}\` (\`${prUrl}\` / \`${prNumber}\` are the shell variables you captured there). ${initialReviewState} ${objective}`+ : `A previous agent finished implementing the work for source task **${sourceTaskId}** and opened **PR ${prUrl}** on branch \`${prBranch}\`. ${initialReviewState} ${objective}`;++ if (verbose) {+ return `+${heading}+${opening}++**Reviewers (in order)**: ${reviewerLabel}${equiv}.+${extraNotes.length ? '\n' + extraNotes.join('\n') + '\n' : ''}+**Run this loop UNTIL all configured reviewers are satisfied (or the stop mode triggers), capped at 10 iterations per reviewer:**++1. ${waitOrInvokeStep}+2. If there are unresolved review findings, fix them in this worktree, run the project's tests, commit (\`feat:\`/\`fix:\` prefix, no Co-Authored-By), push, and (for Copilot) resolve the addressed threads.+3. Re-review with the same reviewer until it reports clean, then advance to the next reviewer in the list.+${closingSteps.join('\n')}++**Hard stop:** if a reviewer's loop hasn't converged after 10 iterations, post a PR comment summarising the unresolved blockers and exit. Do not loop indefinitely.++${repeatedCommentsNote}++${challengeProtocolNote}++PR Details:+- **URL**: ${prUrl}+- **Branch**: \`${prBranch}\`+${prNumber !== '' ? `- **Number**: ${prNumber}` : ''}+${prOwner && prRepo ? `- **Repo**: ${prOwner}/${prRepo}` : ''}+- **Source task**: ${sourceTaskId}+- **Reviewers**: ${reviewerLabel}+${cliReviewerProcedure}${(rprBody && (hasCopilot || hasGithubUser)) ? `\n### /do:rpr Reference — Copilot / @github reviewers (full procedure)\n\nThis is the PR-comment review loop for the **copilot** and **@github** reviewers only (request a review on the PR, poll for comments, resolve threads).${cliReviewerProcedure ? ' It does NOT apply to the local CLI reviewers — for those, follow the **CLI Reviewer Procedure** above instead.' : ''}\n\n${rprBody}\n` : ''}`;+ }++ // Compact light-path variant.+ const compactOpening = inline+ ? opening+ : `A previous agent finished task **${sourceTaskId}** and opened **PR ${prUrl}** on \`${prBranch}\`. ${initialReviewState} ${leaveOpen ? 'Drive the review-and-fix loop to completion — do NOT merge (JIRA-tracked; a human lands it).' : 'Drive the review-and-fix loop to completion and merge.'}`;+ return [+ heading,+ compactOpening,+ `**Reviewers (in order)**: ${reviewerLabel}${equiv}.`,+ ...extraNotes,+ '',+ '**Loop UNTIL all reviewers are satisfied (or the stop mode triggers), capped at 10 iterations per reviewer:**',+ `1. ${waitOrInvokeStep}`,+ '2. If unresolved findings: fix in this worktree, run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push' + (hasCopilot ? ', and (for Copilot) resolve the addressed threads.' : '.'),+ '3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.',+ ...closingSteps,+ '',+ '**Hard stop:** if a reviewer is not converged after 10 rounds, post a PR comment summarising blockers and exit.',+ repeatedCommentsNote,+ '',+ challengeProtocolNote,+ cliReviewerProcedure+ ].filter(Boolean).join('\n');+}++/**+ * The step that replaces the merge steps when a PR is a human's to land — a+ * JIRA-tracked task whose ticket is already "In Review" (see+ * `lib/prDisposition.js`). Merging would land the work while the board still+ * shows it in review, and no completion path here can transition the ticket.+ */+export const LEAVE_PR_OPEN_STEP = (step, jiraTracked = false) => `${step}. **Leave the PR open — do NOT merge it.** ${jiraTracked+ ? 'This task is tracked in JIRA: its ticket is in review and a human lands the PR and the ticket together.'+ : 'This task is configured to stop after opening the PR so a human can inspect and land it.'} Report the PR URL in your summary and stop.`;++/**+ * The CI-gated merge procedure, in numbered steps starting at `startStep`.+ *+ * This is the single definition of "no reviewer is configured, so CI is the+ * merge gate" — shared by every flow that reaches it: the agent's own completion+ * workflow (slashdo TUI + Claude Code CLI via `buildPostPRMergeSteps`) and the+ * merge follow-up agent PortOS spawns when it opened the PR itself. They differ+ * only in how the PR is addressed and whether GitLab commands are offered, so+ * those are parameters rather than hand-written copies that drift.+ *+ * Ends on the same merge command + MERGED verification as the review-loop+ * contract (`buildReviewLoopFollowUpSection`): a true merge commit keeps the+ * branch tip in the base branch's history, which is what lets automated worktree+ * cleanup prove the branch landed.+ *+ * @param {number} startStep - number of the first emitted step.+ * @param {Object} opts+ * @param {string} opts.prRef - how to address the PR in `gh` commands, already+ * quoted: the `"<PR_URL>"` placeholder before the PR exists, or the real URL.+ * @param {string} [opts.mrRef] - how to address the MR in `glab` commands.+ * **`glab mr merge` selects by MR IID or source branch — NOT by URL**, so this+ * is the number (or a `<MR_NUMBER>` placeholder), never `prRef`.+ * @param {'github'|'gitlab'|'unknown'} [opts.forge] - which CLI to name. PortOS+ * opens GitLab MRs too (`git.createPR` falls back to `glab`), so a follow-up+ * whose PR host is a GitLab instance must not be handed `gh` commands it can't+ * run. Callers derive this with `detectForgeCli` — a GitHub Enterprise host is+ * `github`, not "not github.com". `unknown` (the agent's own completion+ * workflow, which runs before the PR exists) emits both, commented.+ * @returns {{lines: string[], nextStep: number}}+ */+export function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>', forge = 'github', alreadyMergedHint = ' (a saved `/do:pr` default can merge it for you)' }) {+ const gh = forge !== 'gitlab';+ const glab = forge !== 'github';+ const both = gh && glab;+ const checksCmd = gh+ ? `\`gh pr checks ${prRef} --watch --fail-fast --interval 30\`${glab ? ' (GitLab: `glab ci status`)' : ''}`+ : '`glab ci status`';+ const mergeableCmd = gh+ ? `\`gh pr view ${prRef} --json mergeable -q .mergeable\` reports \`CONFLICTING\`${glab ? ' (GitLab: `glab mr view ' + mrRef + '` shows a conflict)' : ''}`+ : `\`glab mr view ${mrRef}\` shows a conflict with the target branch`;+ const stateCmd = gh+ ? `\`gh pr view ${prRef} --json state -q .state\` must return \`MERGED\`${glab ? ' (GitLab: `glab mr view ' + mrRef + '` must show it merged)' : ''}`+ : `\`glab mr view ${mrRef}\` must show it merged`;+ const lines = [+ `${startStep}. **Wait for CI to finish**: ${checksCmd}. "No checks reported" is AMBIGUOUS — a just-opened PR reports it while checks are still attaching, and merging on it races the CI this gate exists to wait for. Treat it as green ONLY when the repo genuinely has no CI (${gh ? '`gh workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check is configured' : 'no `.gitlab-ci.yml` and no pipeline is configured'}). If CI IS expected, wait 30s and re-check for up to 5 minutes — and if it still hasn't attached, **leave the PR open and say so**; never merge on checks that were expected but never appeared.`,+ `${startStep + 1}. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (${gh ? `\`gh run view --log-failed\`${glab ? ' on GitHub, `glab ci trace` on GitLab' : ''}` : '`glab ci trace`'}), fix the cause here, run the project's tests, commit (\`fix:\` prefix, no Co-Authored-By), push, and go back to the previous step — cap this at 5 rounds. If ${mergeableCmd}, \`git fetch origin\`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, re-run the tests, \`git push --force-with-lease\`, and re-check.`,+ `${startStep + 2}. **Merge** with exactly these flags, nothing else — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, and any merge-deferral flag leaves the PR open after you exit. If it is already merged${alreadyMergedHint}, skip to the next step:`,+ ' ```bash',+ gh ? ` ${both ? '# GitHub: ' : ''}gh pr merge ${prRef} --merge --delete-branch` : null,+ // `glab mr merge` takes an MR IID or source branch — a URL is not accepted.+ glab ? ` ${both ? '# GitLab: ' : ''}glab mr merge ${mrRef} --yes --remove-source-branch` : null,+ ' ```',+ // Not every repo allows merge commits; a repo restricted to squash/rebase+ // rejects `--merge` outright, which would leave the PR open forever.+ gh ? ` If that is rejected because this repo disallows merge commits, re-check what it allows (\`gh repo view --json mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed\`) and merge with an allowed method instead — \`--squash\` first, else \`--rebase\` — keeping \`--delete-branch\`.` : null,+ `${startStep + 3}. **Confirm the merge before exiting**: ${stateCmd}. If it is still open or was closed unmerged, investigate (failing check, merge conflict, branch protection), fix, and retry. Leave it open — saying so explicitly in your completion summary — if CI stays red after a genuine fix attempt, a conflict needs a human decision, expected checks never attached, or a branch protection you cannot satisfy blocks the merge (a required approving review, a required check only a human can trigger). Hand those to a human rather than retrying until you time out.`,+ ].filter(Boolean);+ return { lines, nextStep: startStep + 4 };+}++/**+ * Build the **merge follow-up** section — the instructions for the agent+ * `spawnReviewLoopFollowUp` spawns when no reviewer survived resolution (Review+ * Loop off, or copilot-only on a non-GitHub forge). Nothing else will touch the+ * PR, so the merge gate is CI alone (`buildCiMergeGateSteps`).+ *+ * @param {Object} opts - PR coordinates + `verbose` (full/api path) vs compact.+ * @returns {string}+ */+function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = '', prRepo = '', prHost = '', sourceTaskId = 'unknown', verbose = false, inlineExitStep = null, forgeCli = null }) {+ const inline = inlineExitStep !== null;+ // PortOS opens GitLab MRs via `glab` too, so a GitLab host must not be handed+ // `gh` commands (the host is persisted by spawnReviewLoopFollowUp). Classify+ // with the shared detector — a GitHub Enterprise host is still `gh`, which a+ // bare `host !== 'github.com'` test would get wrong.+ //+ // An INLINE gate has no persisted host to classify — its PR does not exist yet+ // — so the caller supplies the forge already selected for the create step.+ // Falling back to GitHub preserves the historical manual workflow when no+ // remote metadata is available.+ const gate = buildCiMergeGateSteps(1, {+ prRef: `"${prUrl}"`,+ mrRef: prNumber !== '' ? `${prNumber}` : '<MR_NUMBER>',+ forge: inline+ ? (normalizeForgeCli(forgeCli) === 'glab' ? 'gitlab' : 'github')+ : (detectForgeCli(prHost) === 'glab' ? 'gitlab' : 'github'),+ // An inline run reached this gate through plain `git`/`gh` — it never ran+ // `/do:pr`, so a saved slashdo merge default can't have landed the PR for it.+ alreadyMergedHint: inline ? '' : undefined,+ });+ const steps = [+ ...gate.lines,+ inline+ ? `${gate.nextStep}. ${inlineExitStep} Do NOT start a code review — none is configured for this task.`+ : `${gate.nextStep}. Exit. Do NOT run \`/do:push\`, do NOT open a new PR, and do NOT start a code review — landing this PR is the whole job.`,+ ];+ const prDetails = verbose ? [+ '',+ 'PR Details:',+ `- **URL**: ${prUrl}`,+ `- **Branch**: \`${prBranch}\``,+ prNumber !== '' ? `- **Number**: ${prNumber}` : null,+ prOwner && prRepo ? `- **Repo**: ${prOwner}/${prRepo}` : null,+ `- **Source task**: ${sourceTaskId}`,+ ].filter(Boolean) : [];++ return [+ inline ? '## Merge Gate' : '## Merge Follow-up (PRIMARY OBJECTIVE)',+ inline+ ? `This runs as **step ${INLINE_REVIEW_LOOP_STEP} of the Completion Workflow above**, against the PR you just opened on \`${prBranch}\` (\`${prUrl}\` / \`${prNumber}\` are the shell variables you captured there). **No code review was requested for this task, so nothing else will merge this PR — land it yourself once CI is green.**`+ : `A previous agent finished the work for source task **${sourceTaskId}** and opened **PR ${prUrl}** on \`${prBranch}\`. **No code review was requested for this task, so nothing else will merge this PR — your job is to land it once CI is green.**`,+ '',+ ...steps,+ '',+ '**Hard stop:** if CI is still red after 5 fix rounds, or a conflict needs a product decision you can\'t make, post a PR comment summarising exactly what is blocking the merge and exit with the PR left open. Do not force a merge over red CI.',+ ...prDetails,+ ].join('\n');+}diff --git a/server/services/promptSections/slashdo.js b/server/services/promptSections/slashdo.jsnew file mode 100644index 0000000000..0ed6685cb6--- /dev/null+++ b/server/services/promptSections/slashdo.js@@ -0,0 +1,152 @@+/**+ * Slashdo invocation expansion for agent prompts.+ */++import { loadSlashdoFile, writeResolvedSlashdoBody } from '../../lib/slashdoLoader.js';+import { resolveSlashdoInvocation, buildSlashdoSection, unreachableReviewerIncludes, SLASHDO_INLINE_BUDGET_CHARS } from '../../lib/slashdoInvocation.js';+import { DEFAULT_REVIEWER, resolveReviewerConfig, buildReviewerEffortNote, buildReviewersCsv } from '../../lib/validation.js';++/**+ * Fold a slashdo-backed task's invocation + procedure into its description (#3089).+ *+ * A task that names a bundled workflow persists only the BARE command+ * (`metadata.slashdoCommand`) because the form's provider select defaults to+ * "Auto" — the concrete shape (`/do:x`, `/do-x`, or an Agent Skill selected by+ * name) is only knowable here, once the scheduler has picked a provider.+ *+ * The command body travels with the prompt for every provider, not just the+ * skill-style ones: PortOS ships slashdo as a submodule and only surfaces it as+ * slash commands via the repo-local `.claude/commands/do/` symlinks, which don't+ * exist in the managed-app workspaces most CoS tasks run in.+ *+ * **Size control (#3110).** Expanded bodies run 38KB–317KB. Two independent+ * reductions apply, in this order:+ *+ * 1. **Prune unreachable reviewer variants.** `review`/`better`/`pr` each paste+ * all five of slashdo's reviewer loops though one run drives one of them.+ * Pruning to a single CLI reviewer measured -23% on `review` (258,260 →+ * 198,997 chars), -27% on `pr`, and -28% on `depfree`. (slashdo's+ * orchestration wrapper is never pruned — it dispatches even a single-entry+ * reviewer list — which is ~37KB of the theoretical ceiling.)+ * 2. **Point at a resolved copy on disk when still over budget** — but only for a+ * host with file tools (`cli`/`tui`; an HTTP `api` provider has none and+ * inlines with a warning). On its own this is roughly token-NEUTRAL for an+ * agent that reads the whole procedure; it pays off when the host can invoke+ * slashdo natively or needs only part of the body.+ *+ * Pruning is only sound if the run then uses the reviewers we pruned FOR, so the+ * section emits an explicit `--review-with` pin alongside a pruned body —+ * otherwise the agent could resolve a different reviewer from slashdo's own saved+ * defaults and find that loop missing. No explicit pin ⇒ no prune.+ *+ * The reviewers, usernames, and optional-reviewers are resolved through the SAME+ * three helpers as the inline `/do:pr` completion path further down+ * (`normalizeReviewers` / `resolveReviewUsernames` / `resolveOptionalReviewers`),+ * so what we prune for is exactly what the rest of the prompt resolves — legacy+ * single-`reviewer` tasks and defaults-inherited `optionalReviewers` included.+ *+ * The one case that does NOT authorize pruning is a resolved lone `copilot` that+ * nothing named explicitly (no task pin, no username reviewers, not marked+ * optional): `pickCodeReviewDefaults` and `normalizeReviewers` both fall back to+ * `['copilot']`, so that value can't be told apart from an unconfigured install —+ * and pinning `--review-with copilot` where Copilot review isn't enabled is the+ * #2507 stall. This mirrors `buildReviewWithArgs`'s lone-default suppression,+ * including its exemption for an explicitly-optional copilot.+ *+ * Applied to the description (on a COPY — the stored task is untouched) rather+ * than emitted as its own template slot, because the briefing template renders+ * `{{task.description}}`: a new `{{slashdoSection}}` placeholder would be+ * silently dropped by every install whose customized template predates it.+ *+ * @returns {Promise<Object>} the task, or a copy carrying the invocation+ */+export async function applySlashdoInvocation(task, {+ providerId = null, providerCommand = null, leanMode = false, hasFileTools = false,+ defaultReviewers = null, codeReviewDefaults = null,+} = {}) {+ const command = task.metadata?.slashdoCommand;+ const resolved = resolveSlashdoInvocation({+ command,+ args: task.metadata?.slashdoArgs || '',+ providerId,+ providerCommand,+ leanMode,+ });+ if (!resolved) return task;++ // Resolved through the SAME three helpers the inline `/do:pr` completion path+ // uses below (`taskReviewers` / `taskReviewerUsernames` / `taskOptionalReviewers`),+ // so the reviewers we prune for are exactly the ones the rest of the prompt+ // resolves. Hand-rolling `metadata.reviewers` here instead dropped the legacy+ // single `reviewer` string and the defaults' `optionalReviewers` — pruning for+ // one reviewer while the run resolved another, and pinning an optional reviewer+ // as blocking.+ const {+ reviewers: resolvedReviewers,+ usernames: resolvedUsernames,+ optionalReviewers: resolvedOptional,+ reviewerMaxRounds: resolvedMaxRounds,+ reviewerModels: resolvedModels,+ reviewerEfforts: resolvedEfforts+ } = resolveReviewerConfig(task.metadata, codeReviewDefaults, defaultReviewers);++ // A resolved lone `copilot` with no usernames is ambiguous: it's what an+ // unconfigured install produces (`pickCodeReviewDefaults` and+ // `normalizeReviewers` both fall back to `['copilot']`), so it can't be told+ // apart from a real choice UNLESS something names it explicitly. Absent that,+ // treat it as unconfigured and prune nothing — pinning `--review-with copilot`+ // where Copilot review isn't enabled is the #2507 stall.+ //+ // Marking copilot OPTIONAL — or giving it a `~max=<n>` round cap — is such an+ // explicit naming: nothing defaults to either suffix, so both are deliberate+ // choices, and dropping one would silently turn a non-blocking review blocking+ // or spend an unbudgeted number of rounds. `buildReviewWithArgs` makes the same+ // exemption for its lone-default suppression — keep the two in step. It carries a+ // third clause for a copilot `~effort=`; there is deliberately none here, because+ // copilot has no effort ladder at all (`REVIEWER_EFFORT_LEVELS` is keyed off+ // `reviewerCliBinary`, and copilot names no binary), so `normalizeReviewerEfforts`+ // drops the pin long before either function sees it.+ const taskPinnedReviewer = (Array.isArray(task.metadata?.reviewers) && task.metadata.reviewers.length > 0)+ || (typeof task.metadata?.reviewer === 'string' && !!task.metadata.reviewer);+ const optionalDefaultReviewer = resolvedOptional.some(t => t.toLowerCase() === DEFAULT_REVIEWER);+ const cappedDefaultReviewer = Object.keys(resolvedMaxRounds)+ .some(t => t.toLowerCase() === DEFAULT_REVIEWER);+ const isBareDefault = resolvedReviewers.length === 1+ && resolvedReviewers[0] === DEFAULT_REVIEWER+ && !resolvedUsernames.length+ && !taskPinnedReviewer+ && !optionalDefaultReviewer+ && !cappedDefaultReviewer;+ const skipIncludes = isBareDefault+ ? []+ : unreachableReviewerIncludes({ reviewers: resolvedReviewers, usernames: resolvedUsernames });++ const body = await loadSlashdoFile(command, { stripFrontmatter: true, skipIncludes }).catch(() => null);+ if (!body) console.log(`⚠️ Slashdo command body unavailable, sending invocation only: ${command}`);+ const overBudget = !!body && body.length > SLASHDO_INLINE_BUDGET_CHARS;+ // An HTTP `api` provider can't read a file, so an over-budget body is pasted+ // whole. Surface the cost rather than paying it silently.+ if (overBudget && !hasFileTools) {+ console.warn(`⚠️ Inlining ${Math.round(body.length / 1000)}KB slashdo body for API provider (no file tools): ${command}`);+ }+ // Only spend the write when the pointer will actually be used.+ const bodyPath = (overBudget && hasFileTools)+ ? await writeResolvedSlashdoBody(command, body, { skipIncludes }).catch((err) => {+ console.warn(`⚠️ Could not stage slashdo body for ${command}, inlining instead: ${err.message}`);+ return null;+ })+ : null;++ const reviewWith = skipIncludes.length+ ? buildReviewersCsv(resolvedReviewers, resolvedUsernames, resolvedOptional, resolvedMaxRounds, resolvedModels, resolvedEfforts)+ : '';+ // Gated on the PIN, not on pruning. When `reviewWith` is emitted, each token+ // carries `~effort=<level>` and slashdo's loop applies it — the note would only+ // have the agent pass the flag twice. When nothing is pinned, the workflow+ // resolves reviewers itself and the note is the pin's only route to the CLI it+ // spawns (the `/do:pr` completion step further down is a different invocation+ // entirely, and for a slashdo-backed task usually isn't reached).+ const reviewerEffortNote = buildReviewerEffortNote(resolvedReviewers, resolvedEfforts, { reviewWith, reviewerModels: resolvedModels });+ const section = buildSlashdoSection(resolved, body, { bodyPath, reviewWith, reviewerEffortNote });+ return { ...task, description: `${task.description}\n\n${section}` };+}diff --git a/server/services/promptSections/taskContext.js b/server/services/promptSections/taskContext.jsnew file mode 100644index 0000000000..56b44f8244--- /dev/null+++ b/server/services/promptSections/taskContext.js@@ -0,0 +1,169 @@+/**+ * Shared task, attachment, and compaction prompt sections.+ */++import { join, basename } from 'path';+import { PATHS } from '../../lib/fileUtils.js';+import { TASK_PROMPT_KEY, TASK_CONTEXT_KEY } from '../../lib/cosTaskPrompt.js';+import { PORTOS_APP_ID } from '../apps.js';++/**+ * Build a compaction instruction section for retries after context-limit failures.+ * Provides explicit guidance to the agent on reducing output verbosity.+ */+export function buildCompactionSection(task) {+ const compaction = task.metadata?.compaction;+ if (!compaction?.needed) return '';++ const hints = compaction.retryHints || [];+ const reason = compaction.reason === 'output-limit' ? 'output length limit' : 'context window limit';+ const prevOutputKB = compaction.outputSize ? Math.round(compaction.outputSize / 1024) : 'unknown';++ return `+## Context Compaction Required++**WARNING**: A previous attempt at this task failed because the agent exceeded the ${reason}.+Previous output size: ~${prevOutputKB} KB. You MUST keep your output compact to avoid the same failure.++**Mandatory output constraints**:+${hints.map(h => `- ${h}`).join('\n')}+- Do NOT reproduce entire file contents in your output+- Reference files by path and line number instead of quoting them+- Limit exploratory reads — plan your approach first, then make targeted changes+`;+}++/**+ * Render a file-list task field (screenshots, attachments, …) either as a+ * `### Header` + bulleted-path list (light path) or a single inline+ * `**Header**: a, b` line (full path). Shared by every file-list field in+ * `buildTaskBlock` so a wording tweak or a new field can't drift between them.+ *+ * @param {string} header - Section heading / inline label (e.g. "Screenshots").+ * @param {Array} items - Task-metadata array; anything else renders as ''.+ * @param {(item: any) => string} formatItem - Renders one item for the bulleted list.+ * @param {(item: any) => string} formatInline - Renders one item for the inline join.+ * @param {boolean} asList - Bulleted-list style vs. inline style.+ * @returns {string}+ */+function renderFileListField(header, items, formatItem, formatInline, asList) {+ if (!Array.isArray(items) || items.length === 0) return '';+ return asList+ ? `### ${header}\nUse your filesystem tools to inspect each path:\n` ++ items.map(i => `- ${formatItem(i)}`).join('\n')+ : `**${header}**: ${items.map(formatInline).join(', ')}`;+}++/**+ * Build the shared task block — the description plus optional `**Target App**`,+ * `**Screenshots**`, and `**Attachments**` fields. Used by BOTH the light and+ * full prompt paths so a new task-metadata field gets surfaced in both without+ * drift.+ *+ * Returns pre-rendered slots (`description`, `targetApp`, `screenshots`,+ * `attachments`). Absent fields come back as empty strings so the full path's+ * template literal can interpolate them in fixed positions and preserve+ * byte-identical line spacing. The light path filters out the empty strings+ * and joins what remains.+ *+ * @param {Object} task+ * @param {Object} [opts]+ * @param {boolean} [opts.screenshotsAsList=false] - When true, render screenshots+ * and attachments as a header followed by a bulleted list of paths (light+ * path style). When false, render as a single inline `**Field**: a, b`+ * line (full path style).+ * @returns {{ description: string, targetApp: string, screenshots: string, attachments: string }}+ */+export function buildTaskBlock(task, { screenshotsAsList = false } = {}) {+ const description = task.description;+ // Only surface **Target App** for MANAGED apps — it scopes cross-repo work the+ // agent's cwd wouldn't otherwise reveal. For the PortOS default app the agent+ // already runs in the PortOS directory, so the line is redundant noise.+ const app = task.metadata?.app;+ const targetApp = app && app !== PORTOS_APP_ID ? `**Target App**: ${app}` : '';+ const screenshots = renderFileListField(+ 'Screenshots', task.metadata?.screenshots,+ (s) => `\`${resolveTaskFileRef(s)}\``, (s) => resolveTaskFileRef(s), screenshotsAsList+ );+ const label = (f) => (f?.originalName || f?.filename || f?.path || '').toString();+ const path = (f) => resolveTaskFileRef((f?.path || '').toString());+ const attachments = renderFileListField(+ 'Attachments', task.metadata?.attachments,+ (f) => `\`${path(f)}\` (${label(f)})`, (f) => `${label(f)} (${path(f)})`, screenshotsAsList+ );+ return { description, targetApp, screenshots, attachments };+}++// Map for API-relative upload URLs → the on-disk root the agent should read.+const TASK_REF_ROOTS = {+ '/api/screenshots/': PATHS.screenshots,+ '/api/attachments/': PATHS.cosAttachments,+ '/api/uploads/': PATHS.uploads,+};++/**+ * Resolve a stored screenshot/attachment reference to an absolute filesystem+ * path the CoS agent can open with its filesystem tools.+ *+ * Uploads now return API-relative URLs (`/api/screenshots/<file>`) instead of+ * absolute paths (issue #2518 — absolute paths leaked the install layout in the+ * HTTP response), so tasks created after that change store the relative URL.+ * Convert those back to an absolute path here, at prompt-build time, where the+ * absolute path is local-only and never persisted or published. Legacy tasks+ * that stored an absolute path (or any non-`/api/` value) are passed through+ * unchanged so existing queues keep rendering the same path.+ */+function resolveTaskFileRef(ref) {+ if (typeof ref !== 'string' || !ref) return ref;+ for (const [prefix, root] of Object.entries(TASK_REF_ROOTS)) {+ if (ref.startsWith(prefix)) {+ return join(root, basename(decodeURIComponent(ref)));+ }+ }+ return ref;+}++/**+ * Undo the COS-TASKS.md round-trip split before rendering. The queue path in+ * `cosTaskGenerator.js` persists a generated multi-line prompt by moving the+ * full body into `metadata.prompt` (`metadata.context` before the #4153 split)+ * and keeping only its first line as+ * `description`, so the markdown stays one-line-per-task. Coming back out, the+ * payload therefore *leads with a verbatim copy* of `description` — and every+ * render path emits both (the task block, then the full body again under a+ * `### Context` header). For a swarm task that surfaces as the reported+ * double `# ⚡ SWARM MODE …` header; the same duplication hits any other+ * generated/scheduled/system task that round-trips through the queue.+ *+ * When the split signature is present (the payload's first non-empty line+ * equals `description`), fold it back into `description` so the prompt renders+ * once, as one clean body with no spurious header. The split `prompt` key stays+ * available to customized briefing templates; the legacy `context` payload key+ * is dropped because it is already represented by `description`. A genuinely-+ * separate user-supplied note (first line differs from `description`) is left+ * untouched.+ *+ * Pure and idempotent: returns the same task when nothing matched, otherwise a+ * shallow clone (never mutates the caller's task, so the stored task keeps its+ * one-line `description` for the task-list UI).+ */+export function reconcileSplitContext(task) {+ if (typeof task?.description !== 'string') return task;+ const description = task.description.trim();+ // `prompt` first: that is where the payload lives on a task written by+ // current code (#4153). `context` stays in the loop so a task written before+ // the split — or synced from a peer still on the old code — reconciles too.+ // Keep the new prompt key available to customized templates. Drop only the+ // legacy context key, whose payload is already represented by description.+ for (const key of [TASK_PROMPT_KEY, TASK_CONTEXT_KEY]) {+ const payload = task.metadata?.[key];+ if (typeof payload !== 'string') continue;+ // Mirror firstLine() in cosTaskStore.js: first non-empty, trimmed line.+ const firstNonEmpty = payload.split('\n').map(l => l.trim()).find(Boolean) || '';+ if (firstNonEmpty !== description) continue;+ if (key === TASK_PROMPT_KEY) return { ...task, description: payload };+ const { [key]: _dropped, ...restMeta } = task.metadata;+ return { ...task, description: payload, metadata: restMeta };+ }+ return task;+}