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
schedule an app's applicable quality audits across the week from one form
[._.]/ Adam Eivy6ebae0c30e44
diff --git a/client/src/components/apps/AppQuality.jsx b/client/src/components/apps/AppQuality.jsxindex a15e470a51..50a23bc30a 100644--- a/client/src/components/apps/AppQuality.jsx+++ b/client/src/components/apps/AppQuality.jsx@@ -1,5 +1,6 @@import AppQualityRunner from './AppQualityRunner';import AppQualityHistory from './AppQualityHistory';+import AppQualityScheduleForm from './AppQualityScheduleForm';import { Fragment, useState } from 'react';import { Link, useSearchParams } from 'react-router';import { formatDateShort } from '../../utils/formatters';@@ -110,6 +111,7 @@ export default function AppQuality({ app, detail = false }) {<div className="grid grid-cols-1 xl:grid-cols-2 gap-5 items-start"><div className="min-w-0 space-y-4">{!selectedCategory && runner}+ <AppQualityScheduleForm app={app} /><AppQualityHistory appId={app.id} categories={quality?.categories} /></div>{!!quality?.categories?.length && (diff --git a/client/src/components/apps/AppQuality.test.jsx b/client/src/components/apps/AppQuality.test.jsxindex 95f7728069..5703a1e96d 100644--- a/client/src/components/apps/AppQuality.test.jsx+++ b/client/src/components/apps/AppQuality.test.jsx@@ -3,6 +3,8 @@ import { MemoryRouter } from 'react-router';import { describe, it, expect, vi } from 'vitest';import AppQuality from './AppQuality';vi.mock('./AppQualityRunner', () => ({ default: ({ children }) => children(<div>Runner</div>) }));+// The schedule form owns its own async load and is covered by its own suite.+vi.mock('./AppQualityScheduleForm', () => ({ default: () => <div>Schedule form</div> }));vi.mock('../../services/apiApps', () => ({getAppQualityHistory: vi.fn().mockResolvedValue({ points: [], totalCategories: 25 }),publishAppQualitySnapshot: vi.fn(),diff --git a/client/src/components/apps/AppQualityScheduleForm.jsx b/client/src/components/apps/AppQualityScheduleForm.jsxnew file mode 100644index 0000000000..971a56387a--- /dev/null+++ b/client/src/components/apps/AppQualityScheduleForm.jsx@@ -0,0 +1,242 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { Link } from 'react-router';+import { WEEKDAYS } from '../../utils/cronHelpers';+import { applyAppQualitySchedule, getAppQualitySchedule, previewAppQualitySchedule } from '../../services/apiApps';+import FormField from '../ui/FormField';+import toast from '../ui/Toast';++// The planner lays the week out Monday-first, so the preview reads in the same+// order; WEEKDAYS itself is cron's Sunday-first numbering.+const WEEK_ORDER = [1, 2, 3, 4, 5, 6, 0];+const hourLabel = hour => `${String(hour).padStart(2, '0')}:00`;++// Display copy for the drain types the server offers. An id with no entry here+// still renders — as itself — so adding a drain type server-side is not a+// broken option in the browser.+const CLAIM_TASK_LABELS = {+ 'claim-work': 'Claim work (routes to this app’s tracker)',+ 'claim-issue': 'Claim issue (GitHub/GitLab)',+ 'plan-task': 'Plan task (PLAN.md)',+};++// How long an edited control sits still before the form asks for a new plan.+// The planner is read-only, but each preview is a repository scan and a+// database read, and walking a 24-option hour select fires a change per step.+const PREVIEW_DEBOUNCE_MS = 300;++const selectClass = 'block w-full bg-port-bg border border-port-border rounded p-2';++/**+ * Schedule every applicable quality check for one app in a single form.+ *+ * The user picks WHAT (which checks, filing issues or implementing fixes) and+ * roughly HOW OFTEN; the server picks the actual hours, spreading the checks+ * across all seven days and keeping them out of the windows the app's other+ * scheduled jobs already occupy. Nothing is written until Apply.+ */+export default function AppQualityScheduleForm({ app }) {+ const [data, setData] = useState(null);+ const [error, setError] = useState('');+ const [busy, setBusy] = useState(false);+ const [selected, setSelected] = useState(null);+ const [modes, setModes] = useState({});+ const [options, setOptions] = useState(null);+ // The initial GET already carries the plan for the untouched form, so the+ // first run of the preview effect has nothing to ask for.+ const untouched = useRef(true);+ // Only a preview issued after the newest edit may land; an older in-flight+ // one would repaint the grid with a plan the form no longer describes.+ const revision = useRef(0);++ useEffect(() => {+ let live = true;+ getAppQualitySchedule(app.id)+ .then(response => {+ if (!live) return;+ setData(response);+ setSelected(response.plan.slots.map(slot => slot.taskType));+ setModes(Object.fromEntries(response.plan.slots.map(slot => [slot.taskType, slot.fileIssues])));+ setOptions(response.plan.options);+ })+ .catch(err => live && setError(err.message || 'Could not load the quality schedule'));+ return () => { live = false; };+ }, [app.id]);++ // `options` always comes from the server's own resolved bag, so every field+ // the schema accepts is already present — no client-side default ladder.+ const body = useCallback(() => ({ taskTypes: selected || [], fileIssuesByType: modes, ...options }), [selected, modes, options]);++ // Re-plan after the form settles. The endpoint writes nothing, so the only+ // cost of an extra round trip is the scan behind it — which the debounce and+ // the untouched-first-render guard are there to avoid paying needlessly.+ useEffect(() => {+ if (!selected || !options) return undefined;+ if (untouched.current) { untouched.current = false; return undefined; }+ const mine = ++revision.current;+ const timer = setTimeout(() => {+ previewAppQualitySchedule(app.id, body())+ .then(response => { if (mine === revision.current) { setData(response); setError(''); } })+ .catch(err => { if (mine === revision.current) setError(err.message || 'Could not re-plan the schedule'); });+ }, PREVIEW_DEBOUNCE_MS);+ return () => clearTimeout(timer);+ // `data` is deliberately NOT a dependency — this effect writes it, so+ // depending on it would re-plan forever. `body` closes over every field the+ // plan actually reads.+ }, [app.id, selected, options, body]);++ const apply = async () => {+ setBusy(true);+ const result = await applyAppQualitySchedule(app.id, body()).catch(err => ({ failure: err }));+ setBusy(false);+ if (result?.failure) return toast.error(result.failure.message || 'Could not save the quality schedule');+ setData(result);+ toast.success(`Scheduled ${result.plan.slots.length} quality checks across the week`);+ };++ if (error && !data) return <section aria-label="Weekly quality schedule" className="border-t border-port-border pt-3">+ <h4 className="font-medium">Weekly quality schedule</h4>+ <p role="alert" className="text-sm text-port-error">{error}</p>+ </section>;+ if (!data || !selected || !options) return <p className="text-sm text-gray-400" role="status">Loading the weekly quality schedule…</p>;++ const { plan, checks, capabilities, scanned, busySources, claimTaskTypes = [] } = data;+ const toggle = taskType => setSelected(previous => previous.includes(taskType)+ ? previous.filter(type => type !== taskType)+ : [...previous, taskType]);+ const setOption = (key, value) => setOptions(previous => ({ ...previous, [key]: value }));+ const setMode = (taskType, fileIssues) => setModes(previous => ({ ...previous, [taskType]: fileIssues }));+ const applicable = checks.filter(check => check.applicable);+ const skipped = checks.filter(check => !check.applicable);+ const byDay = WEEK_ORDER.map(day => ({ day, slots: plan.slots.filter(slot => slot.day === day) })).filter(entry => entry.slots.length);++ return (+ <section aria-label="Weekly quality schedule" className="border-t border-port-border pt-3 space-y-3">+ <h4 className="font-medium">Weekly quality schedule</h4>+ <p className="text-xs text-gray-400">+ Spreads the selected checks across all seven days and picks the hours itself, avoiding the windows this app’s other+ scheduled jobs already run in. {applicable.length} of {checks.length} checks apply to this repository+ {scanned > 0 ? '' : ' (repository could not be scanned, so every check is offered)'}+ {skipped.length > 0 && `; ${skipped.length} skipped`}. Nothing is saved until you press Apply.+ </p>++ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 text-sm">+ <FormField label="Checks per day">+ <select className={selectClass} value={options.checksPerDay ?? ''} disabled={busy}+ onChange={event => setOption('checksPerDay', event.target.value === '' ? null : Number(event.target.value))}>+ <option value="">Spread evenly over the week</option>+ {[1, 2, 3, 4, 5, 6].map(count => <option key={count} value={count}>{count} per day</option>)}+ </select>+ </FormField>+ <FormField label="Earliest hour">+ <select className={selectClass} value={options.windowStartHour} disabled={busy}+ onChange={event => setOption('windowStartHour', Number(event.target.value))}>+ {Array.from({ length: 24 }, (_, hour) => <option key={hour} value={hour}>{hourLabel(hour)}</option>)}+ </select>+ </FormField>+ <FormField label="Latest hour">+ <select className={selectClass} value={options.windowEndHour} disabled={busy}+ onChange={event => setOption('windowEndHour', Number(event.target.value))}>+ {Array.from({ length: 24 }, (_, hour) => <option key={hour} value={hour}>{hourLabel(hour)}</option>)}+ </select>+ </FormField>+ <FormField label="Default delivery">+ {/* Changing the form-wide default clears the per-check overrides —+ otherwise a row the user never touched would keep the old mode. */}+ <select className={selectClass} value={options.fileIssues === false ? 'fix' : 'file'} disabled={busy}+ onChange={event => { setModes({}); setOption('fileIssues', event.target.value === 'file'); }}>+ <option value="file">Plan and file issues</option>+ <option value="fix">Implement the fix</option>+ </select>+ </FormField>+ <FormField label="Between checks">+ <select className={selectClass} value={options.claimBetween === false ? '' : options.claimTaskType} disabled={busy}+ onChange={event => setOptions(previous => ({+ ...previous,+ claimBetween: event.target.value !== '',+ ...(event.target.value && { claimTaskType: event.target.value }),+ }))}>+ <option value="">Do not run a claim job</option>+ {claimTaskTypes.map(taskType => (+ <option key={taskType} value={taskType}>{CLAIM_TASK_LABELS[taskType] || taskType}</option>+ ))}+ </select>+ </FormField>+ <FormField label="Claim job starts">+ <select className={selectClass} value={options.claimOffsetHours} disabled={busy || options.claimBetween === false}+ onChange={event => setOption('claimOffsetHours', Number(event.target.value))}>+ {[1, 2, 3, 4, 5, 6, 8, 12].map(hours => <option key={hours} value={hours}>{hours}h after each check</option>)}+ </select>+ </FormField>+ </div>++ {plan.warnings.map(warning => <p key={warning} className="text-xs text-port-warning">{warning}</p>)}+ {error && <p role="alert" className="text-sm text-port-error">{error}</p>}++ <details className="text-xs text-gray-400">+ <summary className="cursor-pointer text-port-accent">Checks ({selected.length} of {checks.length} selected)</summary>+ <ul className="mt-2 space-y-1">{checks.map(check => (+ <li key={check.taskType} className="flex flex-wrap items-baseline gap-x-2 gap-y-1">+ <input type="checkbox" id={`quality-check-${check.taskType}`} className="accent-port-accent" disabled={busy}+ checked={selected.includes(check.taskType)} onChange={() => toggle(check.taskType)} />+ <label htmlFor={`quality-check-${check.taskType}`} className={check.applicable ? 'text-gray-200' : 'text-gray-500'}>+ {check.label}+ </label>+ {selected.includes(check.taskType) && (+ <select aria-label={`${check.label} delivery`} className="bg-port-bg border border-port-border rounded px-1 py-0.5" disabled={busy}+ value={(modes[check.taskType] ?? options.fileIssues !== false) ? 'file' : 'fix'}+ onChange={event => setMode(check.taskType, event.target.value === 'file')}>+ <option value="file">file issues</option>+ <option value="fix">implement</option>+ </select>+ )}+ {check.reason && <span className="text-gray-500">— {check.reason}</span>}+ </li>+ ))}</ul>+ {scanned > 0 && <p className="mt-2">+ Detected in this repository: {Object.entries(capabilities).filter(([, present]) => present).map(([name]) => name).join(', ') || 'none'} ({scanned} tracked files scanned).+ </p>}+ </details>++ {!!busySources.length && <details className="text-xs text-gray-400">+ <summary className="cursor-pointer text-port-accent">Planned around {busySources.length} existing job{busySources.length === 1 ? '' : 's'}</summary>+ <ul className="mt-1">{busySources.map(source => (+ <li key={`${source.taskType}-${source.origin}-${source.cron}`}>{source.taskType} · <code>{source.cron}</code></li>+ ))}</ul>+ </details>}++ {!!byDay.length && <div className="overflow-x-auto">+ <table className="w-full text-xs text-left">+ <caption className="sr-only">Planned weekly quality schedule</caption>+ <thead className="text-gray-400"><tr><th className="py-1 pr-3">Day</th><th className="py-1 pr-3">Checks</th></tr></thead>+ <tbody>{byDay.map(({ day, slots }) => (+ <tr key={day} className="border-t border-port-border align-top">+ <th scope="row" className="py-1.5 pr-3 font-medium whitespace-nowrap">{WEEKDAYS[day].label}</th>+ <td className="py-1.5 pr-3">{slots.map(slot => (+ <span key={slot.taskType} className="inline-block mr-3 whitespace-nowrap">+ <span className="text-gray-400">{hourLabel(slot.hour)}</span> {slot.label}+ <span className="text-gray-500"> ({slot.fileIssues ? 'issues' : 'fix'})</span>+ </span>+ ))}</td>+ </tr>+ ))}</tbody>+ </table>+ </div>}++ {plan.claim && <p className="text-xs text-gray-400">+ <code>{plan.claim.taskType}</code> drains the backlog daily at {plan.claim.hours.map(hourLabel).join(', ')} — {options.claimOffsetHours}h after each check, so the issues an audit files get worked before the next one runs.+ </p>}++ <div className="flex flex-wrap items-center gap-3">+ <button type="button" onClick={apply} disabled={busy || !plan.slots.length}+ className="px-3 py-2 rounded bg-port-accent text-port-bg text-sm font-medium disabled:opacity-50">+ {busy ? 'Applying…' : `Apply schedule (${plan.slots.length} check${plan.slots.length === 1 ? '' : 's'}${plan.claim ? ' + claim job' : ''})`}+ </button>+ <Link to="/cos/schedule" className="text-xs text-port-accent hover:underline">Review on the Schedule page</Link>+ </div>+ <p className="text-xs text-gray-500">+ Applying enables the selected checks on this app with the planned cron expressions and DISABLES the ones you left out.+ Other task types are untouched, and every entry stays editable on the Schedule page afterwards.+ </p>+ </section>+ );+}diff --git a/client/src/components/apps/AppQualityScheduleForm.test.jsx b/client/src/components/apps/AppQualityScheduleForm.test.jsxnew file mode 100644index 0000000000..a87d2af21e--- /dev/null+++ b/client/src/components/apps/AppQualityScheduleForm.test.jsx@@ -0,0 +1,126 @@+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';+import { MemoryRouter } from 'react-router';+import { describe, it, expect, vi, beforeEach } from 'vitest';+import AppQualityScheduleForm from './AppQualityScheduleForm';++vi.mock('../../services/apiApps', () => ({+ getAppQualitySchedule: vi.fn(),+ previewAppQualitySchedule: vi.fn(),+ applyAppQualitySchedule: vi.fn(),+}));+vi.mock('../ui/Toast', () => ({ default: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }) }));++import { applyAppQualitySchedule, getAppQualitySchedule, previewAppQualitySchedule } from '../../services/apiApps';+import toast from '../ui/Toast';++// The server resolves the whole bag, so the form never fills a default itself.+const OPTIONS = { checksPerDay: null, windowStartHour: 0, windowEndHour: 23, claimBetween: true, claimOffsetHours: 3, claimTaskType: 'claim-work', padBeforeHours: 1, padAfterHours: 2, fileIssues: true };++const response = (overrides = {}) => ({+ checks: [+ { taskType: 'security', label: 'Security', applicable: true, reason: null },+ { taskType: 'accessibility', label: 'Accessibility', applicable: false, reason: 'no user interface found in this repository' },+ ],+ capabilities: { ui: false, tests: true },+ scanned: 120,+ claimTaskTypes: ['claim-work', 'claim-issue', 'plan-task'],+ busySources: [{ taskType: 'release-check', cron: '30 3 * * *', origin: 'app' }],+ plan: {+ checksPerDay: 1,+ slots: [{ taskType: 'security', label: 'Security', day: 1, hour: 9, fileIssues: true, cron: '0 9 * * 1' }],+ claim: { taskType: 'claim-work', hours: [12], cron: '0 12 * * *' },+ warnings: [],+ options: OPTIONS,+ },+ ...overrides,+});++const app = { id: 'example-app', name: 'Example App' };+const renderForm = () => render(<MemoryRouter><AppQualityScheduleForm app={app} /></MemoryRouter>);++beforeEach(() => {+ vi.clearAllMocks();+ getAppQualitySchedule.mockResolvedValue(response());+ previewAppQualitySchedule.mockImplementation(async () => response());+ applyAppQualitySchedule.mockImplementation(async () => response());+});++describe('AppQualityScheduleForm', () => {+ it('renders the planned week and says which checks the repository skipped', async () => {+ renderForm();+ expect(await screen.findByRole('heading', { name: 'Weekly quality schedule' })).toBeInTheDocument();+ expect(screen.getByText(/1 of 2 checks apply to this repository/)).toBeInTheDocument();+ // The planned week, not just the checkbox list, names the check and its hour.+ const week = screen.getByRole('table');+ expect(within(week).getByText('Mon')).toBeInTheDocument();+ expect(within(week).getByText('09:00')).toBeInTheDocument();+ expect(within(week).getByText(/Security/)).toBeInTheDocument();+ expect(screen.getByText(/no user interface found in this repository/)).toBeInTheDocument();+ expect(screen.getByText(/Planned around 1 existing job/)).toBeInTheDocument();+ });++ it('writes nothing until Apply is pressed', async () => {+ renderForm();+ await screen.findByRole('heading', { name: 'Weekly quality schedule' });+ fireEvent.change(screen.getByLabelText('Checks per day'), { target: { value: '2' } });+ await waitFor(() => expect(previewAppQualitySchedule).toHaveBeenCalled());+ expect(applyAppQualitySchedule).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole('button', { name: /Apply schedule/ }));+ await waitFor(() => expect(applyAppQualitySchedule).toHaveBeenCalled());+ expect(applyAppQualitySchedule.mock.calls[0][1]).toMatchObject({ taskTypes: ['security'], checksPerDay: 2 });+ expect(toast.success).toHaveBeenCalled();+ });++ it('asks for one plan after a burst of edits, not one per keystroke', async () => {+ renderForm();+ await screen.findByRole('heading', { name: 'Weekly quality schedule' });+ // Arrow-keying a 24-option hour select fires a change per step; each+ // preview behind it is a repository scan and a database read.+ const earliest = screen.getByLabelText('Earliest hour');+ for (const value of ['1', '2', '3', '4', '5']) fireEvent.change(earliest, { target: { value } });+ await waitFor(() => expect(previewAppQualitySchedule).toHaveBeenCalled());+ expect(previewAppQualitySchedule).toHaveBeenCalledTimes(1);+ expect(previewAppQualitySchedule.mock.calls[0][1].windowStartHour).toBe(5);+ });++ it('asks for no plan at all until the form is touched', async () => {+ renderForm();+ await screen.findByRole('heading', { name: 'Weekly quality schedule' });+ // The initial GET already carried the plan for the untouched form.+ await waitFor(() => expect(screen.getByRole('table')).toBeInTheDocument());+ expect(previewAppQualitySchedule).not.toHaveBeenCalled();+ });++ it('sends only the checks still ticked', async () => {+ renderForm();+ await screen.findByRole('heading', { name: 'Weekly quality schedule' });+ fireEvent.click(screen.getByLabelText('Security'));+ await waitFor(() => {+ const last = previewAppQualitySchedule.mock.calls.at(-1)?.[1];+ expect(last?.taskTypes).toEqual([]);+ });+ });++ it('drops the claim job from the request when the user turns it off', async () => {+ renderForm();+ await screen.findByRole('heading', { name: 'Weekly quality schedule' });+ fireEvent.change(screen.getByLabelText('Between checks'), { target: { value: '' } });+ await waitFor(() => expect(previewAppQualitySchedule.mock.calls.at(-1)?.[1].claimBetween).toBe(false));+ });++ it('surfaces a planner warning rather than hiding an unschedulable form', async () => {+ getAppQualitySchedule.mockResolvedValue(response({+ plan: { ...response().plan, warnings: ['26 checks need 4 slots a day, which does not fit in a 3-hour window — widen the window or deselect checks.'] },+ }));+ renderForm();+ expect(await screen.findByText(/does not fit in a 3-hour window/)).toBeInTheDocument();+ });++ it('reports a failed load instead of rendering an empty schedule', async () => {+ getAppQualitySchedule.mockRejectedValue(new Error('Server unreachable'));+ renderForm();+ expect(await screen.findByRole('alert')).toHaveTextContent('Server unreachable');+ expect(screen.queryByRole('button', { name: /Apply schedule/ })).not.toBeInTheDocument();+ });+});diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.jsindex 1d83570b9d..ade008fc38 100644--- a/client/src/services/apiApps.js+++ b/client/src/services/apiApps.js@@ -19,6 +19,17 @@ export const getAppQualityHistory = (id, days, options) => request(`/apps/${id}/// Response: { success, published, reason?, hash?, path }.export const publishAppQualitySnapshot = (id, options = {}) =>request(`/apps/${id}/quality-snapshot`, { method: 'POST', silent: true, ...options });+// The Quality tab's weekly-schedule form. `get` returns the applicable checks,+// the repo shapes that verdict came from, the cron expressions already spoken+// for, and the plan the shipped defaults produce; `preview` re-plans an edited+// form without writing; `apply` persists the plan as per-app task overrides.+// All three are silent — the form renders its own errors and warnings inline.+export const getAppQualitySchedule = (id, options = {}) =>+ request(`/apps/${id}/quality-schedule`, { silent: true, ...options });+export const previewAppQualitySchedule = (id, body, options = {}) =>+ request(`/apps/${id}/quality-schedule/preview`, { method: 'POST', body: JSON.stringify(body), silent: true, ...options });+export const applyAppQualitySchedule = (id, body, options = {}) =>+ request(`/apps/${id}/quality-schedule/apply`, { method: 'POST', body: JSON.stringify(body), silent: true, ...options });// Managed checkout topology: returns sanitized local/fork/upstream revision// state without exposing machine-local repo paths.export const getAppRepositorySources = (id, options = {}) =>diff --git a/docs/API.md b/docs/API.mdindex 4089aeee84..c42e51fc18 100644--- a/docs/API.md+++ b/docs/API.md@@ -101,6 +101,9 @@ legacy list for local Apps/Dashboard views.| GET | `/apps/:id/logs` | Get recent logs || POST | `/apps/:id/refresh-config` | Re-parse ecosystem config || POST | `/apps/:id/quality-snapshot` | Rebuild the app's numeric quality snapshot and commit it to `.quality.json` at its repo root (staged and committed as that one path; never pushed). Answers `{ success, published, path }` plus the commit `hash`, or a `reason` of `no-repo-path` / `not-a-repo` / `no-evidence` / `no-changes` when nothing was written. Not gated on the app's `publishQualitySnapshot` toggle — that toggle only automates the same publish after each audit. Any app's committed `.quality.json` is read back as a "Release snapshot" quality source, PortOS's own checkout included (`npm run quality:snapshot` is the same publish, run from the release step). |+| GET | `/apps/:id/quality-schedule` | The Quality tab's weekly-schedule form: every audit check with its applicability verdict and reason, the repository shapes that verdict came from, the cron expressions already occupied on this app, and the plan the shipped defaults produce. Read-only — no LLM call, no write. |+| POST | `/apps/:id/quality-schedule/preview` | Re-plan for an edited form (selection, per-check delivery mode, checks per day, hour window, claim-drain task and offset). Still read-only; a POST only because the option bag carries a per-check map. |+| POST | `/apps/:id/quality-schedule/apply` | Persist the plan as ordinary per-app task-type overrides: the selected checks enabled with their weekly cron and `fileIssues` mode, the audit types left out disabled with their interval cleared, plus one daily cron for the issue-claim drain. Other task types are untouched. |### Processes & Logsdiff --git a/docs/features/app-quality.md b/docs/features/app-quality.mdindex a077c5b761..ca7b7a18f1 100644--- a/docs/features/app-quality.md+++ b/docs/features/app-quality.md@@ -91,3 +91,55 @@ History begins with newly reported assessments; no scores are invented for oldruns. The local detail endpoint `/api/apps/:id/quality-history?days=90` reads onlythat app's measurements and bounds results to the last measurement per UTC dayand category, including a 30-day lookback to seed the selected range.++## Weekly quality schedule++The app's Quality tab carries a **Weekly quality schedule** form that configures+every applicable audit for that app in one write, instead of hand-picking ~26+cron expressions on the Schedule page. It writes ordinary per-app task-type+overrides, so every entry it creates stays editable there afterwards.++**Which checks.** Checks are pre-selected by applicability. A category an earlier+audit reported as `coverage: not-applicable` is skipped — the auditing agent read+the repository, so its ruling wins. Otherwise applicability comes from the shapes+present in the tracked files (`git ls-files`): the UI lenses (UX, accessibility,+mobile/responsive, UI bugs, console errors, UI lifecycle, copy) need a user+interface or a configured UI port, typing needs TypeScript sources, dependency+freedom needs a dependency manifest, test quality needs existing tests, and API+contracts need a route/API surface. Test **coverage** is deliberately never gated+on tests — a repository with none is the one it has the most to say about. Each+audit declares its own requirement as `requiresCapability` in+`AUDIT_DEFINITIONS` (`server/lib/auditCatalog.js`), beside its other metadata+and under the catalog's guard test; `server/services/appQualitySchedule.js` owns+the detection, and throws at load if a declared capability has no way to be+recognized. Everything is advisory: a skipped check+is still listed with its reason and can be selected by hand, and a repository+that cannot be scanned offers every check rather than deselecting the catalog+for want of evidence.++**When.** The selection is spread across all seven days — 26 checks become four a+day — ordered so each one follows the audits `AUDIT_SUGGESTED_AFTER` names as its+predecessors. The hours are chosen, not entered: the planner collects the+weekday/hour cells already occupied by this app's other cron-scheduled work (the+install-wide CoS cadence for types enabled on this app, each perpetual drain's+recheck cadence, and the app's own cron overrides), pads each by an hour before+and two after, and places slots in the free cells nearest an even spacing. That+is what keeps an audit out of a 03:30 nightly release window. The types the plan+is about to rewrite are excluded from that collection, so re-running the form+does not treat last week's plan as an obstacle to this week's.++**Delivery and the claim drain.** Each check either files issues or implements+the fix (`taskMetadata.fileIssues`), set as a form-wide default with a per-check+override. When at least one check files issues, one claim job — `claim-work` by+default, which routes to whichever tracker the app resolves to — is scheduled a+few hours after each check as a single daily cron (`0 8,16 * * *`), so the issues+an audit files get worked before the next audit runs. Its placement only ever+moves later than the check it follows; no claim drain is scheduled when every+selected check implements its own fixes.++Nothing is written until **Apply**, which is also the whole picture: the selected+checks are enabled with their planned cron and delivery mode, and audit types+left out are disabled with their stale cron cleared. Other task types are+untouched. Endpoints: `GET /api/apps/:id/quality-schedule`,+`POST /api/apps/:id/quality-schedule/preview` (read-only re-plan), and+`POST /api/apps/:id/quality-schedule/apply`.diff --git a/server/lib/README.md b/server/lib/README.mdindex b34f9844ec..95234bb7ba 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -76,6 +76,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `heavyJobClaim.js` | Cross-process, machine-wide accelerator claim: `claimHeavyLocalJob({ kind, id, timeoutMs? })` either acquires an ephemeral `data/` lock or reports its active holder; dead-PID claims are reclaimed, and a spawned child can take over the recorded PID across a server restart. || `agentValidation.js` | Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions. || `autonomousJobTask.js` | `generatedJobTaskFields` — flattens a `generateTaskFromJob` result into the top-level keys the non-raw `cos.addTask` path maps onto metadata. One allowlist shared by the manual "Run now" endpoint and the quota-burn lane, so a key added to the generator cannot reach one and not the other. Pure. |+| `qualitySchedulePlan.js` | Lays a managed app's schedulable quality audits out across a week. `planQualitySchedule({taskTypes, fileIssuesByType, busy, options})` → one weekly cron per check plus ONE daily cron for the issue-claim drain that follows each check by `claimOffsetHours` (placed forward-only, so a drain never precedes the audit it works for); `orderQualityChecks` topologically sorts the selection by `AUDIT_SUGGESTED_AFTER`; `buildBusySlots(occupancies, options)` turns expanded crons into the occupied `"<day>:<hour>"` cells the placement avoids (which is how a 03:30 release job keeps audits out of its window); `resolveQualityScheduleOptions` is the ONE default/window/claim-type resolver the planner and its service caller share. Which repo shape each audit needs is catalog-owned (`auditCapabilityRequirement`), not declared here. Pure: no schedule read, no repo read, no clock. || `quotaBurnConfig.js` | Quota-burn plan shape: the provider families, the burn-job type alphabet + catalog the config page renders its form from, `QUOTA_BURN_BOUNDS` (the one bounds table the normalizer clamps to, the Zod schemas reject against, and the catalog descriptors publish as min/max), and total normalization (`normalizeQuotaBurnConfig`). Owns the dispatch-cap sentinel too (`QUOTA_BURN_UNLIMITED_DISPATCHES` / `isUnlimitedDispatchCap`) — -1 means the window is not counted, and is the default. Also owns the retired executor's task-description parser (`QUOTA_BURN_TASK_PREFIX` / `quotaBurnFamilyOfDescription`), kept for migration 225, and the `run once` vocabulary (`quotaBurnJobKey` / `jobIsSpent`, plus the two family predicates `familyIsConfigured` and `familyHasRunnableJobs`). Pure — no storage, no provider I/O. || `quotaBurnLegacyConversion.js` | The ONE rule turning a LEGACY quota-burn step (copied prompt + quota-only `jobType`) into a scheduled-task reference, shared by migration 359 and the live compat path so the two cannot drift. `planQuotaBurnStepConversion` decides between three outcomes — a recognized unmodified shipped preset onto its scheduled audit counterpart with issues-only pinned explicitly (`AUDIT_TASK_TYPE_BY_PRESET_ID`, inverted from `auditCatalog.js`), the two programmatic types onto their scheduled handlers, and anything customized or targetless onto a `buildQuotaBurnCustomJob` on-demand custom task addressed by the deterministic `quotaBurnCustomJobId` (which is what makes a repeated or resumed conversion create no duplicate). `legacyAgentTaskMetadata` reproduces the retired executor's dispatch posture; `applyQuotaBurnStepConversion` rewrites the step, preserving id, label, enabled and run-once state. Recognition is `matchStoredAuditPreset`, never a label or a partial match. || `quotaBurnOrigin.js` | Quota-burn PROVENANCE on an on-demand scheduled-task request and on the task it produces. `normalizeQuotaBurnProvenance` reads the request block (burn-step id always required, plus an attribution — the family whose window is spent, OR the manual `maintenanceRunId` alone when the run is pinned outside every subscription family — the limiting-window reset and the provider/model/effort overrides); `QUOTA_BURN_PROVENANCE_FIELDS` is the ONE block definition every persistence and projection hop derives from, spread by `quotaBurnTaskMetadata` (flat task-metadata keys), `quotaBurnAgentMetadata` (the agent projection) and read back by `quotaBurnProvenance` / `hasQuotaBurnProvenance`, which accept both the flat keys and a nested `quotaBurn` block; `burnPlanOwnsTask` / `burnPlanOwnsAgent` are the ONE rule for whether the family plan (not a manual maintenance run) owns a burn-provenanced task. `isManualOnDemandRequest` distinguishes explicit runs from automated cadence gates. `onDemandRequestMetadata` is the single spread both on-demand engines apply. Import-light on purpose — `taskScheduleConstants.js` declares the origin string and must not drag the quota-burn config graph. |@@ -85,6 +86,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `quotaBurnValidation.js` | Zod schemas for the Quota Burn routes (partial config PUT, manual-run body, `run once` re-arm body). || `quotaReset.js` | `parseHumanReset` turns a provider CLI's human reset string into ISO 8601 (call it from the adapter); `normalizeResetAt`/`hoursUntilReset` compute time remaining without treating unknown values as imminent resets; `parseObservedReset` pulls the reset a provider stated in its own refusal text, and `isObservedBlockActive` is the shared "is that refusal still holding?" predicate every observed-refusal ledger uses. || `quotaWindows.js` | Classifies a quota window by PERIOD (`windowPeriodHours`); `classifyWindows` splits one card's windows into the weekly allowance that expires unused and the 5-hour one that refuses first, in one pass. `windowLabelOf` names a window. Pure. |+| `cronFields.js` | Cron FIELD semantics (pure, browser-safe): `matchesCronField(value, expr, fieldMin)` — the matcher `services/eventScheduler.js` walks minute by minute with — plus `expandCronField(expr, min, max)` and `cronWeekdayHours(expr)` → `{days, hours}`, the weekday/hour OCCUPANCY view a scheduler planner needs. Sibling of `cronValidation.js` (syntax/range only); one matcher so a planner reading an hour as free and the walker firing in it cannot disagree. `cronWeekdayHours` over-approximates on purpose — a `dayOfMonth`/`month` restriction lands on an unpredictable weekday, so it reports the whole week. || `cronValidation.js` | Cron syntax + field-range validation (pure, import-free, browser-safe). `isValidCronExpression` / `findCronExpressionError` (a user-facing reason string) / `isValidCronField` / `isCronShaped` (5-token SHAPE only — the named-cadence detector, never a stand-in for validity), plus `CRON_FIELD_NAMES` / `CRON_FIELD_BOUNDS`. ONE implementation shared by `services/eventScheduler.js`, the CoS schedule + per-app task-type save routes, the app-override schema in `validation.js`, and the browser cron editor via `client/src/utils/cronHelpers.js` (#6634). Syntax validity is deliberately separate from whether an occurrence exists in the scheduler bounded search window — a leap-day cron is valid. || `recurrenceValidation.js` | Shared Zod shape and vocabulary for anchored calendar recurrences that cannot be represented faithfully by five-field cron. || `appleHealthValidation.js` | Apple Health import payloads. |diff --git a/server/lib/auditCatalog.js b/server/lib/auditCatalog.jsindex 1a5d68add8..e9fa685b7d 100644--- a/server/lib/auditCatalog.js+++ b/server/lib/auditCatalog.js@@ -82,6 +82,32 @@ This banner OVERRIDES any later instruction to file issues, leave source unchangIf you find additional problems, mention them in the summary — do not expand scope. If nothing in the slice is worth changing, say so and stop without a drive-by refactor.`;+/**+ * Repository shapes an audit can REQUIRE to be worth running at all.+ *+ * An app that ships no user interface has nothing for an accessibility audit to+ * look at, so scheduling one buys a weekly `coverage: not-applicable` report and+ * a provider call. Each definition below may name one of these in+ * `requiresCapability`; the DETECTION lives in+ * `services/appQualitySchedule.js`, which is where the shapes are read off a+ * checkout. The requirement lives here, beside the audit it describes, so a new+ * audit cannot be added without the guard test asking the question.+ *+ * `test-coverage` is deliberately ungated: a repository with no tests is the+ * one that audit has the most to say about. Its sibling `better-test-quality`+ * IS gated, because it assesses tests that exist.+ */+export const AUDIT_REPO_CAPABILITIES = Object.freeze(['ui', 'typescript', 'tests', 'dependencies', 'api']);++/** Why an app lacking the capability is not worth scheduling that audit for. */+export const AUDIT_CAPABILITY_MISSING_REASON = Object.freeze({+ ui: 'no user interface found in this repository',+ typescript: 'no TypeScript sources found in this repository',+ tests: 'no test files found in this repository',+ dependencies: 'no dependency manifest found in this repository',+ api: 'no HTTP route or API surface found in this repository',+});+/*** Scheduled audit types that support the file-issues vs do-work toggle.* `quotaBurnId` maps onto `QUOTA_BURN_PROMPT_PRESETS` so a new burn preset@@ -145,6 +171,7 @@ export const AUDIT_DEFINITIONS = Object.freeze({label: 'Accessibility',description: 'Accessibility audit — configurable: file issues or implement fixes',defaultFileIssues: false,+ requiresCapability: 'ui',filing: filing({slugPrefix: 'a11y-',label: 'accessibility-audit',@@ -171,6 +198,7 @@ export const AUDIT_DEFINITIONS = Object.freeze({label: 'UI bugs',description: 'Find UI bugs — configurable: file issues or implement fixes',defaultFileIssues: false,+ requiresCapability: 'ui',filing: filing({slugPrefix: 'ui-bug-',label: 'ui-bug-audit',@@ -184,6 +212,7 @@ export const AUDIT_DEFINITIONS = Object.freeze({label: 'Mobile & responsive',description: 'Mobile/responsive audit — configurable: file issues or implement fixes',defaultFileIssues: false,+ requiresCapability: 'ui',filing: filing({slugPrefix: 'mobile-',label: 'mobile-audit',@@ -210,6 +239,7 @@ export const AUDIT_DEFINITIONS = Object.freeze({label: 'Typing',description: 'TypeScript-types audit — configurable: file issues or implement fixes',defaultFileIssues: false,+ requiresCapability: 'typescript',filing: filing({slugPrefix: 'typing-',label: 'typing-audit',@@ -223,6 +253,7 @@ export const AUDIT_DEFINITIONS = Object.freeze({label: 'Console errors',description: 'Console-error audit — configurable: file issues or implement fixes',defaultFileIssues: false,+ requiresCapability: 'ui',filing: filing({slugPrefix: 'console-',label: 'console-error-audit',@@ -236,6 +267,7 @@ export const AUDIT_DEFINITIONS = Object.freeze({label: 'UX',description: 'UX/design audit — configurable: file issues (default) or implement fixes',defaultFileIssues: true,+ requiresCapability: 'ui',filing: filing({slugPrefix: 'ux-',label: 'UX-audit',@@ -289,6 +321,7 @@ export const AUDIT_DEFINITIONS = Object.freeze({label: 'API & route contracts',description: 'API contract audit — configurable: file issues (default) or implement fixes',defaultFileIssues: true,+ requiresCapability: 'api',filing: filing({slugPrefix: 'api-contract-',label: 'api-contract-audit',@@ -303,6 +336,7 @@ export const AUDIT_DEFINITIONS = Object.freeze({label: 'UI lifecycle & state',description: 'UI lifecycle audit — configurable: file issues (default) or implement fixes',defaultFileIssues: true,+ requiresCapability: 'ui',filing: filing({slugPrefix: 'react-lifecycle-',label: 'react-lifecycle-audit',@@ -332,6 +366,7 @@ export const AUDIT_DEFINITIONS = Object.freeze({label: 'Copy & text clarity',description: 'Copy-clarity audit — configurable: file issues (default) or implement rewrites',defaultFileIssues: true,+ requiresCapability: 'ui',filing: filing({slugPrefix: 'copy-',label: 'copy-audit',@@ -414,6 +449,7 @@ export const AUDIT_DEFINITIONS = Object.freeze({label: 'Dependency freedom',description: 'Dependency-necessity audit — configurable: file issues (default) or implement one removal',defaultFileIssues: true,+ requiresCapability: 'dependencies',doWorkRequiresWorktree: true,filing: filing({slugPrefix: 'depfree-',@@ -428,6 +464,7 @@ export const AUDIT_DEFINITIONS = Object.freeze({label: 'Test quality',description: 'Vacuous/weak/redundant-test audit — configurable: file issues (default) or implement one cleanup',defaultFileIssues: true,+ requiresCapability: 'tests',filing: filing({slugPrefix: 'test-quality-',label: 'test-quality-audit',@@ -440,6 +477,14 @@ export const AUDIT_DEFINITIONS = Object.freeze({export const AUDIT_TASK_TYPES = new Set(Object.keys(AUDIT_DEFINITIONS));+/**+ * The same set as an ordered list, in catalog order. The Set answers+ * membership; anything that has to ENUMERATE the audits — a request schema's+ * enum, a schedule planner laying them out — reads this rather than re-deriving+ * `Object.keys(AUDIT_DEFINITIONS)` and acquiring a second vocabulary.+ */+export const AUDIT_TASK_TYPE_LIST = Object.freeze([...AUDIT_TASK_TYPES]);+/*** Check if a task type is an audit task registered in the catalog.*@@ -552,6 +597,18 @@ export const FILE_ISSUES_DELIVERY_SETTINGS = Object.freeze({simplify: false,});+/**+ * The repository shape this audit needs to be worth scheduling, or null when it+ * applies to any repository. Catalog-owned like `doWorkRequiresWorktree`, so+ * the schedule planner and the detection cannot drift from the audit itself.+ *+ * @param {string} taskType - Task type identifier+ * @returns {string|null} A member of AUDIT_REPO_CAPABILITIES, or null+ */+export function auditCapabilityRequirement(taskType) {+ return AUDIT_DEFINITIONS[taskType]?.requiresCapability || null;+}+/*** Retrieve filing preset configuration for an audit task type.*diff --git a/server/lib/auditCatalog.test.js b/server/lib/auditCatalog.test.jsindex e768faa7a7..0604075bc8 100644--- a/server/lib/auditCatalog.test.js+++ b/server/lib/auditCatalog.test.js@@ -4,6 +4,10 @@ import { requireSlashdoSubmoduleInCi } from './testHelper.js';import {AUDIT_DEFINITIONS,AUDIT_TASK_TYPES,+ AUDIT_TASK_TYPE_LIST,+ AUDIT_REPO_CAPABILITIES,+ AUDIT_CAPABILITY_MISSING_REASON,+ auditCapabilityRequirement,FILE_ISSUES_MODE_CONTRACT,DO_WORK_MODE_CONTRACT,isAuditTaskType,@@ -81,6 +85,26 @@ describe('AUDIT_DEFINITIONS', () => {expect(auditDoWorkRequiresWorktree('simplify')).toBe(false);expect(auditDoWorkRequiresWorktree('unknown')).toBe(false);});++ it('names a known repository shape for every audit that requires one', () => {+ for (const taskType of AUDIT_TASK_TYPE_LIST) {+ const requirement = auditCapabilityRequirement(taskType);+ if (requirement === null) continue;+ expect(AUDIT_REPO_CAPABILITIES).toContain(requirement);+ expect(AUDIT_CAPABILITY_MISSING_REASON[requirement]).toBeTruthy();+ }+ expect(auditCapabilityRequirement('accessibility')).toBe('ui');+ expect(auditCapabilityRequirement('unknown')).toBeNull();+ // Deliberately ungated: the repository with no tests is the one this audit+ // has the most to say about. Its sibling assesses tests that exist.+ expect(auditCapabilityRequirement('test-coverage')).toBeNull();+ expect(auditCapabilityRequirement('better-test-quality')).toBe('tests');+ });++ it('enumerates the audits in catalog order without a second vocabulary', () => {+ expect(AUDIT_TASK_TYPE_LIST).toEqual([...AUDIT_TASK_TYPES]);+ expect(AUDIT_TASK_TYPE_LIST.every(isAuditTaskType)).toBe(true);+ });});describe('isFileIssuesMode', () => {diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.jsindex ca0e92800d..d616f1c28b 100644--- a/server/lib/cosValidation.js+++ b/server/lib/cosValidation.js@@ -20,6 +20,8 @@ import { ORCHESTRATION_MODES, ORCHESTRATION_ROLES } from './orchestrationProfileimport { AGENT_RUN_EVENT_KINDS, RUN_EVENT_READ_LIMITS } from './agentRunEvents.js';import { TASK_STATUS_VALUES, TASK_PRIORITY_VALUES } from './taskParser.js';import { recurrenceRuleSchema } from './recurrenceValidation.js';+import { AUDIT_TASK_TYPE_LIST } from './auditCatalog.js';+import { CLAIM_DRAIN_TASK_TYPES } from './qualitySchedulePlan.js';import { JOB_INTERVAL_VALUES } from './autonomousJobIntervals.js';import { TASK_DATA_INPUT_DEFINITIONS, TASK_DATA_INPUT_IDS } from './taskDataInputCatalog.js';import {@@ -1275,3 +1277,29 @@ export const runEventReconcileSchema = z.object({runId: z.string().min(1).max(128).optional(),limit: z.coerce.number().int().min(1).max(RUN_EVENT_READ_LIMITS.max).optional()}).strict();++// The Quality tab's "schedule every applicable check" form. Every+// field is optional: an untouched form is a valid "plan the applicable checks+// with the shipped defaults", which is the whole point of the feature.+//+// `taskTypes` is bounded by the audit catalog rather than by+// SELF_IMPROVEMENT_TASK_TYPES: the planner lays out AUDITS, and a request+// naming `release-check` would otherwise have its cadence rewritten by a form+// that never showed it. `fileIssuesByType` is keyed the same way and read only+// for the types actually scheduled.+export const qualitySchedulePlanSchema = z.object({+ taskTypes: z.array(z.enum(AUDIT_TASK_TYPE_LIST)).max(AUDIT_TASK_TYPE_LIST.length).optional(),+ // partialRecord, not record: a Zod 4 enum-keyed record demands EVERY key, and+ // the form only sends the checks whose mode the user actually changed.+ fileIssuesByType: z.partialRecord(z.enum(AUDIT_TASK_TYPE_LIST), z.boolean()).optional(),+ // null = spread the selection evenly over the week.+ checksPerDay: z.number().int().min(1).max(24).nullable().optional(),+ windowStartHour: z.number().int().min(0).max(23).optional(),+ windowEndHour: z.number().int().min(0).max(23).optional(),+ claimBetween: z.boolean().optional(),+ claimOffsetHours: z.number().int().min(1).max(23).optional(),+ claimTaskType: z.enum(CLAIM_DRAIN_TASK_TYPES).optional(),+ padBeforeHours: z.number().int().min(0).max(12).optional(),+ padAfterHours: z.number().int().min(0).max(12).optional(),+ fileIssues: z.boolean().optional(),+}).strict();diff --git a/server/lib/cronFields.js b/server/lib/cronFields.jsnew file mode 100644index 0000000000..0adf30c2d8--- /dev/null+++ b/server/lib/cronFields.js@@ -0,0 +1,110 @@+/**+ * Cron FIELD semantics (pure, dependency-free).+ *+ * Sibling of `cronValidation.js`, which answers syntax and range only. This+ * module answers the two questions a reader of an already-valid expression+ * has: does THIS value match that field, and which values does that field+ * fire on?+ *+ * `matchesCronField` is the walker's own matcher (`services/eventScheduler.js`+ * stepped minute by minute using a private copy). It lives here because the+ * schedule PLANNER needs the same reading of `*\/4`, `1-5` and `0,12` — a+ * second implementation would let the planner think an hour is free while the+ * walker fires a task in it.+ *+ * Kept import-free so the browser can use it the way `cronValidation.js` is+ * already used by `client/src/utils/cronHelpers.js`.+ */++import { CRON_FIELD_BOUNDS, CRON_FIELD_COUNT, isCronShaped } from './cronValidation.js';++/**+ * Whether a value matches one cron field expression.+ *+ * @param {number} value - The concrete value (hour, day-of-week, …)+ * @param {string} expr - One cron field (`*`, `5`, `1-5`, `*\/15`, `0,12`)+ * @param {number} [fieldMin] - The field's minimum, used as the implicit start+ * of a bare `*\/n` step+ * @returns {boolean}+ */+export function matchesCronField(value, expr, fieldMin = 0) {+ if (expr === '*') return true;++ if (expr.includes(',')) {+ return expr.split(',').some(part => matchesCronField(value, part.trim(), fieldMin));+ }++ // Steps first (`*\/5`, `0/10`, `1-5/2`) — a step expression may also contain+ // a range, so testing `-` before `/` would misread it.+ if (expr.includes('/')) {+ const [rangeExpr, step] = expr.split('/');+ const stepNum = Number(step);+ let startNum = fieldMin;+ let endNum = Infinity;+ if (rangeExpr === '*') {+ startNum = fieldMin;+ } else if (rangeExpr.includes('-')) {+ const [s, e] = rangeExpr.split('-').map(Number);+ startNum = s;+ endNum = e;+ } else {+ startNum = Number(rangeExpr);+ }+ return value >= startNum && value <= endNum && (value - startNum) % stepNum === 0;+ }++ if (expr.includes('-')) {+ const [start, end] = expr.split('-').map(Number);+ return value >= start && value <= end;+ }++ return Number(expr) === value;+}++/**+ * Every value in `[min, max]` a field fires on.+ *+ * @param {string} expr - One cron field+ * @param {number} min - Inclusive lower bound of the field+ * @param {number} max - Inclusive upper bound of the field+ * @returns {number[]} Matching values, ascending+ */+export function expandCronField(expr, min, max) {+ const values = [];+ for (let value = min; value <= max; value += 1) {+ if (matchesCronField(value, expr, min)) values.push(value);+ }+ return values;+}++/**+ * The weekday/hour cells a 5-field expression can fire in — the occupancy view+ * a planner needs to keep a new task out of a running one's way.+ *+ * Deliberately over-approximates rather than under: a `dayOfMonth`/`month`+ * restriction narrows WHICH dates match, but says nothing about weekday, so an+ * expression carrying one is reported as occupying every weekday at its hours.+ * A planner that guesses low would put work on top of a running job; guessing+ * high only costs it a candidate hour.+ *+ * @param {unknown} cronExpr - A 5-field cron expression+ * @returns {{ days: number[], hours: number[] }|null} null when+ * the value is not cron-shaped+ */+export function cronWeekdayHours(cronExpr) {+ if (!isCronShaped(cronExpr)) return null;+ const fields = cronExpr.trim().split(/\s+/);+ if (fields.length !== CRON_FIELD_COUNT) return null;+ const [, hourExpr, dayOfMonthExpr, monthExpr, dayOfWeekExpr] = fields;++ const hours = expandCronField(hourExpr, ...CRON_FIELD_BOUNDS[1]);+ // A restricted date or month lands on an unpredictable weekday, so the whole+ // week is occupied at those hours.+ const dateRestricted = dayOfMonthExpr !== '*' || monthExpr !== '*';+ const days = dateRestricted+ ? [0, 1, 2, 3, 4, 5, 6]+ // Cron spells Sunday 0 and 7; normalize to the JS 0-6 the planner uses.+ : [...new Set(expandCronField(dayOfWeekExpr, ...CRON_FIELD_BOUNDS[4]).map(day => day % 7))].sort((a, b) => a - b);++ return { days, hours };+}diff --git a/server/lib/cronFields.test.js b/server/lib/cronFields.test.jsnew file mode 100644index 0000000000..7748d1d680--- /dev/null+++ b/server/lib/cronFields.test.js@@ -0,0 +1,58 @@+import { describe, it, expect } from 'vitest';+import { cronWeekdayHours, expandCronField, matchesCronField } from './cronFields.js';++describe('matchesCronField', () => {+ it('reads the forms the scheduler actually stores', () => {+ expect(matchesCronField(7, '*')).toBe(true);+ expect(matchesCronField(7, '7')).toBe(true);+ expect(matchesCronField(7, '1-5')).toBe(false);+ expect(matchesCronField(3, '1-5')).toBe(true);+ expect(matchesCronField(8, '0,8,16')).toBe(true);+ expect(matchesCronField(9, '0,8,16')).toBe(false);+ });++ it('reads a step relative to the field minimum, not to zero', () => {+ // `*/15` on the minute field starts at 0; on a 1-based field it starts at 1,+ // which is why the walker passes `fieldMin` rather than assuming 0.+ expect(matchesCronField(15, '*/15', 0)).toBe(true);+ expect(matchesCronField(16, '*/15', 0)).toBe(false);+ expect(matchesCronField(3, '*/2', 1)).toBe(true);+ expect(matchesCronField(2, '*/2', 1)).toBe(false);+ // A bounded step stops at the end of its range.+ expect(matchesCronField(5, '1-5/2')).toBe(true);+ expect(matchesCronField(7, '1-5/2')).toBe(false);+ });+});++describe('expandCronField', () => {+ it('enumerates the values a field fires on', () => {+ expect(expandCronField('*/6', 0, 23)).toEqual([0, 6, 12, 18]);+ expect(expandCronField('1-3', 0, 23)).toEqual([1, 2, 3]);+ expect(expandCronField('30', 0, 59)).toEqual([30]);+ });+});++describe('cronWeekdayHours', () => {+ it('reports the weekday/hour cells a weekly expression occupies', () => {+ expect(cronWeekdayHours('0 9,21 * * 1')).toEqual({ days: [1], hours: [9, 21] });+ });++ it('normalizes cron Sunday 7 onto the JS 0 a planner indexes by', () => {+ expect(cronWeekdayHours('0 9 * * 7').days).toEqual([0]);+ // Both spellings in one field collapse to a single Sunday.+ expect(cronWeekdayHours('0 9 * * 0,7').days).toEqual([0]);+ });++ it('treats a date-restricted expression as occupying the whole week', () => {+ // The 1st of the month is a different weekday every month, so a planner+ // that believed the `*` weekday field would schedule straight into it.+ expect(cronWeekdayHours('0 4 1 * *').days).toEqual([0, 1, 2, 3, 4, 5, 6]);+ expect(cronWeekdayHours('0 4 * 3 1').days).toEqual([0, 1, 2, 3, 4, 5, 6]);+ });++ it('rejects anything that is not a 5-field expression', () => {+ expect(cronWeekdayHours('on-demand')).toBeNull();+ expect(cronWeekdayHours('0 9 * *')).toBeNull();+ expect(cronWeekdayHours(null)).toBeNull();+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 4ded7123c8..62fdcb0e73 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -33,6 +33,7 @@ export * as characterEvolutionValidation from './characterEvolutionValidation.jsexport * as cosValidation from './cosValidation.js';// Flat: validation.js re-exports these same bindings, and the barrel's collision// check treats an identical identity as a re-export rather than a clash.+export * from './cronFields.js';export * from './cronValidation.js';export * from './cosToolContracts.js';export * as creativeCommissionValidation from './creativeCommissionValidation.js';@@ -221,6 +222,7 @@ export * from './publicReviewSpawnGate.js';// duplicate-identifier collision check.export * as reviewerConfig from './reviewerConfig.js';export * from './reviewerProviderMatchers.js';+export * from './qualitySchedulePlan.js';export * from './quotaBurnConfig.js';export * from './quotaBurnLegacyConversion.js';export * from './quotaBurnOrigin.js';diff --git a/server/lib/qualitySchedulePlan.js b/server/lib/qualitySchedulePlan.jsnew file mode 100644index 0000000000..3f634cf22b--- /dev/null+++ b/server/lib/qualitySchedulePlan.js@@ -0,0 +1,266 @@+/**+ * Lay the quality audits out across a week, around whatever else already runs.+ *+ * The problem this solves: an app has ~26 schedulable audit types+ * (`AUDIT_DEFINITIONS`), each of which would otherwise need a hand-picked cron+ * expression, in an order that respects `AUDIT_SUGGESTED_AFTER`, in hours that+ * do not land on top of a release job. Nobody picks 26 cron expressions by+ * hand, so this module picks them: it distributes the checks over all seven+ * days, and interleaves the issue-claim drain a few hours after each one so+ * the issues a filing audit just wrote get worked before the next audit runs.+ *+ * Pure: the caller supplies the applicable types and the occupied weekday/hour+ * cells (`busy`), and gets cron strings back. Nothing here reads a schedule,+ * a repository, or the clock.+ */++import { AUDIT_DEFINITIONS, AUDIT_SUGGESTED_AFTER, AUDIT_TASK_TYPE_LIST, defaultFileIssuesFor } from './auditCatalog.js';++/** The task types the claim drain can be run through, in preference order. */+export const CLAIM_DRAIN_TASK_TYPES = Object.freeze(['claim-work', 'claim-issue', 'plan-task']);++export const DEFAULT_QUALITY_SCHEDULE_OPTIONS = Object.freeze({+ /** Checks per day. `null` spreads the selected checks evenly over seven days. */+ checksPerDay: null,+ /** Earliest and latest hour (inclusive) an audit slot may be placed in. */+ windowStartHour: 0,+ windowEndHour: 23,+ /** Run the issue-claim drain between checks. */+ claimBetween: true,+ /** Hours after an audit slot the claim drain starts. */+ claimOffsetHours: 3,+ /** Which task type drives the claim drain. */+ claimTaskType: 'claim-work',+ /** Hours around an already-scheduled job treated as occupied. */+ padBeforeHours: 1,+ padAfterHours: 2,+ /** Default delivery mode for every check with no per-check answer. */+ fileIssues: true,+});++const clampHour = (value, fallback) => {+ const hour = Number(value);+ return Number.isInteger(hour) && hour >= 0 && hour <= 23 ? hour : fallback;+};++/**+ * Order the selected checks so each one follows the audits the catalog says+ * should precede it (`AUDIT_SUGGESTED_AFTER`). A predecessor the user did not+ * select imposes no constraint, and a cycle — which the shipped table has none+ * of, but a future edit could introduce — degrades to catalog order for the+ * types it traps rather than dropping them.+ *+ * @param {string[]} taskTypes - Audit task types to order+ * @returns {string[]} The same types, earliest-first+ */+export function orderQualityChecks(taskTypes) {+ const selected = AUDIT_TASK_TYPE_LIST.filter(type => taskTypes.includes(type));+ const pending = new Set(selected);+ const ordered = [];+ while (pending.size) {+ const ready = selected.filter(type => pending.has(type)+ && (AUDIT_SUGGESTED_AFTER[type] || []).every(dep => !pending.has(dep)));+ // A cycle leaves nothing ready; emit the rest in catalog order and stop.+ const batch = ready.length ? ready : selected.filter(type => pending.has(type));+ for (const type of batch) {+ ordered.push(type);+ pending.delete(type);+ }+ }+ return ordered;+}++/**+ * The option bag with every default filled in and the hour window made+ * coherent (`windowEndHour` never before `windowStartHour`).+ *+ * ONE resolver, called by `planQualitySchedule` and by the service that also+ * hands the same bag to `buildBusySlots` — so "what does an omitted option+ * mean" has a single answer rather than one per caller.+ *+ * @param {object} [options] - Partial overrides of DEFAULT_QUALITY_SCHEDULE_OPTIONS+ * @returns {object} The resolved bag+ */+export function resolveQualityScheduleOptions(options = {}) {+ const settings = { ...DEFAULT_QUALITY_SCHEDULE_OPTIONS, ...options };+ const windowStartHour = clampHour(settings.windowStartHour, DEFAULT_QUALITY_SCHEDULE_OPTIONS.windowStartHour);+ return {+ ...settings,+ windowStartHour,+ windowEndHour: Math.max(windowStartHour, clampHour(settings.windowEndHour, DEFAULT_QUALITY_SCHEDULE_OPTIONS.windowEndHour)),+ claimTaskType: CLAIM_DRAIN_TASK_TYPES.includes(settings.claimTaskType)+ ? settings.claimTaskType+ : DEFAULT_QUALITY_SCHEDULE_OPTIONS.claimTaskType,+ };+}++/**+ * Build the occupied-cell lookup the planner avoids.+ *+ * @param {Array<{ days: number[], hours: number[] }>} occupancies - Expanded cron occupancies+ * @param {{ padBeforeHours?: number, padAfterHours?: number }} [options]+ * @returns {Set<string>} `"<day>:<hour>"` keys, padding included+ */+export function buildBusySlots(occupancies = [], {+ padBeforeHours = DEFAULT_QUALITY_SCHEDULE_OPTIONS.padBeforeHours,+ padAfterHours = DEFAULT_QUALITY_SCHEDULE_OPTIONS.padAfterHours,+} = {}) {+ const busy = new Set();+ for (const { days = [], hours = [] } of occupancies) {+ for (const day of days) {+ for (const hour of hours) {+ for (let offset = -padBeforeHours; offset <= padAfterHours; offset += 1) {+ // A padded window crossing midnight lands on the neighbouring day.+ const shifted = hour + offset;+ const dayShift = Math.floor(shifted / 24);+ busy.add(`${(((day + dayShift) % 7) + 7) % 7}:${((shifted % 24) + 24) % 24}`);+ }+ }+ }+ }+ return busy;+}++/** Whether an hour is free on EVERY weekday — the test a daily drain needs. */+const freeAllWeek = (busy, hour) => ![0, 1, 2, 3, 4, 5, 6].some(day => busy.has(`${day}:${hour}`));++/**+ * First hour at or near `target` that is free all week and not already taken.+ * Scans outward (target, +1, -1, +2, …) so a slot lands as close to its even+ * spacing as the occupied hours allow, staying inside `[low, high]`.+ */+function findFreeHour(target, { busy, taken, low, high }) {+ const span = Math.max(target - low, high - target);+ for (let step = 0; step <= span; step += 1) {+ for (const hour of step === 0 ? [target] : [target + step, target - step]) {+ if (hour < low || hour > high) continue;+ if (taken.has(hour)) continue;+ if (freeAllWeek(busy, hour)) return hour;+ }+ }+ return null;+}++/**+ * First free hour at or AFTER `target`, wrapping past midnight.+ *+ * The claim drain works the issues the audit before it just filed, so it may+ * only ever move later. An outward search would happily place it an hour+ * BEFORE its audit when the intervening hours are occupied — which reads as a+ * drain "between" the checks while actually running against the previous+ * night's backlog.+ */+function findFreeHourForward(target, { busy, taken }) {+ for (let step = 0; step < 24; step += 1) {+ const hour = (target + step) % 24;+ if (!taken.has(hour) && freeAllWeek(busy, hour)) return hour;+ }+ return null;+}++/**+ * Plan the week.+ *+ * Audits are laid out as a fixed grid: the same `checksPerDay` hours on every+ * weekday, with each selected check taking one cell. That shape is what lets+ * the claim drain be ONE cron expression (`0 8,16 * * *`) instead of one per+ * day — and it is what a human can hold in their head when they later look at+ * the schedule page and ask why a task ran at 08:00.+ *+ * @param {object} input+ * @param {string[]} input.taskTypes - Audit types to schedule+ * @param {Record<string, boolean>} [input.fileIssuesByType] - Per-check delivery mode+ * @param {Set<string>} [input.busy] - Occupied `"<day>:<hour>"` cells+ * @param {object} [input.options] - Overrides of DEFAULT_QUALITY_SCHEDULE_OPTIONS+ * @returns {{ checksPerDay: number, slots: object[], claim: object|null, warnings: string[], options: object }}+ */+export function planQualitySchedule({ taskTypes = [], fileIssuesByType = {}, busy = new Set(), options = {} } = {}) {+ const settings = resolveQualityScheduleOptions(options);+ const { windowStartHour, windowEndHour } = settings;+ const windowHours = windowEndHour - windowStartHour + 1;+ const warnings = [];+ const ordered = orderQualityChecks(taskTypes);++ if (!ordered.length) {+ return { checksPerDay: 0, slots: [], claim: null, warnings: ['No quality checks selected.'], options: settings };+ }++ // Enough slots to give every check its own cell, unless the user asked for+ // more. A window too narrow to hold that many is reported rather than+ // silently doubling checks onto one hour.+ const requested = Number(settings.checksPerDay);+ const minimumPerDay = Math.ceil(ordered.length / 7);+ let checksPerDay = Math.max(minimumPerDay, Number.isInteger(requested) && requested > 0 ? requested : 0);+ if (checksPerDay > windowHours) {+ warnings.push(`${ordered.length} checks need ${checksPerDay} slots a day, which does not fit in a ${windowHours}-hour window — widen the window or deselect checks.`);+ checksPerDay = windowHours;+ }++ // One audit hour per daily slot, plus its claim hour, all free every weekday.+ const taken = new Set();+ const auditHours = [];+ const claimHours = [];+ for (let slot = 0; slot < checksPerDay; slot += 1) {+ const target = windowStartHour + Math.round((slot * windowHours) / checksPerDay);+ const auditHour = findFreeHour(Math.min(target, windowEndHour), { busy, taken, low: windowStartHour, high: windowEndHour });+ if (auditHour === null) {+ warnings.push('Not enough unoccupied hours in the chosen window for every daily slot; reduce checks per day or widen the window.');+ break;+ }+ taken.add(auditHour);+ auditHours.push(auditHour);++ if (!settings.claimBetween) continue;+ // The claim drain may sit outside the audit window — it is the follow-up+ // work, not an audit — so it searches the whole day.+ const claimTarget = (auditHour + Math.max(1, Number(settings.claimOffsetHours) || 1)) % 24;+ const claimHour = findFreeHourForward(claimTarget, { busy, taken });+ if (claimHour === null) {+ warnings.push('No free hour for the claim drain after every check; it will run on fewer slots.');+ continue;+ }+ taken.add(claimHour);+ claimHours.push(claimHour);+ }++ if (!auditHours.length) {+ return { checksPerDay: 0, slots: [], claim: null, warnings, options: settings };+ }++ const slots = ordered.map((taskType, index) => {+ // Monday-first so the head of the suggested order (security, data safety)+ // opens the working week rather than landing on a Sunday.+ const day = (1 + Math.floor(index / auditHours.length)) % 7;+ const hour = auditHours[index % auditHours.length];+ const fileIssues = typeof fileIssuesByType[taskType] === 'boolean'+ ? fileIssuesByType[taskType]+ : (typeof settings.fileIssues === 'boolean' ? settings.fileIssues : defaultFileIssuesFor(taskType));+ return {+ taskType,+ label: AUDIT_DEFINITIONS[taskType]?.label || taskType,+ day,+ hour,+ fileIssues,+ cron: `0 ${hour} * * ${day}`,+ };+ });++ if (ordered.length > auditHours.length * 7) {+ warnings.push(`Only ${auditHours.length * 7} free weekly slots were available for ${ordered.length} checks; the extras share a slot with an earlier check.`);+ }++ const filingSlots = slots.filter(slot => slot.fileIssues);+ let claim = null;+ if (settings.claimBetween && claimHours.length && filingSlots.length) {+ const hours = [...new Set(claimHours)].sort((a, b) => a - b);+ claim = {+ taskType: settings.claimTaskType,+ hours,+ cron: `0 ${hours.join(',')} * * *`,+ };+ } else if (settings.claimBetween && !filingSlots.length) {+ warnings.push('Every check implements its own fixes, so no issue-claim drain was scheduled.');+ }++ return { checksPerDay: auditHours.length, slots, claim, warnings, options: settings };+}diff --git a/server/lib/qualitySchedulePlan.test.js b/server/lib/qualitySchedulePlan.test.jsnew file mode 100644index 0000000000..6bf49da562--- /dev/null+++ b/server/lib/qualitySchedulePlan.test.js@@ -0,0 +1,141 @@+import { describe, it, expect } from 'vitest';+import { AUDIT_SUGGESTED_AFTER, AUDIT_TASK_TYPE_LIST } from './auditCatalog.js';+import { cronWeekdayHours } from './cronFields.js';+import {+ buildBusySlots,+ orderQualityChecks,+ planQualitySchedule,+ resolveQualityScheduleOptions,+} from './qualitySchedulePlan.js';++const busyFrom = (crons, padding = {}) =>+ buildBusySlots(crons.map(cronWeekdayHours), { padBeforeHours: 1, padAfterHours: 2, ...padding });++const planAll = (overrides = {}) => planQualitySchedule({ taskTypes: [...AUDIT_TASK_TYPE_LIST], ...overrides });++describe('buildBusySlots', () => {+ it('pads around the job and carries the padding across midnight', () => {+ const busy = busyFrom(['30 0 * * 1']);+ // Monday 00:00 ± (1 before, 2 after) reaches back into Sunday 23:00.+ expect(busy.has('1:0')).toBe(true);+ expect(busy.has('1:2')).toBe(true);+ expect(busy.has('0:23')).toBe(true);+ expect(busy.has('1:3')).toBe(false);+ });+});++describe('orderQualityChecks', () => {+ it('puts every selected check after the predecessors the catalog names', () => {+ const ordered = orderQualityChecks([...AUDIT_TASK_TYPE_LIST]);+ for (const [taskType, predecessors] of Object.entries(AUDIT_SUGGESTED_AFTER)) {+ for (const predecessor of predecessors) {+ expect(ordered.indexOf(predecessor)).toBeLessThan(ordered.indexOf(taskType));+ }+ }+ });++ it('ignores a predecessor the user did not select', () => {+ // `module-hygiene` follows `simplify`; with simplify deselected it is free+ // to run first rather than being held back or dropped.+ expect(orderQualityChecks(['module-hygiene'])).toEqual(['module-hygiene']);+ });+});++describe('resolveQualityScheduleOptions', () => {+ it('fills defaults, orders the window, and refuses an unknown claim task', () => {+ const resolved = resolveQualityScheduleOptions({ windowStartHour: 20, windowEndHour: 4, claimTaskType: 'rm-rf' });+ expect(resolved.windowEndHour).toBe(20);+ expect(resolved.claimTaskType).toBe('claim-work');+ expect(resolved.claimOffsetHours).toBe(3);+ });+});++describe('planQualitySchedule', () => {+ it('gives every selected check exactly one weekly slot spread over the week', () => {+ const plan = planAll();+ expect(plan.slots).toHaveLength(AUDIT_TASK_TYPE_LIST.length);+ expect(new Set(plan.slots.map(slot => slot.taskType)).size).toBe(AUDIT_TASK_TYPE_LIST.length);+ expect(new Set(plan.slots.map(slot => slot.day)).size).toBe(7);+ // One check per weekday/hour cell — two audits in one cell would run the+ // same app's repository through two agents at once.+ const cells = plan.slots.map(slot => `${slot.day}:${slot.hour}`);+ expect(new Set(cells).size).toBe(cells.length);+ expect(plan.warnings).toEqual([]);+ });++ it('keeps every audit and the claim drain out of a nightly release window', () => {+ // The shape this feature exists for: a 03:30 release must not have an audit+ // or a claim job running against the same checkout.+ const busy = busyFrom(['30 3 * * *']);+ const plan = planAll({ busy });+ const blocked = [2, 3, 4, 5];+ for (const slot of plan.slots) expect(blocked).not.toContain(slot.hour);+ for (const hour of plan.claim.hours) expect(blocked).not.toContain(hour);+ });++ it('starts the claim drain after the check it follows, never before it', () => {+ // With the natural offset hours occupied, an outward search would place the+ // drain earlier in the day — working last night's backlog instead.+ const plan = planAll({ busy: busyFrom(['30 3 * * *']), options: { checksPerDay: 2, claimOffsetHours: 3 } });+ const auditHours = [...new Set(plan.slots.map(slot => slot.hour))].sort((a, b) => a - b);+ expect(plan.claim.hours).toHaveLength(auditHours.length);+ auditHours.forEach((auditHour, index) => {+ const gap = (plan.claim.hours.slice().sort((a, b) => a - b)[index] - auditHour + 24) % 24;+ expect(gap).toBeGreaterThan(0);+ expect(gap).toBeLessThan(24);+ });+ });++ it('emits one daily cron for the claim drain covering every slot', () => {+ const plan = planAll({ options: { checksPerDay: 2 } });+ expect(plan.claim.cron).toBe(`0 ${plan.claim.hours.join(',')} * * *`);+ expect(plan.claim.taskType).toBe('claim-work');+ });++ it('schedules no claim drain when nothing files issues', () => {+ const plan = planAll({ options: { fileIssues: false } });+ expect(plan.claim).toBeNull();+ expect(plan.slots.every(slot => slot.fileIssues === false)).toBe(true);+ expect(plan.warnings.join(' ')).toMatch(/implements its own fixes/);+ });++ it('honors a per-check delivery mode over the form default', () => {+ const plan = planQualitySchedule({+ taskTypes: ['security', 'ux'],+ fileIssuesByType: { security: false },+ options: { fileIssues: true },+ });+ expect(plan.slots.find(slot => slot.taskType === 'security').fileIssues).toBe(false);+ expect(plan.slots.find(slot => slot.taskType === 'ux').fileIssues).toBe(true);+ });++ it('confines slots to the chosen window and says so when they do not fit', () => {+ const plan = planAll({ options: { windowStartHour: 9, windowEndHour: 11 } });+ for (const slot of plan.slots) {+ expect(slot.hour).toBeGreaterThanOrEqual(9);+ expect(slot.hour).toBeLessThanOrEqual(11);+ }+ expect(plan.warnings.join(' ')).toMatch(/does not fit in a 3-hour window/);+ });++ it('reports rather than silently drops checks when the week runs out of free hours', () => {+ // Every hour but one occupied leaves 7 weekly cells for 26 checks.+ const busy = buildBusySlots([{ days: [0, 1, 2, 3, 4, 5, 6], hours: Array.from({ length: 23 }, (_, h) => h + 1) }], { padBeforeHours: 0, padAfterHours: 0 });+ const plan = planAll({ busy });+ expect(plan.checksPerDay).toBe(1);+ expect(plan.slots).toHaveLength(AUDIT_TASK_TYPE_LIST.length);+ expect(plan.warnings.join(' ')).toMatch(/share a slot/);+ });++ it('returns an empty plan rather than a cron for nothing when no check is selected', () => {+ const plan = planQualitySchedule({ taskTypes: [] });+ expect(plan.slots).toEqual([]);+ expect(plan.claim).toBeNull();+ });++ it('emits crons the scheduler can read back', () => {+ for (const slot of planAll().slots) {+ expect(cronWeekdayHours(slot.cron)).toEqual({ days: [slot.day], hours: [slot.hour] });+ }+ });+});diff --git a/server/routes/apps/taskTypes.js b/server/routes/apps/taskTypes.jsindex 154888eb35..ed2f6c8027 100644--- a/server/routes/apps/taskTypes.js+++ b/server/routes/apps/taskTypes.js@@ -9,6 +9,9 @@* GET /:id/claim-reviewers → { source, reviewers, csv, … }* GET /:id/layered-intelligence → { config, isPortos }* GET /:id/layered-intelligence/outcomes → { stats, execution, metrics, approvalFunnel, rejections, recent }+ * GET /:id/quality-schedule → { checks, capabilities, plan, busySources }+ * POST /:id/quality-schedule/preview → { checks, capabilities, plan, busySources }+ * POST /:id/quality-schedule/apply → { success, plan, applied, disabled }* PUT /:id/task-types/all → { success, taskTypeOverrides }* PUT /:id/task-types/:taskType → { success, taskTypeOverrides }*@@ -20,7 +23,8 @@ import { Router } from 'express';import { logCosScheduleUpdate } from '../../services/userActionScheduleLog.js';import * as appsService from '../../services/apps.js';import { PORTOS_APP_ID } from '../../services/apps.js';-import { sanitizeTaskMetadata, ISSUE_AUTHOR_FILTERS } from '../../lib/validation.js';+import { sanitizeTaskMetadata, ISSUE_AUTHOR_FILTERS, validateRequest, qualitySchedulePlanSchema } from '../../lib/validation.js';+import { buildQualitySchedulePlan, applyQualitySchedulePlan } from '../../services/appQualitySchedule.js';import { listWorkItems } from '../../services/workItems.js';import { resolveClaimWorkMetadata, resolveClaimAuthorFilter, resolveAppClaimReviewers } from '../../services/cosTaskGenerator.js';import { INTERVAL_TYPES, decodeIntervalType, isCronExpression, isKnownIntervalType } from '../../services/taskScheduleConstants.js';@@ -223,6 +227,39 @@ router.get('/:id/layered-intelligence/outcomes', loadApp, asyncHandler(async (re});}));+// GET /api/apps/:id/quality-schedule - What the Quality tab's schedule form+// renders from: every audit check with its applicability verdict and current+// cadence, the repository shapes that verdict was derived from, the cron+// expressions the planner has to work around, and the plan the shipped+// defaults produce. Read-only — no LLM call, no schedule write.+router.get('/:id/quality-schedule', loadApp, asyncHandler(async (req, res) => {+ res.json(await buildQualitySchedulePlan(req.loadedApp));+}));++// POST /api/apps/:id/quality-schedule/preview - The same plan for a form the+// user has edited. A POST rather than a query string because the option bag+// carries a per-check delivery map; still a pure read, so it writes nothing.+router.post('/:id/quality-schedule/preview', loadApp, asyncHandler(async (req, res) => {+ const options = validateRequest(qualitySchedulePlanSchema, req.body || {});+ res.json(await buildQualitySchedulePlan(req.loadedApp, options));+}));++// POST /api/apps/:id/quality-schedule/apply - Write the plan as ordinary+// per-app task-type overrides. Every audit type is touched: the ones in the+// plan get their cron and delivery mode, and the ones left out are DISABLED,+// because the form is the whole picture of this app's quality cadence.+router.post('/:id/quality-schedule/apply', loadApp, asyncHandler(async (req, res) => {+ const options = validateRequest(qualitySchedulePlanSchema, req.body || {});+ const result = await applyQualitySchedulePlan(req.loadedApp, options);+ await logCosScheduleUpdate({+ target: req.loadedApp.id,+ patch: options,+ source: { route: `${req.baseUrl}${req.route?.path ?? ''}`, method: req.method },+ extra: { qualityPlan: true, applied: result.applied, disabled: result.disabled },+ });+ res.json({ success: true, ...result });+}));+// PUT /api/apps/:id/task-types/all - Toggle all task types for an approuter.put('/:id/task-types/all', loadApp, asyncHandler(async (req, res) => {const { enabled } = req.body;diff --git a/server/routes/apps/taskTypes.test.js b/server/routes/apps/taskTypes.test.jsindex 61dc7fc6f3..eb216bb77a 100644--- a/server/routes/apps/taskTypes.test.js+++ b/server/routes/apps/taskTypes.test.js@@ -32,6 +32,14 @@ vi.mock('../../services/layeredIntelligenceOutcomes.js', () => ({vi.mock('../../services/workItems.js', () => ({listWorkItems: vi.fn()}));++// The quality-schedule planner has its own suite (repo scanning, busy-window+// collection, plan placement); here only the route's validation and wiring are+// under test, so the service is a double.+vi.mock('../../services/appQualitySchedule.js', () => ({+ buildQualitySchedulePlan: vi.fn(),+ applyQualitySchedulePlan: vi.fn()+}));vi.mock('../../services/cosTaskGenerator.js', async (importActual) => ({...(await importActual()),resolveClaimWorkMetadata: vi.fn(),@@ -41,6 +49,7 @@ vi.mock('../../services/cosTaskGenerator.js', async (importActual) => ({import * as appsService from '../../services/apps.js';import { listOutcomesResult } from '../../services/layeredIntelligenceOutcomes.js';import { listWorkItems } from '../../services/workItems.js';+import { buildQualitySchedulePlan, applyQualitySchedulePlan } from '../../services/appQualitySchedule.js';import { resolveClaimWorkMetadata, resolveAppClaimReviewers } from '../../services/cosTaskGenerator.js';describe('Apps Task-Type Routes', () => {@@ -502,4 +511,49 @@ describe('Apps Task-Type Routes', () => {expect(response.status).toBe(404);});});++ describe('quality schedule planning', () => {+ const plan = { checksPerDay: 1, slots: [{ taskType: 'security', day: 1, hour: 9, cron: '0 9 * * 1', fileIssues: true }], claim: null, warnings: [], options: {} };+ const payload = { appId: 'app-001', appName: 'App', plan, checks: [], capabilities: {}, scanned: 10, busySources: [], claimTaskTypes: ['claim-work'] };++ beforeEach(() => {+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'App' });+ buildQualitySchedulePlan.mockResolvedValue(payload);+ applyQualitySchedulePlan.mockResolvedValue({ ...payload, applied: 1, disabled: 25 });+ });++ it('serves the service payload verbatim, adding nothing of its own', async () => {+ const response = await request(app).get('/api/apps/app-001/quality-schedule');+ expect(response.status).toBe(200);+ expect(response.body).toEqual(payload);+ expect(buildQualitySchedulePlan).toHaveBeenCalledWith({ id: 'app-001', name: 'App' });+ });++ it('previews an edited form without writing anything', async () => {+ const response = await request(app)+ .post('/api/apps/app-001/quality-schedule/preview')+ .send({ taskTypes: ['security'], checksPerDay: 2, fileIssuesByType: { security: false } });+ expect(response.status).toBe(200);+ expect(buildQualitySchedulePlan.mock.calls[0][1]).toMatchObject({ taskTypes: ['security'], checksPerDay: 2, fileIssuesByType: { security: false } });+ expect(applyQualitySchedulePlan).not.toHaveBeenCalled();+ });++ it('refuses a task type that is not an audit, so a form cannot rewrite the release cadence', async () => {+ const response = await request(app)+ .post('/api/apps/app-001/quality-schedule/apply')+ .send({ taskTypes: ['release-check'] });+ expect(response.status).toBe(400);+ expect(applyQualitySchedulePlan).not.toHaveBeenCalled();+ });++ it('applies the plan and records the schedule change in the operator ledger', async () => {+ const response = await request(app)+ .post('/api/apps/app-001/quality-schedule/apply')+ .send({ taskTypes: ['security'], claimBetween: false });+ expect(response.status).toBe(200);+ expect(response.body).toMatchObject({ success: true, applied: 1, disabled: 25 });+ expect(applyQualitySchedulePlan.mock.calls[0][1]).toMatchObject({ taskTypes: ['security'], claimBetween: false });+ expect(recordUserAction).toHaveBeenCalled();+ });+ });});diff --git a/server/services/appQualitySchedule.js b/server/services/appQualitySchedule.jsnew file mode 100644index 0000000000..c045453b11--- /dev/null+++ b/server/services/appQualitySchedule.js@@ -0,0 +1,302 @@+/**+ * One-form scheduling of a managed app's quality audits.+ *+ * Three questions the Quality tab's schedule form needs answered, and the+ * write that acts on them:+ *+ * 1. WHICH audits are worth running here — an app with no user interface+ * should not burn a weekly provider call on an accessibility audit.+ * 2. WHEN is already spoken for — the app's own release job, its reconcile+ * drains, and every other cron-scheduled task, so a newly planned audit+ * does not run inside a release window.+ * 3. WHAT does the resulting week look like — computed by the pure planner in+ * `lib/qualitySchedulePlan.js`, previewed before anything is saved.+ *+ * The write itself goes through `updateAppTaskTypeOverrides`, the same path the+ * Schedule page uses, so a plan produces ordinary per-app overrides a user can+ * afterwards edit or delete one at a time.+ */++import { readdir } from 'fs/promises';+import { execGit } from '../lib/execGit.js';+import { query } from '../lib/db.js';+import {+ AUDIT_CAPABILITY_MISSING_REASON,+ AUDIT_DEFINITIONS,+ AUDIT_REPO_CAPABILITIES,+ AUDIT_TASK_TYPE_LIST,+ auditCapabilityRequirement,+} from '../lib/auditCatalog.js';+import {+ CLAIM_DRAIN_TASK_TYPES,+ buildBusySlots,+ planQualitySchedule,+ resolveQualityScheduleOptions,+} from '../lib/qualitySchedulePlan.js';+import { cronWeekdayHours } from '../lib/cronFields.js';+import { getAppTaskTypeOverrides, updateAppTaskTypeOverrides } from './apps.js';+import { loadSchedule } from './taskScheduleStore.js';+import { INTERVAL_TYPES, decodeIntervalType, isCronExpression } from './taskScheduleConstants.js';+import { INSTALL_WIDE_TASK_TYPES } from '../lib/taskTargetScope.js';++/** Paths that describe the repository's own shape rather than its sources. */+const VENDOR_SEGMENTS = /(^|\/)(node_modules|vendor|dist|build|out|coverage|\.venv|third_party|__pycache__)(\/|$)/;++// Keyed by AUDIT_REPO_CAPABILITIES — the catalog names the shape an audit+// requires, this table is how that shape is recognized in a checkout. The+// coverage guard below fails if the two ever disagree.+const CAPABILITY_PATTERNS = {+ ui: [/\.(jsx|tsx|vue|svelte|astro)$/i, /\.(html|htm)$/i, /\.(css|scss|sass|less)$/i, /\.storyboard$/i, /\.xib$/i],+ typescript: [/\.(ts|tsx|mts|cts)$/i, /(^|\/)tsconfig(\.\w+)?\.json$/i],+ tests: [/\.(test|spec)\.[cm]?[jt]sx?$/i, /(^|\/)tests?\//i, /(^|\/)__tests__\//i, /(^|\/)test_[^/]+\.py$/i, /[^/]+_test\.(py|go|rb)$/i, /Tests\.swift$/i],+ dependencies: [/(^|\/)package\.json$/i, /(^|\/)requirements[^/]*\.txt$/i, /(^|\/)pyproject\.toml$/i, /(^|\/)Cargo\.toml$/i, /(^|\/)go\.mod$/i, /(^|\/)Gemfile$/i, /(^|\/)composer\.json$/i, /(^|\/)Package\.swift$/i, /(^|\/)pubspec\.yaml$/i],+ api: [/(^|\/)(routes?|api|controllers|handlers|endpoints)\//i, /\.proto$/i, /(^|\/)openapi[^/]*\.(ya?ml|json)$/i, /(^|\/)swagger[^/]*\.(ya?ml|json)$/i, /(^|\/)urls\.py$/i],+};++/**+ * Repository shape changes on the scale of commits, not keystrokes, and the+ * schedule form re-previews on every control change — each of which would+ * otherwise re-run `git ls-files` over the whole checkout. A short TTL keeps+ * the form responsive while still noticing a repo that gained a test suite.+ */+const CAPABILITY_TTL_MS = 60 * 1000;+const capabilityCache = new Map();++const missingPatterns = AUDIT_REPO_CAPABILITIES.filter(capability => !CAPABILITY_PATTERNS[capability]);+if (missingPatterns.length) {+ throw new Error(`No repository detection for audit capability: ${missingPatterns.join(', ')}`);+}++/**+ * List the repository's tracked files. `git ls-files` is the cheap, honest+ * inventory — it already excludes ignored build output and dependency trees,+ * which a directory walk would have to re-derive. A non-repository (or a git+ * failure) falls back to the top two directory levels, enough to see a+ * `package.json` and a `client/` without walking a whole tree.+ */+async function listRepoFiles(repoPath) {+ const result = await execGit(['ls-files'], repoPath, { timeout: 20000, ignoreExitCode: true })+ .catch(() => null);+ if (result?.exitCode === 0 && result.stdout.trim()) {+ return result.stdout.split('\n').map(line => line.trim()).filter(Boolean);+ }+ const entries = await readdir(repoPath, { withFileTypes: true }).catch(() => []);+ const files = [];+ for (const entry of entries) {+ if (entry.name.startsWith('.')) continue;+ if (!entry.isDirectory()) { files.push(entry.name); continue; }+ const nested = await readdir(`${repoPath}/${entry.name}`, { withFileTypes: true }).catch(() => []);+ files.push(entry.name + '/');+ for (const child of nested) files.push(`${entry.name}/${child.name}${child.isDirectory() ? '/' : ''}`);+ }+ return files;+}++/**+ * Which repository shapes this app has, from its tracked files.+ *+ * `detected: false` on every capability with `scanned: 0` means the repository+ * could not be read at all — a caller must treat that as "unknown", never as+ * "this app has no tests", which is why the count is returned alongside.+ *+ * @param {object} app - The managed app record (needs `repoPath`, optionally `uiPort`)+ * @returns {Promise<{ capabilities: Record<string, boolean>, scanned: number }>}+ */+export async function detectRepoCapabilities(app) {+ const capabilities = Object.fromEntries(AUDIT_REPO_CAPABILITIES.map(key => [key, false]));+ if (!app?.repoPath) return { capabilities, scanned: 0 };+ const cached = capabilityCache.get(app.repoPath);+ if (cached && Date.now() - cached.at < CAPABILITY_TTL_MS) return cached.value;++ const files = (await listRepoFiles(app.repoPath)).filter(path => !VENDOR_SEGMENTS.test(path));+ for (const path of files) {+ for (const [capability, patterns] of Object.entries(CAPABILITY_PATTERNS)) {+ if (!capabilities[capability] && patterns.some(pattern => pattern.test(path))) capabilities[capability] = true;+ }+ }+ // A port the app serves a UI on is direct evidence, whatever the sources look+ // like (a compiled or templated front end leaves no `.jsx` behind).+ if (app.uiPort) capabilities.ui = true;+ const value = { capabilities, scanned: files.length };+ capabilityCache.set(app.repoPath, { at: Date.now(), value });+ return value;+}++/**+ * Categories a past audit of THIS app reported as not applicable. The auditing+ * agent inspected the repository, so its ruling outranks the path heuristics+ * above. Read directly rather than through `enrichAppsWithQuality`, which also+ * fans out to sync peers — a peer's view of a different checkout is not+ * evidence about this one.+ */+async function loadNotApplicableCategories(appId) {+ const result = await query(+ `SELECT DISTINCT ON (category) category, report FROM app_quality_measurements+ WHERE app_id = $1 ORDER BY category, assessed_at DESC, agent_id DESC`,+ [appId]+ ).catch(() => null);+ if (!result) return new Set();+ return new Set(result.rows.filter(row => row.report?.coverage === 'not-applicable').map(row => row.category));+}++/**+ * Every quality check with its applicability verdict and current schedule.+ *+ * Applicability is ADVISORY: the form pre-selects what applies and explains+ * what it skipped, but a user who disagrees can still select a skipped check.+ *+ * @param {object} app - The managed app record+ * @returns {Promise<{ checks: object[], capabilities: object, scanned: number }>}+ */+export async function resolveQualityChecks(app) {+ const [{ capabilities, scanned }, notApplicable] = await Promise.all([+ detectRepoCapabilities(app),+ loadNotApplicableCategories(app.id),+ ]);+ // With nothing scanned every capability reads false for want of evidence, so+ // gating on them would deselect most of the catalog over an unreadable path.+ const repoReadable = scanned > 0;++ const checks = AUDIT_TASK_TYPE_LIST.map(taskType => {+ const requirement = auditCapabilityRequirement(taskType);+ let applicable = true;+ let reason = null;+ if (notApplicable.has(taskType)) {+ applicable = false;+ reason = 'a previous audit reported this category as not applicable here';+ } else if (requirement && repoReadable && !capabilities[requirement]) {+ applicable = false;+ reason = AUDIT_CAPABILITY_MISSING_REASON[requirement];+ }+ return { taskType, label: AUDIT_DEFINITIONS[taskType].label, applicable, reason };+ });+ return { checks, capabilities, scanned };+}++/**+ * The weekday/hour cells already claimed by something else on this app.+ *+ * Reads cadence the way `shouldRunTask` does: a task runs for this app when it+ * is enabled here (or is install-wide), and a per-app `interval` REPLACES the+ * global cadence rather than adding to it. A retired named cadence written by+ * an older install is decoded first, so a `weekly` override occupies its hour+ * instead of being read as "no cadence" and scheduled straight over.+ *+ * The types the plan is about to rewrite are excluded — otherwise re-running+ * the form would treat last week's plan as an obstacle to this week's.+ *+ * @param {object} app - The managed app record+ * @param {{ ignoreTaskTypes?: string[] }} [options]+ * @returns {Promise<object[]>} One entry per occupying cron: `{ taskType, cron, origin, days, hours }`+ */+export async function collectBusyOccupancies(app, { ignoreTaskTypes = [] } = {}) {+ const ignore = new Set(ignoreTaskTypes);+ const [schedule, overrides] = await Promise.all([loadSchedule(), getAppTaskTypeOverrides(app.id)]);+ const sources = [];++ const add = (taskType, cron, origin) => {+ if (!isCronExpression(cron)) return;+ const occupancy = cronWeekdayHours(cron);+ if (occupancy) sources.push({ taskType, cron, origin, ...occupancy });+ };++ for (const [taskType, config] of Object.entries(schedule.tasks || {})) {+ const override = overrides[taskType];+ if (ignore.has(taskType) || config.enabled === false) continue;+ if (!INSTALL_WIDE_TASK_TYPES.has(taskType) && override?.enabled !== true) continue;++ const perApp = override?.interval+ ? decodeIntervalType(override.interval, { intervalMs: override.intervalMs })+ : null;+ if (perApp) {+ if (perApp.type === INTERVAL_TYPES.CRON) add(taskType, perApp.cronExpression, 'app');+ } else if (config.type === INTERVAL_TYPES.CRON) {+ add(taskType, config.cronExpression, 'global');+ }+ // `perpetual` is a task-level global property: a per-app row overrides the+ // cadence only, so the recheck window applies either way.+ if (config.perpetual) add(taskType, config.recheckCron, 'recheck');+ }+ return sources;+}++/**+ * Plan the week for one app without writing anything.+ *+ * Returns the whole payload the three quality-schedule endpoints serve, so the+ * route layer adds nothing of its own and cannot drift from the service.+ *+ * @param {object} app - The managed app record+ * @param {object} [options] - Form options; `taskTypes` defaults to every applicable check+ * @returns {Promise<object>} `{ appId, appName, plan, checks, capabilities, scanned, busySources, claimTaskTypes }`+ */+export async function buildQualitySchedulePlan(app, options = {}) {+ const settings = resolveQualityScheduleOptions(options);+ // Independent: the repository scan and the schedule read share no input.+ const [{ checks, capabilities, scanned }, sources] = await Promise.all([+ resolveQualityChecks(app),+ collectBusyOccupancies(app, { ignoreTaskTypes: [...AUDIT_TASK_TYPE_LIST, ...CLAIM_DRAIN_TASK_TYPES] }),+ ]);++ const requested = Array.isArray(options.taskTypes) ? options.taskTypes : null;+ const taskTypes = requested ?? checks.filter(check => check.applicable).map(check => check.taskType);++ const plan = planQualitySchedule({+ taskTypes,+ fileIssuesByType: options.fileIssuesByType || {},+ busy: buildBusySlots(sources, settings),+ options: settings,+ });+ return {+ appId: app.id,+ appName: app.name,+ plan,+ checks,+ capabilities,+ scanned,+ // The drain types the form may choose between, so adding one here does not+ // also need a client edit.+ claimTaskTypes: CLAIM_DRAIN_TASK_TYPES,+ // What the plan worked around, so the preview can say WHY 03:00 is missing.+ busySources: sources.map(({ taskType, cron, origin }) => ({ taskType, cron, origin })),+ };+}++/**+ * Apply a plan: one per-app override per scheduled check, plus the claim drain.+ *+ * Checks the user left out are DISABLED rather than left alone — the form is+ * the whole picture of the app's quality cadence, so an audit dropped from the+ * selection must stop running. Only the audit types and the claim drain are+ * touched; every other task type the app has configured is left exactly as it is.+ *+ * @param {object} app - The managed app record+ * @param {object} [options] - The same option bag `buildQualitySchedulePlan` takes+ * @returns {Promise<object>} The built plan plus `{ applied, disabled }` counts+ */+export async function applyQualitySchedulePlan(app, options = {}) {+ const built = await buildQualitySchedulePlan(app, options);+ const { plan } = built;+ const scheduled = new Map(plan.slots.map(slot => [slot.taskType, slot]));+ const existing = await getAppTaskTypeOverrides(app.id);++ const patches = {};+ for (const taskType of AUDIT_TASK_TYPE_LIST) {+ const slot = scheduled.get(taskType);+ patches[taskType] = slot+ // Merge rather than replace: the stored metadata may carry a provider+ // pin or reviewer choice the user set on the Schedule page, and the plan+ // only has an opinion about the delivery mode.+ ? { enabled: true, interval: slot.cron, taskMetadata: { ...existing[taskType]?.taskMetadata, fileIssues: slot.fileIssues } }+ // Clearing the interval alongside `enabled: false` keeps a stale cron+ // from reviving on the next manual enable.+ : { enabled: false, interval: null };+ }+ if (plan.claim) patches[plan.claim.taskType] = { enabled: true, interval: plan.claim.cron };++ await updateAppTaskTypeOverrides(app.id, patches);+ const applied = plan.slots.length + (plan.claim ? 1 : 0);+ const disabled = AUDIT_TASK_TYPE_LIST.length - plan.slots.length;+ console.log(`📅 Planned ${applied} quality schedule entries for ${app.name} (${disabled} checks disabled)`);+ return { ...built, applied, disabled };+}diff --git a/server/services/appQualitySchedule.test.js b/server/services/appQualitySchedule.test.jsnew file mode 100644index 0000000000..a29b2e5b43--- /dev/null+++ b/server/services/appQualitySchedule.test.js@@ -0,0 +1,189 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++const execGit = vi.fn();+const query = vi.fn();+const getAppTaskTypeOverrides = vi.fn();+const updateAppTaskTypeOverrides = vi.fn();+const loadSchedule = vi.fn();++vi.mock('../lib/execGit.js', () => ({ execGit: (...args) => execGit(...args) }));+vi.mock('../lib/db.js', () => ({ query: (...args) => query(...args) }));+vi.mock('./apps.js', () => ({+ getAppTaskTypeOverrides: (...args) => getAppTaskTypeOverrides(...args),+ updateAppTaskTypeOverrides: (...args) => updateAppTaskTypeOverrides(...args),+}));+vi.mock('./taskScheduleStore.js', () => ({ loadSchedule: (...args) => loadSchedule(...args) }));++const {+ applyQualitySchedulePlan,+ buildQualitySchedulePlan,+ collectBusyOccupancies,+ resolveQualityChecks,+} = await import('./appQualitySchedule.js');++// Each app gets its own repoPath so the module's capability cache — keyed by+// path — never carries one test's repository shape into the next.+let repoCounter = 0;+const appWith = (files, extra = {}) => {+ repoCounter += 1;+ execGit.mockResolvedValue({ exitCode: 0, stdout: files.join('\n'), stderr: '' });+ return { id: `app-${repoCounter}`, name: `App ${repoCounter}`, repoPath: `/repos/app-${repoCounter}`, ...extra };+};++const NODE_SERVICE = ['package.json', 'server/routes/things.js', 'server/services/things.js', 'server/services/things.test.js'];++beforeEach(() => {+ vi.clearAllMocks();+ query.mockResolvedValue({ rows: [] });+ getAppTaskTypeOverrides.mockResolvedValue({});+ updateAppTaskTypeOverrides.mockResolvedValue({});+ loadSchedule.mockResolvedValue({ tasks: {} });+ vi.spyOn(console, 'log').mockImplementation(() => {});+});++describe('resolveQualityChecks', () => {+ it('skips the UI audits for a repository that ships no interface', async () => {+ const { checks, capabilities } = await resolveQualityChecks(appWith(NODE_SERVICE));+ expect(capabilities.ui).toBe(false);+ const byType = Object.fromEntries(checks.map(check => [check.taskType, check]));+ expect(byType.accessibility.applicable).toBe(false);+ expect(byType.accessibility.reason).toMatch(/no user interface/);+ expect(byType['mobile-responsive'].applicable).toBe(false);+ // A server audit with no repo-shape requirement still applies.+ expect(byType.security.applicable).toBe(true);+ expect(byType['api-contract'].applicable).toBe(true);+ });++ it('serves only the fields the form renders', async () => {+ const { checks } = await resolveQualityChecks(appWith(NODE_SERVICE));+ expect(Object.keys(checks[0]).sort()).toEqual(['applicable', 'label', 'reason', 'taskType']);+ });++ it('keeps the UI audits when the app serves a UI port but compiles its front end away', async () => {+ const { checks } = await resolveQualityChecks(appWith(NODE_SERVICE, { uiPort: 5555 }));+ expect(checks.find(check => check.taskType === 'accessibility').applicable).toBe(true);+ });++ it('separates the two test lenses: coverage always applies, quality needs tests to assess', async () => {+ const { checks } = await resolveQualityChecks(appWith(['package.json', 'src/index.js']));+ const byType = Object.fromEntries(checks.map(check => [check.taskType, check]));+ expect(byType['test-coverage'].applicable).toBe(true);+ expect(byType['better-test-quality'].applicable).toBe(false);+ });++ it('lets an auditing agent that reported not-applicable overrule the path heuristics', async () => {+ query.mockResolvedValue({ rows: [{ category: 'security', report: { coverage: 'not-applicable' } }] });+ const { checks } = await resolveQualityChecks(appWith(NODE_SERVICE));+ const security = checks.find(check => check.taskType === 'security');+ expect(security.applicable).toBe(false);+ expect(security.reason).toMatch(/previous audit/);+ });++ it('offers every check when the repository could not be scanned at all', async () => {+ execGit.mockResolvedValue({ exitCode: 128, stdout: '', stderr: 'not a git repository' });+ const { checks, scanned } = await resolveQualityChecks({ id: 'ghost', name: 'Ghost', repoPath: '/repos/missing' });+ expect(scanned).toBe(0);+ // Absent evidence must not read as "this repo has no UI" — that would+ // silently deselect most of the catalog over an unreadable path.+ expect(checks.every(check => check.applicable)).toBe(true);+ });+});++describe('collectBusyOccupancies', () => {+ it('collects the global cadence and the perpetual recheck of types enabled here', async () => {+ loadSchedule.mockResolvedValue({+ tasks: {+ 'release-check': { type: 'cron', enabled: true, cronExpression: '30 3 * * *' },+ 'branch-reconcile': { type: 'on-demand', enabled: true, perpetual: true, recheckCron: '0 3 * * *' },+ 'pr-reviewer': { type: 'cron', enabled: true, cronExpression: '0 8 * * *' },+ },+ });+ getAppTaskTypeOverrides.mockResolvedValue({+ 'release-check': { enabled: true },+ 'branch-reconcile': { enabled: true },+ // Enabled for the install but not for this app — its window is somebody+ // else's problem, so it must not cost this app an hour.+ 'pr-reviewer': { enabled: false },+ });+ const sources = await collectBusyOccupancies({ id: 'a' });+ expect(sources.map(source => source.cron).sort()).toEqual(['0 3 * * *', '30 3 * * *']);+ });++ it('lets a per-app cadence REPLACE the global one, the way the scheduler reads it', async () => {+ loadSchedule.mockResolvedValue({ tasks: { 'release-check': { type: 'cron', enabled: true, cronExpression: '30 3 * * *' } } });+ getAppTaskTypeOverrides.mockResolvedValue({ 'release-check': { enabled: true, interval: '0 20 * * 1' } });+ const sources = await collectBusyOccupancies({ id: 'a' });+ // Blocking 03:00 as well would cost the plan four hours a day that this app+ // never runs anything in.+ expect(sources.map(source => source.cron)).toEqual(['0 20 * * 1']);+ expect(sources[0].origin).toBe('app');+ });++ it('decodes a retired named cadence rather than reading it as no cadence', async () => {+ loadSchedule.mockResolvedValue({ tasks: { 'release-check': { type: 'cron', enabled: true, cronExpression: '30 3 * * *' } } });+ getAppTaskTypeOverrides.mockResolvedValue({ 'release-check': { enabled: true, interval: 'weekly' } });+ const sources = await collectBusyOccupancies({ id: 'a' });+ // An override written by an older install still occupies its hour; treating+ // it as unparseable would schedule an audit straight over the release.+ expect(sources).toHaveLength(1);+ expect(sources[0].hours).toEqual([7]);+ });++ it('ignores the task types the plan is about to rewrite', async () => {+ loadSchedule.mockResolvedValue({ tasks: { security: { type: 'cron', enabled: true, cronExpression: '0 9 * * 1' } } });+ getAppTaskTypeOverrides.mockResolvedValue({ security: { enabled: true, interval: '0 9 * * 1' } });+ expect(await collectBusyOccupancies({ id: 'a' }, { ignoreTaskTypes: ['security'] })).toEqual([]);+ });+});++describe('buildQualitySchedulePlan', () => {+ it('plans only the applicable checks and works around the app release window', async () => {+ loadSchedule.mockResolvedValue({ tasks: { 'release-check': { type: 'cron', enabled: true, cronExpression: '30 3 * * *' } } });+ getAppTaskTypeOverrides.mockResolvedValue({ 'release-check': { enabled: true } });+ const app = appWith(NODE_SERVICE);+ const built = await buildQualitySchedulePlan(app);+ expect(built.plan.slots.map(slot => slot.taskType)).not.toContain('accessibility');+ expect(built.plan.slots.map(slot => slot.taskType)).toContain('security');+ for (const slot of built.plan.slots) expect([2, 3, 4, 5]).not.toContain(slot.hour);+ // The service owns the whole endpoint payload, so the route adds nothing.+ expect(built).toMatchObject({ appId: app.id, appName: app.name, claimTaskTypes: expect.arrayContaining(['claim-work']) });+ expect(built.busySources).toEqual([{ taskType: 'release-check', cron: '30 3 * * *', origin: 'global' }]);+ });++ it('plans exactly the checks the caller named, applicable or not', async () => {+ const { plan } = await buildQualitySchedulePlan(appWith(NODE_SERVICE), { taskTypes: ['accessibility', 'security'] });+ expect(plan.slots.map(slot => slot.taskType).sort()).toEqual(['accessibility', 'security']);+ });+});++describe('applyQualitySchedulePlan', () => {+ it('writes the whole cadence in one patch: planned checks on, unplanned ones off', async () => {+ const app = appWith(NODE_SERVICE);+ const result = await applyQualitySchedulePlan(app, { taskTypes: ['security'] });++ expect(updateAppTaskTypeOverrides).toHaveBeenCalledTimes(1);+ const [appId, patches] = updateAppTaskTypeOverrides.mock.calls[0];+ expect(appId).toBe(app.id);+ expect(patches.security).toEqual({ enabled: true, interval: expect.stringMatching(/^0 \d+ \* \* \d$/), taskMetadata: { fileIssues: true } });+ // A check dropped from the selection must stop running, and its stale cron+ // must not survive to revive on a later manual enable.+ expect(patches.ux).toEqual({ enabled: false, interval: null });+ expect(patches['claim-work'].enabled).toBe(true);+ expect(result.applied).toBe(2);+ });++ it('keeps metadata the user set elsewhere and only overwrites the delivery mode', async () => {+ getAppTaskTypeOverrides.mockResolvedValue({ security: { enabled: true, taskMetadata: { fileIssues: true, reviewLoop: true } } });+ const app = appWith(NODE_SERVICE);+ await applyQualitySchedulePlan(app, { taskTypes: ['security'], fileIssuesByType: { security: false } });+ const [, patches] = updateAppTaskTypeOverrides.mock.calls[0];+ expect(patches.security.taskMetadata).toEqual({ fileIssues: false, reviewLoop: true });+ });++ it('writes no claim drain when every selected check implements its own fixes', async () => {+ const app = appWith(NODE_SERVICE);+ await applyQualitySchedulePlan(app, { taskTypes: ['security'], fileIssues: false });+ const [, patches] = updateAppTaskTypeOverrides.mock.calls[0];+ expect(patches['claim-work']).toBeUndefined();+ });+});diff --git a/server/services/apps.js b/server/services/apps.jsindex 153dcce95d..a143938a24 100644--- a/server/services/apps.js+++ b/server/services/apps.js@@ -667,19 +667,16 @@ export async function getAppTaskTypeIntervalMs(appId, taskType) {}/**- * Update a task type override for a specific app (enable/disable + optional interval)- */-export async function updateAppTaskTypeOverride(id, taskType, { enabled, interval, intervalMs, providerId, model, taskMetadata } = {}) {- const data = await loadApps();- if (!data.apps[id]) return null;-- // Migrate legacy format if needed- await migrateTaskTypeOverrides(id);-- const overrides = data.apps[id].taskTypeOverrides || {};- const existing = overrides[taskType] || {};-- const updated = { ...existing };+ * Merge one override patch into an app's stored overrides, in place.+ *+ * Extracted so a single-type edit and a whole-plan write (the Quality tab's+ * schedule form rewrites ~26 types at once) apply IDENTICAL field semantics —+ * the alternative was a second copy of the absent-vs-null ladder below, which+ * is exactly where "cleared back to inherit" and "left alone" drift apart.+ * Returns the watcher state keys the caller must reset for a disable.+ */+function mergeTaskTypeOverride(overrides, taskType, { enabled, interval, intervalMs, providerId, model, taskMetadata } = {}) {+ const updated = { ...(overrides[taskType] || {}) };if (typeof enabled === 'boolean') updated.enabled = enabled;if (interval !== undefined) updated.interval = interval;// intervalMs / providerId / model are the per-app scheduling fields for@@ -714,19 +711,57 @@ export async function updateAppTaskTypeOverride(id, taskType, { enabled, interva} else {overrides[taskType] = updated;}+}- // Disabling pr-watcher clears its high-water mark AND its execution cooldown- // so a later re-enable baselines promptly (like first enable) instead of- // dispatching the backlog of PRs opened while it was off. See prWatcher.js /- // cosTaskGenerator.js.- if (taskType === 'pr-watcher' && enabled === false) {- delete data.apps[id].prWatcherState;+/**+ * Disabling pr-watcher/issue-watcher clears the high-water mark AND the+ * execution cooldown so a later re-enable baselines promptly (like first+ * enable) instead of dispatching the backlog opened while it was off. See+ * prWatcher.js / cosTaskGenerator.js.+ */+async function resetWatcherStateOnDisable(appRecord, id, taskType, enabled) {+ if (enabled !== false) return;+ if (taskType === 'pr-watcher') {+ delete appRecord.prWatcherState;await resetWatcherCooldown('pr-watcher', id);}- if (taskType === 'issue-watcher' && enabled === false) {- delete data.apps[id].issueWatcherState;+ if (taskType === 'issue-watcher') {+ delete appRecord.issueWatcherState;await resetWatcherCooldown('issue-watcher', id);}+}++/**+ * Update a task type override for a specific app (enable/disable + optional interval)+ */+export async function updateAppTaskTypeOverride(id, taskType, patch = {}) {+ return updateAppTaskTypeOverrides(id, { [taskType]: patch });+}++/**+ * Apply several task-type override patches to one app in a single write.+ *+ * `patches` maps task type → the same patch object `updateAppTaskTypeOverride`+ * takes. One load/save for the whole set: the Quality schedule form touches+ * every audit type at once, and doing that as ~26 sequential read-modify-writes+ * of `apps.json` is both slow and a window in which a partial plan is live.+ *+ * @param {string} id - App id+ * @param {Record<string, object>} patches - Task type → override patch+ * @returns {Promise<object|null>} The updated app record, or null when unknown+ */+export async function updateAppTaskTypeOverrides(id, patches = {}) {+ const data = await loadApps();+ if (!data.apps[id]) return null;++ // Migrate legacy format if needed+ await migrateTaskTypeOverrides(id);++ const overrides = data.apps[id].taskTypeOverrides || {};+ for (const [taskType, patch] of Object.entries(patches)) {+ mergeTaskTypeOverride(overrides, taskType, patch);+ await resetWatcherStateOnDisable(data.apps[id], id, taskType, patch?.enabled);+ }data.apps[id].taskTypeOverrides = overrides;delete data.apps[id].disabledTaskTypes; // Remove legacy field@@ -805,24 +840,8 @@ export async function bulkUpdateAppTaskTypeOverride(taskType, { enabled } = {})for (const id of activeIds) {const overrides = data.apps[id].taskTypeOverrides || {};- const existing = overrides[taskType] || {};- const updated = { ...existing, enabled };-- if (updated.enabled === undefined && !updated.interval && !updated.taskMetadata) {- delete overrides[taskType];- } else {- overrides[taskType] = updated;- }-- // See updateAppTaskTypeOverride: clear pr-watcher's mark + cooldown on disable.- if (taskType === 'pr-watcher' && enabled === false) {- delete data.apps[id].prWatcherState;- await resetWatcherCooldown('pr-watcher', id);- }- if (taskType === 'issue-watcher' && enabled === false) {- delete data.apps[id].issueWatcherState;- await resetWatcherCooldown('issue-watcher', id);- }+ mergeTaskTypeOverride(overrides, taskType, { enabled });+ await resetWatcherStateOnDisable(data.apps[id], id, taskType, enabled);data.apps[id].taskTypeOverrides = overrides;delete data.apps[id].disabledTaskTypes;@@ -850,13 +869,10 @@ export async function toggleAllAppTaskTypes(id, enabled) {overrides[taskType] = { ...existing, enabled };}- // Disabling everything disables pr-watcher too — clear its mark + cooldown so- // a later re-enable baselines promptly. See updateAppTaskTypeOverride.- if (enabled === false) {- delete data.apps[id].prWatcherState;- delete data.apps[id].issueWatcherState;- await resetWatcherCooldown('pr-watcher', id);- await resetWatcherCooldown('issue-watcher', id);+ // Disabling everything disables the watchers too — same reset as any other+ // path that moves their gate, so a later re-enable baselines promptly.+ for (const watcher of ['pr-watcher', 'issue-watcher']) {+ await resetWatcherStateOnDisable(data.apps[id], id, watcher, enabled);}data.apps[id].taskTypeOverrides = overrides;diff --git a/server/services/eventScheduler.js b/server/services/eventScheduler.jsindex adb437c627..128860421e 100644--- a/server/services/eventScheduler.js+++ b/server/services/eventScheduler.js@@ -12,6 +12,9 @@ import { recurrenceRuleSchema } from '../lib/recurrenceValidation.js'// cron editor, so an expression the routes accept is exactly the set this// walker can search (#6634).import { isValidCronField, CRON_FIELD_BOUNDS, CRON_FIELD_NAMES } from '../lib/cronValidation.js'+// Field MATCHING is shared with the quality-schedule planner, so an hour the+// planner reads as free is exactly an hour this walker will not fire in.+import { matchesCronField } from '../lib/cronFields.js'// Maximum safe setTimeout value (2^31 - 1 ms, ~24.8 days)const MAX_TIMEOUT = 2147483647@@ -314,47 +317,6 @@ function parseRecurrenceToNextRun(rule, from = new Date(), timezone = 'UTC', untreturn findNextRecurrenceCandidate(normalized, anchor, from, timezone, maxDate)}-/**- * Check if a value matches a cron field expression- * @param {number} value - Current value- * @param {string} expr - Cron field expression- * @returns {boolean} - True if matches- */-function matchesCronField(value, expr, fieldMin = 0) {- if (expr === '*') return true-- // Handle comma-separated values- if (expr.includes(',')) {- return expr.split(',').some(part => matchesCronField(value, part.trim(), fieldMin))- }-- // Handle step values first (e.g., */5, 0/10, 1-5/2)- if (expr.includes('/')) {- const [rangeExpr, step] = expr.split('/')- const stepNum = Number(step)- let startNum = fieldMin- let endNum = Infinity- if (rangeExpr === '*') {- startNum = fieldMin- } else if (rangeExpr.includes('-')) {- const [s, e] = rangeExpr.split('-').map(Number)- startNum = s- endNum = e- } else {- startNum = Number(rangeExpr)- }- return value >= startNum && value <= endNum && (value - startNum) % stepNum === 0- }-- // Handle ranges (e.g., 1-5)- if (expr.includes('-')) {- const [start, end] = expr.split('-').map(Number)- return value >= start && value <= end- }-- // Direct value match- return Number(expr) === value-}/*** Create a timeout-safe timer