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
feat(quality): leave audit fixes in verified draft pull requests
Adam Eivy2ea86d41d2e2
diff --git a/client/src/components/apps/AppQualityRunner.jsx b/client/src/components/apps/AppQualityRunner.jsxindex 8e24f117e3..1b2d08d094 100644--- a/client/src/components/apps/AppQualityRunner.jsx+++ b/client/src/components/apps/AppQualityRunner.jsx@@ -33,6 +33,7 @@ export default function AppQualityRunner({ app, children }) {return next;});const [mode, setMode] = useState('file-issues');+ const [prCompletion, setPrCompletion] = useState('draft');const [effort, setEffort] = useState('');const [busy, setBusy] = useState(false);const [error, setError] = useState('');@@ -71,6 +72,7 @@ export default function AppQualityRunner({ app, children }) {setError('');const response = await startMaintenanceRun({ appId: app.id, providerId: picker.selectedProviderId, model: picker.selectedModel,effort: effort || null, mode, claimBetweenAudits: false, taskTypes,+ ...(mode === 'fix' && prCompletion ? { prCompletion } : {}),// A category picked by name is the user's explicit choice and runs even if// the repository scan says it cannot apply; batch selections stay gated....(!batchSelection ? { explicitCheck: true } : {}) }, { silent: true }).catch(err => { if (appIdRef.current === app.id) setError(err.message); return null; });@@ -100,11 +102,17 @@ export default function AppQualityRunner({ app, children }) {</select></label></div>+ {mode === 'fix' && <label htmlFor="quality-publication" className="block text-sm">Pull requests+ <select id="quality-publication" className="block w-full bg-port-bg border border-port-border rounded p-2" value={prCompletion} disabled={busy} onChange={event => setPrCompletion(event.target.value)}>+ <option value="draft">Drafts for review — never merge</option>+ <option value="">Use saved completion policy</option>+ </select>+ </label>}<ProviderModelSelector providers={picker.providers} selectedProviderId={picker.selectedProviderId} selectedModel={picker.selectedModel}availableModels={picker.availableModels} onProviderChange={value => { picker.setSelectedProviderId(value); setEffort(''); }}onModelChange={picker.setSelectedModel} effort={effort} onEffortChange={setEffort} loading={picker.loading} disabled={busy}emptyProviderOption="Select a subscription provider" emptyModelOption="Select a model" includeDefaultModel highlightToolUse />- <p className="text-xs text-gray-400">Runs sequentially; launch another batch to run in parallel. {mode === 'fix' ? 'Each audit can change code and open a PR.' : 'Findings become issues; no fixes.'}</p>+ <p className="text-xs text-gray-400">Runs sequentially; launch another batch to run in parallel. {mode === 'fix' ? (prCompletion ? 'Fixes stay in pull requests for your review; automatic quality snapshot publication is skipped.' : 'Fixes and quality snapshots may merge automatically under the saved policy.') : 'Findings become issues; no fixes.'}</p><details className="text-xs"><summary className="cursor-pointer text-port-accent">Selected checks ({taskTypes.length})</summary><p className="mt-1">{selectedCategories.map(category => category.label).join(', ') || emptySelectionMessage}</p></details><button type="button" onClick={start} disabled={busy || picker.loading || !picker.selectedProviderId || !picker.selectedModel || !taskTypes.length || app.quality?.unavailable}className="px-3 py-2 rounded bg-port-accent text-port-bg text-sm font-medium disabled:opacity-50">{taskTypes.length === 1 ? 'Run now' : `Run ${taskTypes.length} checks now`}</button>diff --git a/client/src/components/apps/AppQualityRunner.test.jsx b/client/src/components/apps/AppQualityRunner.test.jsxindex 8684e26f6e..83ae70c5a2 100644--- a/client/src/components/apps/AppQualityRunner.test.jsx+++ b/client/src/components/apps/AppQualityRunner.test.jsx@@ -41,7 +41,7 @@ it('launches missing checks with visible mode and effort, then exposes held runnfireEvent.click(screen.getByText('Use high effort'));fireEvent.click(button);await screen.findByRole('link', { name: 'Open runner settings' });- expect(startMaintenanceRun).toHaveBeenCalledWith({ appId: 'app-1', providerId: 'codex', model: 'gpt-5', effort: 'high', mode: 'fix', claimBetweenAudits: false, taskTypes: ['security', 'ux'] }, { silent: true });+ expect(startMaintenanceRun).toHaveBeenCalledWith({ appId: 'app-1', providerId: 'codex', model: 'gpt-5', effort: 'high', mode: 'fix', prCompletion: 'draft', claimBetweenAudits: false, taskTypes: ['security', 'ux'] }, { silent: true });expect(button).toBeEnabled();});@@ -104,7 +104,7 @@ it('preserves run overrides when reopening the drawer for one category', async (expect(screen.getByLabelText('Mode')).toHaveValue('fix');fireEvent.click(screen.getByRole('button', { name: 'Run now' }));await waitFor(() => expect(startMaintenanceRun).toHaveBeenCalledWith(- { appId: 'app-1', providerId: 'codex', model: 'gpt-5', effort: 'high', mode: 'fix', claimBetweenAudits: false, taskTypes: ['security'], explicitCheck: true },+ { appId: 'app-1', providerId: 'codex', model: 'gpt-5', effort: 'high', mode: 'fix', prCompletion: 'draft', claimBetweenAudits: false, taskTypes: ['security'], explicitCheck: true },{ silent: true }));});@@ -248,3 +248,16 @@ it('keeps a start response when an older status request resolves afterwards', asawait act(async () => resolveRead({ runs: [] }));expect(screen.getByRole('button', { name: 'Stop remaining checks' })).toBeInTheDocument();});++it('defaults audit fixes to draft review and lets the user explicitly inherit saved policy', async () => {+ startMaintenanceRun.mockResolvedValue({ run: { id: 'draft-run', status: 'completed', steps: [] } });+ render(<MemoryRouter><AppQualityRunner app={app} /></MemoryRouter>);+ fireEvent.change(await findEnabledByLabelText('Mode'), { target: { value: 'fix' } });+ expect(screen.getByLabelText('Pull requests')).toHaveValue('draft');+ fireEvent.click(await findEnabledByRole('button', { name: 'Run 2 checks now' }));+ await waitFor(() => expect(startMaintenanceRun).toHaveBeenLastCalledWith(expect.objectContaining({ mode: 'fix', prCompletion: 'draft', claimBetweenAudits: false }), { silent: true }));+ fireEvent.change(await findEnabledByLabelText('Pull requests'), { target: { value: '' } });+ fireEvent.click(await findEnabledByRole('button', { name: 'Run 2 checks now' }));+ await waitFor(() => expect(startMaintenanceRun).toHaveBeenCalledTimes(2));+ expect(startMaintenanceRun.mock.lastCall[0]).not.toHaveProperty('prCompletion');+});diff --git a/server/lib/maintenanceSequence.js b/server/lib/maintenanceSequence.jsindex c25c655131..506585cf03 100644--- a/server/lib/maintenanceSequence.js+++ b/server/lib/maintenanceSequence.js@@ -56,7 +56,7 @@ export const maintenanceStepParams = (taskType, mode = 'file-issues') => (taskTy* invocation yields fresh step identities. An optional claimHandler replaces* the provider/model/effort bundle for drains only; omitted keeps legacy pins.*/-export function buildMaintenanceSteps({ appId, idPrefix, providerId = null, model = null, effort = null, mode = 'file-issues', claimBetweenAudits = true, claimHandler = null, taskTypes = null, explicitCheck = false }) {+export function buildMaintenanceSteps({ appId, idPrefix, providerId = null, model = null, effort = null, mode = 'file-issues', prCompletion = null, claimBetweenAudits = true, claimHandler = null, taskTypes = null, explicitCheck = false }) {if (taskTypes !== null && (!Array.isArray(taskTypes) || !taskTypes.length || taskTypes.some(type => !Object.hasOwn(AUDIT_DEFINITIONS, type)))) {throw new Error('Quality checks must name known audit categories');}@@ -70,6 +70,6 @@ export function buildMaintenanceSteps({ appId, idPrefix, providerId = null, modejobType: null,runOnce: true,drain: taskType === MAINTENANCE_DRAIN_TASK,- overrides: { ...(taskType === MAINTENANCE_DRAIN_TASK && claimHandler ? claimHandler : { providerId, model, effort }), params: taskTypes ? { fileIssues: mode !== 'fix', ...(mode === 'fix' ? { useWorktree: true, openPR: true } : {}), ...(explicitCheck ? { runInapplicableAudit: true } : {}) } : maintenanceStepParams(taskType, mode) },+ overrides: { ...(taskType === MAINTENANCE_DRAIN_TASK && claimHandler ? claimHandler : { providerId, model, effort }), params: taskTypes ? { fileIssues: mode !== 'fix', ...(mode === 'fix' ? { useWorktree: true, openPR: true, ...(prCompletion ? { prCompletion } : {}) } : {}), ...(explicitCheck ? { runInapplicableAudit: true } : {}) } : { ...maintenanceStepParams(taskType, mode), ...(prCompletion ? { prCompletion } : {}) } },}));}diff --git a/server/lib/prDisposition.js b/server/lib/prDisposition.jsindex 332b727296..4ce953e8d5 100644--- a/server/lib/prDisposition.js+++ b/server/lib/prDisposition.js@@ -24,6 +24,8 @@ export const PR_COMPLETIONS = Object.freeze({REVIEW_THEN_MERGE: 'review-then-merge',MERGE_ON_GREEN: 'merge-on-green',LEAVE_OPEN: 'leave-open',+ // A creation contract; lifecycle consumers resolve it to LEAVE_OPEN.+ DRAFT: 'draft',});export const PR_COMPLETION_VALUES = Object.freeze(Object.values(PR_COMPLETIONS));@@ -82,6 +84,7 @@ export const isSelfReviewMode = (mode) => mode === PR_REVIEW_MODES.SELF;* @returns {'review-then-merge'|'merge-on-green'|'leave-open'}*/export function resolvePrCompletion(metadata = {}) {+ if (metadata?.prCompletion === PR_COMPLETIONS.DRAFT) return PR_COMPLETIONS.LEAVE_OPEN;if (PR_COMPLETION_SET.has(metadata?.prCompletion)) return metadata.prCompletion;return isTruthyMeta(metadata?.reviewLoop)? PR_COMPLETIONS.REVIEW_THEN_MERGEdiff --git a/server/routes/cosScheduleRoutes.js b/server/routes/cosScheduleRoutes.jsindex 8c732e9ba2..59c8da3952 100644--- a/server/routes/cosScheduleRoutes.js+++ b/server/routes/cosScheduleRoutes.js@@ -1,3 +1,4 @@+import { PR_COMPLETION_VALUES } from '../lib/prDisposition.js';import { AUDIT_DEFINITIONS } from '../lib/auditCatalog.js';/*** CoS Task Schedule Routes@@ -44,6 +45,7 @@ const maintenanceRunStartSchema = z.object({// so each runs even where the repository scan says it cannot apply.explicitCheck: z.boolean().optional(),mode: z.enum(['file-issues', 'fix']).optional(),+ prCompletion: z.enum(PR_COMPLETION_VALUES).optional(),claimBetweenAudits: z.boolean().optional(),claimHandler: z.object({providerId: z.string().trim().min(1),diff --git a/server/routes/cosScheduleRoutes.test.js b/server/routes/cosScheduleRoutes.test.jsindex bb9954dd24..c62430cd75 100644--- a/server/routes/cosScheduleRoutes.test.js+++ b/server/routes/cosScheduleRoutes.test.js@@ -91,6 +91,14 @@ describe('CoS Schedule Routes', () => {maintenance.updateMaintenanceStep.mockResolvedValue(null);expect((await request(app).patch(url).send(settings)).status).toBe(404);});+ it('accepts an explicit draft disposition and rejects unknown policies', async () => {+ maintenance.startMaintenanceRun.mockResolvedValue({ run: { id: 'draft-run' } });+ const body = { appId: 'app-1', providerId: 'codex', model: 'gpt-6-astra', effort: 'medium', mode: 'fix', prCompletion: 'draft', taskTypes: ['security'] };+ expect((await request(app).post('/api/cos/schedule/maintenance-runs').send(body)).status).toBe(201);+ expect(maintenance.startMaintenanceRun).toHaveBeenCalledWith(body);+ expect((await request(app).post('/api/cos/schedule/maintenance-runs').send({ ...body, prCompletion: 'unknown' })).status).toBe(400);+ });+it('accepts fix mode and rejects unknown modes', async () => {maintenance.startMaintenanceRun.mockResolvedValue({ run: { id: 'maint-1' } });const body = { appId: 'app-1', providerId: 'codex', model: 'gpt-5', mode: 'fix', claimBetweenAudits: false, claimHandler: { providerId: 'claude', model: 'sonnet', effort: 'low' } };diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.jsindex f4668738ab..7fdb8acc22 100644--- a/server/services/agentErrorAnalysis.js+++ b/server/services/agentErrorAnalysis.js@@ -1,3 +1,4 @@+import { PR_COMPLETIONS, resolvePrCompletion } from '../lib/prDisposition.js';import { isPrivateSecurityTask } from '../lib/privateSecurityPolicy.js';/*** Agent Error Analysis@@ -1406,6 +1407,10 @@ export const API_ACCESS_ERROR_CATEGORIES = new Set([]);export async function maybeCreateInvestigationTask(agentId, task, analysis) {+ if (resolvePrCompletion(task?.metadata) === PR_COMPLETIONS.LEAVE_OPEN) {+ emitLog('warn', `Review-only task ${task.id} needs attention; automatic investigation suppressed`, { agentId, taskId: task.id });+ return;+ }if (API_ACCESS_ERROR_CATEGORIES.has(analysis?.category)) {emitLog('debug', `⏭️ Skipping investigation task for ${task.id}: API access error (${analysis.category})`, { agentId, taskId: task.id, category: analysis.category });return;diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.jsindex 34de17f2f7..7d7ac5cdae 100644--- a/server/services/agentErrorAnalysis.test.js+++ b/server/services/agentErrorAnalysis.test.js@@ -1474,3 +1474,9 @@ describe('API_ACCESS_ERROR_CATEGORIES ⊆ ENVIRONMENTAL_ERROR_CATEGORIES (issue}});});++it.each(['draft', 'leave-open'])('keeps failed %s tasks from spawning an unrestricted investigation', async prCompletion => {+ addTask.mockClear();+ await maybeCreateInvestigationTask('a1', { id: 't1', metadata: { prCompletion } }, { category: 'test-failure', actionable: true });+ expect(addTask).not.toHaveBeenCalled();+});diff --git a/server/services/agentFinalization.goalFidelity.test.js b/server/services/agentFinalization.goalFidelity.test.jsindex c763c8266b..f49c243852 100644--- a/server/services/agentFinalization.goalFidelity.test.js+++ b/server/services/agentFinalization.goalFidelity.test.js@@ -561,6 +561,13 @@ describe('finalizeAgent — goal-fidelity gate', () => {runLocalGoalFidelityReviewMock.mockResolvedValue(verdict({ verdict: 'rethink', missing: ['the retry'] }));});+ it.each(['draft', 'leave-open'])('retains findings without filing issues or queuing unrestricted followups for %s', async prCompletion => {+ await finalize({ task: { id: 'task-1', taskType: 'internal', description: 'Add a retry', metadata: { prCompletion } } });+ expect(runGoalFidelityFollowUpMock).not.toHaveBeenCalled();+ expect(completion().goalFidelity.verdict).toBe('rethink');+ expect(cosEvents.emit).toHaveBeenCalledWith(GOAL_FIDELITY_HOLD_EVENT, expect.anything());+ });+it('hands the follow-up the review, and records what it did on the run', async () => {runGoalFidelityFollowUpMock.mockResolvedValue({ran: true,diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsindex 967ba9626d..c5480c4b4f 100644--- a/server/services/agentFinalization.js+++ b/server/services/agentFinalization.js@@ -1,4 +1,4 @@-import { PR_MISSING_CATEGORY, prClaimWasVerified } from '../lib/prDisposition.js';+import { PR_COMPLETIONS, resolvePrCompletion, PR_MISSING_CATEGORY, prClaimWasVerified } from '../lib/prDisposition.js';import { isAuditTaskType } from '../lib/auditCatalog.js';import { isPrivateSecurityTask } from '../lib/privateSecurityPolicy.js';/**@@ -430,6 +430,7 @@ const PR_OBSERVATION = Object.freeze({WORK_LANDED_ELSEWHERE: 'work-landed-elsewhere',/** The change request exists but does not close the issue its branch names. */INVALID_TRAILER: 'invalid-trailer',+ INVALID_DISPOSITION: 'invalid-disposition',/** We could not ask, or could not read the answer. Says nothing about the PR. */FORGE_UNAVAILABLE: 'forge-unavailable',});@@ -467,6 +468,7 @@ const PR_OBSERVATION_POLICY = Object.freeze({// so the run stands as reported. `recordable` so the ledger carries the// stand-down (verified: true) rather than silently omitting the transition.[PR_OBSERVATION.WORK_LANDED_ELSEWHERE]: Object.freeze({ completionOk: true, observed: true, namesBranch: true, recordable: true, category: null }),+ [PR_OBSERVATION.INVALID_DISPOSITION]: Object.freeze({ completionOk: false, observed: true, namesBranch: true, recordable: true, category: 'pr-disposition' }),[PR_OBSERVATION.INVALID_TRAILER]: Object.freeze({ completionOk: false, observed: true, namesBranch: true, recordable: true, category: ISSUE_TRAILER_MISSING_CATEGORY }),[PR_OBSERVATION.FORGE_UNAVAILABLE]: Object.freeze({ completionOk: false, observed: true, namesBranch: true, recordable: false, category: FORGE_UNREACHABLE_CATEGORY }),});@@ -591,13 +593,18 @@ async function observePrClaim({ task, workspacePath, success, prExpected, agentS// on, which on a multi-login host may not even see the PR — reading as// "no PR" for a run that opened one.const { cli, env } = await resolveForgeForRepo(workspacePath).catch(() => ({ cli: 'gh', env: null }));+ const draft = task?.metadata?.prCompletion === PR_COMPLETIONS.DRAFT;const found = cli === 'glab'- ? await (await import('./gitlab.js')).findMergeRequestForBranch(branch, workspacePath)- : await (await import('./github.js')).findPullRequestForBranch(branch, { cwd: workspacePath, env: env || null });+ ? await (await import('./gitlab.js')).findMergeRequestForBranch(branch, workspacePath, ...(draft ? [{ includeDraft: true }] : []))+ : await (await import('./github.js')).findPullRequestForBranch(branch, { cwd: workspacePath, env: env || null, ...(draft ? { includeDraft: true } : {}) });const noun = cli === 'glab' ? 'merge request' : 'pull request';const titleNoun = `${noun[0].toUpperCase()}${noun.slice(1)}`;if (found.status === 'found') {+ if (draft && (found.isDraft !== true || !['OPEN', 'opened'].includes(found.detail))) {+ return prObservation(PR_OBSERVATION.INVALID_DISPOSITION, { branch,+ message: `This run requires an open draft ${noun}; the forge did not confirm that disposition for ${branch}` });+ }const issueNumber = issueNumberFromRef(branch);if (issueNumber === null) return prObservation(PR_OBSERVATION.VERIFIED_CLAIM, { branch });if (typeof found.body !== 'string') {@@ -1465,7 +1472,7 @@ export async function finalizeAgent({// of it on the closure of every suite that reaches finalization. Gated on the// WIDEST trigger so a clean `ship` — the overwhelmingly common verdict — does// not evaluate that graph just to be told there is nothing to act on.- if (goalFidelityFollowUpApplies(fidelity.review, 'any-finding')) {+ if (resolvePrCompletion(task?.metadata) !== PR_COMPLETIONS.LEAVE_OPEN && goalFidelityFollowUpApplies(fidelity.review, 'any-finding')) {const followUp = await import('./goalFidelityFollowUp.js').then(({ runGoalFidelityFollowUp }) => runGoalFidelityFollowUp({ agentId, task, review: fidelity.review, context: fidelity.context })).catch(err => {@@ -1922,7 +1929,10 @@ async function dispatchTaskOutputHook({ agentId, task, success, workspacePath, aconst recorded = await recordAuditQuality({ task, taskType, agentId, success, assessedAt,workspacePath: hookPayloadDir({ task, workspacePath, recovery }) }).catch(err => emitLog('warn', `⚠️ Audit quality was not saved for ${agentId}: ${err.message}`, { agentId }));- if (recorded === true) await publishAppSnapshotFileAfterAudit(task?.metadata?.app);+ // A review-only run must not land a separate snapshot behind the user's back.+ if (recorded === true && resolvePrCompletion(task?.metadata) !== PR_COMPLETIONS.LEAVE_OPEN) {+ await publishAppSnapshotFileAfterAudit(task?.metadata?.app);+ }// Assessment telemetry never waives commit/PR success criteria for fix mode.return { ran: false };}diff --git a/server/services/agentFinalization.outputHooks.test.js b/server/services/agentFinalization.outputHooks.test.jsindex f544793908..85e483b558 100644--- a/server/services/agentFinalization.outputHooks.test.js+++ b/server/services/agentFinalization.outputHooks.test.js@@ -124,6 +124,17 @@ describe('recovery output-hook dispatch (#3182)', () => {// Landing the app's `.quality.json` PR is opt-in and runs outside the request// lifecycle, so it must never fire for an un-opted app nor fail a completion.// Each dispatch needs its own agent id — dispatchTaskOutputHookOnce caches by id.+ it.each(['draft', 'leave-open'])('retains measurements without publishing snapshots for %s, on completion', async prCompletion => {+ const task = { ...TASK, metadata: { ...TASK.metadata, analysisType: 'security', prCompletion } };+ appsRegistry.getAppById.mockResolvedValue({ id: 'app-example', repoPath: '/repo', publishQualitySnapshot: true });+ snapshotFile.publishAppQualitySnapshot.mockClear();+ await dispatchTaskOutputHookOnce({ agentId: `review-only-${prCompletion}`, task, success: true, workspacePath: '/worktree' });+ expect(recordAuditQuality).toHaveBeenCalledWith(expect.objectContaining({ task, success: true }));+ expect(snapshotFile.publishAppQualitySnapshot).not.toHaveBeenCalled();+ await dispatchRecoveredTaskOutputHook({ agentId: persistedAgent.id, task, success: true });+ expect(snapshotFile.publishAppQualitySnapshot).not.toHaveBeenCalled();+ });+it('commits a repo snapshot only for an opted-in app that just recorded a measurement', async () => {const task = { ...TASK, metadata: { ...TASK.metadata, analysisType: 'better-complexity' } };let run = 0;diff --git a/server/services/agentFinalization.prVerification.test.js b/server/services/agentFinalization.prVerification.test.jsindex 1518afa72a..ad3b84d423 100644--- a/server/services/agentFinalization.prVerification.test.js+++ b/server/services/agentFinalization.prVerification.test.js@@ -163,6 +163,18 @@ beforeEach(() => {});describe('verifyPrClaim (#3358)', () => {+ it.each([+ [true, 'OPEN', true], [false, 'OPEN', false], [undefined, 'OPEN', false], [true, 'MERGED', false], [true, 'CLOSED', false],+ ])('requires a verified open draft (%s, %s)', async (isDraft, state, expected) => {+ onBranch('audit/security');+ findPullRequestForBranchMock.mockResolvedValue({ status: 'found', number: 7, isDraft, detail: state });+ const task = prTask(); task.metadata.prCompletion = 'draft';+ const result = await verifyPrClaim({ task, workspacePath: '/w', success: true, prExpected: true });+ expect(result.ok).toBe(expected);+ if (!expected) expect(result.category).toBe('pr-disposition');+ expect(findPullRequestForBranchMock).toHaveBeenCalledWith('audit/security', { cwd: '/w', env: null, includeDraft: true });+ });+it('passes when the forge confirms a PR for the branch', async () => {onBranch('claim/issue-1');const verdict = await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true });diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 12b69736b0..135d817727 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -819,6 +819,7 @@ return `${agentInstructionsSection || ''}${memorySection || ''}${digitalTwinSection ? `\n${digitalTwinSection}\n` : ''}+${task.metadata?.prCompletion === PR_COMPLETIONS.DRAFT ? DRAFT_PR_RULE : ''}${taskBlock.description}${contextBlock ? (contextBlock.includes('\n') ? `\n### Task Context\n\n${contextBlock.trimEnd()}\n` : `\n### Task Context\n\n${contextBlock}\n`) : ''}${taskBlock.targetApp}@@ -908,6 +909,9 @@ export function buildLightContextPromptParts(task, workspaceDir, worktreeInfo, o};}+const DRAFT_PR_RULE = `## Draft pull request delivery+This run must leave its changes in a DRAFT pull request for human review. This overrides other publication instructions, including repository skills and saved defaults. Use gh pr create --draft or glab mr create --draft when you own PR creation. If a workflow opens a ready PR, convert it to draft before completion. Verify it is still open and draft. Never mark it ready, merge, enable auto-merge, deploy, or publish quality snapshots. If PortOS owns PR creation, commit in the assigned worktree and let PortOS open the draft.`;+const BEGIN_WORKING_LINE = 'Begin working on the task now.';function buildLightContextSections(task, workspaceDir, worktreeInfo, { isTui = true, providerId = null, providerCommand = null, providerModel = null, leanMode = false, agentId = null, defaultReviewers, codeReviewDefaults, localAgentLoopBody = null, localAgentLoopBodyPath = null, forgeCli = null } = {}) {@@ -1028,6 +1032,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, { isTui = t// actually stalled on an approval gate, and "no human will answer you" is not// something the agent can infer from AGENTS.md or its cwd.contractSections.push(UNATTENDED_RUN_RULE);+ if (task.metadata?.prCompletion === PR_COMPLETIONS.DRAFT) contractSections.push(DRAFT_PR_RULE);if (isUiAuditTask(task)) contractSections.push(UI_AUDIT_RUNTIME_RULE);// --- Issue filing labels and planner attribution --------------------------diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex 4cd5825426..97c3e8d26b 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -443,6 +443,30 @@ describe('no-code / API-action task completion (CD agents must NOT be told to /d});});+describe('draft review delivery', () => {+ it('puts the draft override in the system contract of a split provider prompt', async () => {+ const task = makeTask({ metadata: { useWorktree: true, openPR: true, reviewLoop: true, prCompletion: 'draft' } });+ const parts = await buildAgentPrompt(task, {}, '/repo', { worktreePath: '/worktree', branchName: 'audit/topic' }, {+ providerType: 'cli', providerId: 'claude-code', providerCommand: 'claude', split: true,+ });+ expect(parts.systemPrompt).toContain('DRAFT pull request for human review');+ expect(parts.systemPrompt).toContain('gh pr create --draft');+ expect(parts.systemPrompt).toContain('--no-merge');+ expect(parts.systemPrompt).not.toMatch(/gh pr merge|glab mr merge|--auto-merge/);+ expect(parts.userPrompt).not.toContain('## Draft pull request delivery');+ });++ it.each([true, false])('overrides merge defaults on the light/full path (%s)', async light => {+ const task = makeTask({ metadata: { useWorktree: true, openPR: true, reviewLoop: true, prCompletion: 'draft' } });+ const prompt = light+ ? buildLightContextPrompt(task, '/repo', { worktreePath: '/worktree', branchName: 'audit/topic' }, { isTui: true, providerId: 'codex-tui', providerCommand: 'codex' })+ : await buildAgentPrompt(task, {}, '/repo', { worktreePath: '/worktree', branchName: 'audit/topic' }, { providerType: 'api' });+ expect(prompt).toContain('DRAFT pull request for human review');+ expect(prompt).toContain('gh pr create --draft');+ expect(prompt).not.toMatch(/gh pr merge|--auto-merge/);+ });+});+describe('claim-flow completion handoff', () => {it.each([true, false])('honors leave-open on the %s light/full claim path', async (light) => {const task = makeTask({ metadata: { analysisType: 'claim-issue', claimFlow: true, useWorktree: false, openPR: false, prCompletion: 'leave-open' } });diff --git a/server/services/agentRepoStateVerification.js b/server/services/agentRepoStateVerification.jsindex 6ee337d6cd..b4a402f3f6 100644--- a/server/services/agentRepoStateVerification.js+++ b/server/services/agentRepoStateVerification.js@@ -44,7 +44,7 @@ import { PATHS } from '../lib/fileUtils.js';import { isTruthyMeta } from './agentState.js';import { RECOVERY_TASK_PREFIX } from './recoveryTasks.js';import { resolveTaskTargetBranch } from '../lib/taskTargetBranch.js';-import { leavesPrForHuman, resolvePrCompletion } from '../lib/prDisposition.js';+import { leavesPrForHuman, resolvePrCompletion, PR_COMPLETIONS } from '../lib/prDisposition.js';import { probePrForBranch } from './prProbe.js';import { ensureTaskThread } from './brainTaskThreads.js';import {@@ -313,6 +313,11 @@ export async function verifyAgentRepoState({ agentId, task, agentState, success,return { verified: true, skipReason: null, issues: [], observed, recoveryTaskId: null };}+ if (resolvePrCompletion(task?.metadata) === PR_COMPLETIONS.LEAVE_OPEN) {+ emitLog('warn', `Review-only branch ${branchName} needs attention; automatic cleanup and recovery suppressed`, { agentId, branchName });+ return { verified: false, skipReason: null, issues, observed, recoveryTaskId: null };+ }+// A merged branch with no remote ref is safe for the deterministic reaper to// retire. Do this before creating another agent task: the common failure is// simply that the completing agent exited before its worktree teardown ran.diff --git a/server/services/agentRepoStateVerification.test.js b/server/services/agentRepoStateVerification.test.jsindex f744e8b8bf..1c54f1da47 100644--- a/server/services/agentRepoStateVerification.test.js+++ b/server/services/agentRepoStateVerification.test.js@@ -429,3 +429,14 @@ describe('remediation coverage', () => {}});});++it.each(['draft', 'leave-open'])('reports divergence without cleanup or recovery for %s delivery', async prCompletion => {+ existsSync.mockReturnValue(true);+ listWorktrees.mockResolvedValue([{ path: WORKTREE, branch: BRANCH }]);+ const result = await run({ task: task({ prCompletion }) });+ expect(result.verified).toBe(false);+ expect(result.issues.length).toBeGreaterThan(0);+ expect(result.recoveryTaskId).toBeNull();+ expect(addTask).not.toHaveBeenCalled();+ expect(cleanupMerged).not.toHaveBeenCalled();+});diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex 32ac5a5d1c..3329e68ccd 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -26,7 +26,7 @@ import { resolveTaskTargetBranch, shouldStripTaskTargetBranch } from '../lib/tasimport { RECOVERY_TASK_PREFIX } from './recoveryTasks.js';import { detectForgeCli } from '../lib/gitForge.js';import { normalizeForkHead } from '../lib/forkHead.js';-import { PR_COMPLETIONS, PR_COMPLETION_VALUES, PR_CREATION, PR_MISSING_CATEGORY, leavesPrForHuman, prClaimWasVerified } from '../lib/prDisposition.js';+import { PR_COMPLETIONS, resolvePrCompletion, PR_COMPLETION_VALUES, PR_CREATION, PR_MISSING_CATEGORY, leavesPrForHuman, prClaimWasVerified } from '../lib/prDisposition.js';import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, MODEL_SELECTABLE_REVIEWERS, EFFORT_SELECTABLE_REVIEWERS, isProviderReviewer, normalizeReviewers, normalizeReviewUsernames, normalizeOptionalReviewers, normalizeReviewerMaxRounds, prioritizeToolFreeReviewers } from '../lib/reviewerConfig.js';// In-flight cleanup per agentId, so two completion paths racing to clean the@@ -175,7 +175,9 @@ async function worktreeCleanupContext(agentId, options) {if (!sourceWorkspace || !worktreeBranch) return { isWorktree: false };const normalized = cleanupOptions(options);return {- ...normalized, isWorktree: true, agentId, sourceWorkspace, worktreeBranch,+ ...normalized,+ ...(normalized.originalTask?.metadata?.prCompletion === PR_COMPLETIONS.DRAFT ? { prCompletion: PR_COMPLETIONS.LEAVE_OPEN, skipMerge: true } : {}),+ isWorktree: true, agentId, sourceWorkspace, worktreeBranch,discardWorktree: isTruthyMeta(normalized.originalTask?.metadata?.discardWorktree),worktreePath: metadata.workspacePath || join(PATHS.worktrees, agentId),warnings: [],@@ -193,7 +195,7 @@ async function probeWorktreePr(context, success) {// DUPLICATE of the change request the summary says already landed.const { extractFinalSummary } = await import('./agentSummaryExtraction.js');const agentSummary = extractFinalSummary(agentOutput);- return verifyPrClaim({ workspacePath: worktreePath, success: true, prExpected: true, agentSummary })+ return verifyPrClaim({ task: context.originalTask, workspacePath: worktreePath, success: true, prExpected: true, agentSummary }).catch(err => ({ ok: false, category: 'forge-unreachable', message: err.message }));}const { findPullRequestForBranch } = await import('./github.js');@@ -306,13 +308,23 @@ async function openWorktreePullRequest(context) {title: prTitle,body: prBody,base: targetBranch,- head: worktreeBranch+ head: worktreeBranch,+ ...(context.originalTask?.metadata?.prCompletion === PR_COMPLETIONS.DRAFT ? { draft: true } : {})}).catch(err => {emitLog('warn', `🌳 Failed to create PR for ${worktreeBranch}: ${err.message}`, { agentId });return null;});if (!prResult?.success) return handlePrCreationFailure(context, prResult, targetBranch);+ if (context.originalTask?.metadata?.prCompletion === PR_COMPLETIONS.DRAFT) {+ const { verifyPrClaim } = await import('./agentFinalization.js');+ const verdict = await verifyPrClaim({ task: context.originalTask, workspacePath: worktreePath, success: true, prExpected: true })+ .catch(() => ({ ok: false }));+ if (!verdict?.ok || !verdict.branch) {+ warnings.push(`Draft PR disposition could not be verified for ${worktreeBranch}; worktree preserved for review`);+ return warnings;+ }+ }return completeOpenedPullRequest(context, prResult);}@@ -1248,6 +1260,12 @@ export async function spawnMergeRecoveryTask(cleanupWarnings, agentId, task, appif (!staleBranch || !sourceWorkspace) return;+ // Review-only runs must not delegate to a recovery agent that can land work.+ if (resolvePrCompletion(task?.metadata) === PR_COMPLETIONS.LEAVE_OPEN) {+ emitLog('warn', `Review-only branch ${staleBranch} needs manual recovery; automatic recovery suppressed`, { agentId, staleBranch });+ return null;+ }+const appId = task?.metadata?.app;if (isMergeFail) {diff --git a/server/services/agentWorktreeCleanup.repoStateAudit.test.js b/server/services/agentWorktreeCleanup.repoStateAudit.test.jsindex 484ec3aa01..807e5feeab 100644--- a/server/services/agentWorktreeCleanup.repoStateAudit.test.js+++ b/server/services/agentWorktreeCleanup.repoStateAudit.test.js@@ -39,9 +39,9 @@ vi.mock('./agentRepoStateVerification.js', () => ({verifyAgentRepoState: vi.fn().mockResolvedValue({ verified: true, issues: [] }),}));-import { cleanupAgentWorktree } from './agentWorktreeCleanup.js';+import { cleanupAgentWorktree, spawnMergeRecoveryTask } from './agentWorktreeCleanup.js';import { verifyAgentRepoState } from './agentRepoStateVerification.js';-import { getAgent, getAgentRecord } from './cos.js';+import { getAgent, getAgentRecord, addTask } from './cos.js';import { removeWorktree } from './worktreeManager.js';const worktreeAgent = {@@ -168,3 +168,10 @@ describe('cleanupAgentWorktree → repo-state audit', () => {.toEqual(['Worktree preserved — uncommitted changes detected']);});});++it.each(['draft', 'leave-open'])('does not queue unrestricted recovery for %s delivery', async prCompletion => {+ for (const warning of ['PR creation failed for branch topic: unavailable', 'Auto-merge failed for branch topic']) {+ await spawnMergeRecoveryTask([warning], 'a1', { metadata: { prCompletion } }, 'App', '/repo');+ }+ expect(addTask).not.toHaveBeenCalled();+});diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.jsindex 76171e7cc2..b8a9b74c93 100644--- a/server/services/branchReconcile.js+++ b/server/services/branchReconcile.js@@ -162,6 +162,9 @@ const PR_LIST_LIMIT = 200;* @returns {'ABANDONED_WIP'|'MERGED'|'CONFLICTED'|'IN_REVIEW'|'NEEDS_PR'|'WIP'}*/export function classifyBranch({ hasUpstream, ahead = null, hasOrigin = false, isMerged, worktreeDirty, abandonedAgentWorktree, abandonedClaimWorktree, liveOwnerReason = null, openPr, prStateUnavailable = false }) {+ // A draft is an explicit human-review handoff, even after its agent exits.+ // Protect it before dirty/merged classification can delegate or retire it.+ if (openPr?.isDraft) return 'WIP';// A dead agent's worktree that still holds uncommitted work is the ONE dirty// case that must be driven rather than skipped — and it must be caught BEFORE// the `isMerged` test, because an agent that exited without committing leaves@@ -1513,6 +1516,7 @@ export const actionOn = (actions, key) => actions?.[key] !== false;*/export function filterActionable(inFlight, actions) {return inFlight.filter((b) => {+ if (b.openPr?.isDraft) return false;if (b.state === 'ABANDONED_WIP') return actionOn(actions, 'finishAbandoned');if (b.state === 'NEEDS_PR') return actionOn(actions, 'openPr');if (b.state === 'CONFLICTED') return actionOn(actions, 'resolveConflicts');diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.jsindex 50c7dd0361..1db708ef51 100644--- a/server/services/branchReconcile.test.js+++ b/server/services/branchReconcile.test.js@@ -2551,3 +2551,10 @@ describe('shutdown interruption (#6992)', () => {expect(error).toHaveBeenCalledWith(expect.stringContaining('signal SIGSEGV'));});});++it.each(['MERGEABLE', 'CONFLICTING'])('protects an open draft (%s) from reconcile and cleanup', mergeable => {+ const openPr = { isDraft: true, mergeable };+ expect(classifyBranch({ openPr, isMerged: false, hasUpstream: true })).toBe('WIP');+ expect(classifyBranch({ openPr, isMerged: true, worktreeDirty: true, abandonedAgentWorktree: true })).toBe('WIP');+ expect(filterActionable([{ branch: 'topic', state: 'IN_REVIEW', openPr }], {})).toEqual([]);+});diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.jsindex 7c2d10afa2..868a99b1db 100644--- a/server/services/cleanupAgentWorktree.test.js+++ b/server/services/cleanupAgentWorktree.test.js@@ -278,6 +278,22 @@ describe('cleanupAgentWorktree - PR-creation path', () => {);});+ it.each([true, false])('verifies a server-created draft before completing cleanup: %s', async ok => {+ git.push.mockResolvedValue(undefined);+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/1' });+ verifyPrClaimMock.mockResolvedValue({ ok, branch: 'cos/task-abc123', category: ok ? null : 'pr-disposition' });+ const originalTask = { metadata: { prCompletion: 'draft', openPR: true } };+ const warnings = await cleanupAgentWorktree('agent-1', true, { prCreation: 'always', originalTask });+ expect(git.createPR).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ draft: true }));+ expect(verifyPrClaimMock).toHaveBeenCalledWith(expect.objectContaining({ task: originalTask, prExpected: true }));+ expect(addTask).not.toHaveBeenCalled();+ if (ok) expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: false });+ else {+ expect(removeWorktree).not.toHaveBeenCalled();+ expect(warnings.join(' ')).toContain('Draft PR disposition could not be verified');+ }+ });+it('should run PR flow when prCreation is always and success is true', async () => {git.push.mockResolvedValue(undefined);git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/1' });diff --git a/server/services/cosTaskGenerator.auditMode.test.js b/server/services/cosTaskGenerator.auditMode.test.jsindex c11e933de7..a1070843b8 100644--- a/server/services/cosTaskGenerator.auditMode.test.js+++ b/server/services/cosTaskGenerator.auditMode.test.js@@ -391,6 +391,32 @@ describe('mode is honored identically from schedule, manual run, and quota burn'expect(task.metadata.notARealFlag).toBeUndefined();});+ it('keeps explicit draft delivery through scheduled defaults, app overrides and the generated Codex contract', async () => {+ const { getTaskInterval } = await import('./taskSchedule.js');+ const { getAppTaskTypeOverrides } = await import('./apps.js');+ getTaskInterval.mockResolvedValue({ type: 'weekly', taskMetadata: {+ fileIssues: true, useWorktree: false, openPR: false, prCompletion: 'merge-on-green',+ } });+ getAppTaskTypeOverrides.mockResolvedValueOnce({ security: { taskMetadata: {+ prCompletion: 'review-then-merge', reviewLoop: true,+ } } });+ const [step] = buildMaintenanceSteps({+ appId: 'app-1', idPrefix: 'draft-review', mode: 'fix', prCompletion: 'draft', taskTypes: ['security'],+ });+ const task = await generate(step.taskRef.taskType, {+ skipPreconditions: true, runOverrides: step.overrides.params,+ });+ expect(task.metadata).toMatchObject({ fileIssues: false, useWorktree: true, openPR: true, prCompletion: 'draft' });+ expect(task.metadata.noCodeOutput).toBeUndefined();+ const prompt = buildLightContextPrompt(task, WORKSPACE, {+ branchName: 'audit/security', worktreePath: WORKSPACE,+ }, { isTui: true, providerId: 'codex-tui', providerCommand: 'codex' });+ expect(prompt).toContain('Mode: implement the highest-value fix');+ expect(prompt).toContain('DRAFT pull request for human review');+ expect(prompt).toContain('Do NOT push, open, or merge a pull request yourself');+ expect(prompt).not.toMatch(/## Merge Gate|## Review Loop|gh pr merge|glab mr merge/);+ });+// Either Priority-0 engine may drain any given request, so a burn step's run// parameters must reach the generator whichever one got there first. They do// by construction now — both engines delegate to the one shared drain — sodiff --git a/server/services/git.forgeTimeout.test.js b/server/services/git.forgeTimeout.test.jsindex f3ca945a79..14530e8afb 100644--- a/server/services/git.forgeTimeout.test.js+++ b/server/services/git.forgeTimeout.test.js@@ -71,6 +71,17 @@ describe('bounded forge mutations', () => {);});+ it.each(['gh', 'glab'])('creates drafts through %s without enabling merging', async cli => {+ mocks.resolveForgeForRepo.mockResolvedValue({ cli, env: pinnedEnv, host: 'example.com', owner: 'example-owner' });+ const child = hungChild(); mocks.spawn.mockReturnValue(child);+ const pending = createPR('/repo', { title: 'Title', body: 'Body', base: 'main', head: 'topic', draft: true });+ await vi.dynamicImportSettled();+ child.stdout.emit('data', 'https://example.com/pr/7'); child.emit('close', 0);+ await expect(pending).resolves.toMatchObject({ success: true });+ expect(mocks.spawn).toHaveBeenCalledWith(cli, expect.arrayContaining(['--draft']), expect.anything());+ expect(mocks.spawn.mock.calls[0][1]).not.toContain('--auto-merge');+ });+it('bounds GitLab MR creation with the resolved forge environment', async () => {mocks.resolveForgeForRepo.mockResolvedValue({cli: 'glab',diff --git a/server/services/git.js b/server/services/git.jsindex 868f762d2b..60db3a661d 100644--- a/server/services/git.js+++ b/server/services/git.js@@ -399,13 +399,14 @@ async function execForgeCli(cli, args, dir, env) {* @param {string} options.head - Head branch (source, must be pushed to remote)* @returns {Promise<{success: boolean, url?: string, error?: string, cli?: string, account?: string|null, owner?: string|null, host?: string|null}>}*/-export async function createPR(dir, { title, body, base, head }) {+export async function createPR(dir, { title, body, base, head, draft = false }) {const { cli, env, host, owner, account } = await resolveForgeForRepo(dir);const args = cli === 'glab'? ['mr', 'create', '--title', title, '--description', body || '', '--target-branch', base, '--source-branch', head]: ['pr', 'create', '--title', title, '--body', body || '', '--base', base, '--head', head];+ if (draft) args.push('--draft');const meta = { cli, account, owner, host };try {diff --git a/server/services/github.js b/server/services/github.jsindex 6df2a4d2d4..3b10f1e623 100644--- a/server/services/github.js+++ b/server/services/github.js@@ -846,10 +846,10 @@ export async function ensureForgeReachable(label, { hostname = null, env = null* account may not even see it, which would read as "no PR".* @returns {Promise<{ status: 'found'|'none'|'unavailable', number: number|null, url: string|null, body: string|null, detail: string|null }>}*/-export async function findPullRequestForBranch(branch, { cwd = null, env = null } = {}) {+export async function findPullRequestForBranch(branch, { cwd = null, env = null, includeDraft = false } = {}) {if (!branch) return { status: 'unavailable', number: null, url: null, detail: 'no branch name' };const raw = await execGh(- ['pr', 'list', '--head', branch, '--state', 'all', '--limit', '1', '--json', 'number,url,body,state'],+ ['pr', 'list', '--head', branch, '--state', 'all', '--limit', '1', '--json', includeDraft ? 'number,url,body,state,isDraft' : 'number,url,body,state'],DEFAULT_EXEC_GH_TIMEOUT_MS,{ cwd, env }).catch(err => err);@@ -864,7 +864,7 @@ export async function findPullRequestForBranch(branch, { cwd = null, env = null}const pr = parsed[0];if (!pr) return { status: 'none', number: null, url: null, detail: null };- return { status: 'found', number: pr.number ?? null, url: pr.url || null, body: typeof pr.body === 'string' ? pr.body : null, detail: pr.state || null };+ return { status: 'found', number: pr.number ?? null, url: pr.url || null, body: typeof pr.body === 'string' ? pr.body : null, detail: pr.state || null, ...(includeDraft ? { isDraft: pr.isDraft === true } : {}) };}/**diff --git a/server/services/gitlab.js b/server/services/gitlab.jsindex 5ef3004e86..a844124eda 100644--- a/server/services/gitlab.js+++ b/server/services/gitlab.js@@ -112,7 +112,7 @@ export async function execGlabJson(args, cwd, timeoutMs = DEFAULT_EXEC_GLAB_TIME* @param {string} cwd - repo root (glab resolves the project from its cwd)* @returns {Promise<{ status: 'found'|'none'|'unavailable', number: number|null, url: string|null, body: string|null, detail: string|null }>}*/-export async function findMergeRequestForBranch(branch, cwd) {+export async function findMergeRequestForBranch(branch, cwd, { includeDraft = false } = {}) {if (!branch || !cwd) return { status: 'unavailable', number: null, url: null, detail: 'no branch or repo path' };const { rows, reason } = await execGlabJson(['mr', 'list', '--source-branch', branch, '--all', '-P', '1'], cwd);// Both failure modes are "we could not ask" here — a zero-exit glab that@@ -123,7 +123,7 @@ export async function findMergeRequestForBranch(branch, cwd) {}const mr = rows[0];if (!mr) return { status: 'none', number: null, url: null, detail: null };- return { status: 'found', number: mr.iid ?? null, url: mr.web_url || null, body: typeof mr.description === 'string' ? mr.description : null, detail: mr.state || null };+ return { status: 'found', number: mr.iid ?? null, url: mr.web_url || null, body: typeof mr.description === 'string' ? mr.description : null, detail: mr.state || null, ...(includeDraft ? { isDraft: mr.draft === true || mr.work_in_progress === true } : {}) };}/**diff --git a/server/services/maintenanceRun.js b/server/services/maintenanceRun.jsindex bb53a46448..b5541d3dde 100644--- a/server/services/maintenanceRun.js+++ b/server/services/maintenanceRun.js@@ -178,7 +178,7 @@ async function assertNoRunningRun(appId) {* The first evaluation runs before this returns, so the caller learns whether* step one actually went out (or why it is holding) in the same response.*/-export async function startMaintenanceRun({ appId, providerId, model = null, effort = null, mode = 'file-issues', claimBetweenAudits = true, claimHandler = null, taskTypes = null, explicitCheck = false }) {+export async function startMaintenanceRun({ appId, providerId, model = null, effort = null, mode = 'file-issues', prCompletion = null, claimBetweenAudits = true, claimHandler = null, taskTypes = null, explicitCheck = false }) {const [{ getAppById }, { getProviderById }, { resolveBurnProvider }] = await Promise.all([import('./apps.js'), import('./providers.js'), import('./scheduledHandlers/providerPick.js'),]);@@ -201,10 +201,10 @@ export async function startMaintenanceRun({ appId, providerId, model = null, effconst now = new Date().toISOString();const pins = { providerId, model: model || null, effort: effort || null };const run = await insertRun({- id, appId, familyId, claimFamilyId, ...pins,+ id, appId, familyId, claimFamilyId, ...pins, prCompletion,taskTypes,status: MAINTENANCE_RUN_STATUS.RUNNING,- steps: buildMaintenanceSteps({ appId, idPrefix: id, ...pins, mode, claimBetweenAudits, claimHandler: effectiveClaimHandler, taskTypes, explicitCheck }),+ steps: buildMaintenanceSteps({ appId, idPrefix: id, ...pins, mode, prCompletion, claimBetweenAudits, claimHandler: effectiveClaimHandler, taskTypes, explicitCheck }),completed: {},active: null,reason: null,diff --git a/server/services/maintenanceRun.test.js b/server/services/maintenanceRun.test.jsindex 4731511342..2ee0691053 100644--- a/server/services/maintenanceRun.test.js+++ b/server/services/maintenanceRun.test.js@@ -406,3 +406,14 @@ it('dispatches independent quality runs while another run is pending and resumesexpect((await getMaintenanceRun(security.id)).status).toBe('running');expect((await getMaintenanceRun(ladder.id)).completed).toEqual({});});++it('preserves draft delivery across persisted resume, provider edits and step completion', async () => {+ const { run } = await startMaintenanceRun({ appId: 'app-1', providerId: 'codex', model: 'gpt-6-astra', effort: 'medium', mode: 'fix', prCompletion: 'draft', taskTypes: ['security', 'documentation'] });+ expect((await getMaintenanceRun(run.id)).prCompletion).toBe('draft');+ await stopMaintenanceRun(run.id);+ await resumeMaintenanceRun(run.id);+ await updateMaintenanceStep(run.id, run.steps[1].id, { providerId: 'codex', model: 'gpt-6-astra', effort: 'medium' });+ await __onMaintenanceAgentCompleted(agentFor(run, 0));+ expect(state.invoked.at(-1).step.overrides).toMatchObject({ model: 'gpt-6-astra', effort: 'medium', params: { fileIssues: false, useWorktree: true, openPR: true, prCompletion: 'draft' } });+ expect((await getMaintenanceRun(run.id)).steps.map(s => s.taskRef.taskType)).toEqual(['security', 'documentation']);+});