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: archive quality run history without discarding evidence

Adam Eivy89d7a89f8b58
diff --git a/client/src/components/apps/AppQualityRunner.jsx b/client/src/components/apps/AppQualityRunner.jsx
index 7e3f046edf..ddd7b3df2e 100644
--- a/client/src/components/apps/AppQualityRunner.jsx
+++ b/client/src/components/apps/AppQualityRunner.jsx
@@ -4,8 +4,9 @@ import ProviderModelSelector from '../ProviderModelSelector';
import MaintenanceRunStatus from '../cos/tabs/schedule/MaintenanceRunStatus';
import useProviderModels from '../../hooks/useProviderModels';
import { useSocketResource } from '../../hooks/useSocketResource';
+import { formatCount } from '../../utils/formatters';
import { enabledProcessProviderFilter } from '../../utils/providers';
-import { getMaintenanceRuns, startMaintenanceRun, stopMaintenanceRun } from '../../services/apiAgents';
+import { getMaintenanceRuns, startMaintenanceRun, stopMaintenanceRun, setMaintenanceRunArchived } from '../../services/apiAgents';
const RUN_EVENTS = ['cos:maintenance:updated'];
@@ -68,6 +69,16 @@ export default function AppQualityRunner({ app, children }) {
{ namespace: 'cos', events: RUN_EVENTS, resourceKey: app.id, matchesEvent: run => run?.appId === app.id },
);
const runs = data ?? [];
+ const showArchived = params.get('qualityHistory') === 'archived';
+ const visibleRuns = runs.filter(run => Boolean(run.archivedAt) === showArchived);
+ const archive = async (id, archived) => {
+ setBusy(true);
+ setError('');
+ const response = await setMaintenanceRunArchived(id, app.id, archived, { silent: true }).catch(err => { if (appIdRef.current === app.id) setError(err.message); return null; });
+ if (appIdRef.current !== app.id) return;
+ if (response) setRuns(previous => (previous ?? []).map(entry => entry.id === response.run.id ? response.run : entry));
+ setBusy(false);
+ };
const start = async () => {
setBusy(true);
setError('');
@@ -110,26 +121,35 @@ export default function AppQualityRunner({ app, children }) {
</select>
</label>
{auditDepth === 'deep' && <p className="text-xs text-gray-400">Spend more time investigating high-risk paths and fixing multiple worthwhile issues in one run. The summary reports coverage and remaining limits; Deep does not certify every file.</p>}
- {mode === 'fix' && <label htmlFor="quality-publication" className="block text-sm">Pull requests
+ {mode === 'fix' && <div><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="inherit">Use saved completion policy</option>
+ <option value="inherit">Follow saved policy — may merge automatically</option>
</select>
- </label>}
+ </label>
+ <p className="text-xs text-gray-400 mt-1">{prCompletion === 'inherit' ? 'Each check uses its saved PR completion policy; fixes and quality snapshots may merge automatically.' : 'Fixes stay in draft pull requests for review. Automatic quality snapshot publication is skipped.'} This setting does not schedule additional checks or rescans.</p>
+ </div>}
<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 !== '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>
+ <p className="text-xs text-gray-400">Batch execution: selected checks run one after another. A separately launched batch can run in parallel. {mode === 'file-issues' && '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>
{(loading || loadError) && <p className="text-xs" role="status">{loadError ? 'Runner status is unavailable.' : 'Loading runner status…'} <button type="button" className="text-port-accent" onClick={loadRuns}>Retry</button></p>}
{error && <p role="alert" className="text-sm text-port-error">{error}</p>}
- {runs.filter((run, index) => run.status === 'running' || run.auditDepth === 'deep' || index === 0).map(run => <div key={run.id} className="space-y-2">
+ <button type="button" className="text-xs text-port-accent" onClick={() => setParams(previous => {
+ const next = new URLSearchParams(previous);
+ if (showArchived) next.delete('qualityHistory'); else next.set('qualityHistory', 'archived');
+ return next;
+ })}>{showArchived ? 'View current runs' : `View archived runs (${formatCount(runs.filter(run => run.archivedAt).length)})`}</button>
+ {showArchived && <p className="text-xs text-gray-400">Archived history retains evidence and findings. Restoring a card does not restart its run.</p>}
+ {visibleRuns.filter((run, index) => showArchived || run.status === 'running' || run.auditDepth === 'deep' || index === 0).map(run => <div key={run.id} className="space-y-2">
<MaintenanceRunStatus run={run} />
- {run.reason && <p className="text-xs break-words">{run.reason} <Link className="text-port-accent underline" to="/cos/schedule">Open runner settings</Link></p>}
+ {run.reason && !(run.auditDepth === 'deep' && !run.auditWorkflow) && <p className="text-xs break-words">{run.reason} <Link className="text-port-accent underline" to="/cos/schedule">Open runner settings</Link></p>}
{run.auditDepth === 'deep' && !run.auditWorkflow && <p className="text-xs text-gray-400">Historical exhaustive audit — evidence retained; start a new Deep run above.</p>}
+ {run.status !== 'running' && <button type="button" className="text-xs text-port-accent" disabled={busy} onClick={() => archive(run.id, !run.archivedAt)}>{run.archivedAt ? 'Restore run history' : 'Archive run history'}</button>}
{run.status === 'running' && <button type="button" className="text-xs text-port-accent" disabled={busy} onClick={() => stop(run.id)}>Stop remaining checks</button>}
</div>)}
</section>;
diff --git a/client/src/components/apps/AppQualityRunner.test.jsx b/client/src/components/apps/AppQualityRunner.test.jsx
index 0f483aafb8..75d5bff2d6 100644
--- a/client/src/components/apps/AppQualityRunner.test.jsx
+++ b/client/src/components/apps/AppQualityRunner.test.jsx
@@ -21,9 +21,9 @@ import AppQualityRunner from './AppQualityRunner';
import AppQuality from './AppQuality';
import { awaitEnabled, findEnabledByLabelText, findEnabledByRole } from '../../test/enabledBarrier.js';
vi.mock('./AppQualityHistory', () => ({ default: () => null }));
-import { getMaintenanceRuns, startMaintenanceRun, stopMaintenanceRun } from '../../services/apiAgents';
+import { getMaintenanceRuns, startMaintenanceRun, stopMaintenanceRun, setMaintenanceRunArchived } from '../../services/apiAgents';
import useProviderModels from '../../hooks/useProviderModels';
-vi.mock('../../services/apiAgents', () => ({ getMaintenanceRuns: vi.fn(), startMaintenanceRun: vi.fn(), stopMaintenanceRun: vi.fn() }));
+vi.mock('../../services/apiAgents', () => ({ getMaintenanceRuns: vi.fn(), startMaintenanceRun: vi.fn(), stopMaintenanceRun: vi.fn(), setMaintenanceRunArchived: vi.fn() }));
vi.mock('../../hooks/useProviderModels', () => ({ default: vi.fn(() => ({ providers: [], selectedProviderId: 'codex', selectedModel: 'gpt-5', availableModels: [], loading: false })) }));
vi.mock('../ProviderModelSelector', () => ({ default: ({ onEffortChange }) => <button onClick={() => onEffortChange('high')}>Use high effort</button> }));
const app = { id: 'app-1', quality: { categories: [
@@ -279,3 +279,23 @@ it('explains extended Deep and preserves old evidence without offering legacy re
expect(screen.getByText(/multiple worthwhile issues in one run/)).toBeInTheDocument();
expect(screen.getByRole('option', { name: 'Deep — extended investigation and multiple fixes' })).toBeInTheDocument();
});
+
+it('archives and restores history without dispatch, while keeping active runs visible', async () => {
+ const old = { id: 'old', appId: app.id, status: 'stopped', auditDepth: 'deep', reason: 'Resume explicitly to continue.', steps: [], completed: { step: { success: false } } };
+ const active = { id: 'active', appId: app.id, status: 'running', steps: [] };
+ getMaintenanceRuns.mockResolvedValue({ runs: [old, active] });
+ setMaintenanceRunArchived.mockImplementation(async (_id, _app, archived) => ({ run: { ...old, archivedAt: archived ? '2026-01-01' : null } }));
+ render(<MemoryRouter><AppQualityRunner app={app} /></MemoryRouter>);
+ fireEvent.click(await screen.findByRole('button', { name: 'Archive run history' }));
+ await waitFor(() => expect(screen.queryByText(/Historical exhaustive/)).not.toBeInTheDocument());
+ expect(screen.getByRole('button', { name: 'Stop remaining checks' })).toBeInTheDocument();
+ expect(screen.queryByText(/Resume explicitly/)).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'View archived runs (1)' }));
+ fireEvent.click(await screen.findByRole('button', { name: 'Restore run history' }));
+ await waitFor(() => expect(screen.queryByRole('button', { name: 'Restore run history' })).not.toBeInTheDocument());
+ fireEvent.click(screen.getByRole('button', { name: 'View current runs' }));
+ expect(screen.getByRole('button', { name: 'Archive run history' })).toBeInTheDocument();
+ expect(setMaintenanceRunArchived).toHaveBeenNthCalledWith(1, 'old', app.id, true, { silent: true });
+ expect(startMaintenanceRun).not.toHaveBeenCalled();
+ expect(stopMaintenanceRun).not.toHaveBeenCalled();
+});
diff --git a/client/src/components/cos/tabs/schedule/MaintenanceRunStatus.jsx b/client/src/components/cos/tabs/schedule/MaintenanceRunStatus.jsx
index 4e7df08f9a..1af4c7f3f0 100644
--- a/client/src/components/cos/tabs/schedule/MaintenanceRunStatus.jsx
+++ b/client/src/components/cos/tabs/schedule/MaintenanceRunStatus.jsx
@@ -54,7 +54,7 @@ export default function MaintenanceRunStatus({ run, showSteps = false, renderSte
{run.active.status || 'queued'}
{run.active.agentId && <a className="underline" href={`/cos/agents/${encodeURIComponent(run.active.agentId)}`} target="_blank" rel="noopener noreferrer">Open agent in new tab</a>}
</p>}
- {run.reason && <details><summary className="cursor-pointer">Run details</summary><p className="break-all max-h-36 overflow-y-auto">{run.reason}</p></details>}
+ {run.reason && !(run.auditDepth === 'deep' && !run.auditWorkflow) && <details><summary className="cursor-pointer">Run details</summary><p className="break-all max-h-36 overflow-y-auto">{run.reason}</p></details>}
{showSteps && <MaintenanceStepChecklist steps={run.steps} completed={run.completed} activeStepId={run.active?.stepId} renderStepSettings={renderStepSettings} />}
</div>;
}
diff --git a/client/src/hooks/useOnDemandTaskToast.js b/client/src/hooks/useOnDemandTaskToast.js
index 62bc4def50..f835920724 100644
--- a/client/src/hooks/useOnDemandTaskToast.js
+++ b/client/src/hooks/useOnDemandTaskToast.js
@@ -53,6 +53,7 @@ export function useOnDemandTaskToast() {
socket.on('connect', subscribe);
const maintenanceStates = new Map();
const handleMaintenance = run => {
+ if (run.historyOnly) return;
const { current, total } = maintenanceRunProgress(run);
const label = `Maintenance · ${current}/${total} · ${run.status}`;
const signature = JSON.stringify([run.status, run.completed, run.active, run.reason]);
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index f54e479aa0..f718149112 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -442,3 +442,7 @@ export const triggerFeatureAgent = (id, options = {}) => request(`/feature-agent
export const stopFeatureAgent = (id, options = {}) => request(`/feature-agents/${id}/stop`, { method: 'POST', ...options });
export const getFeatureAgentRuns = (id, limit) => request(`/feature-agents/${id}/runs${limit ? `?limit=${limit}` : ''}`);
export const getFeatureAgentOutput = (id) => request(`/feature-agents/${id}/output`);
+
+export const setMaintenanceRunArchived = (id, appId, archived, options = {}) => request(`/cos/schedule/maintenance-runs/${id}/archive`, {
+ method: 'PATCH', body: JSON.stringify({ appId, archived }), ...options
+});
diff --git a/docs/DEEP-AUDITS.md b/docs/DEEP-AUDITS.md
index 5316bb233a..84e5223cb1 100644
--- a/docs/DEEP-AUDITS.md
+++ b/docs/DEEP-AUDITS.md
@@ -13,3 +13,7 @@ New manual, scheduled and custom Deep launches persist `auditWorkflow: "extended
Previous exhaustive Deep ledgers, source pins, findings and worktrees are preserved. They remain visibly historical and incomplete; new Deep runs neither reuse them nor credit their receipts. Normal resume of those certification runs is disabled on the server and in the Quality UI. Their authenticated ledger endpoint remains available at `GET /api/cos/schedule/deep-audits/:id`.
See [historical evidence format](DEEP-AUDITS-LEGACY.md) for the archived architecture. No data migration marks those ledgers complete or removes them. Starting a new Deep audit creates a separate ordinary audit task; it does not delete or repurpose retained source work.
+
+Quality run history is separate from tasks: deleting a task does not delete its batch record. Use **Archive run history** to hide an inactive run from the default Quality sidebar. **View archived runs** and **Restore run history** bring it back without resuming it. Evidence and findings remain stored. Runs with outstanding work cannot be archived.
+
+The PR choice controls delivery only: drafts stay open for review, while the saved policy may allow merging. Selected checks execute sequentially within a batch regardless of that choice; it does not schedule rescans.
diff --git a/server/routes/cosScheduleRoutes.js b/server/routes/cosScheduleRoutes.js
index bf7458018c..5800db4e71 100644
--- a/server/routes/cosScheduleRoutes.js
+++ b/server/routes/cosScheduleRoutes.js
@@ -15,7 +15,7 @@ import { EFFORT_LEVELS } from '../lib/providerModels.js';
import { INTERVAL_TYPES, decodeIntervalType, isCronExpression, isKnownIntervalType } from '../services/taskScheduleConstants.js';
import { normalizeSuggestedAfter, SUGGESTED_AFTER_MAX } from '../lib/scheduleRunOrder.js';
import { findCronExpressionError } from '../lib/cronValidation.js';
-import { updateMaintenanceStep, listMaintenanceRuns, resumeMaintenanceRun, startMaintenanceRun, stopMaintenanceRun } from '../services/maintenanceRun.js';
+import { setMaintenanceRunArchived, updateMaintenanceStep, listMaintenanceRuns, resumeMaintenanceRun, startMaintenanceRun, stopMaintenanceRun } from '../services/maintenanceRun.js';
const templateTaskSchema = z.object({
name: z.string().min(1),
@@ -315,6 +315,13 @@ router.patch('/schedule/maintenance-runs/:id/steps/:stepId', asyncHandler(async
res.json({ run });
}));
+router.patch('/schedule/maintenance-runs/:id/archive', asyncHandler(async (req, res) => {
+ const body = validateRequest(z.object({ appId: z.string().min(1), archived: z.boolean() }).strict(), req.body || {});
+ const run = await setMaintenanceRunArchived(req.params.id, body);
+ if (!run) throw new ServerError('Maintenance run not found for this app', { status: 404, code: 'NOT_FOUND' });
+ res.json({ run });
+}));
+
router.post('/schedule/maintenance-runs/:id/stop', asyncHandler(async (req, res) => {
const run = await stopMaintenanceRun(req.params.id);
if (!run) throw new ServerError('Maintenance run not found', { status: 404, code: 'NOT_FOUND' });
diff --git a/server/services/maintenanceRun.js b/server/services/maintenanceRun.js
index fd339b71b5..42630126bf 100644
--- a/server/services/maintenanceRun.js
+++ b/server/services/maintenanceRun.js
@@ -125,7 +125,7 @@ export async function listMaintenanceRuns() {
*/
async function writeRuns(runs) {
let finished = 0;
- await atomicWrite(runsFile(), { runs: runs.filter((entry) => entry.status === MAINTENANCE_RUN_STATUS.RUNNING || (entry.auditDepth === 'deep' && entry.status !== MAINTENANCE_RUN_STATUS.COMPLETED) || ++finished <= RUN_HISTORY_LIMIT) });
+ await atomicWrite(runsFile(), { runs: runs.filter((entry) => entry.archivedAt || entry.historyRetained || entry.status === MAINTENANCE_RUN_STATUS.RUNNING || (entry.auditDepth === 'deep' && entry.status !== MAINTENANCE_RUN_STATUS.COMPLETED) || ++finished <= RUN_HISTORY_LIMIT) });
}
const insertRun = (run) => writeQueue(async () => {
@@ -142,7 +142,7 @@ const insertRun = (run) => writeQueue(async () => {
* `completed` back over a Stop or a completion that landed meanwhile. The
* completion ledger merges key-wise for the same reason: it only ever grows.
*/
-const patchRun = (id, patch) => writeQueue(async () => {
+const patchRun = (id, patch, { historyOnly = false } = {}) => writeQueue(async () => {
const runs = await listMaintenanceRuns();
const current = runs.find((entry) => entry.id === id);
if (!current) return null;
@@ -153,7 +153,7 @@ const patchRun = (id, patch) => writeQueue(async () => {
updatedAt: new Date().toISOString(),
};
await writeRuns(runs.map((entry) => (entry.id === id ? updated : entry)));
- cosEvents.emit('maintenance:updated', updated);
+ cosEvents.emit('maintenance:updated', historyOnly ? { ...updated, historyOnly: true } : updated);
return updated;
});
@@ -250,6 +250,26 @@ export function stopMaintenanceRun(id) {
});
}
+/** Archiving only hides history; restoration never resumes execution. */
+export function setMaintenanceRunArchived(id, { appId, archived }) {
+ return perRun(id, async () => {
+ const run = await getMaintenanceRun(id);
+ if (!run || run.appId !== appId) return null;
+ if (run.status === MAINTENANCE_RUN_STATUS.RUNNING) throw new ServerError('Stop the run before archiving its history', { status: 409, code: 'MAINTENANCE_RUN_ACTIVE' });
+ if (archived) {
+ const [{ getAllTasks }, { getOnDemandRequests }] = await Promise.all([import('./cosTaskStore.js'), import('./taskSchedule.js')]);
+ // Match dispatch's queue -> handoff -> task read order across preparation.
+ const queued = (await getOnDemandRequests()).some(request => request?.burn?.maintenanceRunId === id);
+ const preparing = Object.values(await getOnDemandHandoffs()).some(claim => claim.request.burn?.maintenanceRunId === id && claim.status === 'preparing');
+ const { user, cos } = await getAllTasks();
+ const outstanding = [...(user?.tasks || []), ...(cos?.tasks || [])].some(task => quotaBurnProvenance(task.metadata).maintenanceRunId === id && ACTIVE_TASK_STATUSES.has(task.status));
+ if (queued || preparing || outstanding) throw new ServerError('Wait for this run’s outstanding work to finish before archiving', { status: 409, code: 'MAINTENANCE_RUN_ACTIVE' });
+ }
+ if (Boolean(run.archivedAt) === archived) return run;
+ return patchRun(id, { archivedAt: archived ? new Date().toISOString() : null, historyRetained: true }, { historyOnly: true });
+ });
+}
+
/** Editing shares the dispatch queue: a stale browser cannot change a started step. */
export function updateMaintenanceStep(id, stepId, { providerId, model, effort = null }) {
return perRun(id, async () => {
@@ -286,6 +306,7 @@ function latestRunHandoff(run, handoffs) {
export async function resumeMaintenanceRun(id) {
const resumed = await perRun(id, async () => {
const run = await getMaintenanceRun(id);
+ if (run?.archivedAt) throw new ServerError('Restore archived history before resuming', { status: 409, code: 'MAINTENANCE_RUN_ARCHIVED' });
if (run && isLegacyDeepAudit(run)) throw new ServerError('Historical Deep certification runs are read-only; start a new Deep audit', { status: 409, code: 'DEEP_AUDIT_HISTORICAL' });
if (!run || run.status === MAINTENANCE_RUN_STATUS.RUNNING) return { run, alreadyRunning: true };
if (!run.taskTypes) await assertNoRunningRun(run.appId);
diff --git a/server/services/maintenanceRun.test.js b/server/services/maintenanceRun.test.js
index 6b4d3e3a37..9fd1994f51 100644
--- a/server/services/maintenanceRun.test.js
+++ b/server/services/maintenanceRun.test.js
@@ -52,7 +52,7 @@ vi.mock('./quotaBurnStore.js', () => ({ getQuotaBurnConfig: vi.fn(async () => {
const { getQuotaBurnConfig } = await import('./quotaBurnStore.js');
const { invokeQuotaBurnStep } = await import('./quotaBurnInvoke.js');
const {
- updateMaintenanceStep, startMaintenanceRun, stopMaintenanceRun, resumeMaintenanceRun, evaluateMaintenanceRun, getMaintenanceRun, listMaintenanceRuns,
+ setMaintenanceRunArchived, updateMaintenanceStep, startMaintenanceRun, stopMaintenanceRun, resumeMaintenanceRun, evaluateMaintenanceRun, getMaintenanceRun, listMaintenanceRuns,
__onMaintenanceAgentSpawned, __onMaintenanceAgentCompleted, __retryMaintenanceRuns, __resetMaintenanceRunScheduler,
} = await import('./maintenanceRun.js');
@@ -538,3 +538,34 @@ it('acknowledges the exact active request when refusal timestamps tie', async ()
expect(resumed.result.dispatched).toBe(true);
getOnDemandHandoffs.mockResolvedValue({});
});
+
+it('scopes reversible history archiving and refuses active runs without changing evidence or dispatching', async () => {
+ const { default: express } = await import('express');
+ const { request } = await import('../lib/testHelper.js');
+ const { default: routes } = await import('../routes/cosScheduleRoutes.js');
+ const http = express(); http.use(express.json()); http.use('/cos', routes);
+ const { run } = await start();
+ const route = `/cos/schedule/maintenance-runs/${run.id}/archive`;
+ expect((await request(http).patch(route).send({ appId: 'wrong-app', archived: true })).status).toBe(404);
+ expect((await request(http).patch(route).send({ appId: run.appId, archived: true })).status).toBe(409);
+ await stopMaintenanceRun(run.id);
+ state.tasks = [{ id: 'still-working', status: 'in_progress', metadata: { quotaBurnMaintenanceRunId: run.id } }];
+ expect((await request(http).patch(route).send({ appId: run.appId, archived: true })).status).toBe(409);
+ state.tasks = [];
+ const before = await getMaintenanceRun(run.id);
+ const { readFile, writeFile } = await import('fs/promises');
+ const file = join(tempRoot, 'cos', 'maintenance-runs.json');
+ const stored = JSON.parse(await readFile(file, 'utf8'));
+ stored.runs.unshift(...Array.from({ length: 25 }, (_, i) => ({ id: `history-${i}`, appId: run.appId, status: 'completed' })));
+ await writeFile(file, JSON.stringify(stored));
+ const calls = state.invoked.length;
+ const archived = await request(http).patch(route).send({ appId: run.appId, archived: true });
+ expect(archived.status).toBe(200);
+ expect(archived.body.run.archivedAt).toBeTruthy();
+ expect(await setMaintenanceRunArchived(run.id, { appId: run.appId, archived: true })).toEqual(archived.body.run);
+ await expect(resumeMaintenanceRun(run.id)).rejects.toMatchObject({ code: 'MAINTENANCE_RUN_ARCHIVED' });
+ const restored = await request(http).patch(route).send({ appId: run.appId, archived: false });
+ expect(restored.status).toBe(200);
+ expect(restored.body.run).toMatchObject({ ...before, archivedAt: null, historyRetained: true, updatedAt: expect.any(String) });
+ expect(state.invoked).toHaveLength(calls);
+});