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

fix(quality): preserve draft delivery across HTTP and pipeline stages

Adam Eivy16504b2cb724
diff --git a/client/src/components/apps/AppQualityRunner.jsx b/client/src/components/apps/AppQualityRunner.jsx
index 1b2d08d094..d41c704ea9 100644
--- a/client/src/components/apps/AppQualityRunner.jsx
+++ b/client/src/components/apps/AppQualityRunner.jsx
@@ -105,14 +105,14 @@ export default function AppQualityRunner({ app, children }) {
{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>
+ <option value="inherit">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' ? (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>
+ <p className="text-xs text-gray-400">Runs sequentially; launch another batch to run in parallel. {mode === 'fix' ? (prCompletion !== 'inherit' ? '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.jsx
index 83ae70c5a2..8be673ebfd 100644
--- a/client/src/components/apps/AppQualityRunner.test.jsx
+++ b/client/src/components/apps/AppQualityRunner.test.jsx
@@ -256,8 +256,8 @@ it('defaults audit fixes to draft review and lets the user explicitly inherit sa
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.change(await findEnabledByLabelText('Pull requests'), { target: { value: 'inherit' } });
fireEvent.click(await findEnabledByRole('button', { name: 'Run 2 checks now' }));
await waitFor(() => expect(startMaintenanceRun).toHaveBeenCalledTimes(2));
- expect(startMaintenanceRun.mock.lastCall[0]).not.toHaveProperty('prCompletion');
+ expect(startMaintenanceRun.mock.lastCall[0].prCompletion).toBe('inherit');
});
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index d444a0c5b4..d1bb71b553 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -382,9 +382,9 @@ export const updateCosTaskInterval = (taskType, settings, options = {}) => reque
// Manual maintenance runs — the Schedule tab's "Run maintenance now" (server:
// services/maintenanceRun.js).
export const getMaintenanceRuns = (options) => request('/cos/schedule/maintenance-runs', options);
-export const startMaintenanceRun = ({ appId, providerId, model, effort = null, mode = 'file-issues', claimBetweenAudits = true, claimHandler, taskTypes, explicitCheck }, options = {}) => request('/cos/schedule/maintenance-runs', {
+export const startMaintenanceRun = ({ appId, providerId, model, effort = null, mode = 'file-issues', prCompletion, claimBetweenAudits = true, claimHandler, taskTypes, explicitCheck }, options = {}) => request('/cos/schedule/maintenance-runs', {
method: 'POST',
- body: JSON.stringify({ appId, providerId, model, effort, mode, claimBetweenAudits, claimHandler, taskTypes, explicitCheck }),
+ body: JSON.stringify({ appId, providerId, model, effort, mode, prCompletion, claimBetweenAudits, claimHandler, taskTypes, explicitCheck }),
...options
});
export const stopMaintenanceRun = (id, options = {}) => request(`/cos/schedule/maintenance-runs/${id}/stop`, { method: 'POST', ...options });
diff --git a/client/src/services/apiAgents.test.js b/client/src/services/apiAgents.test.js
index 7a6d672228..5d25cf26c3 100644
--- a/client/src/services/apiAgents.test.js
+++ b/client/src/services/apiAgents.test.js
@@ -7,6 +7,8 @@ afterEach(() => vi.unstubAllGlobals());
it.each([
{ mode: 'fix', claimBetweenAudits: true, claimHandler: { providerId: 'claude', model: 'sonnet', effort: 'low' } },
{ mode: 'file-issues', claimBetweenAudits: false },
+ { mode: 'fix', prCompletion: 'draft', claimBetweenAudits: false, taskTypes: ['security'], effort: 'medium' },
+ { mode: 'fix', prCompletion: 'inherit', claimBetweenAudits: false, taskTypes: ['security'] },
])('sends maintenance choices to the server: %j', async choices => {
const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 201, json: async () => ({ run: { id: 'example' } }) });
vi.stubGlobal('fetch', fetchMock);
diff --git a/server/routes/cosScheduleRoutes.js b/server/routes/cosScheduleRoutes.js
index 59c8da3952..a056ebc5f0 100644
--- a/server/routes/cosScheduleRoutes.js
+++ b/server/routes/cosScheduleRoutes.js
@@ -45,7 +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(),
+ prCompletion: z.enum([...PR_COMPLETION_VALUES, 'inherit']).optional(),
claimBetweenAudits: z.boolean().optional(),
claimHandler: z.object({
providerId: z.string().trim().min(1),
diff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.js
index e6bb9a2355..981f816037 100644
--- a/server/services/agentCompletionCleanup.js
+++ b/server/services/agentCompletionCleanup.js
@@ -41,7 +41,7 @@ import * as git from './git.js';
import { isTruthyMeta } from './agentState.js';
import { resolveReviewLoopOptions } from './codeReview.js';
import { cleanupAgentWorktree, spawnMergeRecoveryTask, releaseRetryHold } from './agentWorktreeCleanup.js';
-import { PR_CREATION, resolvePrCompletion, resolvePrCreation } from '../lib/prDisposition.js';
+import { PR_COMPLETIONS, PR_CREATION, resolvePrCompletion, resolvePrCreation } from '../lib/prDisposition.js';
import { resolvePrOpenedBy, PR_OPENED_BY } from '../lib/slashdoInvocation.js';
import { isPublicReviewRestrictedProfile, publicReviewPostureForProfile } from '../lib/agentExecutionProfiles.js';
import { ensureTaskThread } from './brainTaskThreads.js';
@@ -201,7 +201,11 @@ export async function handlePipelineProgression(task, agentId, success) {
const stageReadOnly = nextStage.readOnly ?? false;
const taskDefaults = pipeline.taskDefaults || {};
for (const flag of PIPELINE_STAGE_BEHAVIOR_FLAGS) {
- if (flag in nextStage) {
+ // A stage may choose its work posture, but cannot relax a run's draft-only
+ // publication policy. Keep it even while the stage performs no code work.
+ if (flag === 'prCompletion' && taskDefaults.prCompletion === PR_COMPLETIONS.DRAFT) {
+ nextTask.metadata.prCompletion = PR_COMPLETIONS.DRAFT;
+ } else if (flag in nextStage) {
nextTask.metadata[flag] = nextStage[flag];
} else if (stageReadOnly) {
nextTask.metadata[flag] = false;
diff --git a/server/services/agentCompletionCleanup.test.js b/server/services/agentCompletionCleanup.test.js
index 488d4a3a3d..c247240d10 100644
--- a/server/services/agentCompletionCleanup.test.js
+++ b/server/services/agentCompletionCleanup.test.js
@@ -65,6 +65,33 @@ const runningPipeline = (overrides = {}) => ({
beforeEach(() => { vi.clearAllMocks(); });
describe('handlePipelineProgression', () => {
+ it('preserves a run-level draft restriction across a read-only stage and a later merge-configured stage', async () => {
+ const task = { id: 'draft-pipeline', taskType: 'internal', metadata: {
+ prCompletion: 'draft', openPR: true, useWorktree: true,
+ pipeline: runningPipeline({
+ taskDefaults: { prCompletion: 'draft', openPR: true, useWorktree: true },
+ stages: [{ name: 'Audit' }, { name: 'Inspect', readOnly: true }, { name: 'Fix', prCompletion: 'merge-on-green' }],
+ }),
+ } };
+ await handlePipelineProgression(task, 'audit-agent', true);
+ const readOnlyStage = addTask.mock.calls.at(-1)[0];
+ expect(readOnlyStage.metadata).toMatchObject({ prCompletion: 'draft', readOnly: true, openPR: false, useWorktree: false });
+ await handlePipelineProgression(readOnlyStage, 'inspect-agent', true);
+ expect(addTask.mock.calls.at(-1)[0].metadata).toMatchObject({ prCompletion: 'draft', readOnly: false, openPR: true, useWorktree: true });
+ });
+
+ it('still permits stage-specific delivery when the pipeline has no run-level draft restriction', async () => {
+ const task = { id: 'ordinary-pipeline', taskType: 'internal', metadata: {
+ prCompletion: 'draft',
+ pipeline: runningPipeline({
+ taskDefaults: { prCompletion: 'review-then-merge' },
+ stages: [{ name: 'Draft stage', prCompletion: 'draft' }, { name: 'Land', prCompletion: 'merge-on-green' }],
+ }),
+ } };
+ await handlePipelineProgression(task, 'draft-stage-agent', true);
+ expect(addTask.mock.calls.at(-1)[0].metadata.prCompletion).toBe('merge-on-green');
+ });
+
it('is a no-op when the pipeline is not running', async () => {
const task = { id: 't', taskType: 'user', metadata: { pipeline: runningPipeline({ status: 'completed' }) } };
await handlePipelineProgression(task, 'agent-1', true);
diff --git a/server/services/cosTaskGenerator.auditMode.test.js b/server/services/cosTaskGenerator.auditMode.test.js
index a1070843b8..ecab0041fe 100644
--- a/server/services/cosTaskGenerator.auditMode.test.js
+++ b/server/services/cosTaskGenerator.auditMode.test.js
@@ -391,6 +391,20 @@ describe('mode is honored identically from schedule, manual run, and quota burn'
expect(task.metadata.notARealFlag).toBeUndefined();
});
+ it.each([{ prCompletion: 'merge-on-green' }, { readOnly: true }])('preserves run-level draft delivery through pipeline stage zero %j', async stagePosture => {
+ const { getTaskInterval } = await import('./taskSchedule.js');
+ getTaskInterval.mockResolvedValue({ type: 'weekly', taskMetadata: {
+ pipeline: { stages: [{ name: 'Audit', promptKey: 'security', ...stagePosture }] },
+ } });
+ const [step] = buildMaintenanceSteps({
+ appId: 'app-1', idPrefix: 'pipeline-draft', mode: 'fix', prCompletion: 'draft', taskTypes: ['security'],
+ });
+ const task = await generate('security', { skipPreconditions: true, runOverrides: step.overrides.params });
+ expect(task.metadata.prCompletion).toBe('draft');
+ expect(task.metadata.pipeline.taskDefaults.prCompletion).toBe('draft');
+ if (stagePosture.readOnly) expect(task.metadata).toMatchObject({ readOnly: true, openPR: false, useWorktree: false });
+ });
+
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');
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 0760b1cae6..340977ac29 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -59,7 +59,7 @@ import { isRecoveryTask } from './recoveryTasks.js';
import { getCodeReviewDefaults } from './codeReview.js';
import { getSkipReason } from './cosTaskClaim.js';
import { ensureInstanceId } from './instanceIdentity.js';
-import { PR_COMPLETION_VALUES } from '../lib/prDisposition.js';
+import { PR_COMPLETIONS, PR_COMPLETION_VALUES } from '../lib/prDisposition.js';
import { resolveTrackerFilingBlock } from '../lib/workTracker.js';
import {
isAuditTaskType,
@@ -1666,6 +1666,9 @@ function initializePipelineMetadata(metadata) {
const stageReadOnly = stage0.readOnly ?? false;
for (const flag of PIPELINE_STAGE_BEHAVIOR_FLAGS) {
if (metadata[flag] !== undefined) metadata.pipeline.taskDefaults[flag] = metadata[flag];
+ // Draft delivery constrains the whole run, including read-only stages whose
+ // audit output could otherwise publish an automatically merged snapshot.
+ if (flag === 'prCompletion' && metadata.pipeline.taskDefaults.prCompletion === PR_COMPLETIONS.DRAFT) continue;
if (flag in stage0) {
metadata[flag] = stage0[flag];
} else if (stageReadOnly) {
diff --git a/server/services/maintenanceRun.js b/server/services/maintenanceRun.js
index b5541d3dde..ea44b5a088 100644
--- a/server/services/maintenanceRun.js
+++ b/server/services/maintenanceRun.js
@@ -197,6 +197,10 @@ export async function startMaintenanceRun({ appId, providerId, model = null, eff
}
if (!taskTypes) await assertNoRunningRun(appId);
+ // Older clients may omit this field. An explicit quality fix must fail safe
+ // to drafts; inheriting a potentially merging policy requires a named choice.
+ prCompletion = prCompletion === 'inherit' ? null : prCompletion ?? (taskTypes && mode === 'fix' ? 'draft' : null);
+
const id = `maint-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
const now = new Date().toISOString();
const pins = { providerId, model: model || null, effort: effort || null };
diff --git a/server/services/maintenanceRun.test.js b/server/services/maintenanceRun.test.js
index 2ee0691053..d86a2ec8ae 100644
--- a/server/services/maintenanceRun.test.js
+++ b/server/services/maintenanceRun.test.js
@@ -71,6 +71,43 @@ beforeEach(async () => {
});
afterAll(cleanup);
+// Exercise the actual browser adapter's serialization before the route and
+// persisted run. Form tests replace this adapter, which hid a dropped policy.
+// Read it as source rather than importing client code into the server graph.
+it.each(['draft', 'inherit', undefined])('carries the browser delivery choice %s through HTTP into persisted dispatch', async prCompletion => {
+ const [{ readFile }, { parse }, { runInNewContext }, { default: express }, { request }, { default: routes }] = await Promise.all([
+ import('fs/promises'), import('@babel/parser'), import('node:vm'), import('express'),
+ import('../lib/testHelper.js'), import('../routes/cosScheduleRoutes.js'),
+ ]);
+ const source = await readFile(new URL('../../client/src/services/apiAgents.js', import.meta.url), 'utf8');
+ const ast = parse(source, { sourceType: 'module' });
+ const adapter = ast.program.body.flatMap(node => node.declaration?.declarations || [])
+ .find(node => node.id.name === 'startMaintenanceRun')?.init;
+ expect(adapter).toBeDefined();
+ const app = express();
+ app.use(express.json());
+ app.use('/cos', routes);
+ let wireBody;
+ const sendFromBrowser = runInNewContext(`(${source.slice(adapter.start, adapter.end)})`, {
+ request: (url, options) => {
+ expect(options.method).toBe('POST');
+ wireBody = JSON.parse(options.body);
+ return request(app).post(url).send(wireBody);
+ },
+ });
+ const response = await sendFromBrowser({
+ appId: 'app-1', providerId: 'codex', model: 'gpt-6-astra', effort: 'medium', mode: 'fix',
+ taskTypes: ['security'], ...(prCompletion ? { prCompletion } : {}),
+ });
+ expect(wireBody.prCompletion).toBe(prCompletion);
+ expect(response.status).toBe(201);
+ const run = await getMaintenanceRun(response.body.run.id);
+ const expectedPolicy = prCompletion === 'inherit' ? null : 'draft';
+ expect(run.prCompletion).toBe(expectedPolicy);
+ expect(run.steps[0].overrides.params.prCompletion).toBe(expectedPolicy || undefined);
+ expect(state.invoked[0].step.overrides.params.prCompletion).toBe(expectedPolicy || undefined);
+});
+
describe('manual maintenance run', () => {
it('runs a check the user chose by name even where it does not apply', async () => {
state.inapplicable = { 'mobile-responsive': 'no user interface found in this repository' };