Skip to content

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

stop telling auto-merge worktree agents to /do:push their branch

[._.]/ Adam Eivyb8b4354227ae
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 9d4a3f6869..b3cbdb93f7 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -47,6 +47,7 @@ import {
claimReviewersCsv,
inlinePrLifecycleSection,
isPrBranchWorktree,
+ portosMergesBranchOnExit,
worktreeCommitGuidance,
} from './promptSections/completion.js';
import { buildLocalReviewLoopSection, buildReviewLoopFollowUpSection, isMergeOnlyFollowUp, prepareLocalReviewLoopBody, prepareSandboxedReviewLoopBody } from './promptSections/reviewLifecycle.js';
@@ -416,6 +417,9 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo
const willOpenPR = isTruthyMetaFn(task.metadata?.openPR);
const whenDone = task.metadata?.whenDone === 'commit-push' ? 'commit-push' : 'leave-uncommitted';
const claimFlow = isClaimFlowTask(task, isTruthyMetaFn);
+ // Worktree with no PR: PortOS merges the branch back on exit, so every
+ // commit/push instruction below is commit-only (see portosMergesBranchOnExit).
+ const portosMergesBranch = portosMergesBranchOnExit({ worktreeInfo, willOpenPR });
const prCompletion = resolvePrCompletion(task.metadata);
// A discard (reasoning-only) worktree: the agent reasons in it but it's thrown
// away on exit with no commit/merge/PR (see agentWorktreeCleanup.js). Suppresses
@@ -488,7 +492,7 @@ ${buildResumeSection(task, worktreeInfo)}` : '';
// Discard tasks don't commit, so the simplify-before-commit step is moot.
const simplifySection = simplifyEnabled && !isTui && !discardWorktree && !claimFlow ? `
## Simplify Step
-After completing your work and before committing, ${simplifyInstruction}. Fix any issues found, then ${worktreeInfo && willOpenPR ? 'commit your changes (do NOT push — on a successful run the system will push and open the PR after you exit; if the run fails, no push or PR happens)' : 'commit and push using `/do:push`'}.
+After completing your work and before committing, ${simplifyInstruction}. Fix any issues found, then ${worktreeInfo && willOpenPR ? 'commit your changes (do NOT push — on a successful run the system will push and open the PR after you exit; if the run fails, no push or PR happens)' : portosMergesBranch ? 'commit your changes (do NOT push — PortOS merges this branch back into the source checkout after you exit; a pushed copy would only be left behind on origin)' : 'commit and push using `/do:push`'}.
` : '';
// Resolve the user's ordered reviewer list + flags (task metadata wins; else the
@@ -526,7 +530,9 @@ After completing your work and before committing, ${simplifyInstruction}. Fix an
// sentinel is the done signal — PortOS finalizes via the watcher and kills
// the session, so the prompt does NOT ask the agent to `/quit` (it's a UI
// command the agent can't invoke). See `buildTuiCompletionSection` below.)
- const tuiCompletionCommand = willOpenPR ? '/do:pr' : '/do:push';
+ // `null` under the auto-merge posture: there is no command to run — the step
+ // is a plain commit (buildCompletionGuidelineBullet renders that case).
+ const tuiCompletionCommand = willOpenPR ? '/do:pr' : portosMergesBranch ? null : '/do:push';
const sentinelPath = resolveSentinelPath(worktreeInfo, workspaceDir, agentId);
// A discard task's completion is the sentinel-only contract (no push/PR/merge),
// and this applies to every provider type — so it wins over the isTui fork and
@@ -548,7 +554,7 @@ After completing your work and before committing, ${simplifyInstruction}. Fix an
? buildClaimFlowCompletionSection({ isTui, sentinelPath, reviewersCsv: claimReviewersCsv(task, codeReviewDefaults, defaultReviewers) })
: isTui
? buildTuiCompletionSection({
- willOpenPR, prCompletion, simplifyEnabled, noChangeSuccess,
+ willOpenPR, prCompletion, simplifyEnabled, noChangeSuccess, portosMergesBranch,
// Unreachable today — every `tui`/`cli` provider returns early at the
// LIGHT_CONTEXT gate above, so `isTui` is always false on this path
// (same situation as buildCompletionGuidelineBullet's `isTui` arm).
@@ -747,6 +753,8 @@ ${skillSection ? `## Task-Type Skill Guidelines\n\n${skillSection}\n` : ''}${too
? 'Follow the claim workflow prompt above; it owns its worktree, PR/MR, review, merge or human-handoff, and cleanup. Do not stop after committing.'
: isReviewLoopFollowUp
? 'Follow the follow-up section above — push any fixes you make to the PR branch; a run that needed no fix makes no commit and that is a success, not a miss'
+ : portosMergesBranch
+ ? `Commit your changes (see ${isTui ? 'Completion Workflow above' : 'Git Hygiene below'}) — do NOT push, PortOS merges this branch back on exit`
: isTui
? `Commit, push, and ${willOpenPR ? 'open the PR (see Completion Workflow above)' : 'push the branch (see Completion Workflow above)'}`
: worktreeInfo && willOpenPR
@@ -789,6 +797,8 @@ ${toolFreeReasoning
? `- **Push fixes straight to the PR branch you are on** (the follow-up section above is the procedure). Stage specific files, use a \`fix:\` prefix, no Co-Authored-By annotations. Do NOT open a new PR.`
: isTui && tuiSlashdoFree
? `- **Commit only — do NOT push.** Stage specific files, use \`feat:\`/\`fix:\`/\`breaking:\` prefix in the commit message, no Co-Authored-By annotations, then write the completion sentinel. PortOS will handle the branch after it closes the session.`
+ : portosMergesBranch
+ ? `- **Commit only — do NOT push.** Stage specific files (no \`git add -A\`), use \`feat:\`/\`fix:\`/\`breaking:\` prefix in the commit message, no Co-Authored-By annotations. PortOS merges this branch back into the source checkout after you exit and deletes it, so do NOT run \`git push\` or \`/do:push\` yourself — a pushed copy would only be left behind on origin.`
: isTui
? `- **Use \`${tuiCompletionCommand}\` to ${willOpenPR ? 'commit, push, and open the PR' : 'commit and push the branch'}** — see the Completion Workflow section above. Stage specific files (no \`git add -A\`), use \`feat:\`/\`fix:\`/\`breaking:\` prefix in the commit message, no Co-Authored-By annotations.`
: worktreeInfo && willOpenPR
@@ -854,6 +864,9 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
task = reconcileSplitContext(task);
const willOpenPR = isTruthyMetaFn(task.metadata?.openPR);
const claimFlow = isClaimFlowTask(task, isTruthyMetaFn);
+ // Worktree with no PR: PortOS merges the branch back on exit, so the commit
+ // guidance and completion workflow are commit-only (portosMergesBranchOnExit).
+ const portosMergesBranch = portosMergesBranchOnExit({ worktreeInfo, willOpenPR });
const prCompletion = resolvePrCompletion(task.metadata);
const simplifyEnabled = isTruthyMetaFn(task.metadata?.simplify);
const isReadOnly = isTruthyMetaFn(task.metadata?.readOnly);
@@ -1084,7 +1097,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
}
} else if (isTui) {
contractSections.push(buildTuiCompletionSection({
- willOpenPR, prCompletion, simplifyEnabled, noChangeSuccess, slashdoFree: tuiSlashdoFree, ownsPrWorkflow,
+ willOpenPR, prCompletion, simplifyEnabled, noChangeSuccess, slashdoFree: tuiSlashdoFree, ownsPrWorkflow, portosMergesBranch,
sentinelPath: resolveSentinelPath(worktreeInfo, workspaceDir, agentId),
branchName: worktreeInfo?.branchName || null,
baseBranch: worktreeInfo?.baseBranch || null,
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index df1db56b8b..8c6eb57b6a 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -112,6 +112,7 @@ vi.mock('./codeReview.js', () => ({
}));
import { buildLightContextPrompt, buildAgentPrompt, buildCompletionGuidelineBullet, reconcileSplitContext, buildReviewLoopFollowUpSection, getAppWorkspace, getAgentInstructionsContext, detectSkillTemplates, loadSkillTemplates, UI_AUDIT_RUNTIME_RULE, UI_AUDIT_TASK_TYPES, UNATTENDED_RUN_RULE } from './agentPromptBuilder.js';
+import { portosMergesBranchOnExit } from './promptSections/completion.js';
import { getCodeReviewDefaults } from './codeReview.js'; // mocked above — control the configured default
import { isTruthyMeta } from './agentState.js';
import { buildPrompt } from './promptService.js'; // mocked above — inspect call args
@@ -963,7 +964,9 @@ describe('buildLightContextPrompt', () => {
expect(prompt).toMatch(/review your changed code for reuse, quality, and efficiency/i);
});
- it('renders the Completion Workflow with /do:push when openPR is false', () => {
+ it('renders the Completion Workflow with /do:push when openPR is false and there is no worktree', () => {
+ // No worktree: the agent stands on the branch it should push, and PortOS
+ // merges nothing on exit — so /do:push is the right completion step.
const prompt = buildLightContextPrompt(
makeTask({ metadata: { simplify: true, openPR: false } }),
'/r', null, isTruthyMeta, { isTui: true });
@@ -973,6 +976,28 @@ describe('buildLightContextPrompt', () => {
expect(prompt).not.toMatch(/gh pr merge/);
});
+ it('renders a commit-only Completion Workflow for a worktree with openPR false — PortOS merges it back', () => {
+ // Worktree + no PR is the auto-merge posture: cleanup merges the branch
+ // into the source checkout and deletes it. A push has no consumer there,
+ // and the remote copy `/do:push` left behind is what the repo-state audit
+ // reported as "never deleted" and filed recovery agents for (every
+ // module-hygiene audit of 2026-09-06/07).
+ const prompt = buildLightContextPrompt(
+ makeTask({ metadata: { simplify: true, openPR: false } }),
+ '/r',
+ { branchName: 'cos/task-1/agent-a', worktreePath: '/tmp/wt', baseBranch: 'main' },
+ isTruthyMeta, { isTui: true });
+ expect(prompt).toMatch(/## Completion Workflow/);
+ expect(prompt).toMatch(/^1\. `\/simplify`/m);
+ expect(prompt).toMatch(/^2\. Stage only the files you changed \(never `git add -A` \/ `git add \.`\) and commit with a conventional message/m);
+ expect(prompt).toMatch(/Do NOT push and do NOT open a PR: PortOS merges this branch into `main` in the source checkout after you exit and deletes it/);
+ expect(prompt).not.toMatch(/^\s*\d+\.\s+`\/do:push/m);
+ expect(prompt).not.toMatch(/`\/do:pr`/);
+ expect(prompt).not.toMatch(/gh pr merge/);
+ // The sentinel still names the branch PortOS is about to merge.
+ expect(prompt).toMatch(/## Branch/);
+ });
+
it('runs slashdo-free local reviewers before GitHub PR creation, then keeps PR-side review after it', () => {
// OpenCode TUI doesn't load Claude Code slash commands, so /do:pr / /do:push
// would be uninvokable — but it runs `git`/`gh` and the reviewer CLIs fine,
@@ -1658,17 +1683,20 @@ describe('buildLightContextPrompt', () => {
expect(prompt).toMatch(/gh pr merge "<PR_URL>" --merge --delete-branch/);
});
- it('uses /do:push (not /do:pr) for Claude Code CLI when openPR is false', () => {
+ it('tells Claude Code CLI to commit only (no /do:push) when PortOS merges the worktree branch back', () => {
+ // Same auto-merge posture as the TUI case above, on the CLI path.
const prompt = buildLightContextPrompt(
makeTask({ metadata: { openPR: false, simplify: true } }),
'/r',
- { branchName: 'b', worktreePath: '/tmp/wt' },
+ { branchName: 'b', worktreePath: '/tmp/wt', baseBranch: 'main' },
isTruthyMeta,
{ isTui: false, providerId: 'claude-code' });
- expect(prompt).toMatch(/`\/do:push`/);
+ expect(prompt).toMatch(/^\s*\d+\.\s+Stage only the files you changed \(never `git add -A` \/ `git add \.`\) and commit with a conventional message/m);
+ expect(prompt).toMatch(/Do NOT push and do NOT open a PR: PortOS merges this branch into `main` in the source checkout after you exit and deletes it/);
+ expect(prompt).not.toMatch(/^\s*\d+\.\s+`\/do:push/m);
expect(prompt).not.toMatch(/`\/do:pr`/);
- // /do:push doesn't open a PR — no merge step should be emitted.
expect(prompt).not.toMatch(/gh pr merge/);
+ expect(prompt).not.toMatch(/git push/);
});
it('suppresses the PR completion workflow but still writes a sentinel when readOnly + TUI', () => {
@@ -2294,11 +2322,9 @@ describe('buildLightContextPrompt', () => {
expect(prompt).not.toMatch(/## Resuming Unfinished Work/);
});
- it('worktreeCommitGuidance: hasSlashdo + !willOpenPR emits the push-only Completion wording', () => {
- // Claude Code CLI with a worktree but no PR (e.g. a managed-app task
- // whose flow is "push the branch, no PR"). The agent owns its own
- // /simplify + /do:push, so the worktree guidance points at the
- // Completion section's push (not the PR variant).
+ it('worktreeCommitGuidance: hasSlashdo + !willOpenPR says commit only — PortOS merges the branch back', () => {
+ // Claude Code CLI with a worktree but no PR is the auto-merge posture: the
+ // worktree guidance must not point the agent at a push nothing consumes.
const prompt = buildLightContextPrompt(
makeTask({ metadata: { openPR: false, simplify: true } }),
'/r',
@@ -2306,9 +2332,8 @@ describe('buildLightContextPrompt', () => {
isTruthyMeta,
{ isTui: false, providerId: 'claude-code' });
expect(prompt).toMatch(/## Git Worktree/);
- // Push-only Completion wording — NOT the "push and PR" variant.
- expect(prompt).toMatch(/the \*\*Completion\*\* section below drives the push\./);
- expect(prompt).not.toMatch(/drives the push and PR/);
+ expect(prompt).toMatch(/Commit your changes here — do NOT push\. PortOS merges this branch back after you exit/);
+ expect(prompt).not.toMatch(/drives the push/);
// And NOT the post-exit handoff message (that's the codex/antigravity path).
expect(prompt).not.toMatch(/The system will push and open a PR after you exit/);
});
@@ -2525,21 +2550,29 @@ describe('buildAgentPrompt — provider type routing', () => {
});
it('without leanMode a claude TUI still gets the slashdo workflow', async () => {
+ // A worktree with no PR is commit-only on every path (PortOS merges it
+ // back), so the slashdo marker is `/simplify` — only a slashdo-capable
+ // session is told to run it.
+ const task = splitTask();
const prompt = await buildAgentPrompt(
- splitTask(), {}, '/r', wt, isTruthyMeta,
+ { ...task, metadata: { ...task.metadata, simplify: true } }, {}, '/r', wt, isTruthyMeta,
{ providerType: 'tui', providerId: 'claude-code-tui', providerCommand: 'claude' });
- expect(prompt).toMatch(/\/do:push/);
+ expect(prompt).toMatch(/^1\. `\/simplify`/m);
+ expect(prompt).not.toMatch(/does NOT have slashdo/);
+ expect(prompt).not.toMatch(/^\s*\d+\.\s+`\/do:push/m);
});
it('splits a STANDARD (non-lean) claude TUI too, keeping slashdo in the system prompt', async () => {
+ const task = splitTask();
const parts = await buildAgentPrompt(
- splitTask(), {}, '/r', wt, isTruthyMeta,
+ { ...task, metadata: { ...task.metadata, simplify: true } }, {}, '/r', wt, isTruthyMeta,
{ providerType: 'tui', providerId: 'claude-code-tui', providerCommand: 'claude', split: true });
// Task in the user prompt, contract (with slashdo — NOT slashdo-free) in system.
expect(parts.userPrompt).toMatch(/Add a button to the dashboard/);
expect(parts.userPrompt).not.toMatch(/## Completion Workflow/);
expect(parts.systemPrompt).toMatch(/## Completion Workflow/);
- expect(parts.systemPrompt).toMatch(/\/do:push/);
+ expect(parts.systemPrompt).toMatch(/^1\. `\/simplify`/m);
+ expect(parts.systemPrompt).not.toMatch(/does NOT have slashdo/);
});
it('split parts carry exactly the combined prompt for a standard claude CLI (no drift)', async () => {
@@ -4036,3 +4069,55 @@ describe('planner attribution', () => {
expect(prompt).not.toMatch(/planner:/);
});
});
+
+describe('auto-merge posture (worktree, no PR) is commit-only on every path', () => {
+ // `portosMergesBranchOnExit` is the one decision the completion, hygiene and
+ // worktree sections all key on. Pinned as a table because a wrong answer here
+ // re-arms the `/do:push` that filed a recovery agent after every
+ // module-hygiene audit on 2026-09-06/07.
+ it('answers true only for a worktree run with no PR', () => {
+ const worktreeInfo = { branchName: 'b', worktreePath: '/tmp/wt' };
+ expect(portosMergesBranchOnExit({ worktreeInfo, willOpenPR: false })).toBe(true);
+ expect(portosMergesBranchOnExit({ worktreeInfo, willOpenPR: true })).toBe(false);
+ expect(portosMergesBranchOnExit({ worktreeInfo: null, willOpenPR: false })).toBe(false);
+ });
+
+ it('api path: the simplify step, instructions and Git Hygiene all say commit only, never /do:push', async () => {
+ const prompt = await buildAgentPrompt(
+ makeTask({ metadata: { openPR: false, simplify: true } }),
+ {}, '/r',
+ { branchName: 'cos/task-1/agent-a', worktreePath: '/tmp/wt', baseBranch: 'main' },
+ isTruthyMeta, { providerType: 'api' });
+ expect(prompt).toMatch(/Fix any issues found, then commit your changes \(do NOT push — PortOS merges this branch back into the source checkout after you exit/);
+ expect(prompt).toMatch(/Commit your changes \(see Git Hygiene below\) — do NOT push, PortOS merges this branch back on exit/);
+ expect(prompt).toMatch(/\*\*Commit only — do NOT push\.\*\* Stage specific files \(no `git add -A`\), use `feat:`\/`fix:`\/`breaking:` prefix in the commit message, no Co-Authored-By annotations\. PortOS merges this branch back into the source checkout after you exit and deletes it, so do NOT run `git push` or `\/do:push` yourself/);
+ expect(prompt).not.toMatch(/Commit and push using `\/do:push`/);
+ expect(prompt).not.toMatch(/Commit and push your changes/);
+ // The Guidelines bullet already described the merge-back; it still does.
+ expect(prompt).toMatch(/Your worktree branch will be automatically merged back to the source branch/);
+ });
+
+ it('api path: the same task WITHOUT a worktree keeps commit-and-push', async () => {
+ const prompt = await buildAgentPrompt(
+ makeTask({ metadata: { openPR: false, simplify: true } }),
+ {}, '/r', null, isTruthyMeta, { providerType: 'api' });
+ expect(prompt).toMatch(/commit and push using `\/do:push`/);
+ expect(prompt).toMatch(/Commit and push using `\/do:push`/);
+ expect(prompt).not.toMatch(/PortOS merges this branch back/);
+ });
+
+ it('buildCompletionGuidelineBullet renders the commit-only TUI wording when there is no completion command', () => {
+ const bullet = buildCompletionGuidelineBullet({
+ isReadOnly: false, isTui: true, tuiCompletionCommand: null,
+ worktreeInfo: { worktreePath: '/wt' }, willOpenPR: false,
+ });
+ expect(bullet).toMatch(/commit only — no push; PortOS merges your branch back after you exit/);
+ expect(bullet).not.toMatch(/`\/do:push`/);
+ // The command form is untouched when one exists.
+ const withCommand = buildCompletionGuidelineBullet({
+ isReadOnly: false, isTui: true, tuiCompletionCommand: '/do:push',
+ worktreeInfo: null, willOpenPR: false,
+ });
+ expect(withCommand).toMatch(/`\/do:push`/);
+ });
+});
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index 0dce5e1044..25ab23bef3 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -22,6 +22,7 @@ import * as git from './git.js';
import { removeWorktree, classifyWorktreeDirt } from './worktreeManager.js';
import { isTruthyMeta } from './agentState.js';
import { PATHS } from '../lib/fileUtils.js';
+import { execGit } from '../lib/execGit.js';
import { isRetryHoldOwner, clearedRetryHoldMetadata } from '../lib/taskRetryHold.js';
import { resolveTaskTargetBranch, shouldStripTaskTargetBranch } from '../lib/taskTargetBranch.js';
import { RECOVERY_TASK_PREFIX } from './recoveryTasks.js';
@@ -470,6 +471,14 @@ async function runCleanupAgentWorktree(agentId, success, { prCreation = PR_CREAT
});
warnings.push(...(result?.warnings || []));
+ // The branch just landed by local merge. If the agent pushed it anyway — an
+ // older prompt said `/do:push` under this posture, and the repo's own
+ // "commit and push" convention still reaches every agent — origin holds a
+ // copy nothing will ever read, which the post-completion audit reports as a
+ // leaked remote branch and hands to a recovery agent. Finish the job here,
+ // deterministically, instead of paying a model to run one `git push --delete`.
+ if (result?.merged) await deleteMergedRemoteCopy(agentId, sourceWorkspace, worktreeBranch);
+
// The branch is released now, so the follow-up can check it out.
if (strandedPrUrl) {
await spawnReviewLoopFollowUp({
@@ -490,6 +499,46 @@ async function runCleanupAgentWorktree(agentId, success, { prCreation = PR_CREAT
return warnings;
}
+/**
+ * Delete origin's copy of a worktree branch that cleanup just merged locally.
+ *
+ * Cheap on the common path, narrow on the rare one:
+ * - A push from the worktree updates the shared clone's remote-tracking ref,
+ * so `refs/remotes/origin/<branch>` answers "did this agent push?" with one
+ * local rev-parse and no network. Absent ⇒ nothing to do. (A push from some
+ * other clone is invisible here; the repo-state audit still reports it.)
+ * - Merged-ness is `git.isBranchMergedInto` — the definition the branch-
+ * reconcile reaper and `removeWorktree` already use — so a copy the agent
+ * amended or rebased after pushing (patch-equivalent, not an ancestor) still
+ * counts as landed, and an unresolvable object fails closed.
+ * - The delete is lease-protected against the SHA this clone last pushed: one
+ * round trip that asserts and deletes atomically, refused as "stale info" if
+ * origin has since moved. Nothing is deleted on stale knowledge.
+ * Never adds a warning: a warning is what spawns cleanup's own merge-recovery
+ * task, and a copy that could not be deleted is exactly what the audit exists
+ * to catch on its own.
+ */
+async function deleteMergedRemoteCopy(agentId, sourceWorkspace, branchName) {
+ const remoteRef = `refs/heads/${branchName}`;
+ const tracked = await execGit(['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${branchName}`], sourceWorkspace, { ignoreExitCode: true })
+ .catch(() => null);
+ const pushedSha = tracked?.exitCode === 0 ? tracked.stdout.trim() : '';
+ if (!pushedSha) return;
+ const landed = await git.isBranchMergedInto(sourceWorkspace, pushedSha, 'HEAD').catch(() => false);
+ if (!landed) {
+ emitLog('warn', `🌳 origin/${branchName} (${pushedSha.slice(0, 7)}) is not merged into the checkout that received the branch — left in place for the repo-state audit`, { agentId, branchName });
+ return;
+ }
+ const pushed = await execGit(['push', `--force-with-lease=${remoteRef}:${pushedSha}`, 'origin', `:${remoteRef}`], sourceWorkspace, { ignoreExitCode: true })
+ .catch(err => ({ exitCode: 1, stderr: err.message }));
+ if (pushed.exitCode === 0) {
+ emitLog('info', `🌳 ${agentId} pushed ${branchName} but cleanup merged it locally — deleted the remote copy`, { agentId, branchName });
+ return;
+ }
+ const why = String(pushed.stderr || '').trim().split('\n').pop() || `exit ${pushed.exitCode}`;
+ emitLog('warn', `🌳 Could not delete origin/${branchName} after merging it locally (${why}) — left for the repo-state audit`, { agentId, branchName });
+}
+
/**
* What, if anything, should a retry of this task pick up from the run that just
* died? Called after cleanup has decided what to preserve, so the answer reflects
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index d2b6648d96..ae7a0c35cc 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -212,6 +212,14 @@ vi.mock('./github.js', () => ({
findPullRequestForBranch: (...args) => findPullRequestForBranchMock(...args)
}));
+// `deleteMergedRemoteCopy` reads the remote-tracking ref and runs its
+// lease-protected delete through execGit directly (git.js has no helper for
+// either). Defaults to a non-zero exit — the answer that leaves everything alone.
+const execGitMock = vi.fn().mockResolvedValue({ exitCode: 128, stdout: '', stderr: '' });
+vi.mock('../lib/execGit.js', () => ({
+ execGit: (...args) => execGitMock(...args)
+}));
+
// The `if-missing` safety net asks finalize's own PR-claim check whether
// the agent actually opened the PR it was told to open (#3733).
const verifyPrClaimMock = vi.fn();
@@ -2104,3 +2112,70 @@ describe('cleanupAgentWorktree — re-entrancy (duplicate completion paths)', ()
expect(removeWorktree).toHaveBeenCalledTimes(2);
});
});
+
+describe('cleanupAgentWorktree - remote copy of a locally merged branch', () => {
+ // The auto-merge posture (worktree, no PR) lands the branch by local merge and
+ // deletes it. An agent that pushed the branch anyway leaves origin a copy
+ // nothing reads, which the repo-state audit then reports and files a recovery
+ // agent for. Cleanup deletes that copy itself — off the shared clone's
+ // remote-tracking ref (a worktree push updates it, so the common no-push case
+ // never touches the network), only when the pushed tip is already merged, and
+ // lease-protected so a copy origin moved past is refused rather than deleted.
+ const BRANCH = 'cos/task-abc123';
+ const REF = `refs/heads/${BRANCH}`;
+ const SHA = 'a'.repeat(40);
+ const mergedLocally = () => removeWorktree.mockResolvedValue({ merged: true, removed: true, uncommittedSaved: false, warnings: [] });
+ const tracking = (sha) => ({ exitCode: sha ? 0 : 1, stdout: sha ? `${sha}\n` : '', stderr: '' });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getAgent.mockResolvedValue(mockWorktreeAgent());
+ });
+
+ it('deletes origin\'s copy, lease-protected, when the pushed tip is already merged', async () => {
+ mergedLocally();
+ execGitMock
+ .mockResolvedValueOnce(tracking(SHA))
+ .mockResolvedValueOnce({ exitCode: 0, stdout: '', stderr: '' });
+ git.isBranchMergedInto.mockResolvedValueOnce(true);
+ const warnings = await cleanupAgentWorktree('agent-1', true, {});
+ expect(execGitMock).toHaveBeenNthCalledWith(1, ['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${BRANCH}`], '/mock/workspace', { ignoreExitCode: true });
+ expect(git.isBranchMergedInto).toHaveBeenCalledWith('/mock/workspace', SHA, 'HEAD');
+ expect(execGitMock).toHaveBeenNthCalledWith(2, ['push', `--force-with-lease=${REF}:${SHA}`, 'origin', `:${REF}`], '/mock/workspace', { ignoreExitCode: true });
+ // A clean finish, not a cleanup issue — no warning, so no recovery task.
+ expect(warnings).toEqual([]);
+ });
+
+ it('never touches the network when this clone never pushed the branch', async () => {
+ mergedLocally();
+ execGitMock.mockResolvedValueOnce(tracking(null));
+ await cleanupAgentWorktree('agent-1', true, {});
+ expect(execGitMock).toHaveBeenCalledTimes(1);
+ expect(git.isBranchMergedInto).not.toHaveBeenCalled();
+ });
+
+ it('leaves the copy alone when the pushed tip is not merged into the checkout', async () => {
+ mergedLocally();
+ execGitMock.mockResolvedValueOnce(tracking(SHA));
+ git.isBranchMergedInto.mockResolvedValueOnce(false);
+ const warnings = await cleanupAgentWorktree('agent-1', true, {});
+ expect(execGitMock).toHaveBeenCalledTimes(1);
+ expect(warnings).toEqual([]);
+ });
+
+ it('never asks about the remote unless cleanup actually merged the branch', async () => {
+ removeWorktree.mockResolvedValue({ merged: false, removed: true, uncommittedSaved: false, warnings: [] });
+ await cleanupAgentWorktree('agent-1', true, { skipMerge: true });
+ expect(execGitMock).not.toHaveBeenCalled();
+ });
+
+ it('a refused or failed delete is logged, not warned — the repo-state audit reports what is left', async () => {
+ mergedLocally();
+ execGitMock
+ .mockResolvedValueOnce(tracking(SHA))
+ .mockResolvedValueOnce({ exitCode: 1, stdout: '', stderr: ` ! [rejected] ${BRANCH} (stale info)` });
+ git.isBranchMergedInto.mockResolvedValueOnce(true);
+ const warnings = await cleanupAgentWorktree('agent-1', true, {});
+ expect(warnings).toEqual([]);
+ });
+});
diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.js
index e90904ebf7..5f47e8733b 100644
--- a/server/services/promptSections/completion.js
+++ b/server/services/promptSections/completion.js
@@ -31,7 +31,9 @@ function withNoChangeAuditGuidance(guidance, noChangeSuccess) {
* @param {Object} opts
* @param {boolean} opts.isReadOnly
* @param {boolean} opts.isTui
- * @param {string} opts.tuiCompletionCommand - `/do:pr` or `/do:push`
+ * @param {string|null} opts.tuiCompletionCommand - `/do:pr` or `/do:push`; `null`
+ * when PortOS merges the branch back itself and the workflow is commit-only
+ * (see `portosMergesBranchOnExit`)
* @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
@@ -87,7 +89,9 @@ export function buildCompletionGuidelineBullet({
// 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}\`)`;
+ : tuiCompletionCommand
+ ? `the Completion Workflow above (\`${tuiCompletionCommand}\`)`
+ : 'the Completion Workflow above (commit only — no push; PortOS merges your branch back after you exit)';
return withNoChangeAuditGuidance(`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\`.`, noChangeSuccess);
}
if (worktreeInfo && willOpenPR) {
@@ -102,7 +106,7 @@ export function buildCompletionGuidelineBullet({
: ' 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 withNoChangeAuditGuidance(`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}`, noChangeSuccess);
}
- if (worktreeInfo) {
+ if (portosMergesBranchOnExit({ worktreeInfo, willOpenPR })) {
return withNoChangeAuditGuidance('Your worktree branch will be automatically merged back to the source branch when your task completes — do NOT open a PR.', noChangeSuccess);
}
return whenDone === null ? null : whenDone === 'commit-push'
@@ -321,6 +325,52 @@ export function buildClaimFlowCompletionSection({ isTui = false, sentinelPath =
return lines.join('\n');
}
+/**
+ * Does PortOS land this run's branch ITSELF? True under the worktree-without-PR
+ * posture (`useWorktree: true`, `openPR: false`): once the agent exits,
+ * `agentWorktreeCleanup.js` merges the worktree branch into the source checkout
+ * and deletes it (`removeWorktree` with `merge: true`). Nothing on that path
+ * reads a remote copy of the branch, so a push has no consumer — and because
+ * the local branch is deleted the moment the merge lands, a pushed copy becomes
+ * an orphan that the post-completion audit (`agentRepoStateVerification.js`)
+ * reports as "remote branch was never deleted" and hands to a recovery agent.
+ * The `/do:push` completion step this posture used to get produced exactly
+ * that, run after run (every module-hygiene audit on 2026-09-06/07, and user
+ * tasks with the same posture before them — each followed by a recovery agent
+ * that then pushed the merged commit straight to the default branch). So under
+ * this posture the contract is commit-only, on every path that can type slashdo.
+ *
+ * The other worktree contracts (discard, claim flow, PR follow-up, no-code) are
+ * decided BEFORE this question is asked — callers apply their precedence first,
+ * the way `buildCompletionGuidelineBullet` does.
+ *
+ * @param {object} params
+ * @param {object|null} params.worktreeInfo
+ * @param {boolean} params.willOpenPR
+ * @returns {boolean}
+ */
+export function portosMergesBranchOnExit({ worktreeInfo, willOpenPR }) {
+ return Boolean(worktreeInfo) && !willOpenPR;
+}
+
+// The one commit-hygiene sentence every manual commit step composes — the
+// slashdo-free TUI workflow, the PR-owning CLI workflow and the auto-merge
+// commit step — so a hygiene change lands in all three at once.
+const COMMIT_HYGIENE_SENTENCE = '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)';
+
+/**
+ * The commit step of a completion workflow whose branch PortOS merges back
+ * (`portosMergesBranchOnExit`). One string for the Claude TUI and Claude CLI
+ * workflows so the two cannot drift into different pushing advice.
+ *
+ * @param {string|null} [baseBranch] - the branch the worktree was cut from
+ * @returns {string}
+ */
+export function buildAutoMergeCommitStep(baseBranch = null) {
+ const target = baseBranch ? `\`${baseBranch}\`` : 'the source branch';
+ return `${COMMIT_HYGIENE_SENTENCE}. Do NOT push and do NOT open a PR: PortOS merges this branch into ${target} in the source checkout after you exit and deletes it, so a pushed copy is never read — it is only left behind on origin.`;
+}
+
/**
* Worktree commit-guidance helper for the light prompt. Picks the right
* single-sentence instruction based on whether the agent will run its own
@@ -338,7 +388,9 @@ export function worktreeCommitGuidance({ isTui, hasSlashdo, ownsPrWorkflow = fal
return withNoChangeAuditGuidance('Commit your changes here — the **Completion** section below drives the push and PR.', noChangeSuccess);
}
if (hasSlashdo) {
- return withNoChangeAuditGuidance('Commit your changes here — the **Completion** section below drives the push.', noChangeSuccess);
+ // Reached in a worktree with no PR: the auto-merge posture
+ // (portosMergesBranchOnExit) — nothing drives a push, so say so.
+ return withNoChangeAuditGuidance('Commit your changes here — do NOT push. PortOS merges this branch back after you exit; the **Completion** section below has the exact step.', noChangeSuccess);
}
if (ownsPrWorkflow && willOpenPR) {
return withNoChangeAuditGuidance('Commit your changes here — the **Completion** section below drives the push, the PR, the review loop, and the merge.', noChangeSuccess);
@@ -471,7 +523,7 @@ function localReviewCompletionInstruction(localReviewRequired = true) {
* 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', noChangeSuccess = false, localReviewSection = '', localReviewRequired = true, postPrReview = null }) {
+export function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, simplifyEnabled, sentinelPath, slashdoFree = false, ownsPrWorkflow = false, portosMergesBranch = false, branchName = null, baseBranch = null, leavePrOpen = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewerModels = {}, reviewerEfforts = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, forgeCli = 'gh', noChangeSuccess = false, localReviewSection = '', localReviewRequired = true, postPrReview = null }) {
const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;
const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;
if (slashdoFree) {
@@ -527,7 +579,11 @@ export function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLE
'When the task is complete, run these in order:',
'',
simplifyStep,
- `2. \`${cmd}${reviewerArg}\`${reviewSuffix}`,
+ // No command under the auto-merge posture: PortOS lands the branch itself,
+ // so step 2 is a plain commit and any push is debris (portosMergesBranchOnExit).
+ portosMergesBranch
+ ? `2. ${buildAutoMergeCommitStep(baseBranch)}`
+ : `2. \`${cmd}${reviewerArg}\`${reviewSuffix}`,
...(effortNote ? [` ${effortNote}`] : []),
...merge.lines,
...buildSentinelWriteSteps(sentinelStep, sentinelPath, sentinelTail)
@@ -695,7 +751,7 @@ function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLET
: '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):',
+ `2. ${COMMIT_HYGIENE_SENTENCE}:`,
'',
' ```bash',
' git add <file> [<file> ...]',
@@ -864,7 +920,10 @@ export function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompleti
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.`);
+ // Slashdo + worktree + no PR (the PR case returned above) is the auto-merge
+ // posture: PortOS lands the branch itself, so the step is a plain commit —
+ // `/do:push` here only left a copy behind on origin (portosMergesBranchOnExit).
+ lines.push(`${step++}. ${buildAutoMergeCommitStep(worktreeInfo.baseBranch || null)}`);
return lines.join('\n');
}
// Non-slashdo CLI that IS a real coding harness (codex, grok/agy, OpenCode):
@@ -879,7 +938,7 @@ export function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompleti
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(`${step++}. ${COMMIT_HYGIENE_SENTENCE}.`);
if (localReviewSection) {
lines.push(`${step++}. ${localReviewCompletionInstruction(localReviewRequired)}`);
lines.push('', localReviewSection, '');