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
fix: defer local reviewer pushes until pre-PR gate (#5106)
[._.]/ Adam Eivy149f07382baa
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex d0bb9dd3c4..40be19287e 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -45,7 +45,7 @@ import {isPrBranchWorktree,worktreeCommitGuidance,} from './promptSections/completion.js';-import { buildLocalReviewLoopSection, buildReviewLoopFollowUpSection, isMergeOnlyFollowUp } from './promptSections/reviewLifecycle.js';+import { buildLocalReviewLoopSection, buildReviewLoopFollowUpSection, isMergeOnlyFollowUp, prepareLocalReviewLoopBody } from './promptSections/reviewLifecycle.js';export {detectDomainSkillTemplate,@@ -248,14 +248,17 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfoconst localAgentLoopBody = (isFollowUpNeedingRecipes || isInlineNeedingRecipes)? await loadSlashdoLib('local-agent-review-loop').catch(() => null): null;+ const localAgentLoopBodyForInline = (isInlineNeedingRecipes && !isFollowUpNeedingRecipes)+ ? prepareLocalReviewLoopBody(localAgentLoopBody)+ : localAgentLoopBody;// The recipe is ~40KB. A follow-up agent inlines it — driving the loop is that// agent's entire job, so it will read all of it anyway. An INLINE loop is a// later phase of a run whose context is already carrying the actual task, so an// over-budget recipe is staged on disk and pointed at instead (#3110's split,// applied to the same body). Every host that reaches here has file tools.const localAgentLoopBodyPath = (isInlineNeedingRecipes && !isFollowUpNeedingRecipes- && localAgentLoopBody && localAgentLoopBody.length > SLASHDO_INLINE_BUDGET_CHARS)- ? await writeResolvedSlashdoBody('local-agent-review-loop', localAgentLoopBody).catch((err) => {+ && localAgentLoopBodyForInline && localAgentLoopBodyForInline.length > SLASHDO_INLINE_BUDGET_CHARS)+ ? await writeResolvedSlashdoBody('local-agent-review-loop', localAgentLoopBodyForInline).catch((err) => {console.warn(`⚠️ Could not stage the CLI-reviewer recipe, inlining instead: ${err.message}`);return null;})@@ -263,7 +266,7 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfoif (LIGHT_CONTEXT_PROVIDER_TYPES.has(providerType)) {const forgeCli = await resolveManualForgeCli(workspaceDir, worktreeInfo, task);- const lightOptions = { isTui, providerId, providerCommand, leanMode, agentId, defaultReviewers, codeReviewDefaults, localAgentLoopBody, localAgentLoopBodyPath, forgeCli };+ const lightOptions = { isTui, providerId, providerCommand, leanMode, agentId, defaultReviewers, codeReviewDefaults, localAgentLoopBody: localAgentLoopBodyForInline, localAgentLoopBodyPath, forgeCli };return options.split === true? buildLightContextPromptParts(task, workspaceDir, worktreeInfo, isTruthyMetaFn, lightOptions): buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTruthyMetaFn, lightOptions);diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex e4c9c14e27..eada19b234 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -76,6 +76,7 @@ vi.mock('../lib/slashdoLoader.js', async (importOriginal) => {return {...actual,loadSlashdoFile: vi.fn().mockResolvedValue(null),+ loadSlashdoLib: vi.fn().mockResolvedValue(null),// #3110 — staging the resolved copy is real disk I/O; mocked so tests can// assert the pointer path without writing under data/.writeResolvedSlashdoBody: vi.fn().mockResolvedValue(null),@@ -99,7 +100,7 @@ import { buildPrompt } from './promptService.js'; // mocked above — inspect caimport { getMemorySection } from './memoryRetriever.js';import { getDigitalTwinForPrompt } from './digital-twin.js';import { getToolsSummaryForPrompt } from './tools.js';-import { loadSlashdoFile, writeResolvedSlashdoBody } from '../lib/slashdoLoader.js'; // mocked above — control the inlined body+import { loadSlashdoFile, loadSlashdoLib, writeResolvedSlashdoBody } from '../lib/slashdoLoader.js'; // mocked above — control the inlined bodyimport { SLASHDO_INLINE_BUDGET_CHARS } from '../lib/slashdoInvocation.js';// The heading a task-type hook's prompt points at to locate the sentinel path.import { PROGRAMMATIC_OUTPUT_COMPLETION_HEADING } from '../lib/agentSentinel.js';@@ -876,6 +877,64 @@ describe('buildLightContextPrompt', () => {expect(prompt).not.toMatch(/^\s*\d+\.\s*`\/quit`/m);});+ it('defers the local CLI recipe push until after the local review gate', () => {+ const localRecipe = [+ '### Maintained local recipe',+ '5. **Push verified changes**:',+ ' git push origin {BRANCH_NAME}',+ ' If the push fails: git pull --rebase --autostash && git push origin {BRANCH_NAME}',+ '6. **Re-loop or stop**:',+ ].join('\n');+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex'] } }),+ '/r',+ { branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'main' },+ isTruthyMeta,+ {+ isTui: true,+ providerId: 'opencode-ollama-tui',+ providerCommand: 'opencode',+ localAgentLoopBody: localRecipe,+ });+ const localStart = prompt.indexOf('### Local Review Before Opening the PR/MR');+ const prPush = prompt.indexOf('git push -u origin claim/issue-1');+ const localSection = prompt.slice(localStart, prPush);++ expect(localStart).toBeGreaterThanOrEqual(0);+ expect(prPush).toBeGreaterThan(localStart);+ expect(localSection).toContain('Keep verified changes local');+ expect(localSection).not.toMatch(/^\s*(?:git pull --rebase --autostash && )?git push\b/m);+ expect(localSection).not.toContain('git push origin');+ });++ it('keeps reviewer-applies local fixes off the remote branch', () => {+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex'], reviewerApplies: true } }),+ '/r',+ { branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'main' },+ isTruthyMeta,+ { isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode', localAgentLoopBody: 'RECIPE' });+ const localStart = prompt.indexOf('### Local Review Before Opening the PR/MR');+ const prPush = prompt.indexOf('git push -u origin claim/issue-1');+ const localSection = prompt.slice(localStart, prPush);++ expect(localSection).toContain('keep fixes committed locally');+ expect(localSection).toContain('Do NOT push or open the PR/MR from this loop');+ expect(localSection).not.toContain('then verify, run tests, and push');+ });++ it('quotes the base branch in local review diff commands', () => {+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex'] } }),+ '/r',+ { branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'release; echo bad' },+ isTruthyMeta,+ { isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode', localAgentLoopBody: 'RECIPE' });++ expect(prompt).toContain("git diff 'release; echo bad'...HEAD");+ expect(prompt).not.toContain('git diff release; echo bad...HEAD');+ });+it('runs local review before GitLab MR creation and leaves @ reviewers after it', () => {const prompt = buildLightContextPrompt(makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['ollama'], usernames: ['alice'] } }),@@ -2880,6 +2939,8 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {beforeEach(() => {// mockReset (not just a new return value): several tests here assert the// staging helper was NOT called, so a prior test's call must not leak in.+ vi.mocked(loadSlashdoLib).mockReset();+ vi.mocked(loadSlashdoLib).mockResolvedValue(null);vi.mocked(writeResolvedSlashdoBody).mockReset();vi.mocked(loadSlashdoFile).mockReset();vi.mocked(loadSlashdoFile).mockResolvedValue(OVER);@@ -2937,6 +2998,32 @@ describe('buildAgentPrompt — slashdo prompt-size controls', () => {warn.mockRestore();});+ it('stages a push-free local reviewer recipe for the inline workflow', async () => {+ const body = [+ 'RECIPE HEADER',+ '5. **Push verified changes**:',+ ' git push origin {BRANCH_NAME}',+ ' If the push fails: git pull --rebase --autostash && git push origin {BRANCH_NAME}',+ '6. **Re-loop or stop**:',+ ' continue',+ 'x'.repeat(SLASHDO_INLINE_BUDGET_CHARS + 500),+ ].join('\n');+ vi.mocked(loadSlashdoLib).mockResolvedValue(body);+ vi.mocked(writeResolvedSlashdoBody).mockResolvedValue('/install/data/cos/slashdo-resolved/local-agent-review-loop.md');++ const prompt = await buildAgentPrompt(+ makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex'] } }),+ {}, '/r',+ { branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'main' },+ isTruthyMeta,+ { providerType: 'tui', providerId: 'opencode-tui', providerCommand: 'opencode' });+ const [, stagedBody] = vi.mocked(writeResolvedSlashdoBody).mock.calls.at(-1);++ expect(prompt).toContain('/install/data/cos/slashdo-resolved/local-agent-review-loop.md');+ expect(stagedBody).toContain('Keep verified changes local');+ expect(stagedBody).not.toMatch(/^\s*(?:git pull --rebase --autostash && )?git push\b/m);+ });+// A pinned reviewer list carries the effort as slashdo's own `~effort=<level>`// suffix, so the section states it ONCE — on the pin. The prose instruction is// for the unpinned case, where the workflow resolves reviewers itself.diff --git a/server/services/promptSections/reviewLifecycle.js b/server/services/promptSections/reviewLifecycle.jsindex b7ab25324f..4b4563ae4f 100644--- a/server/services/promptSections/reviewLifecycle.js+++ b/server/services/promptSections/reviewLifecycle.js@@ -5,6 +5,7 @@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 { shellQuote } from '../../lib/shellQuote.js';import { INLINE_REVIEW_LOOP_STEP } from './constants.js';import { normalizeForgeCli } from './forge.js';@@ -21,6 +22,27 @@ export function isMergeOnlyFollowUp(metadata = {}) {return metadata?.reviewLoopMergeOnly === true || metadata?.reviewLoopMergeOnly === 'true';}+/**+ * Adapt slashdo's local-agent recipe for the pre-PR half of a manual workflow.+ * The normal recipe pushes after each reviewer pass so a later PR-side reviewer+ * sees the fixes. A local-only section must keep every fix on the branch until+ * all local reviewers finish; the outer completion workflow performs the one+ * push after that gate.+ */+export function prepareLocalReviewLoopBody(body) {+ if (typeof body !== 'string' || !body) return body;+ const withoutPushStep = body.replace(+ /\r?\n[ \t]*5\. \*\*Push verified changes\*\*:[\s\S]*?(?=\r?\n[ \t]*6\. \*\*Re-loop or stop\*\*:)/,+ '\n5. **Keep verified changes local**:\n Skip the push step here. The outer Completion Workflow pushes the branch only after every local reviewer is clean.\n',+ );+ // Keep a future recipe revision fail-safe if it moves the push command out of+ // the numbered step that the replacement above recognizes.+ return withoutPushStep.replace(+ /^[ \t]*(?:git pull --rebase --autostash && )?git push\b[^\r\n]*\r?$/gm,+ ' # Push is deferred until every local reviewer is clean.',+ );+}+/*** Build the **review-loop follow-up** section — the instructions for the* agent spawned by `spawnReviewLoopFollowUp` to drive Copilot's review-and-fix@@ -47,6 +69,12 @@ export function isMergeOnlyFollowUp(metadata = {}) {* 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.localOnly=false] - Render the pre-PR local-review half+ * of a manual workflow, deferring pushes and PR/MR creation to the caller.+ * @param {string} [opts.baseBranch='<base-branch>'] - Base ref used by local+ * review diff commands when `localOnly` is set.+ * @param {number} [opts.inlineWorkflowStep=INLINE_REVIEW_LOOP_STEP] - Completion+ * workflow step referenced by an inline review or merge-gate section.* @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:@@ -66,6 +94,10 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,const prOwner = metadata.reviewLoopPROwner ?? '';const prRepo = metadata.reviewLoopPRRepo ?? '';const sourceTaskId = metadata.sourceTaskId || 'unknown';+ const renderedBaseBranch = localOnly ? shellQuote(baseBranch) : baseBranch;+ const preparedLocalAgentLoopBody = localOnly+ ? prepareLocalReviewLoopBody(localAgentLoopBody)+ : localAgentLoopBody;const reviewForgeCli = normalizeForgeCli(forgeCli)|| (detectForgeCli(metadata.reviewLoopPRHost) === 'glab' ? 'glab' : 'gh');// Merge-only follow-up (Review Loop off): no reviewer to wait on or invoke —@@ -165,7 +197,7 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,// 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)+ const cliProcedurePointer = (hasCli && preparedLocalAgentLoopBody)? ' 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@@ -253,7 +285,7 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,'diff: .'].join(', ');const diffCommand = localOnly- ? `git diff ${baseBranch}...HEAD`+ ? `git diff ${renderedBaseBranch}...HEAD`: reviewForgeCli === 'glab'? `glab mr diff ${prNumber || '<MR_NUMBER>'}`: `gh pr diff ${prNumber || '<PR_NUMBER>'}`;@@ -282,13 +314,13 @@ Only a successfully extracted \`.findings\` value is the review text; treat it lhasCopilot ? `**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 ${baseBranch}...HEAD\`${localOnly ? '' : `; on GitHub \`gh pr diff ${prNumber || ''}\` also works`}).${cliBinaryNote}${reviewerPinNote}${cliProcedurePointer}` : 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 ${renderedBaseBranch}...HEAD\`${localOnly ? '' : `; 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 ${baseBranch}...HEAD\`${localOnly ? '' : `; on GitHub \`gh pr diff ${prNumber || ''}\` also works`}). Capture its findings as concrete issues to address.${reviewerPinNote}${cliProcedurePointer}`;+ 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 ${renderedBaseBranch}...HEAD\`${localOnly ? '' : `; 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;@@ -306,8 +338,12 @@ Only a successfully extracted \`.findings\` value is the review text; treat it lconst 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).")+ ? (localOnly+ ? '**Reviewer applies:** let each CLI reviewer apply its own fixes to the working tree, then verify and run tests; keep fixes committed locally. Do NOT push or open the PR/MR from this loop.'+ : '**Reviewer applies:** let each CLI reviewer apply its own fixes to the working tree, then verify, run tests, and push.')+ : (localOnly+ ? "**Reviewer applies (off):** read each CLI reviewer's findings and apply the fixes yourself (default); keep fixes committed locally. Do NOT push or open the PR/MR from this loop."+ : "**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,@@ -350,35 +386,40 @@ Only a successfully extracted \`.findings\` value is the review text; treat it lconst 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`,+ // Inline slashdo's local-agent review loop 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.+ // engineers the invocation, wasting calls. For the pre-PR local section,+ // `preparedLocalAgentLoopBody` removes the recipe's push step so the agent+ // keeps fixes local until every local reviewer is clean. The normal PR-side+ // follow-up still receives the maintained body verbatim. Both variants agree+ // with `cliBinaryNote`: 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`;+ const localOnlyProcedureNote = localOnly+ ? '**Pre-PR local-review rule:** keep every reviewer fix committed locally. Do NOT push or open a PR/MR from this procedure; the outer Completion Workflow performs the push after every local reviewer is clean.\n\n'+ : '';+ const cliProcedureHeader = `\n### CLI Reviewer Procedure (${cliReviewerHeading})\n\n${localOnlyProcedureNote}Drive 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)+ const cliReviewerProcedure = (hasCli && preparedLocalAgentLoopBody)? (localAgentLoopBodyPath- ? `${cliProcedureHeader}${oversizedBodyPointer(localAgentLoopBodyPath, localAgentLoopBody)}\n`- : `${cliProcedureHeader}${localAgentLoopBody}\n`)+ ? `${cliProcedureHeader}${oversizedBodyPointer(localAgentLoopBodyPath, preparedLocalAgentLoopBody)}\n`+ : `${cliProcedureHeader}${preparedLocalAgentLoopBody}\n`): '';// A JIRA-tracked PR is a human's to land (its ticket is already "In Review" and