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
inline slashdo's CLI-reviewer recipe into CoS follow-up prompts so agents don't improvise it
[._.]/ Adam Eivy248eea728748
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6c57578901..e76aea2ff9 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -59,6 +59,7 @@- **Hugging Face models with a custom quant scheme no longer produce an uninstallable Ollama id** — `quantFromFilename` matched a standard quant anywhere at the end of a GGUF filename, so a repo-specific scheme suffix bled into a bogus tag (`BTL-3-Compact-AVQ2.gguf` → `Q2`) and the resulting `hf.co/<repo>:Q2` pull failed with Ollama's `400 The specified tag is not a valid quantization scheme`. The quant now has to be its own trailing token (start-of-name or after a `-`/`_`/`.`); when nothing parses, the install id falls back to the bare repo, which Ollama resolves through its `latest` manifest.- **CoS task cards no longer render a wall of prompt text** — a task's `context`, `blockedReason`/`blocker`, and challenge `reason` are now clamped to two lines with a Show more/Show less toggle, matching the description. Orchestrator tasks (e.g. the Creative Director production plan) store their entire prompt in `metadata.context`, so one pending task previously rendered as thousands of pixels of unclamped text the user had to scroll past to reach the rest of the queue; auto-blocked tasks had the same problem with LLM/stderr-derived block reasons, and a challenge reason is free text a worker agent writes to argue its case. The clamp+toggle (measured overflow, so the toggle only appears when the text actually spills) is extracted from `TaskItem` into a shared `client/src/components/ui/CollapsibleText.jsx`. Editing a task's context also moves from a single-line `<input>` to a bounded scrolling `<textarea>`, which was unusable for a multi-thousand-character prompt.- CoS claim agents (plan-task, claim-issue, claim-issue-gitlab, claim-issue-jira) now create their git worktree under PortOS's own shared `data/cos/worktrees/` (via a new `{worktreesRoot}` prompt placeholder resolved to `PATHS.worktrees`) instead of a repo-relative path inside the managed app's checkout. An agent working a *managed app* previously left a `data/cos/worktrees/claim-…` tree inside that app's working directory (e.g. a stray `data/` in the target repo); the checkout now lands in PortOS's data dir — exactly where `cleanupExternalRepoWorktrees` already reaps external-repo worktrees. Prompt versions bumped and the outgoing repo-relative defaults preserved for cross-install auto-upgrade.+- **A CoS review-loop agent (esp. codex reviewing with `claude`) no longer burns a dozen calls figuring out how to run the reviewer** — the follow-up agent used to be told only "invoke that CLI to review this branch's diff", so a headless codex agent reverse-engineered the `claude` CLI from scratch (`claude --help`, `claude -p 'hello'`, `--output-format json`, `--tools ''`, byte-level output inspection) before it landed a working review. PortOS now inlines slashdo's exact local-agent review-loop recipe — the precise per-CLI headless invocation (`claude -p "$LOCAL_PROMPT" --dangerously-skip-permissions`, `codex --sandbox read-only review --base …`, etc.) and the review-only prompt contract — into the follow-up prompt whenever a spawnable CLI reviewer (codex/antigravity/claude/grok) is configured, and points the invocation step at it. The new `loadSlashdoLib()` helper — and `loadSlashdoFile()` — now resolve slashdo's `<!-- if:teams -->` conditional blocks (PortOS inlines slashdo markdown without going through slashdo's own installer, so both the Claude-Code-only in-process-Agent-tool branch and the subprocess branch were previously leaking into agent prompts unresolved and contradicting each other; this also affected user-dispatched CoS commands like `/do:better`). Fixed alongside: inlining a slashdo lib into a command body used a bare-string `String.replace`, which interpreted `$\``/`$'` tokens in the shell-heavy review-loop libs — corrupting the inlined text and ballooning a ~66KB command past 2MB; the review-loop procedure PortOS already inlined into every follow-up agent prompt was affected. It now inserts lib content verbatim.- `executeTuiRun`'s `finish()` now always settles its run promise even if a finalization step throws, so a one-shot TUI run can no longer hang forever (leaking the PTY and wedging `/runs`).- `execGh` now times out (60s default, overridable) and kills a stalled `gh` CLI child, so a hung network/credential prompt can't wedge the scheduled PR-watcher / issue- and branch-reconcile / update-check jobs or orphan `gh` processes.- `NextActionBanner`'s question fetch is guarded against stale responses, so a slow earlier request can no longer overwrite a newer question.diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex 2aaec50ae3..f4b7a7381d 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -858,8 +858,68 @@ export function formatDuration(ms) {}/**- * Load a slashdo command markdown file, resolving !`cat ~/.claude/lib/...` includes.- * Optionally strips YAML frontmatter.+ * Resolve all `!`cat ~/.claude/lib/<name>`` include directives in `content` by+ * inlining the referenced slashdo lib file. Iterates so an inlined lib that+ * itself carries a `!`cat`` include is resolved too (bounded to avoid a cyclic+ * include spinning forever). Shared by loadSlashdoFile and loadSlashdoLib.+ */+async function resolveSlashdoIncludes(content, libDir) {+ for (let pass = 0; pass < 5; pass++) {+ const matches = [...content.matchAll(/!`cat ~\/.claude\/lib\/([^`]+)`/g)];+ if (matches.length === 0) break;+ const replacements = await Promise.all(matches.map(async (match) => {+ const libContent = await readFile(join(libDir, match[1]), 'utf-8').catch(() => null);+ return { pattern: match[0], content: libContent };+ }));+ let changed = false;+ for (const { pattern, content: libContent } of replacements) {+ // Replace via a function, NOT a string: a string replacement makes+ // String.replace interpret `$&`/`$\``/`$'`/`$n` tokens, and the shell-heavy+ // lib files are full of `$` — a bare-string replacement both corrupts the+ // inlined text and balloons it (a `$\`` token splices in everything before+ // the match, blowing a 66KB command up to ~2.5MB). A function replacer+ // inserts libContent verbatim.+ if (libContent) { content = content.replace(pattern, () => libContent); changed = true; }+ }+ if (!changed) break;+ }+ return content;+}++/**+ * Resolve slashdo's `<!-- if:<cap> -->…<!-- else -->…<!-- /if:<cap> -->`+ * conditional blocks — the same templating slashdo's own installer resolves+ * per target environment (see `lib/slashdo/src/transformer.js`). PortOS inlines+ * slashdo markdown into CoS-agent prompts WITHOUT going through that installer,+ * so unless we resolve these here the agent receives BOTH branches verbatim+ * (e.g. the Claude-Code-only "in-process Agent tool" reviewer branch AND the+ * `claude -p` subprocess branch), which is self-contradictory and makes a+ * headless agent improvise its own reviewer invocation.+ *+ * Only the `teams` capability is recognized (matching slashdo's+ * CONDITIONAL_CAPABILITIES). `teams=false` keeps the `else` branch — the+ * subprocess (`claude -p …`) reviewer path that works from any host — which is+ * the correct choice for PortOS's headless CoS agents (they have no in-process+ * Agent tool and are not billing against an interactive Claude Code plan).+ * Unknown capabilities are left untouched so a stray comment never deletes+ * content. Blocks do not nest.+ */+function resolveSlashdoConditionals(content, { teams = false } = {}) {+ const blockRe = /<!--\s*if:([a-zA-Z]+)\s*-->\n?([\s\S]*?)(?:<!--\s*else\s*-->\n?([\s\S]*?))?<!--\s*\/if:\1\s*-->\n?/g;+ return content.replace(blockRe, (match, cap, ifContent, elseContent = '') => {+ if (cap !== 'teams') return match;+ return teams ? ifContent : elseContent;+ });+}++/**+ * Load a slashdo command markdown file, resolving !`cat ~/.claude/lib/...`+ * includes AND the `<!-- if:teams -->` conditional blocks (to the non-teams+ * `else` branch — see resolveSlashdoConditionals). Both are needed because+ * PortOS inlines these command bodies into headless CoS-agent prompts without+ * running slashdo's own installer: e.g. `commands/do/better.md` ships an+ * `if:teams` block, and a `/do:better` CoS dispatch would otherwise hand the+ * agent both contradictory branches. Optionally strips YAML frontmatter.** Cached: slashdo files are static within a server lifetime (submodule updates* require restart). Cache resets on process restart, which is the right behavior.@@ -875,19 +935,35 @@ export async function loadSlashdoFile(commandName, { stripFrontmatter = false }if (stripFrontmatter) {content = content.replace(/^---[\s\S]*?---\s*/, '');}- const libDir = join(PATHS.slashdo, 'lib');- const matches = [...content.matchAll(/!`cat ~\/.claude\/lib\/([^`]+)`/g)];- const replacements = await Promise.all(matches.map(async (match) => {- const libContent = await readFile(join(libDir, match[1]), 'utf-8').catch(() => null);- return { pattern: match[0], content: libContent };- }));- for (const { pattern, content: libContent } of replacements) {- if (libContent) content = content.replace(pattern, libContent);- }+ content = await resolveSlashdoIncludes(content, join(PATHS.slashdo, 'lib'));+ content = resolveSlashdoConditionals(content);slashdoFileCache.set(cacheKey, content);return content;}+/**+ * Load a slashdo *lib* file (`lib/slashdo/lib/<name>.md`) — the shared+ * procedure fragments that command files `!`cat``-include — for inlining+ * directly into a CoS-agent prompt. Same include + conditional resolution as+ * loadSlashdoFile; the differences are that this reads the `lib/` dir (not+ * `commands/do/`) and exposes the `teams` override (loadSlashdoFile always+ * resolves to the non-teams branch). Defaults to the non-teams (`else`) branch+ * so a headless agent gets the subprocess reviewer invocation, not both.+ */+const slashdoLibCache = new Map();+export async function loadSlashdoLib(libName, { teams = false } = {}) {+ const cacheKey = `${libName}::${teams}`;+ if (slashdoLibCache.has(cacheKey)) return slashdoLibCache.get(cacheKey);++ const libDir = join(PATHS.slashdo, 'lib');+ let content = await readFile(join(libDir, `${libName}.md`), 'utf-8').catch(() => null);+ if (!content) return null;+ content = await resolveSlashdoIncludes(content, libDir);+ content = resolveSlashdoConditionals(content, { teams });+ slashdoLibCache.set(cacheKey, content);+ return content;+}+export function formatBytes(bytes) {if (!bytes) return '0 B';const units = ['B', 'KB', 'MB', 'GB', 'TB'];diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.jsindex 0f7e4b320a..78ad1142d1 100644--- a/server/lib/fileUtils.test.js+++ b/server/lib/fileUtils.test.js@@ -51,6 +51,8 @@ import {SONGBOOK_ATTACHMENT_EXTENSIONS,saveBase64Upload,serveLocalFile,+ loadSlashdoLib,+ loadSlashdoFile,} from './fileUtils.js';import { copyFileSync, existsSync, mkdirSync } from 'fs';import { dirname } from 'path';@@ -59,6 +61,57 @@ import { fileURLToPath } from 'url';const __dirname_test = dirname(fileURLToPath(import.meta.url));describe('fileUtils', () => {+ // Regression guard for the CoS review-loop bug: PortOS inlines slashdo lib+ // markdown into headless CoS-agent prompts WITHOUT going through slashdo's+ // own per-environment installer, so it must resolve the `<!-- if:teams -->`+ // conditionals itself. Leaving both branches in shipped a self-contradictory+ // reviewer spec (in-process Agent tool AND `claude -p`) to a codex agent,+ // which then improvised its own `claude` invocation via a dozen probe calls.+ describe('loadSlashdoLib', () => {+ it('resolves if:teams conditionals to the non-teams (subprocess) branch by default', async () => {+ const body = await loadSlashdoLib('local-agent-review-loop');+ expect(body).toBeTruthy();+ // No conditional markers survive — both branches must be resolved, not inlined.+ expect(body).not.toMatch(/<!--\s*(if:|else|\/if:)/);+ // The subprocess reviewer invocation (else branch) is present…+ expect(body).toContain('claude -p "$LOCAL_PROMPT"');+ // …and the Claude-Code-only in-process Agent-tool branch is stripped.+ expect(body).not.toMatch(/in-process sub-agent via the .?Agent.? tool/i);+ });++ it('keeps the teams (in-process Agent-tool) branch when teams=true', async () => {+ const body = await loadSlashdoLib('local-agent-review-loop', { teams: true });+ expect(body).toBeTruthy();+ expect(body).not.toMatch(/<!--\s*(if:|else|\/if:)/);+ expect(body).toMatch(/in-process sub-agent via the .?Agent.? tool/i);+ });++ it('returns null for a lib file that does not exist', async () => {+ expect(await loadSlashdoLib('no-such-lib-file-xyz')).toBeNull();+ });+ });++ describe('loadSlashdoFile', () => {+ // `better.md` ships both `if:teams` conditional blocks and `!`cat`` includes+ // of shell-heavy lib files, and is reachable as a user-dispatched CoS command+ // — so it exercises both fixes below.+ it('resolves if:teams conditionals in a command body (not just libs)', async () => {+ const body = await loadSlashdoFile('better');+ expect(body).toBeTruthy();+ expect(body).not.toMatch(/<!--\s*(if:|else|\/if:)/);+ });++ it('inlines lib includes literally — no $-token blowup or corruption', async () => {+ const body = await loadSlashdoFile('better');+ // A bare-string String.replace would interpret `$\``/`$'` tokens in the+ // shell-heavy libs and splice the pre-match content in, ballooning a ~66KB+ // command past 2MB. The function-form replacer keeps it near the sum of the+ // raw sizes (~240KB) and preserves `$`-tokens verbatim.+ expect(body.length).toBeLessThan(600_000);+ expect(body).toContain('$LOCAL_PROMPT');+ });+ });+describe('isValidJSON', () => {it('should return true for valid JSON object', () => {expect(isValidJSON('{"key": "value"}')).toBe(true);diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex e535eb7683..a18ba886b6 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -15,7 +15,7 @@ import { buildPrompt } from './promptService.js';import { getToolsSummaryForPrompt } from './tools.js';import { getActiveProvider } from './providers.js';import { runPromptThroughProvider } from '../lib/promptRunner.js';-import { readJSONFile, loadSlashdoFile, PATHS, tryReadFile } from '../lib/fileUtils.js';+import { readJSONFile, loadSlashdoFile, loadSlashdoLib, PATHS, tryReadFile } from '../lib/fileUtils.js';import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, LOCAL_LLM_REVIEWERS, MODEL_CAPABLE_CLI_REVIEWERS, normalizeReviewers, normalizeReviewUsernames, normalizeOptionalReviewers, resolveReviewUsernames, resolveOptionalReviewers, resolveKeyedReviewers, buildReviewWithArgs } from '../lib/validation.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import { isOpencodeCommand } from '../lib/providerModels.js';@@ -310,9 +310,14 @@ export function reconcileSplitContext(task) {* `/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.* @returns {string}*/-export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false, rprBody = null } = {}) {+export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false, rprBody = null, localAgentLoopBody = null } = {}) {const prUrl = metadata.reviewLoopPRUrl || '';const prBranch = metadata.reviewLoopPRBranch || '';const prNumber = metadata.reviewLoopPRNumber ?? '';@@ -363,6 +368,15 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,const reviewerModelNote = reviewerModelEntries.length? ` When invoking a reviewer with a pinned model, pass it: ${reviewerModelEntries.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.'+ : '';// "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.@@ -394,11 +408,11 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,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 ? `**codex / antigravity / claude / grok**: 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).${reviewerModelNote}` : null,+ hasCli ? `**codex / antigravity / claude / grok**: 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).${reviewerModelNote}${cliProcedurePointer}` : null,hasLocalLlm ? `**lmstudio / ollama**: ${localLlmInvocation}` : null,hasGithubUser ? `**@github reviewers**: ${githubUsersInvocation}` : null,].filter(Boolean).join(' ');- const singleCliInvocation = `Invoke the ${reviewerLabel} 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). Capture its findings as concrete issues to address.${reviewerModelNote}`;+ const singleCliInvocation = `Invoke the ${reviewerLabel} 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). Capture its findings as concrete issues to address.${reviewerModelNote}${cliProcedurePointer}`;// Resolved sequentially so a future reviewer kind only adds one branch// instead of deepening the nested ternary.let waitOrInvokeStep;@@ -441,6 +455,19 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,].join('\n');const extraNotes = [stopModeNote, applyNote].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. 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.+ const cliReviewerProcedure = (hasCli && localAgentLoopBody)+ ? `\n### CLI Reviewer Procedure (codex / antigravity / claude / grok)\n\nDrive each spawnable CLI reviewer EXACTLY as the slashdo local-agent review loop below 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${localAgentLoopBody}\n`+ : '';+if (verbose) {return `## Review-Loop Follow-up (PRIMARY OBJECTIVE)@@ -475,7 +502,7 @@ ${prNumber !== '' ? `- **Number**: ${prNumber}` : ''}${prOwner && prRepo ? `- **Repo**: ${prOwner}/${prRepo}` : ''}- **Source task**: ${sourceTaskId}- **Reviewers**: ${reviewerLabel}-${rprBody ? `\n### /do:rpr Reference (full procedure)\n\nWhen following the procedure below, run it once per reviewer in the list (${reviewerLabel}); substitute the active reviewer for any reference to Copilot — the loop structure is the same but the reviewer source differs.\n\n${rprBody}\n` : ''}`;+${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). 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.@@ -501,7 +528,8 @@ ${rprBody ? `\n### /do:rpr Reference (full procedure)\n\nWhen following the proc'**Hard stop:** if a reviewer is not converged after 10 rounds, post a PR comment summarising blockers and exit.',repeatedCommentsNote,'',- challengeProtocolNote+ challengeProtocolNote,+ cliReviewerProcedure].filter(Boolean).join('\n');}@@ -692,8 +720,16 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfoconst codeReviewDefaults = await getCodeReviewDefaults().catch(() => null);const defaultReviewers = codeReviewDefaults?.reviewers;+ // Preload slashdo's local-agent review-loop recipe once for review-loop+ // follow-up tasks; both the light/TUI path (via lightOptions) and the full+ // path (the verbose builder below) reuse this single value to inline the exact+ // CLI-reviewer invocation. Cheap + cached; only read for follow-ups.+ const localAgentLoopBody = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp)+ ? await loadSlashdoLib('local-agent-review-loop').catch(() => null)+ : null;+if (LIGHT_CONTEXT_PROVIDER_TYPES.has(providerType)) {- const lightOptions = { isTui, providerId, providerCommand, leanMode: options.leanMode === true, defaultReviewers, codeReviewDefaults };+ const lightOptions = { isTui, providerId, providerCommand, leanMode: options.leanMode === true, defaultReviewers, codeReviewDefaults, localAgentLoopBody };return options.split === true? buildLightContextPromptParts(task, workspaceDir, worktreeInfo, isTruthyMetaFn, lightOptions): buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTruthyMetaFn, lightOptions);@@ -853,7 +889,10 @@ After your task completes, the system will spawn a follow-up agent that runs thelet reviewLoopFollowUpSection = '';if (isReviewLoopFollowUp) {const rprBody = await loadSlashdoFile('rpr').catch(() => null);- reviewLoopFollowUpSection = buildReviewLoopFollowUpSection(task.metadata || {}, { verbose: true, rprBody });+ // localAgentLoopBody (the CLI-reviewer recipe) was already preloaded at the+ // top of buildAgentPrompt under the same reviewLoopFollowUp guard — reuse it+ // rather than re-reading the lib a second time.+ reviewLoopFollowUpSection = buildReviewLoopFollowUpSection(task.metadata || {}, { verbose: true, rprBody, localAgentLoopBody });}// Build JIRA context section if applicable@@ -1054,7 +1093,7 @@ export function buildLightContextPromptParts(task, workspaceDir, worktreeInfo, iconst BEGIN_WORKING_LINE = 'Begin working on the task now.';-function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMetaFn, { isTui = true, providerId = null, providerCommand = null, leanMode = false, defaultReviewers, codeReviewDefaults } = {}) {+function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMetaFn, { isTui = true, providerId = null, providerCommand = null, leanMode = false, defaultReviewers, codeReviewDefaults, localAgentLoopBody = null } = {}) {// Idempotent with the reconcile in buildAgentPrompt; also protects the// directly-exported buildLightContextPrompt/Parts entry points.task = reconcileSplitContext(task);@@ -1184,7 +1223,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMetsentinelPath: `${worktreeInfo?.worktreePath || workspaceDir}/.agent-done`,}));} else if (isReviewLoopFollowUp) {- sections.push(buildReviewLoopFollowUpSection(task.metadata || {}, { verbose: false }));+ sections.push(buildReviewLoopFollowUpSection(task.metadata || {}, { verbose: false, localAgentLoopBody }));} else if (isTui) {sections.push(buildTuiCompletionSection({willOpenPR, willReviewLoop, simplifyEnabled, providerId, slashdoFree: tuiSlashdoFree,diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex d902a4e662..62add8a6e8 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -63,7 +63,7 @@ vi.mock('./codeReview.js', () => ({getCodeReviewDefaults: vi.fn().mockResolvedValue({ reviewers: ['copilot'] }),}));-import { buildLightContextPrompt, buildAgentPrompt, buildCompletionGuidelineBullet, reconcileSplitContext } from './agentPromptBuilder.js';+import { buildLightContextPrompt, buildAgentPrompt, buildCompletionGuidelineBullet, reconcileSplitContext, buildReviewLoopFollowUpSection } from './agentPromptBuilder.js';import { getCodeReviewDefaults } from './codeReview.js'; // mocked above — control the configured defaultimport { isTruthyMeta } from './agentState.js';import { buildPrompt } from './promptService.js'; // mocked above — inspect call args@@ -1222,3 +1222,50 @@ describe('buildAgentPrompt — reviewer resolution honors Code Review Defaults (expect(prompt).not.toMatch(/--review-with claude/);});});++describe('buildReviewLoopFollowUpSection — CLI reviewer procedure inlining', () => {+ // The follow-up agent used to receive only "invoke that CLI to review this+ // branch's diff", so a headless codex agent reverse-engineered the `claude`+ // invocation with a dozen probe calls. It now inlines slashdo's local-agent+ // review-loop recipe (passed in as localAgentLoopBody) whenever a spawnable+ // CLI reviewer is configured — never for a copilot/@github-only loop.+ const LOOP_SENTINEL = 'SLASHDO-LOCAL-AGENT-LOOP-BODY-SENTINEL';+ const baseMeta = {+ reviewLoopFollowUp: true,+ sourceTaskId: 't1',+ reviewLoopPRUrl: 'https://github.com/o/r/pull/1',+ reviewLoopPRBranch: 'feature-b',+ };++ for (const verbose of [false, true]) {+ it(`inlines the CLI Reviewer Procedure for a CLI reviewer (verbose=${verbose})`, () => {+ const out = buildReviewLoopFollowUpSection(+ { ...baseMeta, reviewLoopReviewers: ['claude'] },+ { verbose, localAgentLoopBody: LOOP_SENTINEL }+ );+ expect(out).toContain('CLI Reviewer Procedure');+ expect(out).toContain(LOOP_SENTINEL);+ // The vague invocation step points the agent at the inlined procedure.+ expect(out).toMatch(/do NOT probe the CLI/i);+ });+ }++ it('does NOT inline the procedure for a copilot-only loop', () => {+ const out = buildReviewLoopFollowUpSection(+ { ...baseMeta, reviewLoopReviewers: ['copilot'] },+ { verbose: false, localAgentLoopBody: LOOP_SENTINEL }+ );+ expect(out).not.toContain('CLI Reviewer Procedure');+ expect(out).not.toContain(LOOP_SENTINEL);+ });++ it('degrades gracefully when no loop body is available (CLI reviewer, body null)', () => {+ const out = buildReviewLoopFollowUpSection(+ { ...baseMeta, reviewLoopReviewers: ['codex'] },+ { verbose: false, localAgentLoopBody: null }+ );+ expect(out).not.toContain('CLI Reviewer Procedure');+ // Still emits the base invocation step so the loop is not broken.+ expect(out).toMatch(/codex/);+ });+});