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

address review (codex): forge-correct merge commands, leave JIRA PRs open

[._.]/ Adam Eivy0dcd3d60ecb2
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 94bea157d2..37f99d58e1 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -20,6 +20,7 @@ import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, LOCAL_LL
import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
import { isOpencodeCommand } from '../lib/providerModels.js';
import { shellQuote } from '../lib/shellQuote.js';
+import { detectForgeCli } from '../lib/gitForge.js';
import * as jiraService from './jira.js';
import { emitLog } from './cosEvents.js';
import { PORTOS_APP_ID } from './apps.js';
@@ -573,16 +574,20 @@ ${cliReviewerProcedure}${(rprBody && (hasCopilot || hasGithubUser)) ? `\n### /do
*
* @param {number} startStep - number of the first emitted step.
* @param {Object} opts
- * @param {string} opts.prRef - how to address the PR in commands, already
+ * @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 known non-GitHub must not be handed `gh` commands it can't
- * run. `unknown` (the agent's own completion workflow, which runs before the
- * PR exists) emits both, commented.
+ * 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, forge = 'github' }) {
+function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>', forge = 'github' }) {
const gh = forge !== 'gitlab';
const glab = forge !== 'github';
const both = gh && glab;
@@ -590,18 +595,19 @@ function buildCiMergeGateSteps(startStep, { prRef, forge = 'github' }) {
? `\`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\``
- : 'the MR reports a conflict with its target branch';
+ ? `\`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 mr view` must show it merged';
+ ? `\`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}. A repo with no checks configured reports "no checks reported" — treat that as green.`,
- `${startStep + 1}. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (\`gh run view --log-failed\` on GitHub), 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 + 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 (a saved \`/do:pr\` default can merge it for you), skip to the next step:`,
' ```bash',
gh ? ` ${both ? '# GitHub: ' : ''}gh pr merge ${prRef} --merge --delete-branch` : null,
- glab ? ` ${both ? '# GitLab: ' : ''}glab mr merge ${both ? '"<MR_URL>"' : prRef} --yes --remove-source-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,
' ```',
`${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 ONLY if CI stays red after a genuine fix attempt, or a conflict needs a human decision — and say so explicitly in your completion summary.`,
].filter(Boolean);
@@ -618,11 +624,14 @@ function buildCiMergeGateSteps(startStep, { prRef, forge = 'github' }) {
* @returns {string}
*/
function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = '', prRepo = '', prHost = '', sourceTaskId = 'unknown', verbose = false }) {
- // PortOS opens GitLab MRs via `glab` too, so a non-GitHub host must not be
- // handed `gh` commands (the host is persisted by spawnReviewLoopFollowUp).
+ // 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.
const gate = buildCiMergeGateSteps(1, {
prRef: `"${prUrl}"`,
- forge: (prHost && prHost !== 'github.com') ? 'gitlab' : 'github',
+ mrRef: prNumber !== '' ? `${prNumber}` : '<MR_NUMBER>',
+ forge: detectForgeCli(prHost) === 'glab' ? 'gitlab' : 'github',
});
const steps = [
...gate.lines,
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index 05aa156dd0..1762315705 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -403,7 +403,9 @@ describe('buildLightContextPrompt', () => {
expect(prompt).toMatch(/gh pr create --fill --base main/);
expect(prompt).toMatch(/gh pr checks "<PR_URL>" --watch --fail-fast/);
expect(prompt).toMatch(/gh pr merge "<PR_URL>" --merge --delete-branch/);
- expect(prompt).toMatch(/glab mr merge "<MR_URL>" --yes --remove-source-branch/);
+ // `glab mr merge` selects by IID or source branch — never by URL.
+ expect(prompt).toMatch(/glab mr merge <MR_NUMBER> --yes --remove-source-branch/);
+ expect(prompt).not.toMatch(/glab mr merge "?http/);
expect(prompt).toMatch(/gh pr view "<PR_URL>" --json state -q \.state/);
expect(prompt).not.toMatch(/do NOT merge it yourself/);
});
@@ -650,12 +652,34 @@ describe('buildLightContextPrompt', () => {
{ branchName: 'b', worktreePath: '/tmp/wt' },
isTruthyMeta);
expect(prompt).toMatch(/## Merge Follow-up/);
- expect(prompt).toMatch(/glab mr merge "https:\/\/gitlab\.com\/g\/p\/-\/merge_requests\/5" --yes --remove-source-branch/);
+ // Addressed by MR IID — `glab mr merge` does not accept a URL.
+ expect(prompt).toMatch(/glab mr merge 5 --yes --remove-source-branch/);
expect(prompt).toMatch(/glab ci status/);
+ expect(prompt).toMatch(/glab mr view 5/);
expect(prompt).not.toMatch(/gh pr merge/);
expect(prompt).not.toMatch(/gh pr checks/);
});
+ it('a merge-only follow-up on GitHub Enterprise keeps gh commands', () => {
+ // Regression: classifying "host !== github.com" as GitLab handed a GHES PR
+ // glab commands that cannot merge it.
+ const prompt = buildLightContextPrompt(
+ makeTask({ metadata: {
+ reviewLoopFollowUp: true,
+ reviewLoopMergeOnly: true,
+ reviewLoopPRUrl: 'https://github.example.com/o/r/pull/7',
+ reviewLoopPRBranch: 'b',
+ reviewLoopPRNumber: 7,
+ reviewLoopPRHost: 'github.example.com',
+ sourceTaskId: 'task-src-4',
+ }}),
+ '/r',
+ { branchName: 'b', worktreePath: '/tmp/wt' },
+ isTruthyMeta);
+ expect(prompt).toMatch(/gh pr merge "https:\/\/github\.example\.com\/o\/r\/pull\/7" --merge --delete-branch/);
+ expect(prompt).not.toMatch(/glab/);
+ });
+
it('threads a non-default reviewer (claude) into the follow-up block via --review-with', () => {
const prompt = buildLightContextPrompt(
makeTask({ metadata: {
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index d7acbb01b4..8c40fdf9a1 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -22,8 +22,30 @@ import { removeWorktree } from './worktreeManager.js';
import { isTruthyMeta } from './agentState.js';
import { PATHS } from '../lib/fileUtils.js';
import { RECOVERY_TASK_PREFIX } from './recoveryTasks.js';
+import { detectForgeCli } from '../lib/gitForge.js';
import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, MODEL_CAPABLE_CLI_REVIEWERS, normalizeReviewers, normalizeReviewUsernames, normalizeOptionalReviewers } from '../lib/validation.js';
+/**
+ * Scheduled task types whose prompt deliberately hands the PR to a human and
+ * records that hand-off somewhere PortOS can't update afterwards. For
+ * `jira-sprint-manager` that's the ticket it transitions to "In Review": merging
+ * the PR here would land the work while the board still shows it in review, and
+ * nothing in this path knows the ticket key to transition it to Done.
+ *
+ * Keep this list tiny — the default for an opened PR is that something lands it.
+ */
+const PR_STAYS_OPEN_TASK_TYPES = new Set(['jira-sprint-manager']);
+
+/**
+ * True when a task's PR must be left open for a human rather than merged by a
+ * follow-up: an exempt task type, or any task carrying a JIRA ticket (the ticket
+ * status is the hand-off, and this path can't transition it).
+ */
+function leavesPrForHuman(task) {
+ const analysisType = task?.metadata?.analysisType;
+ return (!!analysisType && PR_STAYS_OPEN_TASK_TYPES.has(analysisType)) || !!task?.metadata?.jiraTicketId;
+}
+
/**
* Clean up a worktree for a completed agent.
* Reads worktree metadata from the agent's registered state and removes the worktree.
@@ -169,28 +191,37 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, r
// review pass) and invokes the CLI reviewers itself. The only reviewer dropped is
// copilot on a non-GitHub forge, handled centrally in spawnReviewLoopFollowUp.
//
- // A follow-up is ALWAYS spawned for a PR PortOS opened, because something has
- // to land it. `spawnReviewLoopFollowUp` picks the mode from what actually
+ // A follow-up is spawned for a PR PortOS opened, because something has to
+ // land it. `spawnReviewLoopFollowUp` picks the mode from what actually
// survives reviewer resolution: reviewers left → review-then-merge; none left
- // (Review Loop off, or copilot-only on a non-GitHub forge) → merge on green CI.
+ // (Review Loop off, or copilot-only on a GitLab forge) → merge on green CI.
// Deciding it there rather than here is what keeps a stripped reviewer list
// from silently producing an orphaned PR.
- await spawnReviewLoopFollowUp({
- originalAgentId: agentId,
- originalTask,
- prUrl: prResult.url,
- prBranch: worktreeBranch,
- sourceWorkspace,
- reviewers: shouldRequestCopilot ? reviewerList : [],
- usernames: shouldRequestCopilot ? usernames : [],
- optionalReviewers: shouldRequestCopilot ? optionalReviewers : [],
- reviewStopMode,
- reviewerApplies,
- reviewerModels
- }).catch(err => {
- emitLog('warn', `🤖 Failed to spawn PR follow-up for ${prResult.url}: ${err.message}`, { agentId, prUrl: prResult.url });
- warnings.push(`PR follow-up spawn failed for ${prResult.url}: ${err.message}`);
- });
+ //
+ // The exception is a JIRA-tracked task (see PR_STAYS_OPEN_TASK_TYPES): its
+ // prompt moves the ticket to "In Review" and hands the PR to a human, and
+ // nothing here can transition the ticket afterwards — merging behind the
+ // board's back would leave the work merged but permanently "In Review".
+ if (leavesPrForHuman(originalTask)) {
+ emitLog('info', `🤝 Leaving ${prResult.url} open for a human — JIRA-tracked task keeps its ticket in review`, { agentId, prUrl: prResult.url });
+ } else {
+ await spawnReviewLoopFollowUp({
+ originalAgentId: agentId,
+ originalTask,
+ prUrl: prResult.url,
+ prBranch: worktreeBranch,
+ sourceWorkspace,
+ reviewers: shouldRequestCopilot ? reviewerList : [],
+ usernames: shouldRequestCopilot ? usernames : [],
+ optionalReviewers: shouldRequestCopilot ? optionalReviewers : [],
+ reviewStopMode,
+ reviewerApplies,
+ reviewerModels
+ }).catch(err => {
+ emitLog('warn', `🤖 Failed to spawn PR follow-up for ${prResult.url}: ${err.message}`, { agentId, prUrl: prResult.url });
+ warnings.push(`PR follow-up spawn failed for ${prResult.url}: ${err.message}`);
+ });
+ }
const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: false }).catch(err => {
emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });
@@ -255,9 +286,12 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p
const parsedPr = git.parsePullRequestUrl(prUrl);
// Copilot is GitHub-only; CLI-based reviewers (claude/antigravity/codex/grok) work on any
- // forge because the agent invokes the CLI directly. On a non-GitHub forge, drop
- // copilot from the list.
- const isNonGithubForge = parsedPr && parsedPr.host && parsedPr.host !== 'github.com';
+ // forge because the agent invokes the CLI directly. On a GitLab forge, drop
+ // copilot from the list. Classify with the shared detector rather than
+ // `host !== 'github.com'` — a GitHub Enterprise host still has Copilot, and
+ // misreading it as non-GitHub would strip the only reviewer and silently
+ // downgrade the run to merge-only.
+ const isNonGithubForge = !!parsedPr?.host && detectForgeCli(parsedPr.host) !== 'gh';
// An EXPLICITLY empty list means "no review was requested" and must stay empty —
// normalizeReviewers' `[copilot]` default would otherwise resurrect a reviewer.
const reviewerList = (Array.isArray(reviewers) && reviewers.length === 0) ? [] : normalizeReviewers({ reviewers });
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index b8d23ca71d..8bb003b493 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -535,6 +535,34 @@ describe('cleanupAgentWorktree - openPR path', () => {
expect(removeWorktree).toHaveBeenCalled();
});
+ it('leaves a jira-sprint-manager PR open — no follow-up merges behind the board', async () => {
+ // That task type transitions its ticket to "In Review" and hands the PR to a
+ // human; merging here would land the work while JIRA still shows it in review,
+ // and nothing in this path knows the ticket key to move it to Done.
+ git.push.mockResolvedValue(undefined);
+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/77' });
+
+ await cleanupAgentWorktree('agent-1', true, {
+ openPR: true, requestCopilotReview: false, description: 'X',
+ originalTask: { id: 'task-orig', metadata: { analysisType: 'jira-sprint-manager' }, description: 'X' }
+ });
+
+ expect(addTask).not.toHaveBeenCalled();
+ expect(removeWorktree).toHaveBeenCalled();
+ });
+
+ it('leaves a JIRA-ticketed task PR open regardless of task type', async () => {
+ git.push.mockResolvedValue(undefined);
+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/78' });
+
+ await cleanupAgentWorktree('agent-1', true, {
+ openPR: true, requestCopilotReview: false, description: 'X',
+ originalTask: { id: 'task-orig', metadata: { jiraTicketId: 'PROJ-1' }, description: 'X' }
+ });
+
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
it('spawns a merge-only follow-up on non-GitHub forges when copilot was the only reviewer', async () => {
// Copilot can't review a GitLab MR, so the review loop has nothing to run — but
// the MR still has to land, so the follow-up degrades to merge-only rather than