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: honor maintenance run mode and preview configurable claim steps
Adam Eivy22aade60ca11
diff --git a/client/src/components/cos/tabs/ScheduleTab.jsx b/client/src/components/cos/tabs/ScheduleTab.jsxindex 47a5639175..746a48aad0 100644--- a/client/src/components/cos/tabs/ScheduleTab.jsx+++ b/client/src/components/cos/tabs/ScheduleTab.jsx@@ -5,7 +5,6 @@ import toast from '../../ui/Toast';import * as api from '../../../services/api';import { formatDateTime, formatTimeOfDaySeconds, timeAgo } from '../../../utils/formatters';import Banner from '../../ui/Banner';-import { MAINTENANCE_ORDER_GUIDANCE } from '../../../lib/quotaBurnTasks';import { CodeReviewDefaultsProvider } from '../../../hooks/useCodeReviewDefaults';import { useAppOverrideActions } from '../../../hooks/useAppOverrideActions';import AppTaskTypeSection from './schedule/AppTaskTypeSection';@@ -189,8 +188,7 @@ export default function ScheduleTab({ apps, providers, providersLoaded, activePr</div><Banner size="md" title="Recommended maintenance order">- <p className="text-sm break-words">{MAINTENANCE_ORDER_GUIDANCE}</p>- <p className="text-xs mt-1">Resolve findings between audits, then document the resulting code. Run the whole sequence now from here, or schedule it under quota gates in Quota Burn; Run now offers issue filing with claim-issue between audits, or audit and fix with one final claim-issue drain.</p>+ <p className="text-xs">Choose how to handle findings, then review the steps before starting.</p><details className="mt-2"><summary className="cursor-pointer text-sm font-medium">Run maintenance now</summary><MaintenanceRunForm schedule={{ ...schedule, tasks }} apps={apps} providers={providers} providersLoaded={providersLoaded} improvementDisabled={improvementDisabled} daemonRunning={daemonRunning} onRefresh={fetchSchedule} />diff --git a/client/src/components/cos/tabs/schedule/MaintenanceRunForm.jsx b/client/src/components/cos/tabs/schedule/MaintenanceRunForm.jsxindex 7cd757a5d6..b94b36e9f6 100644--- a/client/src/components/cos/tabs/schedule/MaintenanceRunForm.jsx+++ b/client/src/components/cos/tabs/schedule/MaintenanceRunForm.jsx@@ -2,6 +2,8 @@ import { useCallback, useEffect, useRef, useState } from 'react';import { Link } from 'react-router';import socket from '../../../../services/socket';import MaintenanceRunStatus from './MaintenanceRunStatus';+import MaintenanceStepChecklist from './MaintenanceStepChecklist';+import { buildMaintenanceSteps } from '../../../../../../server/lib/maintenanceSequence';import ProviderModelSelector from '../../../ProviderModelSelector';import * as api from '../../../../services/api';import { useAutoRefetch } from '../../../../hooks/useAutoRefetch';@@ -19,6 +21,7 @@ export default function MaintenanceRunForm({ schedule, apps = [], providers = []const [model, setModel] = useState('');const [effort, setEffort] = useState('');const [mode, setMode] = useState('file-issues');+ const [claimBetweenAudits, setClaimBetweenAudits] = useState(true);const [consent, setConsent] = useState(false);const [busy, setBusy] = useState(false);const [preparing, setPreparing] = useState(false);@@ -30,7 +33,8 @@ export default function MaintenanceRunForm({ schedule, apps = [], providers = []const availableProviders = providers.filter(provider => provider.enabled && isProcessProvider(provider) && familyForProvider(provider));const provider = availableProviders.find(entry => entry.id === providerId);const groups = buildQuotaBurnTaskCatalog({ schedule, apps });- const prerequisites = maintenancePrerequisites(groups, appId);+ const prerequisites = maintenancePrerequisites(groups, appId, { mode, claimBetweenAudits });+ const plannedSteps = buildMaintenanceSteps({ appId, idPrefix: 'preview', mode, claimBetweenAudits });const ready = Boolean(appId) && prerequisites.length === 0;const blocked = improvementDisabled || daemonRunning === false;@@ -105,7 +109,7 @@ export default function MaintenanceRunForm({ schedule, apps = [], providers = []if (busy || blocked || !ready || !provider || !model || !consent) return;setBusy(true);setMessage('Starting maintenance…');- const response = await api.startMaintenanceRun({ appId, providerId, model, effort: effort || null, mode }, { silent: true }).catch(error => {+ const response = await api.startMaintenanceRun({ appId, providerId, model, effort: effort || null, mode, claimBetweenAudits }, { silent: true }).catch(error => {setMessage(`Could not start maintenance: ${error.message}`);return null;});@@ -160,9 +164,20 @@ export default function MaintenanceRunForm({ schedule, apps = [], providers = []<option value="fix">Audit and fix</option></select></label>+ {mode === 'file-issues' && <label htmlFor="maintenance-run-claims" className="block">+ Issue handling+ <select id="maintenance-run-claims" value={String(claimBetweenAudits)} disabled={busy} onChange={event => { setClaimBetweenAudits(event.target.value === 'true'); setConsent(false); }} className="mt-1 w-full bg-port-bg border border-port-border rounded p-2 text-white">+ <option value="true">Resolve issues between audits</option>+ <option value="false">Leave issues open for review</option>+ </select>+ </label>}<p className="text-xs">{mode === 'fix'- ? 'Audits fix findings directly, then documentation runs, followed by one final claim-issue drain for remaining issues.'- : 'Audits file issues, with a claim-issue drain between audits to resolve findings before the next step.'}</p>+ ? 'Fix findings in each audit; finish with documentation and one final claim pass.'+ : claimBetweenAudits ? 'Claim passes resolve the backlog before the next audit.' : 'File findings for review; run documentation last. No claim jobs.'}</p>+ <div className="space-y-2">+ <p className="font-medium">Planned steps · {plannedSteps.length}</p>+ <MaintenanceStepChecklist steps={plannedSteps} label="Planned maintenance steps" />+ </div><ProviderModelSelectorproviders={availableProviders}selectedProviderId={providerId}@@ -186,17 +201,17 @@ export default function MaintenanceRunForm({ schedule, apps = [], providers = []</li>)}</ul>{onRefresh && !prerequisites.some(item => item.unavailable) && <>- <p className="text-xs">Enable the listed tasks globally and for this app, and set claim-issue to perpetual. This also allows their existing schedules to run.</p>+ <p className="text-xs">Enable the listed tasks globally and for this app. Claim jobs require perpetual mode. Existing schedules may also run.</p><button type="button" onClick={prepare} disabled={busy} className="px-3 py-1.5 bg-port-accent text-white rounded disabled:opacity-50">{preparing ? 'Enabling…' : 'Enable required tasks'}</button></>}</div>}{blocked && <p role="status">Enable Improvement and start the CoS daemon before running maintenance.</p>}- <p className="text-xs">Runs every step now, in order: each audit starts when the previous step finishes, and each claim-issue drain repeats until the app’s issue backlog is empty. Independent of Quota Burn — no master switch, no quota gates, nothing to re-arm. Supports subscription CLI/TUI providers. Blank effort inherits each scheduled task’s saved effort.</p>+ <p className="text-xs">Runs sequentially, without Quota Burn gates. Blank effort uses each task’s saved setting.</p><label className="flex items-start gap-2" htmlFor="maintenance-run-consent"><input id="maintenance-run-consent" type="checkbox" checked={consent} disabled={busy} onChange={event => setConsent(event.target.checked)} />- <span>Run the whole maintenance sequence for this app on the selected provider now, spending its quota as needed.</span>+ <span>Run these steps now using the selected provider’s quota.</span></label><div className="flex items-center gap-3 flex-wrap"><button type="button" onClick={run} disabled={busy || blocked || !ready || !provider || !model || !consent || !providersLoaded} className="px-3 py-1.5 bg-port-accent text-white rounded disabled:opacity-50">@@ -210,7 +225,7 @@ export default function MaintenanceRunForm({ schedule, apps = [], providers = []return <li key={entry.id} className="border border-port-border rounded p-2 flex flex-wrap items-center gap-x-3 gap-y-1"><span className="font-medium">{getAppName(entry.appId, apps, entry.appId)}</span><span className="text-xs">{entry.providerId}{entry.model ? ` · ${entry.model}` : ''}</span>- <MaintenanceRunStatus run={entry} />+ <MaintenanceRunStatus run={entry} showSteps />{entry.status === 'running'? <button type="button" onClick={() => stop(entry.id)} className="px-2 py-1 text-xs bg-port-border rounded">Stop</button>: entry.status === 'stopped' && <button type="button" onClick={() => resume(entry.id)} className="px-2 py-1 text-xs bg-port-border rounded">Resume</button>}diff --git a/client/src/components/cos/tabs/schedule/MaintenanceRunForm.test.jsx b/client/src/components/cos/tabs/schedule/MaintenanceRunForm.test.jsxindex be3c4043ff..92fb029e9a 100644--- a/client/src/components/cos/tabs/schedule/MaintenanceRunForm.test.jsx+++ b/client/src/components/cos/tabs/schedule/MaintenanceRunForm.test.jsx@@ -51,7 +51,7 @@ describe('maintenance launch', () => {await select(user);await user.click(screen.getByRole('button', { name: 'Run now' }));expect(screen.getByRole('button', { name: 'Starting…' })).toBeDisabled();- expect(api.startMaintenanceRun).toHaveBeenCalledWith({ appId: 'example', providerId: 'claude', model: 'sonnet', effort: 'high', mode: 'file-issues' }, { silent: true });+ expect(api.startMaintenanceRun).toHaveBeenCalledWith({ appId: 'example', providerId: 'claude', model: 'sonnet', effort: 'high', mode: 'file-issues', claimBetweenAudits: true }, { silent: true });finishStart({ run: runRecord(), result: { dispatched: true, taskType: 'better-structural-drift' } });expect(await screen.findByText(/Maintenance started with better-structural-drift/)).toBeInTheDocument();const row = screen.getByRole('list', { name: 'Maintenance runs' });@@ -181,8 +181,24 @@ it('launches fix mode only after renewed consent', async () => {await select(user);await user.selectOptions(screen.getByLabelText('Audit mode'), 'fix');expect(screen.getByRole('button', { name: 'Run now' })).toBeDisabled();- expect(screen.getByText(/one final claim-issue drain/)).toBeInTheDocument();+ expect(screen.getByText(/one final claim pass/)).toBeInTheDocument();+ expect(screen.getByText('Planned steps · 8')).toBeInTheDocument();+ expect(screen.queryByLabelText('Issue handling')).not.toBeInTheDocument();await user.click(screen.getByRole('checkbox'));await user.click(screen.getByRole('button', { name: 'Run now' }));expect(api.startMaintenanceRun).toHaveBeenCalledWith(expect.objectContaining({ mode: 'fix' }), { silent: true });});++it('previews and starts issue filing without requiring claim jobs', async () => {+ const user = userEvent.setup();+ show({ schedule: { tasks: { ...tasks, 'claim-issue': { enabled: false } } } });+ await select(user);+ await user.selectOptions(screen.getByLabelText('Issue handling'), 'false');+ expect(screen.getByRole('button', { name: 'Run now' })).toBeDisabled();+ expect(screen.getByText('Planned steps · 7')).toBeInTheDocument();+ expect(screen.getByRole('list', { name: 'Planned maintenance steps' })).not.toHaveTextContent('claim-issue');+ expect(screen.queryByText(/Run now needs these saved task settings/)).not.toBeInTheDocument();+ await user.click(screen.getByRole('checkbox'));+ await user.click(screen.getByRole('button', { name: 'Run now' }));+ expect(api.startMaintenanceRun).toHaveBeenCalledWith(expect.objectContaining({ mode: 'file-issues', claimBetweenAudits: false }), { silent: true });+});diff --git a/client/src/components/cos/tabs/schedule/MaintenanceRunStatus.jsx b/client/src/components/cos/tabs/schedule/MaintenanceRunStatus.jsxindex b3161abc55..cd712d25cc 100644--- a/client/src/components/cos/tabs/schedule/MaintenanceRunStatus.jsx+++ b/client/src/components/cos/tabs/schedule/MaintenanceRunStatus.jsx@@ -1,9 +1,11 @@+import MaintenanceStepChecklist from './MaintenanceStepChecklist';+/** Shared live progress content for the schedule card and corner notification. */-export default function MaintenanceRunStatus({ run }) {+export default function MaintenanceRunStatus({ run, showSteps = false }) {const done = Object.keys(run.completed || {}).length;const total = run.steps?.length || 0;const step = run.active?.taskType || run.steps?.find(entry => !run.completed?.[entry.id])?.taskRef?.taskType;- return <div className="space-y-1 text-xs" role="status">+ return <div className={`space-y-1 text-xs min-w-0 ${showSteps ? 'w-full' : ''}`} role="status"><p>{run.status} · {done}/{total} steps{run.status === 'running' && step ? ` · ${step}` : ''}</p><progress aria-label="Maintenance steps completed" value={done} max={total || 1} className="w-full h-1 accent-port-accent" />{run.active && <p className="flex items-center gap-2">@@ -11,6 +13,7 @@ export default function MaintenanceRunStatus({ run }) {{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 && <p>{run.reason}</p>}+ {run.reason && <details><summary className="cursor-pointer">Run details</summary><p className="break-all">{run.reason}</p></details>}+ {showSteps && <MaintenanceStepChecklist steps={run.steps} completed={run.completed} activeStepId={run.active?.stepId} />}</div>;}diff --git a/client/src/components/cos/tabs/schedule/MaintenanceStepChecklist.jsx b/client/src/components/cos/tabs/schedule/MaintenanceStepChecklist.jsxnew file mode 100644index 0000000000..29ce398368--- /dev/null+++ b/client/src/components/cos/tabs/schedule/MaintenanceStepChecklist.jsx@@ -0,0 +1,17 @@+import { CheckCircle2, Circle, LoaderCircle } from 'lucide-react';++/** Preview and saved progress both render the runner's actual ordered steps. */+export default function MaintenanceStepChecklist({ steps = [], completed = {}, activeStepId, label = 'Maintenance steps' }) {+ return <ol aria-label={label} className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2 text-xs">+ {steps.map((step, index) => {+ const done = Object.hasOwn(completed, step.id);+ const active = !done && step.id === activeStepId;+ const Icon = done ? CheckCircle2 : active ? LoaderCircle : Circle;+ return <li key={step.id} aria-current={active ? 'step' : undefined} className={`flex items-center gap-2 rounded border p-2 ${active ? 'border-port-accent bg-port-accent/10' : 'border-port-border'}`}>+ <Icon size={16} aria-hidden="true" className={`shrink-0 ${done || active ? 'text-port-accent' : 'text-port-text-muted'} ${active ? 'motion-safe:animate-spin' : ''}`} />+ <span className="min-w-0 break-words">{index + 1}. {step.taskRef.taskType}</span>+ <span className="sr-only">{done ? 'Completed' : active ? 'Current' : 'Pending'}</span>+ </li>;+ })}+ </ol>;+}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex c00d302c41..0bb9428401 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -131,7 +131,7 @@ grep -i "what you want to do" client/src/lib/README.md| `clientErrorReporter.js` | `reportClientError({ type, error?, message?, ... })` — POSTs window.onerror + unhandledrejection events to `/api/client-errors` with throttle + dedup, dropping browser-extension errors (see `extensionErrors.js`) before either gate. Wired from `main.jsx`; never call directly from React components. || `clinicianReport.js` | Pure builders for the MeatSpace clinician-export view (`/meatspace/export`). `buildClinicianReport({ tests, config })` → structured report model (blood panels grouped by category with reference ranges + out-of-range flags, plus a lifestyle summary); `reportToMarkdown(report)` → copy-paste markdown. Reuses the Blood tab's `REFERENCE_RANGES` / `getBloodValueStatus` so printed flags match the UI. Also exports `buildBloodTestModel`, `buildLifestyleModel`, `getCategoryForKey`, `formatRange`. || `quotaBurnPatch.js` | `mergeQuotaBurnPatch(base, patch)` — mirrors the server's quota-burn config merge (top-level + per-family keys merge, a family's `jobs` array replaces) so the Quota Burn page can apply an edit optimistically and accumulate debounced edits into one PUT body. `quotaBurnJobIsSpent(job, ranAt)` — whether a `run once` step has had its one dispatch, gated on the optimistic config's own `runOnce` so a just-ticked checkbox reads as spent before the save round-trips (the client mirror of the server's `jobIsSpent`). `UNLIMITED_DISPATCHES` / `isUnlimitedDispatchCap(cap)` / `dispatchCapInput(value)` — the -1 "no dispatch cap" sentinel (the default), mirrored from the server. |-| `quotaBurnTasks.js` | `MAINTENANCE_TASK_ORDER` / `MAINTENANCE_ORDER_GUIDANCE` document the default ladder; `maintenanceSequence` populates audit and claim-drain references; `maintenancePrerequisites` lists missing saved settings and scoped setup patches. The Quota Burn page's view of the SHARED scheduled-task catalog. `buildQuotaBurnTaskCatalog({ schedule, jobs, apps })` groups PortOS built-in task types and app custom jobs into the picker's two groups (dropping what a burn may never invoke, and stamping a `blockedReason` on what is merely disabled or untargetable); `searchTaskCatalog` / `flattenTaskCatalog` / `findTaskEntry` query it. `taskRefKey` / `stepFromTaskEntry` / `taskEntryNeedsApp` build and address a step's `taskRef`. `effectiveQuotaBurnSettings(step, saved)` mirrors the server's `effectiveSettings` (overrides layered over the task's saved settings, params merged key-by-key). `quotaBurnStepPayload(job)` reduces a step to what the strict PUT schema accepts, dropping the top-level override mirrors that would otherwise outrank the `overrides` bag. `taskSourceHref(entry)` / `CREATE_TASK_HREF` link out to the source task. |+| `quotaBurnTasks.js` | `MAINTENANCE_TASK_ORDER` / `MAINTENANCE_ORDER_GUIDANCE` document the default ladder; `maintenanceSequence` populates audit and claim-drain references; `maintenancePrerequisites` lists missing saved settings and scoped setup patches for the selected mode and claim policy. The Quota Burn page's view of the SHARED scheduled-task catalog. `buildQuotaBurnTaskCatalog({ schedule, jobs, apps })` groups PortOS built-in task types and app custom jobs into the picker's two groups (dropping what a burn may never invoke, and stamping a `blockedReason` on what is merely disabled or untargetable); `searchTaskCatalog` / `flattenTaskCatalog` / `findTaskEntry` query it. `taskRefKey` / `stepFromTaskEntry` / `taskEntryNeedsApp` build and address a step's `taskRef`. `effectiveQuotaBurnSettings(step, saved)` mirrors the server's `effectiveSettings` (overrides layered over the task's saved settings, params merged key-by-key). `quotaBurnStepPayload(job)` reduces a step to what the strict PUT schema accepts, dropping the top-level override mirrors that would otherwise outrank the `overrides` bag. `taskSourceHref(entry)` / `CREATE_TASK_HREF` link out to the source task. || `clipboard.js` | `copyToClipboard`, `writeClipboardSilently`, `readClipboard` — safe across insecure-origin contexts. Use these instead of `navigator.clipboard.writeText` inline. || `effortCostEstimate.js` | `withEstimatedCosts(observations)` / `deriveEffortCostRatios(observations)` — fill the reasoning-effort rows Artificial Analysis publishes a quality score but no cost per task for, by scaling each model's own published cost anchor along the effort-cost curve measured across the models that do publish a full set. Estimated rows are flagged `costEstimated`; nothing is written back to the catalog. || `falVideoHandoff.js` | `buildFalH3MaxPrompt(prompt, negativePrompt)` composes the provider-neutral shot prompt fal's free MiniMax H3 Max tool is driven with; `FAL_H3_MAX_FREE_URL` and `FAL_H3_MAX_FREE_ALLOWANCE_NOTE` carry the tool URL and current vendor allowance copy. The free web allowance is deliberately a handoff, not the separately metered fal API. |diff --git a/client/src/lib/quotaBurnTasks.js b/client/src/lib/quotaBurnTasks.jsindex ecbd3b92e3..c8f1a171cf 100644--- a/client/src/lib/quotaBurnTasks.js+++ b/client/src/lib/quotaBurnTasks.js@@ -12,7 +12,7 @@* inheritance display and the PUT payload without a server.*/-import { MAINTENANCE_DRAIN_TASK, MAINTENANCE_SEQUENCE_TYPES, MAINTENANCE_TASK_ORDER, maintenanceStepParams } from '../../../server/lib/maintenanceSequence.js';+import { buildMaintenanceSteps, MAINTENANCE_DRAIN_TASK, MAINTENANCE_SEQUENCE_TYPES, maintenanceStepParams } from '../../../server/lib/maintenanceSequence.js';/** Mirrors `QUOTA_BURN_TASK_REF_KIND` in `server/lib/quotaBurnTaskRef.js`. */export const QUOTA_BURN_TASK_REF_KIND = Object.freeze({ BUILTIN: 'builtin', CUSTOM: 'custom' });@@ -263,10 +263,11 @@ export const CREATE_TASK_HREF = '/cos/jobs';export { MAINTENANCE_TASK_ORDER, MAINTENANCE_ORDER_GUIDANCE } from '../../../server/lib/maintenanceSequence.js';/** Saved settings required by the maintenance ladder, including actionable patches. */-export function maintenancePrerequisites(groups, appId) {+export function maintenancePrerequisites(groups, appId, options = {}) {if (!appId) return [];const entries = flattenTaskCatalog(groups);- return [...MAINTENANCE_TASK_ORDER, MAINTENANCE_DRAIN_TASK].flatMap(taskType => {+ const types = buildMaintenanceSteps({ appId, ...options }).map(step => step.taskRef.taskType);+ return [...new Set(types)].flatMap(taskType => {const entry = entries.find(candidate => candidate.taskType === taskType);if (!entry) return [{ taskType, reason: 'unavailable in Scheduled Tasks', unavailable: true }];const settings = {diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.jsindex 34d60919f2..20dfdb8720 100644--- a/client/src/services/apiAgents.js+++ b/client/src/services/apiAgents.js@@ -308,9 +308,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 }, options = {}) => request('/cos/schedule/maintenance-runs', {+export const startMaintenanceRun = ({ appId, providerId, model, effort = null, mode = 'file-issues', claimBetweenAudits = true }, options = {}) => request('/cos/schedule/maintenance-runs', {method: 'POST',- body: JSON.stringify({ appId, providerId, model, effort }),+ body: JSON.stringify({ appId, providerId, model, effort, mode, claimBetweenAudits }),...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.jsnew file mode 100644index 0000000000..71973422b6--- /dev/null+++ b/client/src/services/apiAgents.test.js@@ -0,0 +1,18 @@+import { afterEach, expect, it, vi } from 'vitest';+import { startMaintenanceRun } from './apiAgents';++// Exercise the real API wrapper through HTTP serialization: mocking the wrapper+// in the form test cannot catch a selected mode being dropped before POST.+afterEach(() => vi.unstubAllGlobals());+it.each([+ { mode: 'fix', claimBetweenAudits: true },+ { mode: 'file-issues', claimBetweenAudits: false },+])('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);+ await startMaintenanceRun({ appId: 'example', providerId: 'codex', model: 'example-model', ...choices });+ const [url, options] = fetchMock.mock.calls[0];+ expect(url).toContain('/cos/schedule/maintenance-runs');+ expect(options.method).toBe('POST');+ expect(JSON.parse(options.body)).toEqual({ appId: 'example', providerId: 'codex', model: 'example-model', effort: null, ...choices });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex 6d93179ac3..35a5732389 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -181,7 +181,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `mediaModelBuckets.js` | Names and resolves the video registry's two model buckets (#4142). The split is by RUNTIME FAMILY — `mlx` (Apple MLX runtimes) vs `cuda` (plain torch+CUDA, which runs on Windows *and* Linux) — not by operating system, which is why `activeVideoBucket()` keys on `process.platform === 'darwin'` instead of on "is this Windows". `readVideoBucket` / `readVideoDefault` / `matchesVideoBucket` resolve the canonical key first and fall back to the pre-#4142 `macos` / `windows` / `defaultMacos` / `defaultWindows` spellings, so any registry written by an older install still loads untouched; `canonicalizeVideoBuckets` performs the one-time rename (migration 270 and the load-time twin in `mediaModels.js`). Kept separate from `mediaModels.js` so `scripts/migrations/` can share the alias resolution without importing the registry loader, which seeds `data/` as a side effect. || `mediaModels.js` | Single source of truth for image/video model metadata. Entry fields are documented in the module docblock — note `repoFiles[]`, which narrows a model's own repo to an explicit file list for an aggregate repo that holds far more than the runner loads (MiniMax H3 CUDA). || `videoFailure.js` | `normalizeVideoFailure` classifies and scrubs local video causes; `createVideoDiagnosticTail` retains bounded stdout/stderr diagnostics without grouping bare exit codes. |-| `maintenanceSequence.js` | The maintenance ladder shared by both runners: `MAINTENANCE_TASK_ORDER` / `MAINTENANCE_ORDER_GUIDANCE`, the interleaved `MAINTENANCE_SEQUENCE_TYPES` (a perpetual `claim-issue` drain between every pair of audits), `maintenanceStepParams` (audits file issues, documentation does the work), and `buildMaintenanceSteps` (optional fix mode runs audits directly with one final drain) which emits quota-burn-shaped run-once steps so `quotaBurnInvoke.js` can run a step from the Schedule tab's manual run or a Quota Burn family plan alike. Pure. |+| `maintenanceSequence.js` | The maintenance ladder shared by both runners: `MAINTENANCE_TASK_ORDER` / `MAINTENANCE_ORDER_GUIDANCE`, the interleaved `MAINTENANCE_SEQUENCE_TYPES` (a perpetual `claim-issue` drain between every pair of audits), `maintenanceStepParams` (audits file issues, documentation does the work), and `buildMaintenanceSteps` (fix mode runs audits directly with one final drain; issue filing can omit claim jobs) which emits quota-burn-shaped run-once steps so `quotaBurnInvoke.js` can run a step from the Schedule tab's manual run or a Quota Burn family plan alike. Pure. || `meetingUrl.js` | Selects the one cacheable join URL (`selectMeetingUrl`) out of a raw Google Calendar event — first http(s) `video` entry point, else `hangoutLink` — and owns the shared `MEETING_URL_MAX` bound. Three-state: `undefined` = the producer never described conferencing, `null` = described with none usable. || `minimaxH3Memory.js` | The declared weight-placement table for the three MiniMax H3 entries (#5420) — H3 is the one video model family whose components fit nowhere unassisted, so "does this box have enough" is a render gate, not a UI fact. `MINIMAX_H3_MEMORY_PROFILES` maps entry id → `{ shippedRepo, shippedRevision, profiles }`, each profile carrying an honest `minMemoryGb` host floor and (CUDA only) a `minVramGb` device floor, ordered best-first. Every capacity number is HOISTED from what already existed — the CUDA tiers are `resolve_offload_profile()`'s own thresholds in `scripts/generate_minimax_h3_cuda.py`, the host floors are the entries' `memoryGb` — the sole new number being `MINIMAX_H3_HOST_RESERVE_GB`, a policy reserve held back for the OS. `applyMiniMaxH3MemoryProfiles(list)` is the load-time backfill (twin of migration 317) and guards BOTH `repo` and `revision`, like the speed-profile decorator. `selectMiniMaxH3MemoryProfile({ model, totalMemoryGb })` picks the best profile the HOST can hold (VRAM is the runner's call — the server has no synchronous device view); `miniMaxH3MemoryDeclineReason()` RETURNS the fail-closed reason so the render path can 400 it and a status surface can show it, and returns `null` on an UNMEASURED host — "not measured" is a deferral to the runner, never the same as zero. `validateMiniMaxH3MemoryProfileTable` / `sanitizeMiniMaxH3MemoryProfiles` warn + strip a hand-edited table (NaN floor, duplicate/reserved id, mis-ordered tiers) at load. || `videoContinuity.js` | How chunk N+1 of a chained video render is conditioned on chunk N. `resolveContextFrames(requested)` normalizes the tail-window size (absent → `DEFAULT_CONTEXT_FRAMES` = 22 ≈ 1s @ 24fps; an explicit `0` is preserved as "last frame only", NOT collapsed into the default) and clamps to `MIN_CONTEXT_FRAMES`..`MAX_CONTEXT_FRAMES`. `resolveContinuityStrategy({model, contextFrames})` picks `'window'` (LTX-2 `extend_from_video` conditioned on the prior chunk's last N frames — motion, not just a pose) or `'frame'` (extract the last frame, run i2v), degrading to `'frame'` on any runtime outside `CONTEXT_WINDOW_RUNTIMES` rather than rejecting. `extendLatentFrames` / `extendedPixelFrames` convert across the VAE's `LATENT_FRAME_STRIDE` (8 pixel frames per latent), `contextPrefixFrames({totalFrames, extendLatents})` measures how much of an extend render is echoed context to trim back off before stitching (0 = leave it alone), and `tailWindowStartFrame` gives the cut index for the window itself. Pure — importable from `prepareParams.js` without dragging in `local.js`. Mirrored for the picker in `client/src/lib/videoGenParams.js`, pinned by `videoContinuity.parity.test.js`. |diff --git a/server/lib/maintenanceSequence.js b/server/lib/maintenanceSequence.jsindex 07e4ee2bb3..ced281199b 100644--- a/server/lib/maintenanceSequence.js+++ b/server/lib/maintenanceSequence.js@@ -2,7 +2,8 @@* The maintenance ladder: the ordered audits PortOS recommends running against a* managed app, with a perpetual `claim-issue` drain between every pair so each* audit's findings are resolved before the next audit reads the code. Fix mode- * instead resolves findings in each audit and runs one final drain.+ * instead resolves findings in each audit and runs one final drain. Issue-only+ * runs can skip all drains to leave findings open for human review.** ONE definition, shared by both runners. `services/maintenanceRun.js` walks* these steps directly for the Schedule tab's "Run now" — no quota gates, no@@ -48,8 +49,8 @@ export const maintenanceStepParams = (taskType, mode = 'file-issues') => (taskTy* task's saved effort. Ids are `${idPrefix}-${index}`, so a fresh prefix per* invocation yields fresh step identities.*/-export function buildMaintenanceSteps({ appId, idPrefix, providerId = null, model = null, effort = null, mode = 'file-issues' }) {- const types = mode === 'fix' ? [...MAINTENANCE_TASK_ORDER, MAINTENANCE_DRAIN_TASK] : MAINTENANCE_SEQUENCE_TYPES;+export function buildMaintenanceSteps({ appId, idPrefix, providerId = null, model = null, effort = null, mode = 'file-issues', claimBetweenAudits = true }) {+ const types = mode === 'fix' ? [...MAINTENANCE_TASK_ORDER, MAINTENANCE_DRAIN_TASK] : claimBetweenAudits ? MAINTENANCE_SEQUENCE_TYPES : MAINTENANCE_TASK_ORDER;return types.map((taskType, index) => ({id: `${idPrefix}-${index}`,enabled: true,diff --git a/server/routes/cosScheduleRoutes.js b/server/routes/cosScheduleRoutes.jsindex 9d16c72106..51c6fcc0c3 100644--- a/server/routes/cosScheduleRoutes.js+++ b/server/routes/cosScheduleRoutes.js@@ -36,6 +36,7 @@ const suggestedAfterSchema = z.array(z.string()).max(SUGGESTED_AFTER_MAX);// inherits each scheduled task's saved effort.const maintenanceRunStartSchema = z.object({mode: z.enum(['file-issues', 'fix']).optional(),+ claimBetweenAudits: z.boolean().optional(),appId: z.string().trim().min(1),providerId: z.string().trim().min(1),model: z.string().trim().min(1),diff --git a/server/routes/cosScheduleRoutes.test.js b/server/routes/cosScheduleRoutes.test.jsindex 6f701fb1c0..a039edaaf9 100644--- a/server/routes/cosScheduleRoutes.test.js+++ b/server/routes/cosScheduleRoutes.test.js@@ -77,10 +77,11 @@ describe('CoS Schedule Routes', () => {describe('manual maintenance runs', () => {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' };+ const body = { appId: 'app-1', providerId: 'codex', model: 'gpt-5', mode: 'fix', claimBetweenAudits: false };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, mode: 'unknown' })).status).toBe(400);+ expect((await request(app).post('/api/cos/schedule/maintenance-runs').send({ ...body, claimBetweenAudits: 'false' })).status).toBe(400);});it('starts a run from a validated body and reports the first dispatch', async () => {maintenance.startMaintenanceRun.mockResolvedValue({ run: { id: 'maint-1', status: 'running' }, result: { dispatched: true, taskType: 'better-structural-drift' } });diff --git a/server/services/maintenanceRun.js b/server/services/maintenanceRun.jsindex 3e53461396..0b5430bfcb 100644--- a/server/services/maintenanceRun.js+++ b/server/services/maintenanceRun.js@@ -138,7 +138,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' }) {+export async function startMaintenanceRun({ appId, providerId, model = null, effort = null, mode = 'file-issues', claimBetweenAudits = true }) {const [{ getAppById }, { getProviderById }, { resolveBurnProvider }] = await Promise.all([import('./apps.js'), import('./providers.js'), import('./scheduledHandlers/providerPick.js'),]);@@ -155,7 +155,7 @@ export async function startMaintenanceRun({ appId, providerId, model = null, effconst run = await insertRun({id, appId, familyId, ...pins,status: MAINTENANCE_RUN_STATUS.RUNNING,- steps: buildMaintenanceSteps({ appId, idPrefix: id, ...pins, mode }),+ steps: buildMaintenanceSteps({ appId, idPrefix: id, ...pins, mode, claimBetweenAudits }),completed: {},active: null,reason: null,diff --git a/server/services/maintenanceRun.test.js b/server/services/maintenanceRun.test.jsindex f0c75cebbb..04ede744cd 100644--- a/server/services/maintenanceRun.test.js+++ b/server/services/maintenanceRun.test.js@@ -199,3 +199,15 @@ it('runs fixes consecutively and drains remaining issues only after documentatioawait __onMaintenanceAgentCompleted(agentFor(run, MAINTENANCE_TASK_ORDER.length));expect(await getMaintenanceRun(run.id)).toMatchObject({ status: 'completed' });});++it('files findings consecutively and finishes without claiming when claims are disabled', async () => {+ const { run } = await startMaintenanceRun({ appId: 'app-1', providerId: 'codex', model: 'gpt-5', mode: 'file-issues', claimBetweenAudits: false });+ expect(run.steps.map(step => step.taskRef.taskType)).toEqual(MAINTENANCE_TASK_ORDER);+ for (let index = 0; index < run.steps.length; index++) {+ expect(state.invoked.at(-1).step.overrides.params.fileIssues).toBe(index < run.steps.length - 1);+ await __onMaintenanceAgentCompleted(agentFor(run, index));+ }+ expect(dispatchedTypes()).toEqual(MAINTENANCE_TASK_ORDER);+ expect(await getMaintenanceRun(run.id)).toMatchObject({ status: 'completed' });+ expect((await listMaintenanceRuns())[0].steps).toHaveLength(7);+});