Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix eight defects the pre-PR review found in the quality-schedule planner
[._.]/ Adam Eivy721c5648c04f
diff --git a/client/src/components/apps/AppQualityScheduleForm.jsx b/client/src/components/apps/AppQualityScheduleForm.jsxindex 971a56387a..cf1fa5d47f 100644--- a/client/src/components/apps/AppQualityScheduleForm.jsx+++ b/client/src/components/apps/AppQualityScheduleForm.jsx@@ -1,4 +1,4 @@-import { useCallback, useEffect, useRef, useState } from 'react';+import { useCallback, useEffect, useId, useRef, useState } from 'react';import { Link } from 'react-router';import { WEEKDAYS } from '../../utils/cronHelpers';import { applyAppQualitySchedule, getAppQualitySchedule, previewAppQualitySchedule } from '../../services/apiApps';@@ -35,12 +35,20 @@ const selectClass = 'block w-full bg-port-bg border border-port-border rounded p* scheduled jobs already occupy. Nothing is written until Apply.*/export default function AppQualityScheduleForm({ app }) {+ // Scopes the per-check checkbox ids, which are otherwise page-global.+ const fieldPrefix = useId();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);+ // Bumping this re-runs the load effect, which is how the failure state retries.+ const [reloadToken, setReloadToken] = useState(0);+ // True while the form describes something the rendered plan does not yet.+ // Apply gates on it: the grid and the button label read the LAST plan, so+ // applying mid-debounce would write a selection the user never saw previewed.+ const [planStale, setPlanStale] = useState(false);// 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);@@ -50,6 +58,18 @@ export default function AppQualityScheduleForm({ app }) {useEffect(() => {let live = true;+ // Reset first: a different app must never render the previous app's plan,+ // nor let Apply write the previous app's selection onto this one. The+ // parent currently remounts us on `app.id`, but that invariant lives two+ // files away — the guard belongs here (client/src/AGENTS.md).+ setData(null);+ setSelected(null);+ setOptions(null);+ setModes({});+ setError('');+ setPlanStale(false);+ untouched.current = true;+ revision.current += 1;getAppQualitySchedule(app.id).then(response => {if (!live) return;@@ -60,7 +80,7 @@ export default function AppQualityScheduleForm({ app }) {}).catch(err => live && setError(err.message || 'Could not load the quality schedule'));return () => { live = false; };- }, [app.id]);+ }, [app.id, reloadToken]);// `options` always comes from the server's own resolved bag, so every field// the schema accepts is already present — no client-side default ladder.@@ -73,10 +93,22 @@ export default function AppQualityScheduleForm({ app }) {if (!selected || !options) return undefined;if (untouched.current) { untouched.current = false; return undefined; }const mine = ++revision.current;+ setPlanStale(true);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'); });+ .then(response => {+ if (mine !== revision.current) return;+ setData(response);+ setError('');+ setPlanStale(false);+ })+ .catch(err => {+ if (mine !== revision.current) return;+ setError(err.message || 'Could not re-plan the schedule');+ // Still stale — the shown plan does not describe the form, and Apply+ // must stay shut rather than write something never previewed.+ setPlanStale(true);+ });}, PREVIEW_DEBOUNCE_MS);return () => clearTimeout(timer);// `data` is deliberately NOT a dependency — this effect writes it, so@@ -96,26 +128,43 @@ export default function AppQualityScheduleForm({ app }) {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>+ <button type="button" onClick={() => { setError(''); setReloadToken(token => token + 1); }}+ className="mt-2 text-xs text-port-accent hover:underline">Try again</button></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 { plan, checks, capabilities, scanned, complete, 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 }));+ // The window cannot wrap past midnight, so moving one end past the other+ // drags the other along — otherwise the server silently collapses the window+ // and the two selects go on describing one it never planned against.+ const setWindow = (key, hour) => setOptions(previous => ({+ ...previous,+ windowStartHour: key === 'windowStartHour' ? hour : Math.min(previous.windowStartHour, hour),+ windowEndHour: key === 'windowEndHour' ? hour : Math.max(previous.windowEndHour, hour),+ }));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);+ const daysUsed = byDay.length;+ // The realized gap, which is not the requested offset whenever a busy hour+ // pushed the drain later. Stating the request here would be a lie exactly+ // when the planner did its job.+ const claimGap = plan.claim?.gapHours?.length+ ? (plan.claim.gapHours.length === 1 ? `${plan.claim.gapHours[0]}h` : `${plan.claim.gapHours[0]}–${plan.claim.gapHours.at(-1)}h`)+ : null;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+ Spreads the selected checks over {daysUsed === 7 ? 'all seven days' : `${daysUsed} day${daysUsed === 1 ? '' : 's'}`} and picks the hours itself, avoiding the windows this app’s otherscheduled 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)'}+ {complete ? '' : ' (the repository could not be fully scanned, so every check is offered)'}{skipped.length > 0 && `; ${skipped.length} skipped`}. Nothing is saved until you press Apply.</p>@@ -123,27 +172,38 @@ export default function AppQualityScheduleForm({ app }) {<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>)}+ <option value="">Spread evenly over the week ({plan.checksPerDay} a day)</option>+ {/* Below the floor the plan needs, the planner raises the number and+ says so; offering those values as if they took effect would lie. */}+ {[1, 2, 3, 4, 5, 6].filter(count => count >= plan.checksPerDay).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))}>+ onChange={event => setWindow('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))}>+ onChange={event => setWindow('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'); }}>+ otherwise a row the user never touched would keep the old mode.+ "Each check's default" is the shipped answer: 11 audits declare+ `defaultFileIssues: false` in the catalog, and forcing them all to+ file issues would silently contradict every other dispatch path. */}+ <select className={selectClass} value={options.fileIssues === null ? 'default' : options.fileIssues ? 'file' : 'fix'} disabled={busy}+ onChange={event => {+ setModes({});+ setOption('fileIssues', event.target.value === 'default' ? null : event.target.value === 'file');+ }}>+ <option value="default">Each check’s default</option><option value="file">Plan and file issues</option><option value="fix">Implement the fix</option></select>@@ -176,14 +236,14 @@ export default function AppQualityScheduleForm({ app }) {<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}+ <input type="checkbox" id={`${fieldPrefix}-${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'}>+ <label htmlFor={`${fieldPrefix}-${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'}+ value={(modes[check.taskType] ?? plan.slots.find(slot => slot.taskType === check.taskType)?.fileIssues ?? true) ? 'file' : 'fix'}onChange={event => setMode(check.taskType, event.target.value === 'file')}><option value="file">file issues</option><option value="fix">implement</option>@@ -192,7 +252,7 @@ export default function AppQualityScheduleForm({ app }) {{check.reason && <span className="text-gray-500">— {check.reason}</span>}</li>))}</ul>- {scanned > 0 && <p className="mt-2">+ {complete && <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>@@ -223,13 +283,13 @@ export default function AppQualityScheduleForm({ app }) {</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.+ <code>{plan.claim.taskType}</code> drains the backlog daily at {plan.claim.hours.map(hourLabel).join(', ')}{claimGap && ` — ${claimGap} 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}+ <button type="button" onClick={apply} disabled={busy || planStale || !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' : ''})`}+ {busy ? 'Applying…' : planStale ? 'Re-planning…' : `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>diff --git a/client/src/components/apps/AppQualityScheduleForm.test.jsx b/client/src/components/apps/AppQualityScheduleForm.test.jsxindex a87d2af21e..e4f80427eb 100644--- a/client/src/components/apps/AppQualityScheduleForm.test.jsx+++ b/client/src/components/apps/AppQualityScheduleForm.test.jsx@@ -14,7 +14,7 @@ import { applyAppQualitySchedule, getAppQualitySchedule, previewAppQualityScheduimport 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 OPTIONS = { checksPerDay: null, windowStartHour: 0, windowEndHour: 23, claimBetween: true, claimOffsetHours: 3, claimTaskType: 'claim-work', padBeforeHours: 1, padAfterHours: 2, fileIssues: null };const response = (overrides = {}) => ({checks: [@@ -23,12 +23,13 @@ const response = (overrides = {}) => ({],capabilities: { ui: false, tests: true },scanned: 120,+ complete: true,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 * * *' },+ claim: { taskType: 'claim-work', hours: [12], gapHours: [3], cron: '0 12 * * *' },warnings: [],options: OPTIONS,},@@ -109,6 +110,62 @@ describe('AppQualityScheduleForm', () => {await waitFor(() => expect(previewAppQualitySchedule.mock.calls.at(-1)?.[1].claimBetween).toBe(false));});+ it('will not apply a plan the user has not seen', async () => {+ renderForm();+ await screen.findByRole('heading', { name: 'Weekly quality schedule' });+ // Untick everything and click immediately: the grid and the button label+ // still describe the OLD plan, so applying here would wipe the whole+ // cadence from a button that promised to schedule it.+ fireEvent.click(screen.getByLabelText('Security'));+ expect(screen.getByRole('button', { name: /Re-planning/ })).toBeDisabled();+ expect(applyAppQualitySchedule).not.toHaveBeenCalled();+ await waitFor(() => expect(screen.getByRole('button', { name: /Apply schedule/ })).toBeEnabled());+ });++ it('re-enables Apply after a failed save instead of locking the form', async () => {+ applyAppQualitySchedule.mockRejectedValue(new Error('Disk full'));+ renderForm();+ await screen.findByRole('heading', { name: 'Weekly quality schedule' });+ fireEvent.click(screen.getByRole('button', { name: /Apply schedule/ }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Disk full'));+ expect(screen.getByRole('button', { name: /Apply schedule/ })).toBeEnabled();+ });++ it('keeps the last good plan on screen when a re-plan fails, and says so', async () => {+ renderForm();+ await screen.findByRole('heading', { name: 'Weekly quality schedule' });+ previewAppQualitySchedule.mockRejectedValue(new Error('Server unreachable'));+ fireEvent.change(screen.getByLabelText('Earliest hour'), { target: { value: '5' } });+ expect(await screen.findByRole('alert')).toHaveTextContent('Server unreachable');+ // The week the user was looking at is still there — and Apply stays shut,+ // because the form no longer describes it.+ expect(screen.getByRole('table')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /Re-planning/ })).toBeDisabled();+ });++ it('sends a per-check delivery override', async () => {+ renderForm();+ await screen.findByRole('heading', { name: 'Weekly quality schedule' });+ fireEvent.change(screen.getByLabelText('Security delivery'), { target: { value: 'fix' } });+ await waitFor(() => expect(previewAppQualitySchedule.mock.calls.at(-1)?.[1].fileIssuesByType)+ .toEqual({ security: false }));+ });++ it('clears the per-check overrides when the form-wide default changes', async () => {+ renderForm();+ await screen.findByRole('heading', { name: 'Weekly quality schedule' });+ fireEvent.change(screen.getByLabelText('Security delivery'), { target: { value: 'fix' } });+ await waitFor(() => expect(previewAppQualitySchedule).toHaveBeenCalled());+ fireEvent.change(screen.getByLabelText('Default delivery'), { target: { value: 'file' } });+ await waitFor(() => {+ const last = previewAppQualitySchedule.mock.calls.at(-1)?.[1];+ // Otherwise a row the user never touched keeps contradicting the default+ // they just picked.+ expect(last.fileIssuesByType).toEqual({});+ expect(last.fileIssues).toBe(true);+ });+ });+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.'] },@@ -117,6 +174,21 @@ describe('AppQualityScheduleForm', () => {expect(await screen.findByText(/does not fit in a 3-hour window/)).toBeInTheDocument();});+ it('does not render one app’s plan under another app’s name', async () => {+ // The parent currently remounts on app.id, but that invariant lives two+ // files away; without the reset here a switch would show app A's week and+ // let Apply write A's selection onto B.+ const { rerender } = render(<MemoryRouter><AppQualityScheduleForm app={app} /></MemoryRouter>);+ await screen.findByRole('table');+ let resolveSecond;+ getAppQualitySchedule.mockReturnValue(new Promise(resolve => { resolveSecond = resolve; }));+ rerender(<MemoryRouter><AppQualityScheduleForm app={{ id: 'other-app', name: 'Other App' }} /></MemoryRouter>);+ expect(screen.queryByRole('table')).not.toBeInTheDocument();+ expect(screen.getByRole('status')).toHaveTextContent('Loading the weekly quality schedule');+ resolveSecond(response({ plan: { ...response().plan, slots: [] } }));+ await waitFor(() => expect(getAppQualitySchedule).toHaveBeenCalledWith('other-app'));+ });+it('reports a failed load instead of rendering an empty schedule', async () => {getAppQualitySchedule.mockRejectedValue(new Error('Server unreachable'));renderForm();diff --git a/docs/API.md b/docs/API.mdindex c42e51fc18..84fcad94ed 100644--- a/docs/API.md+++ b/docs/API.md@@ -103,7 +103,7 @@ legacy list for local Apps/Dashboard views.| 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. |+| 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, and — when at least one selected check files issues — one daily cron for the issue-claim drain (one an earlier plan planted is retired when it is switched off or replaced). Other task types are untouched. |### Processes & Logsdiff --git a/docs/features/app-quality.md b/docs/features/app-quality.mdindex ca7b7a18f1..49284988b8 100644--- a/docs/features/app-quality.md+++ b/docs/features/app-quality.md@@ -95,8 +95,8 @@ and category, including a 30-day lookback to seed the selected range.## Weekly quality scheduleThe 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+every applicable audit for that app in one write, instead of hand-picking a+cron expression per audit on the Schedule page. It writes ordinary per-app task-typeoverrides, so every entry it creates stays editable there afterwards.**Which checks.** Checks are pre-selected by applicability. A category an earlier@@ -113,29 +113,42 @@ audit declares its own requirement as `requiresCapability` inand under the catalog's guard test; `server/services/appQualitySchedule.js` ownsthe detection, and throws at load if a declared capability has no way to berecognized. 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+is still listed with its reason and can be selected by hand, and a repository that could not be+fully inventoried offers every check rather than deselecting the catalog for want+of evidence — a `git ls-files` that fails falls back to a two-level listing, which+is explicitly not evidence of absence.++**When.** The selection is spread across the week — the 25 shipped checks become+four a day — ordered so each one follows the audits `AUDIT_SUGGESTED_AFTER` names+as its predecessors, and laid out in clock order within each day so that sequence+survives. Asking for more checks per day uses fewer days; asking for fewer than+the week needs is raised to the floor, with a warning saying so. The hours are+chosen, not entered: the planner collects the weekday/hour cells already occupied+by this app's other cron-scheduled work (the CoS cadence of every type enabled for+this app plus every install-wide type whether or not it is, each perpetual drain's+recheck cadence, and the app's own cron overrides — where a per-app cadence+REPLACES the global one, as `shouldRunTask` reads it), pads each by an hour beforeand two after, and places slots in the free cells nearest an even spacing. Thatis what keeps an audit out of a 03:30 nightly release window. The types the planis 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.+does not treat last week's plan as an obstacle to this week's. A window cannot+wrap past midnight; asking for one is reported rather than silently collapsed.++**Delivery and the claim drain.** Each check either files issues or implements the+fix (`taskMetadata.fileIssues`). The form defaults to **each check's own catalog+default** — 11 audits ship `defaultFileIssues: false`, and a form-wide default+would silently contradict every other dispatch path — with a form-wide override+and a per-check override above it. 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 (with the+shipped defaults, `0 3,9,15,21 * * *`), so the issues an audit files get worked+before the next audit runs. Its placement only ever moves later **in the same+day** than the check it follows — a daily cron that wrapped past midnight would+run before every audit, not after — and the slot is dropped rather than wrapped+when the day has no room left. No claim drain is scheduled when every selected+check implements its own fixes, and Apply retires a drain an earlier plan planted+when the drain is switched off or switched to another type (recognized by the+cron shape this planner emits, so a claim cadence set by hand survives).Nothing is written until **Apply**, which is also the whole picture: the selectedchecks are enabled with their planned cron and delivery mode, and audit typesdiff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.jsindex d616f1c28b..d921a77a53 100644--- a/server/lib/cosValidation.js+++ b/server/lib/cosValidation.js@@ -1301,5 +1301,7 @@ export const qualitySchedulePlanSchema = z.object({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(),+ // null = let each audit's catalog default decide (the form's default),+ // which is NOT the same as an absent key meaning the same thing by accident.+ fileIssues: z.boolean().nullable().optional(),}).strict();diff --git a/server/lib/qualitySchedulePlan.js b/server/lib/qualitySchedulePlan.jsindex 3f634cf22b..3db5e062c7 100644--- a/server/lib/qualitySchedulePlan.js+++ b/server/lib/qualitySchedulePlan.js@@ -34,8 +34,13 @@ export const DEFAULT_QUALITY_SCHEDULE_OPTIONS = Object.freeze({/** 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,+ /**+ * Form-wide delivery mode. `null` means "ask the catalog per audit"+ * (`defaultFileIssuesFor`), which is the default because 11 audits ship+ * `defaultFileIssues: false` — a form-wide `true` here would silently flip+ * every one of them to issues-only on an untouched Apply.+ */+ fileIssues: null,});const clampHour = (value, fallback) => {@@ -82,7 +87,13 @@ export function orderQualityChecks(taskTypes) {* @returns {object} The resolved bag*/export function resolveQualityScheduleOptions(options = {}) {- const settings = { ...DEFAULT_QUALITY_SCHEDULE_OPTIONS, ...options };+ // Pick, never spread: the caller hands us the whole request body, and the+ // client seeds its form from the returned bag — so an echoed `taskTypes`+ // would come back as an option and override the user's live selection.+ const picked = Object.fromEntries(Object.keys(DEFAULT_QUALITY_SCHEDULE_OPTIONS)+ .filter(key => options[key] !== undefined)+ .map(key => [key, options[key]]));+ const settings = { ...DEFAULT_QUALITY_SCHEDULE_OPTIONS, ...picked };const windowStartHour = clampHour(settings.windowStartHour, DEFAULT_QUALITY_SCHEDULE_OPTIONS.windowStartHour);return {...settings,@@ -151,13 +162,25 @@ function findFreeHour(target, { busy, taken, low, high }) {* night's backlog.*/function findFreeHourForward(target, { busy, taken }) {- for (let step = 0; step < 24; step += 1) {- const hour = (target + step) % 24;+ // Bounded at 23, never wrapping: the drain runs on a DAILY cron, so an hour+ // "after" midnight is not later than the audit — it is 21 hours earlier the+ // same day, which is exactly the backlog-ordering bug the forward search+ // exists to prevent. No free hour left in the day drops the slot instead.+ for (let hour = target; hour <= 23; hour += 1) {if (!taken.has(hour) && freeAllWeek(busy, hour)) return hour;}return null;}+/**+ * The cron shape this planner emits for a claim drain: minute zero, an explicit+ * hour list, every day. `applyQualitySchedulePlan` uses it to recognize a drain+ * a previous plan wrote, so switching the drain type — or turning it off — can+ * retire the old one without touching a claim cadence a human set by hand.+ */+export const PLANNED_CLAIM_CRON = /^0 \d{1,2}(?:,\d{1,2})* \* \* \*$/;+export const isPlannedClaimCron = (interval) => typeof interval === 'string' && PLANNED_CLAIM_CRON.test(interval.trim());+/*** Plan the week.*@@ -181,6 +204,13 @@ export function planQualitySchedule({ taskTypes = [], fileIssuesByType = {}, busconst warnings = [];const ordered = orderQualityChecks(taskTypes);+ // An overnight window (22:00 → 06:00) is the natural way to ask for one, and+ // the resolver collapses it to a single hour. Say so rather than reporting a+ // "1-hour window" the user never chose.+ if (Number.isInteger(options.windowEndHour) && options.windowEndHour < windowStartHour) {+ warnings.push(`Latest hour ${String(options.windowEndHour).padStart(2, '0')}:00 is before the earliest hour, and a window cannot wrap past midnight — planning in ${String(windowStartHour).padStart(2, '0')}:00 only.`);+ }+if (!ordered.length) {return { checksPerDay: 0, slots: [], claim: null, warnings: ['No quality checks selected.'], options: settings };}@@ -191,15 +221,17 @@ export function planQualitySchedule({ taskTypes = [], fileIssuesByType = {}, busconst requested = Number(settings.checksPerDay);const minimumPerDay = Math.ceil(ordered.length / 7);let checksPerDay = Math.max(minimumPerDay, Number.isInteger(requested) && requested > 0 ? requested : 0);+ if (Number.isInteger(requested) && requested > 0 && requested < minimumPerDay) {+ warnings.push(`${ordered.length} checks need at least ${minimumPerDay} a day to each get their own slot in a week, so ${requested} a day was raised to ${minimumPerDay}.`);+ }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.+ // One audit hour per daily slot, plus the claim hour that follows it.const taken = new Set();- const auditHours = [];- const claimHours = [];+ const placements = [];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 });@@ -208,21 +240,28 @@ export function planQualitySchedule({ taskTypes = [], fileIssuesByType = {}, busbreak;}taken.add(auditHour);- auditHours.push(auditHour);+ const placement = { auditHour, claimHour: null };+ placements.push(placement);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 });+ // work, not an audit — but never past midnight (see findFreeHourForward).+ const claimTarget = auditHour + Math.max(1, Number(settings.claimOffsetHours) || 1);+ const claimHour = claimTarget > 23 ? null : 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.');+ warnings.push('No free hour left in the day for the claim drain after every check; it will run on fewer slots.');continue;}taken.add(claimHour);- claimHours.push(claimHour);+ placement.claimHour = claimHour;}+ // Audits run in clock order within a day: `findFreeHour` searches OUTWARD from+ // each target, so slot 2 can resolve to an earlier hour than slot 1 — and+ // assigning the ordered checks to unsorted hours would run an audit before the+ // predecessor `orderQualityChecks` just placed ahead of it.+ const auditHours = placements.map(placement => placement.auditHour).sort((a, b) => a - b);+if (!auditHours.length) {return { checksPerDay: 0, slots: [], claim: null, warnings, options: settings };}@@ -250,12 +289,17 @@ export function planQualitySchedule({ taskTypes = [], fileIssuesByType = {}, bus}const filingSlots = slots.filter(slot => slot.fileIssues);+ const claimPlacements = placements.filter(placement => placement.claimHour !== null);let claim = null;- if (settings.claimBetween && claimHours.length && filingSlots.length) {- const hours = [...new Set(claimHours)].sort((a, b) => a - b);+ if (settings.claimBetween && claimPlacements.length && filingSlots.length) {+ const hours = [...new Set(claimPlacements.map(placement => placement.claimHour))].sort((a, b) => a - b);+ // The REALIZED gaps, not the requested offset: an occupied target hour+ // pushes the drain later, and the preview has to say what it will do.+ const gapHours = [...new Set(claimPlacements.map(placement => placement.claimHour - placement.auditHour))].sort((a, b) => a - b);claim = {taskType: settings.claimTaskType,hours,+ gapHours,cron: `0 ${hours.join(',')} * * *`,};} else if (settings.claimBetween && !filingSlots.length) {diff --git a/server/lib/qualitySchedulePlan.test.js b/server/lib/qualitySchedulePlan.test.jsindex 6bf49da562..bd6b51e66b 100644--- a/server/lib/qualitySchedulePlan.test.js+++ b/server/lib/qualitySchedulePlan.test.js@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest';-import { AUDIT_SUGGESTED_AFTER, AUDIT_TASK_TYPE_LIST } from './auditCatalog.js';+import { AUDIT_SUGGESTED_AFTER, AUDIT_TASK_TYPE_LIST, defaultFileIssuesFor } from './auditCatalog.js';import { cronWeekdayHours } from './cronFields.js';import {buildBusySlots,@@ -74,21 +74,90 @@ describe('planQualitySchedule', () => {});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);+ // With the natural offset hours occupied, an outward or wrapping search+ // would place the drain EARLIER in the day — the claim cron is daily, so+ // "01:00" is not after a 22:00 audit, it is 21 hours before the next one.+ const plan = planAll({ busy: busyFrom(['30 3 * * *']), options: { checksPerDay: 4, claimOffsetHours: 3 } });+ const auditHours = [...new Set(plan.slots.map(slot => slot.hour))];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);+ // Every claim hour is strictly later in the SAME day than the audit it+ // follows, and by at least the requested offset.+ for (const claimHour of plan.claim.hours) {+ const follows = auditHours.filter(hour => hour < claimHour);+ expect(follows.length).toBeGreaterThan(0);+ expect(claimHour - Math.max(...follows)).toBeGreaterThanOrEqual(3);+ }+ expect(Math.min(...plan.claim.gapHours)).toBeGreaterThanOrEqual(3);+ });++ it('places the audits in clock order within a day, so the suggested order holds', () => {+ // Only three hours free all week, far enough apart that the outward search+ // in `findFreeHour` resolves slot 2 BELOW slot 1 — which used to assign+ // `performance` an hour before the `code-quality` it must follow.+ const free = new Set([0, 4, 10]);+ const busy = buildBusySlots(+ [{ days: [0, 1, 2, 3, 4, 5, 6], hours: Array.from({ length: 24 }, (_, hour) => hour).filter(hour => !free.has(hour)) }],+ { padBeforeHours: 0, padAfterHours: 0 },+ );+ const plan = planQualitySchedule({+ taskTypes: ['performance', 'code-quality', 'security'],+ busy,+ options: { checksPerDay: 3, claimBetween: false },+ });+ const monday = plan.slots.filter(slot => slot.day === 1);+ expect(monday.map(slot => slot.hour)).toEqual([0, 4, 10]);+ const hourOf = taskType => monday.find(slot => slot.taskType === taskType).hour;+ expect(hourOf('code-quality')).toBeLessThan(hourOf('performance'));+ });++ it('drops the claim slot rather than wrapping it past midnight', () => {+ // A 23:00 audit has no room left in the day for a +3h drain. Wrapping to+ // 02:00 on a DAILY cron would run it before every audit, not after.+ const plan = planQualitySchedule({+ taskTypes: ['security'],+ options: { windowStartHour: 23, windowEndHour: 23, claimOffsetHours: 3 },});+ expect(plan.slots[0].hour).toBe(23);+ expect(plan.claim).toBeNull();+ expect(plan.warnings.join(' ')).toMatch(/No free hour left in the day/);});- 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(',')} * * *`);+ it('defers to each audit catalog default rather than forcing one delivery mode', () => {+ // 11 audits ship `defaultFileIssues: false`. A form-wide `true` default+ // would flip every one of them to issues-only on an untouched Apply.+ const plan = planAll();+ for (const slot of plan.slots) expect(slot.fileIssues).toBe(defaultFileIssuesFor(slot.taskType));+ expect(plan.slots.some(slot => slot.fileIssues)).toBe(true);+ expect(plan.slots.some(slot => !slot.fileIssues)).toBe(true);+ });++ it('reports a checks-per-day below the floor instead of silently raising it', () => {+ const plan = planAll({ options: { checksPerDay: 1 } });+ expect(plan.checksPerDay).toBe(Math.ceil(AUDIT_TASK_TYPE_LIST.length / 7));+ expect(plan.warnings.join(' ')).toMatch(/1 a day was raised to 4/);+ });++ it('says so when an overnight window is collapsed rather than planning a window nobody chose', () => {+ const plan = planAll({ options: { windowStartHour: 22, windowEndHour: 6 } });+ expect(plan.warnings.join(' ')).toMatch(/cannot wrap past midnight/);+ for (const slot of plan.slots) expect(slot.hour).toBe(22);+ });++ it('keeps a request field from riding back as a planning option', () => {+ // The client seeds its form from `plan.options`; an echoed `taskTypes`+ // there would override the user's live selection on the next request.+ const plan = planQualitySchedule({ taskTypes: ['security'], options: { taskTypes: ['ux'], nonsense: 1 } });+ expect(plan.options.taskTypes).toBeUndefined();+ expect(plan.options.nonsense).toBeUndefined();+ expect(plan.slots.map(slot => slot.taskType)).toEqual(['security']);+ });++ it('emits one daily cron covering every slot, not one per day', () => {+ const plan = planAll();+ // The literal, not the production expression restated: a planner that+ // emitted one claim hour for four daily slots would pass that version.+ expect(plan.claim.cron).toBe('0 3,9,15,21 * * *');+ expect(plan.claim.hours).toHaveLength(plan.checksPerDay);expect(plan.claim.taskType).toBe('claim-work');});diff --git a/server/routes/apps/taskTypes.test.js b/server/routes/apps/taskTypes.test.jsindex eb216bb77a..5725cb658d 100644--- a/server/routes/apps/taskTypes.test.js+++ b/server/routes/apps/taskTypes.test.js@@ -529,7 +529,7 @@ describe('Apps Task-Type Routes', () => {expect(buildQualitySchedulePlan).toHaveBeenCalledWith({ id: 'app-001', name: 'App' });});- it('previews an edited form without writing anything', async () => {+ it('routes a preview to the planner, never to the writer', async () => {const response = await request(app).post('/api/apps/app-001/quality-schedule/preview').send({ taskTypes: ['security'], checksPerDay: 2, fileIssuesByType: { security: false } });@@ -553,7 +553,12 @@ describe('Apps Task-Type Routes', () => {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();+ // The ledger entry is the audit trail for a write that rewrote every+ // audit cadence on the app — a bare "was called" would not notice the+ // counts going missing.+ expect(recordUserAction).toHaveBeenCalledWith(expect.objectContaining({+ payload: expect.objectContaining({ qualityPlan: true, applied: 1, disabled: 25 }),+ }));});});});diff --git a/server/services/appQualitySchedule.js b/server/services/appQualitySchedule.jsindex c045453b11..ed165fa284 100644--- a/server/services/appQualitySchedule.js+++ b/server/services/appQualitySchedule.js@@ -30,6 +30,7 @@ import {import {CLAIM_DRAIN_TASK_TYPES,buildBusySlots,+ isPlannedClaimCron,planQualitySchedule,resolveQualityScheduleOptions,} from '../lib/qualitySchedulePlan.js';@@ -78,7 +79,7 @@ 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);+ return { files: result.stdout.split('\n').map(line => line.trim()).filter(Boolean), complete: true };}const entries = await readdir(repoPath, { withFileTypes: true }).catch(() => []);const files = [];@@ -89,7 +90,9 @@ async function listRepoFiles(repoPath) {files.push(entry.name + '/');for (const child of nested) files.push(`${entry.name}/${child.name}${child.isDirectory() ? '/' : ''}`);}- return files;+ // `complete: false` on purpose — this listing stops at depth 2, so a miss is+ // "not looked at", never "not there".+ return { files, complete: false };}/**@@ -103,23 +106,34 @@ async function listRepoFiles(repoPath) {* @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 empty = Object.fromEntries(AUDIT_REPO_CAPABILITIES.map(key => [key, false]));+ if (!app?.repoPath) return { capabilities: empty, scanned: 0, complete: false };+const cached = capabilityCache.get(app.repoPath);- if (cached && Date.now() - cached.at < CAPABILITY_TTL_MS) return cached.value;+ const scan = cached && Date.now() - cached.at < CAPABILITY_TTL_MS+ ? cached.value+ : await scanRepoCapabilities(app.repoPath);+ if (scan !== cached?.value) capabilityCache.set(app.repoPath, { at: Date.now(), value: scan });++ // `uiPort` is a property of the APP, not of the checkout, and two apps can+ // share one repoPath — so it is OR'd in AFTER the (path-keyed) cache read.+ // A compiled or templated front end leaves no .jsx behind, but a served UI+ // port is direct evidence there is an interface to audit.+ const capabilities = { ...scan.capabilities, ui: scan.capabilities.ui || Boolean(app.uiPort) };+ return { capabilities, scanned: scan.scanned, complete: scan.complete || Boolean(app.uiPort) };+}- const files = (await listRepoFiles(app.repoPath)).filter(path => !VENDOR_SEGMENTS.test(path));- for (const path of files) {+/** The file-derived half of the verdict — cacheable because it is per-checkout. */+async function scanRepoCapabilities(repoPath) {+ const capabilities = Object.fromEntries(AUDIT_REPO_CAPABILITIES.map(key => [key, false]));+ const { files, complete } = await listRepoFiles(repoPath);+ const scanned = files.filter(path => !VENDOR_SEGMENTS.test(path));+ for (const path of scanned) {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;+ return { capabilities, scanned: scanned.length, complete: complete && scanned.length > 0 };}/**@@ -149,13 +163,14 @@ async function loadNotApplicableCategories(appId) {* @returns {Promise<{ checks: object[], capabilities: object, scanned: number }>}*/export async function resolveQualityChecks(app) {- const [{ capabilities, scanned }, notApplicable] = await Promise.all([+ const [{ capabilities, scanned, complete }, 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;+ // Only a COMPLETE inventory licenses a negative. An unreadable path scans+ // nothing, and the shallow fallback stops at depth 2 — in both cases a+ // capability reads false for want of evidence, and gating on that would+ // deselect most of the catalog over a repository nobody actually looked at.const checks = AUDIT_TASK_TYPE_LIST.map(taskType => {const requirement = auditCapabilityRequirement(taskType);@@ -164,13 +179,13 @@ export async function resolveQualityChecks(app) {if (notApplicable.has(taskType)) {applicable = false;reason = 'a previous audit reported this category as not applicable here';- } else if (requirement && repoReadable && !capabilities[requirement]) {+ } else if (requirement && complete && !capabilities[requirement]) {applicable = false;reason = AUDIT_CAPABILITY_MISSING_REASON[requirement];}return { taskType, label: AUDIT_DEFINITIONS[taskType].label, applicable, reason };});- return { checks, capabilities, scanned };+ return { checks, capabilities, scanned, complete };}/**@@ -233,7 +248,7 @@ export async function collectBusyOccupancies(app, { ignoreTaskTypes = [] } = {})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([+ const [{ checks, capabilities, scanned, complete }, sources] = await Promise.all([resolveQualityChecks(app),collectBusyOccupancies(app, { ignoreTaskTypes: [...AUDIT_TASK_TYPE_LIST, ...CLAIM_DRAIN_TASK_TYPES] }),]);@@ -254,6 +269,7 @@ export async function buildQualitySchedulePlan(app, options = {}) {checks,capabilities,scanned,+ complete,// The drain types the form may choose between, so adding one here does not// also need a client edit.claimTaskTypes: CLAIM_DRAIN_TASK_TYPES,@@ -293,10 +309,20 @@ export async function applyQualitySchedulePlan(app, options = {}) {: { enabled: false, interval: null };}if (plan.claim) patches[plan.claim.taskType] = { enabled: true, interval: plan.claim.cron };+ // Retire a drain an earlier plan planted. Without this, switching the drain+ // type leaves BOTH running daily, and "Do not run a claim job" leaves the old+ // one firing forever — the form would offer no way to undo what it created.+ // Only a cron of this planner's own shape is cleared (`isPlannedClaimCron`),+ // so a claim cadence a human set by hand on the Schedule page survives.+ for (const taskType of CLAIM_DRAIN_TASK_TYPES) {+ if (taskType === plan.claim?.taskType) continue;+ if (!isPlannedClaimCron(existing[taskType]?.interval)) continue;+ patches[taskType] = { enabled: false, interval: null };+ }await updateAppTaskTypeOverrides(app.id, patches);- const applied = plan.slots.length + (plan.claim ? 1 : 0);- const disabled = AUDIT_TASK_TYPE_LIST.length - plan.slots.length;+ const applied = Object.values(patches).filter(patch => patch.enabled).length;+ const disabled = Object.values(patches).length - applied;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.jsindex a29b2e5b43..a8b2d8968b 100644--- a/server/services/appQualitySchedule.test.js+++ b/server/services/appQualitySchedule.test.js@@ -1,11 +1,13 @@import { describe, it, expect, vi, beforeEach } from 'vitest';const execGit = vi.fn();+const readdir = vi.fn();const query = vi.fn();const getAppTaskTypeOverrides = vi.fn();const updateAppTaskTypeOverrides = vi.fn();const loadSchedule = vi.fn();+vi.mock('fs/promises', () => ({ readdir: (...args) => readdir(...args) }));vi.mock('../lib/execGit.js', () => ({ execGit: (...args) => execGit(...args) }));vi.mock('../lib/db.js', () => ({ query: (...args) => query(...args) }));vi.mock('./apps.js', () => ({@@ -18,6 +20,7 @@ const {applyQualitySchedulePlan,buildQualitySchedulePlan,collectBusyOccupancies,+ detectRepoCapabilities,resolveQualityChecks,} = await import('./appQualitySchedule.js');@@ -38,6 +41,7 @@ beforeEach(() => {getAppTaskTypeOverrides.mockResolvedValue({});updateAppTaskTypeOverrides.mockResolvedValue({});loadSchedule.mockResolvedValue({ tasks: {} });+ readdir.mockResolvedValue([]);vi.spyOn(console, 'log').mockImplementation(() => {});});@@ -79,14 +83,30 @@ describe('resolveQualityChecks', () => {expect(security.reason).toMatch(/previous audit/);});- it('offers every check when the repository could not be scanned at all', async () => {+ it('treats a repository it could only skim as unknown, not as empty', async () => {+ // `git ls-files` unavailable (not a checkout, git missing, timeout) falls+ // back to a two-level listing, which cannot see src/components/App.jsx.+ // Reading that miss as "no UI" would deselect seven audits for an app that+ // has one.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.+ readdir.mockResolvedValue([]);+ const { checks, complete } = await resolveQualityChecks({ id: 'skim', name: 'Skim', repoPath: '/repos/skim' });+ expect(complete).toBe(false);expect(checks.every(check => check.applicable)).toBe(true);});++ it('does not let one app’s uiPort decide a sibling app sharing the checkout', async () => {+ // The capability cache is keyed by repoPath; uiPort is a property of the+ // APP. Baking it into the cached value made a headless sibling read ui:true+ // for a minute and pre-select seven audits that can only answer N/A.+ execGit.mockResolvedValue({ exitCode: 0, stdout: NODE_SERVICE.join('\n'), stderr: '' });+ const shared = '/repos/shared-monorepo';+ const withUi = await detectRepoCapabilities({ id: 'a', repoPath: shared, uiPort: 5555 });+ const headless = await detectRepoCapabilities({ id: 'b', repoPath: shared });+ expect(withUi.capabilities.ui).toBe(true);+ expect(headless.capabilities.ui).toBe(false);+ });+});describe('collectBusyOccupancies', () => {@@ -157,9 +177,39 @@ describe('buildQualitySchedulePlan', () => {});describe('applyQualitySchedulePlan', () => {+ it('retires a claim drain an earlier plan planted when the drain is switched off', async () => {+ getAppTaskTypeOverrides.mockResolvedValue({ 'claim-work': { enabled: true, interval: '0 6,14 * * *' } });+ const app = appWith(NODE_SERVICE);+ await applyQualitySchedulePlan(app, { taskTypes: ['security'], claimBetween: false });+ const [, patches] = updateAppTaskTypeOverrides.mock.calls[0];+ // Without this the drain the form created keeps firing daily forever and+ // the form offers no way to undo it.+ expect(patches['claim-work']).toEqual({ enabled: false, interval: null });+ });++ it('retires the previous drain when the drain TYPE is switched', async () => {+ getAppTaskTypeOverrides.mockResolvedValue({ 'claim-work': { enabled: true, interval: '0 6,14 * * *' } });+ const app = appWith(NODE_SERVICE);+ await applyQualitySchedulePlan(app, { taskTypes: ['security'], fileIssues: true, claimTaskType: 'claim-issue' });+ const [, patches] = updateAppTaskTypeOverrides.mock.calls[0];+ expect(patches['claim-issue'].enabled).toBe(true);+ expect(patches['claim-work']).toEqual({ enabled: false, interval: null });+ });++ it('leaves a claim cadence a human set by hand alone', async () => {+ // A weekly cron is not a shape this planner emits, so it was not ours to+ // retire — clearing it would silently delete the user's own schedule.+ getAppTaskTypeOverrides.mockResolvedValue({ 'claim-work': { enabled: true, interval: '0 9 * * 1' } });+ const app = appWith(NODE_SERVICE);+ await applyQualitySchedulePlan(app, { taskTypes: ['security'], claimBetween: false });+ const [, patches] = updateAppTaskTypeOverrides.mock.calls[0];+ expect(patches['claim-work']).toBeUndefined();+ });++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'] });+ const result = await applyQualitySchedulePlan(app, { taskTypes: ['security'], fileIssues: true });expect(updateAppTaskTypeOverrides).toHaveBeenCalledTimes(1);const [appId, patches] = updateAppTaskTypeOverrides.mock.calls[0];@@ -172,6 +222,16 @@ describe('applyQualitySchedulePlan', () => {expect(result.applied).toBe(2);});+ it('writes each audit\u2019s catalog delivery default when the form states no preference', async () => {+ const app = appWith(NODE_SERVICE);+ await applyQualitySchedulePlan(app, { taskTypes: ['security', 'ux'] });+ const [, patches] = updateAppTaskTypeOverrides.mock.calls[0];+ // security ships defaultFileIssues:false, ux ships true — a form-wide+ // default would have flattened both.+ expect(patches.security.taskMetadata).toEqual({ fileIssues: false });+ expect(patches.ux.taskMetadata).toEqual({ fileIssues: true });+ });+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);