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: complete TUI agent PR lifecycle
[._.]/ Adam Eivy1248f82f9ac7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c166c021b1..731e7a6da4 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -3,6 +3,7 @@## Added- **Malware scans now leave a durable, reviewable report trail.** Git-link scans save an owned markdown artifact, surface it from the completed agent summary and Review Hub, and mark repositories with an explicit `DANGEROUS` verdict using a skull danger treatment on the Git links card.+- **Slashdo-free TUI agent PRs now complete their lifecycle.** Codex, Antigravity, OpenCode, and lean Claude agents hand committed work back to PortOS so it can generate a non-empty PR description, run configured reviewers, and merge after the selected gates pass instead of leaving an ownerless PR open.## Quota burndiff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex e8d5b674ea..73bc053d13 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -561,6 +561,7 @@ async function runAgentSpawn(task) {laneName,cleanupWorktreeFn: cleanupAgentWorktree,isTruthyMetaFn: isTruthyMeta,+ leanMode,});}if (useRunner) {diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 29bbce757e..2de892e250 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -754,11 +754,10 @@ const LEAVE_PR_OPEN_STEP = (step, jiraTracked = false) => `${step}. **Leave the** This is the single definition of "no reviewer is configured, so CI is the* merge gate" — shared by every flow that reaches it: the agent's own completion- * workflow (slashdo TUI + Claude Code CLI via `buildPostPRMergeSteps`), the- * manual/OpenCode TUI workflow, and the merge follow-up agent PortOS spawns when- * it opened the PR itself. They differ only in how the PR is addressed and- * whether GitLab commands are offered, so those are parameters rather than three- * hand-written copies that drift.+ * workflow (slashdo TUI + Claude Code CLI via `buildPostPRMergeSteps`) and the+ * merge follow-up agent PortOS spawns when it opened the PR itself. They differ+ * only in how the PR is addressed and whether GitLab commands are offered, so+ * those are parameters rather than hand-written copies that drift.** Ends on the same merge command + MERGED verification as the review-loop* contract (`buildReviewLoopFollowUpSection`): a true merge commit keeps the@@ -868,8 +867,8 @@ function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = '* @param {boolean} opts.isReadOnly* @param {boolean} opts.isTui* @param {string} opts.tuiCompletionCommand - `/do:pr` or `/do:push`- * @param {boolean} [opts.slashdoFree] - TUI without slashdo (OpenCode): the bullet- * points at the manual git/gh Completion Workflow instead of a `/do:*` command.+ * @param {boolean} [opts.slashdoFree] - TUI without slashdo: the bullet points+ * at the manual commit + system-handoff workflow instead of a `/do:*` command.* @param {Object|null} opts.worktreeInfo* @param {boolean} opts.willOpenPR* @param {'review-then-merge'|'merge-on-green'|'leave-open'} opts.prCompletion@@ -903,7 +902,7 @@ export function buildCompletionGuidelineBullet({// buildTuiCompletionSection — not this bullet). It's kept provider-aware and// directly unit-tested so the guideline stays correct if that routing changes.const howTo = slashdoFree- ? 'the Completion Workflow above (plain `git`/`gh` commands — this provider has no slashdo commands)'+ ? 'the Completion Workflow above (plain `git` commit + PortOS handoff — this provider has no slashdo commands)': `the Completion Workflow above (\`${tuiCompletionCommand}\`)`;return `On successful completion, YOU run ${howTo}, then write the sentinel and stop — PortOS closes the session once it sees the sentinel; do NOT run \`/quit\`.`;}@@ -1490,6 +1489,8 @@ ${discardWorktree? `- **Do NOT commit, push, or open a PR.** This worktree is discarded on exit — your only output is the completion sentinel (see the Completion section above).`: isReviewLoopFollowUp? `- **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.`: 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@@ -1592,7 +1593,8 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet// block where PortOS handles push+PR on exit.const hasSlashdo = !isTui && canTypeSlash;// TUI: a session that does NOT load Claude Code slash commands can't run- // `/do:pr` / `/do:push`, so its completion workflow uses plain git/gh instead+ // `/do:pr` / `/do:push`, so its completion workflow uses plain git and hands+ // the post-exit push / PR lifecycle back to PortOS// — an OpenCode TUI, a codex/antigravity/grok TUI, or a lean-mode Claude// session (`--bare` skips project command discovery, and the small local models// lean mode targets fumble multi-step slashdo flows anyway).@@ -1859,40 +1861,25 @@ function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.M/*** Manual (slashdo-free) TUI completion-workflow block — for an OpenCode TUI that* does NOT load Claude Code slash commands and so can't run `/do:pr` / `/do:push`.- * Drives a plain `git` commit → push → (open PR/MR) → sentinel handshake, so the- * `.agent-done` signal still fires and the task completes.+ * Drives a plain `git` commit → sentinel handshake. PortOS owns the post-exit+ * push / PR / review / merge lifecycle, just as it does for non-TUI providers+ * that cannot invoke project slash commands.*- * PortOS forces `openPR:false, skipMerge:true` on TUI worktree cleanup (see- * agentTuiSpawning.js), so nothing happens after the agent exits — the agent owns- * the push and the PR itself.- *- * With review-then-merge configured, it opens the PR/MR and stops:- * this provider can't drive the reviewer CLIs (no slashdo `/do:pr` review loop)- * and PortOS runs no post-exit review for a TUI, so merging here would ship work- * the user asked to have reviewed. With the review loop OFF there is no reviewer- * and no follow-up coming, so leaving it open just leaks the PR — the agent- * merges it once CI is green, matching every other no-review-loop flow.- *- * Forge-aware (GitHub `gh` + GitLab `glab`) to match the slashdo path; refs are- * shell-quoted because a git ref can legally contain shell metacharacters.+ * Keeping PR creation system-owned also guarantees a real generated body rather+ * than `gh pr create --fill` producing an empty description from a one-line+ * commit, and lets the existing follow-up machinery run configured reviewers.*/-function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, simplifyEnabled, sentinelPath, branchName = null, baseBranch = null, leavePrOpen = false }) {+function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, simplifyEnabled, sentinelPath, leavePrOpen = false }) {const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;- const branchRef = shellQuote(branchName || 'HEAD');- // Pin the PR base to the worktree's base branch when known, so the forge CLI- // doesn't guess (and a fork install targets the intended branch). `--fill`- // still supplies title/body from the commits.- const ghBaseArg = baseBranch ? ` --base ${shellQuote(baseBranch)}` : '';- const glabBaseArg = baseBranch ? ` --target-branch ${shellQuote(baseBranch)}` : '';const simplifyStep = simplifyEnabled? `1. Before committing, ${SIMPLIFY_INLINE_REVIEW} and fix any findings.`: '1. (simplify disabled — skip)';- const sentinelTail = willOpenPR ? ' ## PR\n <PR URL>' : ' ## Branch\n <branch name>';+ const sentinelTail = ' ## Branch\n <branch name>';const lines = ['## Completion Workflow',- 'This provider does NOT have slashdo (`/do:*`) commands, so finish the handoff with plain `git` (and your forge\'s CLI). Run these in order:',+ 'This provider does NOT have slashdo (`/do:*`) commands, so finish the handoff with plain `git`. Run these in order:','',simplifyStep,'2. Stage only the files you changed (never `git add -A` / `git add .`) and commit with a conventional message (`feat:`/`fix:`/`breaking:` prefix, no Co-Authored-By annotations):',@@ -1901,36 +1888,20 @@ function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLET' git add <file> [<file> ...]',' git commit -m "feat: <description>"',' ```',- '3. Push your branch (it is a fresh worktree branch, so set upstream on first push):',- '',- ' ```bash',- ` git push -u origin ${branchRef}`,- ' ```',];- let step = 4;+ let step = 3;if (willOpenPR) {- const openNote = policyLeavesOpen- ? '**Leave it open — do NOT merge it.** This task is configured to stop after opening the PR so you can inspect it.'+ const handoff = policyLeavesOpen+ ? 'PortOS will push the branch, create a pull request with your completion summary as its description, and leave it open for inspection.': leavePrOpen- ? '**Leave it open — do NOT merge it.** This task is tracked in JIRA: its ticket is in review and a human lands the PR and the ticket together.'+ ? 'PortOS will push the branch and create a pull request for the JIRA-linked human handoff.': runsReviewLoop- ? '**Leave it open for review — do NOT merge it yourself.** This provider can\'t run the reviewer loop, and PortOS won\'t merge it for a TUI task, so a configured reviewer or a human reviews and merges it.'- : 'No review loop is configured for this task, so you merge it yourself in the next step — nothing else will.';- lines.push(- `${step++}. Open a pull/merge request against the base branch using the CLI for this repo's forge (check \`git remote -v\`), and capture the URL it prints. ${openNote}`,- '',- ' ```bash',- ` # GitHub: gh pr create --fill${ghBaseArg}`,- ` # GitLab: glab mr create --fill${glabBaseArg}`,- ' ```',- );- if (!runsReviewLoop && !leavePrOpen && !policyLeavesOpen) {- // Same CI-gate procedure the slashdo workflow and the merge follow-up use.- const gate = buildCiMergeGateSteps(step, { prRef: '"<PR_URL>"', forge: 'unknown' });- lines.push(...gate.lines);- step = gate.nextStep;- }+ ? 'PortOS will push the branch, create a pull request with your completion summary as its description, run the configured reviewer follow-up, and merge only after review and CI pass.'+ : 'PortOS will push the branch, create a pull request with your completion summary as its description, and merge it once CI is green.';+ lines.push(`${step++}. Do NOT push, open, or merge a pull request yourself. ${handoff}`);+ } else {+ lines.push(`${step++}. Do NOT push this worktree branch yourself. PortOS will merge it back after completion.`);}lines.push(diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex f9da8e2cf3..eb3db9c876 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -394,8 +394,8 @@ describe('buildLightContextPrompt', () => {{ branchName: 'claim/x', worktreePath: '/tmp/wt', baseBranch: 'main' },isTruthyMeta,{ isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode' });- expect(prompt).toMatch(/gh pr create --fill/);- expect(prompt).toMatch(/do NOT merge it/);+ expect(prompt).not.toMatch(/gh pr create/);+ expect(prompt).toMatch(/JIRA-linked human handoff/);expect(prompt).not.toMatch(/gh pr merge/);expect(prompt).not.toMatch(/glab mr merge/);});@@ -463,12 +463,10 @@ describe('buildLightContextPrompt', () => {expect(prompt).not.toMatch(/gh pr merge/);});- it('emits a slashdo-free, forge-aware Completion Workflow for an OpenCode TUI + openPR + Review Loop (opens PR, no auto-merge)', () => {+ it('hands a slashdo-free OpenCode TUI PR to PortOS for description, review, and merge', () => {// OpenCode TUI doesn't load Claude Code slash commands, so /do:pr / /do:push- // would be uninvokable. The agent commits, pushes, opens the PR/MR for review,- // and writes the sentinel with plain git + the forge CLI. With a Review Loop- // configured it must NOT auto-merge (it can't run the reviewer loop and PortOS- // runs no post-exit review for a TUI).+ // would be uninvokable. The agent commits and writes the sentinel; PortOS+ // owns the PR body, configured reviewer follow-up, and merge.const prompt = buildLightContextPrompt(makeTask({ metadata: { simplify: true, openPR: true, reviewLoop: true } }),'/r',@@ -482,42 +480,34 @@ describe('buildLightContextPrompt', () => {expect(prompt).not.toMatch(/`\/simplify`/);// /simplify is a Claude built-in — OpenCode gets the inline equivalent.expect(prompt).toMatch(/review your changed code for reuse, quality, and efficiency/i);- // Plain git commit → push → open PR. Base pinned to the worktree base branch.+ // Plain git commit only — no agent-owned push or forge action.expect(prompt).toMatch(/git commit -m/);- expect(prompt).toMatch(/git push -u origin claim\/issue-1/);- // Forge-aware: both GitHub (gh) and GitLab (glab) create commands, base-pinned.- expect(prompt).toMatch(/gh pr create --fill --base main/);- expect(prompt).toMatch(/glab mr create --fill --target-branch main/);- // Opens for review — never auto-merges.+ expect(prompt).not.toMatch(/git push/);+ expect(prompt).not.toMatch(/gh pr create/);+ expect(prompt).not.toMatch(/glab mr create/);expect(prompt).not.toMatch(/gh pr merge/);expect(prompt).not.toMatch(/glab mr merge/);- expect(prompt).toMatch(/do NOT merge it yourself/);+ expect(prompt).toMatch(/PortOS will push the branch, create a pull request with your completion summary as its description, run the configured reviewer follow-up, and merge only after review and CI pass/);// Sentinel handshake still drives completion; never tell the agent to run /quit.expect(prompt).toMatch(/\.agent-done/);expect(prompt).toMatch(/NOT run `\/quit`/);expect(prompt).not.toMatch(/^\s*\d+\.\s*`\/quit`/m);});- it('OpenCode TUI + openPR WITHOUT a Review Loop merges on green CI (forge-aware)', () => {- // No reviewer and no PortOS follow-up is coming for a TUI task, so leaving the- // PR open would leak it — the agent gates on CI and merges itself.+ it('hands a slashdo-free OpenCode TUI PR to PortOS for a green-CI merge', () => {const prompt = buildLightContextPrompt(makeTask({ metadata: { simplify: true, openPR: true } }),'/r',{ branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'main' },isTruthyMeta,{ isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode' });- 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/);- // `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/);+ expect(prompt).not.toMatch(/gh pr create/);+ expect(prompt).not.toMatch(/gh pr checks/);+ expect(prompt).not.toMatch(/gh pr merge/);+ expect(prompt).toMatch(/PortOS will push the branch, create a pull request with your completion summary as its description, and merge it once CI is green/);});- it('OpenCode TUI without openPR pushes the branch but opens no PR', () => {+ it('OpenCode TUI without openPR leaves the committed branch for PortOS to merge', () => {const prompt = buildLightContextPrompt(makeTask({ metadata: { openPR: false } }),'/r',@@ -526,24 +516,22 @@ describe('buildLightContextPrompt', () => {{ isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode' });expect(prompt).toMatch(/## Completion Workflow/);expect(prompt).not.toMatch(/`\/do:push`/);- expect(prompt).toMatch(/git push -u origin claim\/issue-2/);- // No PR is opened, so no forge create/merge steps.+ expect(prompt).not.toMatch(/git push/);expect(prompt).not.toMatch(/gh pr create/);expect(prompt).not.toMatch(/glab mr create/);expect(prompt).not.toMatch(/gh pr merge/);expect(prompt).toMatch(/\.agent-done/);});- it('shell-quotes a branch ref containing shell metacharacters in the manual push command', () => {- // Git refs can legally contain `;` etc.; the emitted push command must quote it.+ it('does not interpolate a branch ref into a shell command in the system-owned handoff', () => {const prompt = buildLightContextPrompt(makeTask({ metadata: { openPR: false } }),'/r',{ branchName: 'weird;rm -rf', worktreePath: '/tmp/wt' },isTruthyMeta,{ isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode' });- expect(prompt).toMatch(/git push -u origin 'weird;rm -rf'/);- expect(prompt).not.toMatch(/git push -u origin weird;rm/);+ expect(prompt).not.toMatch(/git push/);+ expect(prompt).not.toMatch(/git .*weird;rm -rf/);});// #3114 acceptance criteria — the completion gates derive from@@ -564,9 +552,11 @@ describe('buildLightContextPrompt', () => {expect(prompt).toMatch(/does NOT have slashdo/);expect(prompt).not.toMatch(/`\/do:pr`/);expect(prompt).not.toMatch(/`\/do:push`/);- // Plain git + forge CLI instead.- expect(prompt).toMatch(/git push -u origin claim\/x/);- expect(prompt).toMatch(/gh pr create --fill --base main/);+ // Plain commit + system-owned PR handoff instead.+ expect(prompt).toMatch(/git commit -m/);+ expect(prompt).not.toMatch(/git push/);+ expect(prompt).not.toMatch(/gh pr create/);+ expect(prompt).toMatch(/PortOS will push the branch/);expect(prompt).toMatch(/\.agent-done/);});@@ -594,7 +584,8 @@ describe('buildLightContextPrompt', () => {isTruthyMeta,{ isTui: true, providerId: 'antigravity-tui', providerCommand: 'agy' });expect(prompt).not.toMatch(/`\/do:push`/);- expect(prompt).toMatch(/git push -u origin b/);+ expect(prompt).not.toMatch(/git push/);+ expect(prompt).toMatch(/PortOS will merge it back/);});it('a non-OpenCode TUI (claude-code-tui) keeps the slashdo /do:pr workflow', () => {@@ -1480,12 +1471,12 @@ describe('buildCompletionGuidelineBullet', () => {expect(bullet).toMatch(/do NOT run `\/quit`/);});- it('slashdo-free TUI bullet points at the plain git/gh workflow, not a /do:* command', () => {+ it('slashdo-free TUI bullet points at the commit + PortOS handoff, not a /do:* command', () => {const bullet = buildCompletionGuidelineBullet({isReadOnly: false, isTui: true, slashdoFree: true,tuiCompletionCommand: '/do:pr', worktreeInfo: { worktreePath: '/wt' }, willOpenPR: true, willReviewLoop: false,});- expect(bullet).toMatch(/plain `git`\/`gh`/);+ expect(bullet).toMatch(/plain `git` commit \+ PortOS handoff/);expect(bullet).toMatch(/no slashdo commands/);expect(bullet).not.toMatch(/`\/do:pr`/);expect(bullet).toMatch(/do NOT run `\/quit`/);diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 3ed613ab43..5ed415678c 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -19,7 +19,11 @@ import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';import { activeAgents, userTerminatedAgents, pausedAgents, isFalsyMeta } from './agentState.js';import { PATHS } from '../lib/fileUtils.js';import { DONE_SENTINEL_NAME, parseSentinelPayload } from '../lib/agentSentinel.js';+import { resolvePrCompletion } from '../lib/prDisposition.js';+import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';+import { normalizeReviewers } from '../lib/validation.js';import * as git from './git.js';+import { resolveReviewLoopOptions } from './codeReview.js';import { shellQuote } from '../lib/shellQuote.js';import { resolveCliModel, buildEffortArgs, resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, isClaudeCommand, applyLeanClaudeArgs, providerSuppliesGithubToken } from '../lib/providerModels.js';import { createStreamingAnsiStripper, stripAnsi } from '../lib/ansiStrip.js';@@ -223,6 +227,7 @@ export async function spawnTuiAgent({laneName,cleanupWorktreeFn,isTruthyMetaFn,+ leanMode = false,}) {const outputFile = join(agentDir, 'output.txt');// Raw PTY bytes spool to disk continuously rather than accumulate in-memory.@@ -504,15 +509,29 @@ export async function spawnTuiAgent({} finally {if (workspacePath) await rm(join(workspacePath, DONE_SENTINEL_NAME)).catch(() => {});- // TUI agents run /do:pr (or /do:push) themselves before signaling via- // .agent-done, so the system-side cleanup must NOT also push or open a- // PR — that would double-fire. `skipMerge` is forced on so the- // post-exit auto-merge doesn't trip over a branch the agent already- // pushed. The worktree directory itself is still cleaned up.+ // A slashdo-capable Claude TUI owns /do:pr itself. Slashdo-free TUIs+ // (Codex, Antigravity, OpenCode, lean Claude) only commit and signal;+ // PortOS must own their push + PR + reviewer/merge follow-up. Derive this+ // from the same predicate used by the prompt builder so neither side can+ // believe the other owns the PR.+ const taskOpenPR = isTruthyMetaFn(task.metadata?.openPR);+ const agentOwnsPR = taskOpenPR && canTypeSlashCommands({+ providerId: provider?.id,+ providerCommand: provider?.command,+ leanMode,+ });+ const reviewOptions = finalSuccess && taskOpenPR && !agentOwnsPR+ ? await resolveReviewLoopOptions(task.metadata, { normalize: normalizeReviewers, isTruthyMeta: isTruthyMetaFn })+ .catch(err => {+ emitLog('warn', `TUI review options unavailable for ${agentId}: ${err.message}`, { agentId });+ return {};+ })+ : {};await cleanupWorktreeFn(agentId, finalSuccess, {- openPR: false,- requestCopilotReview: false,- skipMerge: true,+ openPR: agentOwnsPR ? false : taskOpenPR,+ prCompletion: resolvePrCompletion(task.metadata),+ ...reviewOptions,+ skipMerge: agentOwnsPR,description: task.description,agentOutput: getOutputBuffer(),originalTask: taskdiff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 26b10ed5e1..576ba99df1 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -64,6 +64,18 @@ vi.mock('./agentFinalization.js', () => ({releaseAgentLane: vi.fn()}));+vi.mock('./codeReview.js', () => ({+ resolveReviewLoopOptions: vi.fn().mockResolvedValue({+ reviewers: ['codex'],+ usernames: [],+ optionalReviewers: [],+ reviewerMaxRounds: {},+ reviewStopMode: 'on-clean',+ reviewerApplies: false,+ reviewerModels: {},+ })+}));+vi.mock('./agentState.js', () => ({activeAgents: new Map(),userTerminatedAgents: new Set(),@@ -511,6 +523,53 @@ describe('spawnTuiAgent runtime', () => {await completeDone;});+ it('hands a slashdo-free TUI PR to PortOS for creation and review/merge follow-up', async () => {+ const cleanupWorktreeFn = vi.fn().mockResolvedValue(undefined);+ const spawnPromise = runSpawn({+ provider: { id: 'codex-tui', name: 'Codex TUI', type: 'tui', command: 'codex', envVars: {} },+ task: {+ id: 'task-1',+ description: 'do the thing',+ metadata: { openPR: true, prCompletion: 'review-then-merge', reviewers: ['codex'] },+ },+ helpers: { cleanupWorktreeFn, isTruthyMetaFn: (value) => value === true || value === 'true' },+ });+ await flushMicrotasks();++ await capturedOnExit({ exitCode: 0, killed: false });+ await spawnPromise;++ expect(cleanupWorktreeFn).toHaveBeenCalledWith('agent-1', true, expect.objectContaining({+ openPR: true,+ prCompletion: 'review-then-merge',+ reviewers: ['codex'],+ skipMerge: false,+ }));+ });++ it('does not double-fire a PR owned by a slashdo-capable Claude TUI', async () => {+ const cleanupWorktreeFn = vi.fn().mockResolvedValue(undefined);+ const spawnPromise = runSpawn({+ provider: { id: 'claude-code-tui', name: 'Claude TUI', type: 'tui', command: 'claude', envVars: {} },+ task: {+ id: 'task-1',+ description: 'do the thing',+ metadata: { openPR: true, prCompletion: 'review-then-merge' },+ },+ helpers: { cleanupWorktreeFn, isTruthyMetaFn: (value) => value === true || value === 'true' },+ });+ await flushMicrotasks();++ await capturedOnExit({ exitCode: 0, killed: false });+ await spawnPromise;++ expect(cleanupWorktreeFn).toHaveBeenCalledWith('agent-1', true, expect.objectContaining({+ openPR: false,+ prCompletion: 'review-then-merge',+ skipMerge: true,+ }));+ });+// ── 1. Successful idle-complete path ────────────────────────────────────────it('idle-complete: calls finalizeAgent(success:true) with completionReason=idle-complete when idle fires after enough output and runtime', async () => {// Wire finalizeAgent to resolve a promise we can await, so we can detectdiff --git a/server/services/malwareScanReports.js b/server/services/malwareScanReports.jsindex c004b70ed5..d3cc4064fd 100644--- a/server/services/malwareScanReports.js+++ b/server/services/malwareScanReports.js@@ -4,12 +4,15 @@ import { readFile } from 'fs/promises';import { join } from 'path';import { PATHS, ensureDir } from '../lib/fileUtils.js';-export const SCAN_REPORTS_DIR = join(PATHS.brain, 'scans');const REPORT_ID_RE = /^[a-f0-9-]{36}$/i;const VERDICTS = new Set(['CLEAN', 'CAUTION', 'DANGEROUS']);+export function getScanReportsDirectory() {+ return join(PATHS.brain, 'scans');+}+export function reportPathForId(reportId) {- return REPORT_ID_RE.test(reportId || '') ? join(SCAN_REPORTS_DIR, `${reportId}.md`) : null;+ return REPORT_ID_RE.test(reportId || '') ? join(getScanReportsDirectory(), `${reportId}.md`) : null;}export function extractScanVerdict(report) {@@ -20,7 +23,7 @@ export function extractScanVerdict(report) {}export async function prepareScanReportDirectory() {- await ensureDir(SCAN_REPORTS_DIR);+ await ensureDir(getScanReportsDirectory());}export async function getScanReport(reportId) {