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
feat: add service and data-platform quality audits, and skip audits that cannot apply
[._.]/ Adam Eivy57b8f3f906c1
diff --git a/client/src/components/apps/AppQuality.jsx b/client/src/components/apps/AppQuality.jsxindex 834c0b3358..0250cd0d49 100644--- a/client/src/components/apps/AppQuality.jsx+++ b/client/src/components/apps/AppQuality.jsx@@ -53,6 +53,9 @@ export default function AppQuality({ app, detail = false }) {const score = quality?.score;const sortedCategories = quality?.categories? [...quality.categories].sort((a, b) => {+ // Categories that cannot apply to this repository sink below every+ // category that can, whichever sort is active.+ if ((a.applicable === false) !== (b.applicable === false)) return a.applicable === false ? 1 : -1;if (categorySort === 'oldest-run') {const aRun = Date.parse(a.assessedAt);const bRun = Date.parse(b.assessedAt);@@ -68,13 +71,15 @@ export default function AppQuality({ app, detail = false }) {return a.label.localeCompare(b.label) || a.id.localeCompare(b.id);}): [];+ // Pre-applicability servers send no `applicableCategories`; fall back to the catalog size.+ const categoryCount = quality?.applicableCategories ?? quality?.totalCategories ?? 0;const hasAssessments = quality?.categories?.some(category => category.assessedAt);const unscoredLabel = hasAssessments ? 'Quality: no qualifying score' : 'Quality: not assessed';const label = quality?.unavailable ? 'Quality unavailable': score == null ? unscoredLabel : `Quality: ${score}/100`;if (!detail) return (<Link to={`/apps/${app.id}/quality`} className="text-xs text-port-accent hover:underline" title="View audit scores and coverage">- {label}{score != null && ` · ${quality.ratedCategories}/${quality.totalCategories} categories`}+ {label}{score != null && ` · ${quality.ratedCategories}/${categoryCount} categories`}</Link>);const panelLink = (name, categoryId) => {@@ -111,7 +116,7 @@ export default function AppQuality({ app, detail = false }) {</InfoTooltip></h3><p className="text-xs text-gray-400">- {quality?.ratedCategories ?? 0}/{quality?.totalCategories ?? 0} categories contribute+ {quality?.ratedCategories ?? 0}/{categoryCount} applicable categories contribute{federation && ` · ${federation.available ?? 0} sync peers`}</p></div>@@ -185,13 +190,14 @@ function CategoryRow({ category, below, runLink }) {...(!category.sourcePeerId && category.agentId ? [{ id: 'run', label: 'View audit run', to: `/cos/agents/${category.agentId}` }] : []),...(category.sourcePeerId ? [{ id: 'instances', label: 'View instances', to: '/instances' }] : []),];- const evidence = <>+ const inapplicable = category.applicable === false;+ const evidence = inapplicable ? <>Not applicable · {category.inapplicableReason}</> : <>{category.stale ? 'Stale · ' : ''}{category.coverage}{category.confidence && ` · ${category.confidence}`}{category.assessedAt && ` · ${formatDateShort(category.assessedAt)}`}{category.sourcePeerId || category.sourcePeerName ? ` · ${category.sourcePeerName || 'federated peer'}` : ''}</>;return (- <tr className={`border-t border-port-border align-middle${below ? ' bg-port-warning/10' : ''}`}>+ <tr className={`border-t border-port-border align-middle${below ? ' bg-port-warning/10' : ''}${inapplicable ? ' text-gray-500' : ''}`}><th scope="row" className="py-1.5 px-2 font-medium"><span className="inline-flex items-center gap-1.5">{category.label}diff --git a/client/src/components/apps/AppQuality.test.jsx b/client/src/components/apps/AppQuality.test.jsxindex 0c9c98bca8..258f095143 100644--- a/client/src/components/apps/AppQuality.test.jsx+++ b/client/src/components/apps/AppQuality.test.jsx@@ -15,7 +15,7 @@ import { publishAppQualitySnapshot } from '../../services/apiApps';import toast from '../ui/Toast';it('shows zero as a real score up front and keeps the scoring explanation in a tooltip', async () => {- const app = { id: 'portos-default', quality: { score: 0, ratedCategories: 1, totalCategories: 25, categories: [+ const app = { id: 'portos-default', quality: { score: 0, ratedCategories: 1, totalCategories: 25, applicableCategories: 18, categories: [{ id: 'security', label: 'Security', score: 0, coverage: 'broad', confidence: 'high', summary: 'Critical failure', scannedFiles: 5, totalFiles: 5, worstSeverity: 10 },{ id: 'ux', label: 'UX', score: 80, coverage: 'partial', stale: true, summary: 'Only one journey inspected' },] } };@@ -23,7 +23,7 @@ it('shows zero as a real score up front and keeps the scoring explanation in a tawait screen.findByText(/No scored assessments/);expect(screen.getByRole('heading', { name: 'Quality: 0/100' })).toBeInTheDocument();expect(screen.getAllByText('Stale · partial')).not.toHaveLength(0);- expect(screen.getByText(/1\/25 categories contribute/)).toBeInTheDocument();+ expect(screen.getByText(/1\/18 applicable categories contribute/)).toBeInTheDocument();expect(screen.queryByText(/Equal-weight mean/)).not.toBeInTheDocument();fireEvent.click(screen.getByRole('button', { name: 'How the quality score works' }));expect(screen.getByRole('tooltip')).toHaveTextContent(/Equal-weight mean/);diff --git a/client/src/components/apps/AppQualityRunner.jsx b/client/src/components/apps/AppQualityRunner.jsxindex c337cbbf85..9c82037c2e 100644--- a/client/src/components/apps/AppQualityRunner.jsx+++ b/client/src/components/apps/AppQualityRunner.jsx@@ -7,7 +7,12 @@ import { useAutoRefetch } from '../../hooks/useAutoRefetch';import { enabledProcessProviderFilter } from '../../utils/providers';import { getMaintenanceRuns, startMaintenanceRun, stopMaintenanceRun } from '../../services/apiAgents';+// Inapplicable here (no UI for an accessibility audit, say): the server skips+// the dispatch anyway, so the batch selections leave it out. Picking the one+// category by name still offers it, and the server explains the skip.+const isApplicable = category => category.applicable !== false;const needsCheck = category => {+ if (!isApplicable(category)) return false;if (category.coverage === 'not-applicable' || (category.coverage === 'unavailable' && category.assessedAt)) return false;return category.score == null || category.stale || category.coverage !== 'broad' || category.confidence === 'low';};@@ -29,8 +34,8 @@ export default function AppQualityRunner({ app, children }) {const [runs, setRuns] = useState([]);const [loaded, setLoaded] = useState(false);const revision = useRef(0);- const picker = useProviderModels({ filter: enabledProcessProviderFilter, withEffort: true });- const taskTypes = categories.filter(category => selection === 'all' || (selection === 'missing' ? needsCheck(category) : category.id === selection)).map(category => category.id);+ const picker = useProviderModels({ filter: enabledProcessProviderFilter, withEffort: true, preselectDefaults: true });+ const taskTypes = categories.filter(category => (selection === 'all' && isApplicable(category)) || (selection === 'missing' ? needsCheck(category) : category.id === selection)).map(category => category.id);const loadRuns = useCallback(async () => {const requestedRevision = revision.current;const response = await getMaintenanceRuns({ silent: true }).catch(() => null);@@ -60,7 +65,7 @@ export default function AppQualityRunner({ app, children }) {<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm"><label htmlFor="quality-checks">Checks<select id="quality-checks" className="block w-full bg-port-bg border border-port-border rounded p-2" value={selection} disabled={busy} onChange={event => setSelection(event.target.value)}>- <option value="missing">Missing or outdated evidence</option><option value="all">All categories</option>+ <option value="missing">Missing or outdated evidence</option><option value="all">All applicable categories</option>{categories.map(category => <option key={category.id} value={category.id}>{category.label}</option>)}</select></label>@@ -75,7 +80,7 @@ export default function AppQualityRunner({ app, children }) {onModelChange={picker.setSelectedModel} effort={effort} onEffortChange={setEffort} loading={picker.loading} disabled={busy}emptyProviderOption="Select a subscription provider" emptyModelOption="Select a model" includeDefaultModel highlightToolUse /><p className="text-xs text-gray-400">Runs sequentially; launch another batch to run in parallel. {mode === 'fix' ? 'Each audit can change code and open a PR.' : 'Findings become issues; no fixes.'}</p>- <details className="text-xs"><summary className="cursor-pointer text-port-accent">Selected checks ({taskTypes.length})</summary><p className="mt-1">{categories.filter(category => taskTypes.includes(category.id)).map(category => category.label).join(', ') || 'No checks need evidence. Unavailable assessments and N/A categories are excluded.'}</p></details>+ <details className="text-xs"><summary className="cursor-pointer text-port-accent">Selected checks ({taskTypes.length})</summary><p className="mt-1">{categories.filter(category => taskTypes.includes(category.id)).map(category => category.label).join(', ') || 'No checks need evidence. Unavailable assessments and categories that do not apply to this repository are excluded.'}</p></details><button type="button" onClick={start} disabled={busy || picker.loading || !picker.selectedProviderId || !picker.selectedModel || !taskTypes.length || app.quality?.unavailable}className="px-3 py-2 rounded bg-port-accent text-port-bg text-sm font-medium disabled:opacity-50">{taskTypes.length === 1 ? 'Run now' : `Run ${taskTypes.length} checks now`}</button>{!loaded && <p className="text-xs" role="status">Loading runner status… <button type="button" className="text-port-accent" onClick={loadRuns}>Retry</button></p>}diff --git a/client/src/components/apps/AppQualityRunner.test.jsx b/client/src/components/apps/AppQualityRunner.test.jsxindex 5df814a4e5..e9a2404302 100644--- a/client/src/components/apps/AppQualityRunner.test.jsx+++ b/client/src/components/apps/AppQualityRunner.test.jsx@@ -101,6 +101,30 @@ it('excludes known unavailable and N/A assessments from suggestions while allowiawait waitFor(() => expect(startMaintenanceRun).toHaveBeenLastCalledWith(expect.objectContaining({ taskTypes: ['typing', 'console-errors', 'security'] }), { silent: true }));});+it('opens on the configured default provider instead of a hardcoded one', async () => {+ render(<MemoryRouter><AppQualityRunner app={app} /></MemoryRouter>);+ await waitFor(() => expect(useProviderModels).toHaveBeenCalled());+ expect(useProviderModels.mock.calls[0][0]).toMatchObject({ preselectDefaults: true });+});++it('leaves audits that cannot apply to this repository out of batch runs, but runs one on request', async () => {+ const categories = [+ { id: 'security', label: 'Security', score: null, applicable: true },+ { id: 'accessibility', label: 'Accessibility', score: null, applicable: false, inapplicableReason: 'no user interface found in this repository' },+ ];+ startMaintenanceRun.mockResolvedValue({ run: { id: 'run-4', status: 'running', steps: [] } });+ render(<MemoryRouter><AppQualityRunner app={{ ...app, quality: { categories } }} /></MemoryRouter>);+ const missing = await findEnabledByRole('button', { name: 'Run now' });+ fireEvent.click(missing);+ await waitFor(() => expect(startMaintenanceRun).toHaveBeenLastCalledWith(expect.objectContaining({ taskTypes: ['security'] }), { silent: true }));+ await findEnabledByLabelText('Checks');+ fireEvent.change(screen.getByLabelText('Checks'), { target: { value: 'all' } });+ expect(screen.getByRole('button', { name: 'Run now' })).toBeInTheDocument();+ fireEvent.change(screen.getByLabelText('Checks'), { target: { value: 'accessibility' } });+ fireEvent.click(await findEnabledByRole('button', { name: 'Run now' }));+ await waitFor(() => expect(startMaintenanceRun).toHaveBeenLastCalledWith(expect.objectContaining({ taskTypes: ['accessibility'] }), { silent: true }));+});+it('offers every enabled process provider regardless of subscription family, and hides disabled ones', async () => {render(<MemoryRouter><AppQualityRunner app={app} /></MemoryRouter>);await waitFor(() => expect(useProviderModels).toHaveBeenCalled());diff --git a/client/src/hooks/useProviderModels.js b/client/src/hooks/useProviderModels.jsindex 2367a71c7a..d3da333b0b 100644--- a/client/src/hooks/useProviderModels.js+++ b/client/src/hooks/useProviderModels.js@@ -5,6 +5,7 @@ import {filterSelectableModels,isProviderHardwareCompatible,isProviderModelHardwareCompatible,+ isTuiProvider,providerModelList,selectableModelsForProvider,withStaleAntigravityPin,@@ -28,6 +29,13 @@ const sourceModels = (provider, withEffort) => {return withEffort ? selectableModelsForProvider(provider, models) : models;};+/** The provider a `preselectDefaults` picker opens on (see that option). */+export function preferredInitialProvider(providers, activeProviderId, { allowDefault = false } = {}) {+ const active = providers.find(provider => provider.id === activeProviderId);+ if (active || allowDefault) return active || null;+ return providers.find(isTuiProvider) || providers[0] || null;+}+/*** Hook for loading AI providers and managing two-step provider > model selection.* @param {Object} options@@ -40,7 +48,10 @@ const sourceModels = (provider, withEffort) => {* `ProviderModelSelector`.* @param {boolean} [options.preselectDefaults] - Seed a session override with the* active provider and its configured model. If the active provider is excluded- * by the picker policy, leave Auto selected rather than choosing another.+ * by the picker policy, leave Auto selected rather than choosing another —+ * unless `allowDefault` is false, where there is no Auto to leave: the picker+ * then prefers the first TUI provider (the shipped agent default) over list+ * order, so it never lands on whichever CLI happens to be listed first.* @param {boolean} [options.silent] - Suppress the default error toast when the* provider fetch fails (the empty-list fallback still applies). Use when the* picker is a secondary control whose failure shouldn't interrupt the page.@@ -144,7 +155,7 @@ export default function useProviderModels({ filter, allowDefault = false, preselif ((!allowDefault || preselectDefaults) && filtered.length > 0 && !hasSetInitialRef.current) {hasSetInitialRef.current = true;const initial = preselectDefaults- ? filtered.find(provider => provider.id === data.activeProvider)+ ? preferredInitialProvider(filtered, data.activeProvider, { allowDefault }): filtered[0];if (initial) {setSelectedProviderId(initial.id);diff --git a/client/src/hooks/useProviderModels.test.js b/client/src/hooks/useProviderModels.test.jsindex 06793eceee..a6b225004c 100644--- a/client/src/hooks/useProviderModels.test.js+++ b/client/src/hooks/useProviderModels.test.js@@ -57,6 +57,25 @@ describe('useProviderModels — Antigravity base models', () => {expect(result.current.selectedModel).toBe('');});+ // A picker with no Auto option (the Quality runner) opens on the configured+ // default instead of whichever provider the registry happens to list first.+ it('opens a required picker on the configured default provider and its default model', async () => {+ const CLAUDE_TUI = { id: 'claude-code-tui', type: 'tui', enabled: true, defaultModel: 'example-model', models: ['example-model'] };+ api.getProviders.mockResolvedValue({ activeProvider: 'claude-code-tui', providers: [CODEX, CLAUDE_TUI] });+ const { result } = renderHook(() => useProviderModels({ preselectDefaults: true }));+ await waitFor(() => expect(result.current.loading).toBe(false));+ expect(result.current.selectedProviderId).toBe('claude-code-tui');+ expect(result.current.selectedModel).toBe('example-model');+ });++ it('falls back to a TUI provider, not list order, when a required picker filters out the default', async () => {+ const TUI = { id: 'example-tui', type: 'tui', enabled: true, defaultModel: 'm', models: ['m'] };+ api.getProviders.mockResolvedValue({ activeProvider: 'example-api', providers: [CODEX, TUI] });+ const { result } = renderHook(() => useProviderModels({ preselectDefaults: true }));+ await waitFor(() => expect(result.current.loading).toBe(false));+ expect(result.current.selectedProviderId).toBe('example-tui');+ });+it('does not substitute another provider when the active default is filtered out', async () => {api.getProviders.mockResolvedValue({ activeProvider: 'missing', providers: [CODEX] });const { result } = renderHook(() => useProviderModels({ allowDefault: true, preselectDefaults: true }));diff --git a/docs/features/app-quality.md b/docs/features/app-quality.mdindex 68d17d9588..02ca00f369 100644--- a/docs/features/app-quality.md+++ b/docs/features/app-quality.md@@ -8,7 +8,7 @@ Nothing calls an AI provider when a page loads or when the server starts.The browser explicitly requests `includeQuality=true` on app reads; bare`/api/apps` peer probes retain their existing response without assessment prose.-All 25 scheduled audit categories first inventory first-party source roots, scan+All 30 scheduled audit categories first inventory first-party source roots, scanfor their category's signals, rank the top five candidates (or all if fewer),and validate the strongest candidates before selecting a bounded investigation.The raw worst offender may be passed over only with an explanation such as a@@ -42,7 +42,13 @@ eligible inventory; deep investigation still stays bounded. Partial, stale,low-confidence, unavailable and inapplicable assessments remain visible but donot contribute. Missing categories do not count as 100. The contributing categorycount is shown beside the score so a single good category cannot imply complete-coverage. An app with no eligible assessments shows **not assessed**, not zero.+coverage. Its denominator is the number of categories that **apply** to the+repository (`applicableCategories`): a category is inapplicable when the+repository scan says so (see "Which checks" below — the app detail read runs it)+or its own fresh assessment reported `not-applicable`, unless a fresh rated+assessment shows it applies after all. Inapplicable categories stay listed at+the bottom of the breakdown with their reason; `totalCategories` keeps the+catalog size for existing readers. An app with no eligible assessments shows **not assessed**, not zero.Database failures show **unavailable** while app management stays usable.The completion sentinel summary contains one `QUALITY_AUDIT_JSON: {...}` line@@ -67,7 +73,27 @@ boundaries. Product-facing coverage comes from UX (including onboarding andsuccessful task completion), UI bugs, console errors, accessibility,mobile/responsive behavior and copy clarity.-This change keeps those 25 lenses rather than adding overlapping tasks.+Those lenses grew out of a web app with a UI, so five service and+data-platform lenses cover what a backend API, data platform, or infrastructure+repository is judged on and nothing above owns:++| Category | Owns | Distinct from |+| --- | --- | --- |+| `infrastructure` | IaC, containers, orchestration, platform manifests, CI: exposure, identity grants, secrets, pinning, resource limits and probes, state config, CI supply chain, environment drift | `security` (application code), `dependency-updates` |+| `data-integrity` | Runtime data correctness: idempotency under retry/redelivery, partial writes, lost updates, boundary validation, schema evolution of stored data, semantic corruption, pagination, retention reach, transfer checks | `data-safety` (upgrades, migrations, destructive defaults, backups) |+| `reliability` | System behavior under restart, overload and multiple instances: shutdown draining, truthful health checks, backpressure, job leasing/checkpoints, startup fragility, mixed-version deploys | `error-handling` (per-call timeouts, retries, fallbacks) |+| `privacy` | Personal/sensitive data: operational exposure, third-party minimization, API over-exposure, retention, erasure reach, real data in fixtures — under the project's documented sharing model | `security` (authz, injection) |+| `cost-efficiency` | Metered spend: repeated paid/model calls, unrequested provider work, retry multiplication, unbounded cloud scans, storage growth, over-provisioning, egress | `performance` (latency, throughput) |++All five default to file-issues. `infrastructure` is gated on deployment+configuration being present; the others apply to any repository and report+`not-applicable` when they do not. The same pass broadened five existing+prompts for services: `security` (tenant isolation, SSRF, unsafe+deserialization), `performance` (query plans, streaming, batch shape, pools,+partition pruning, cold start), `api-contract` (framework-neutral; spec drift,+breaking changes, idempotency keys, pagination bounds), `observability`+(correlation, alertable metrics, truthful health, audit trails) and+`data-safety` (backup restorability, bulk/backfill safety, retention reach).Real-user product outcomes such as retention or satisfaction cannot be inferredreliably from a source audit and are not fabricated into this codebase score.A future distinct category must register both its scheduled prompt and a@@ -115,7 +141,12 @@ objects. Upgrading the file does not require every peer to upgrade.Readers accept a v1 `.quality.json` and, when that file is absent, the historical`quality-snapshot.json` name. A read never rewrites the checkout. Future schemas,unrecognized documents (including TSV, CSV, or NDJSON), malformed snapshots, and-oversize files are not evidence and are not overwritten. TSV is not the+oversize files are not evidence and are not overwritten. A v2 file whose+category dictionary names categories this install does not know yet — written by+a newer install after the catalog grew — is read for the rows it does know and is+never rewritten, since canonicalizing it would drop the newer rows. (Installs+predating that rule treat such a file as malformed: safe, but its scores are not+shown until they upgrade.) TSV is not thecanonical artifact: an append-only text log would grow without a bound and wouldbe harder to validate, while the database is already the history.@@ -134,13 +165,15 @@ cron expression per audit on the Schedule page. It writes ordinary per-app task-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+audit reported as `coverage: not-applicable` within the last 30 days is skipped —+the auditing agent read the repository, so its ruling wins until it ages out+(a repository that later gains a UI gets its UI audits back). Otherwise applicability comes from the shapespresent in the tracked files (`git ls-files`): the UI lenses (UX, accessibility,mobile/responsive, UI bugs, console errors, UI lifecycle, copy) need a userinterface or a configured UI port, typing needs TypeScript sources, dependencyfreedom needs a dependency manifest, test quality needs existing tests, and API-contracts need a route/API surface. Test **coverage** is deliberately never gated+contracts need a route/API surface, and infrastructure needs IaC, container,+deployment, process-manager, or CI configuration. Test **coverage** is deliberately never gatedon tests — a repository with none is the one it has the most to say about. Eachaudit declares its own requirement as `requiresCapability` in`AUDIT_DEFINITIONS` (`server/lib/auditCatalog.js`), beside its other metadata@@ -152,8 +185,21 @@ fully inventoried offers every check rather than deselecting the catalog for wanof evidence — a `git ls-files` that fails falls back to a two-level listing, whichis 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+**Dispatch-time bail-out.** The same verdict (`resolveAuditApplicability`) is+checked again before any agent is spawned, on every lane: the scheduler, a+manual Run, a maintenance run, and a quota-burn step. An inapplicable audit is+skipped with a logged reason and no provider call — the scheduled lane records+the execution so its cadence advances, a manual Run reports why nothing ran, a+maintenance run completes the step as skipped (recorded in the run's `skipped`+map) and moves on, and a quota-burn step is declined so the burn picks other+work. Detection failures never block: the gate only removes work it has+evidence against. The Quality tab's **Run checks** batch selections leave+inapplicable categories out; picking one by name still offers it (and the+server then explains the skip).++**When.** The selection is spread across the week as evenly as it allows — the+30 shipped checks become five slots a day, filled 5,5,4,4,4,4,4 so no day is+left empty — ordered so each one follows the audits `AUDIT_SUGGESTED_AFTER` namesas its predecessors, and laid out in clock order within each day so that sequencesurvives. Asking for more checks per day uses fewer days; asking for fewer thanthe week needs is raised to the floor, with a warning saying so. The hours arediff --git a/docs/features/scheduled-audit-organization.md b/docs/features/scheduled-audit-organization.mdindex 0a52bb8262..c8e4a8c4c5 100644--- a/docs/features/scheduled-audit-organization.md+++ b/docs/features/scheduled-audit-organization.md@@ -11,7 +11,9 @@ better-test-coverage, better-performance, better-accessibility,better-documentation, better-ui-bugs, better-mobile-responsive,better-error-handling, better-typing, better-console-errors, better-ux,better-data-safety, better-simplify, better-module-hygiene, better-api-contract,-better-ui-lifecycle, better-observability, and better-copy. The six existing+better-ui-lifecycle, better-observability, and better-copy, plus the service+and data-platform lenses better-infrastructure, better-data-integrity,+better-reliability, better-privacy, and better-cost-efficiency. The six existingbetter-* names remain unchanged.Operational tasks (claims, review pipelines, reconciliation, releases, repo sync),diff --git a/server/lib/auditCatalog.js b/server/lib/auditCatalog.jsindex 7c33185c30..f4cf9fda3a 100644--- a/server/lib/auditCatalog.js+++ b/server/lib/auditCatalog.js@@ -97,7 +97,7 @@ If you find additional problems, mention them in the summary — do not expand s* 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']);+export const AUDIT_REPO_CAPABILITIES = Object.freeze(['ui', 'typescript', 'tests', 'dependencies', 'api', 'infrastructure']);/** Read aliases kept only for in-flight tasks and historical quality records. */export const LEGACY_AUDIT_TASK_TYPE_ALIASES = Object.freeze({ 'react-lifecycle': 'ui-lifecycle' });@@ -112,6 +112,7 @@ export const AUDIT_CAPABILITY_MISSING_REASON = Object.freeze({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',+ infrastructure: 'no infrastructure-as-code, container, deployment, or CI configuration found in this repository',});/**@@ -473,6 +474,86 @@ export const AUDIT_DEFINITIONS = Object.freeze({noun: 'test-quality finding(s)',}),},+ // Service and data-platform lenses. The catalog above grew out of a web app+ // with a UI; these cover what a backend service, data platform, or+ // infrastructure repository is judged on and nothing above owns: the+ // deployment it describes, the correctness of the data flowing through it,+ // how it behaves under restarts and load, what it does with personal data,+ // and what it costs to run. Each defaults to file-issues — their findings+ // usually touch production configuration, where an unattended edit is the+ // wrong default.+ infrastructure: {+ quotaBurnId: null,+ label: 'Infrastructure & deployment',+ description: 'Infrastructure-as-code, container, deployment and CI audit — configurable: file issues (default) or implement fixes',+ defaultFileIssues: true,+ requiresCapability: 'infrastructure',+ filing: filing({+ slugPrefix: 'infrastructure-',+ label: 'infrastructure-audit',+ issueLabel: 'infrastructure',+ labelDescription: 'Proposed from an infrastructure/deployment audit',+ noun: 'infrastructure finding(s)',+ }),+ },+ 'data-integrity': {+ quotaBurnId: null,+ label: 'Data integrity & pipelines',+ description: 'Data-correctness audit (ingestion, idempotency, consistency, schema evolution) — configurable: file issues (default) or implement fixes',+ defaultFileIssues: true,+ filing: filing({+ slugPrefix: 'data-integrity-',+ label: 'data-integrity-audit',+ // Same category as its upgrade-time sibling; the metric label+ // `data-integrity` separates runtime data correctness in the backlog.+ issueLabel: 'data-safety',+ labelDescription: 'Proposed from a data-integrity/pipeline audit',+ noun: 'data-integrity finding(s)',+ }),+ },+ reliability: {+ quotaBurnId: null,+ label: 'Reliability & operability',+ description: 'Service reliability audit (shutdown, health checks, backpressure, job leasing, mixed-version deploys) — configurable: file issues (default) or implement fixes',+ defaultFileIssues: true,+ filing: filing({+ slugPrefix: 'reliability-',+ label: 'reliability-audit',+ // Filed beside error-handling's call-level findings; the metric label+ // `reliability` marks the system-level ones.+ issueLabel: 'resilience',+ labelDescription: 'Proposed from a reliability/operability audit',+ noun: 'reliability finding(s)',+ }),+ },+ privacy: {+ quotaBurnId: null,+ label: 'Privacy & data governance',+ description: 'Personal/sensitive-data handling audit (exposure, minimization, retention, erasure) — configurable: file issues (default) or implement fixes',+ defaultFileIssues: true,+ filing: filing({+ slugPrefix: 'privacy-',+ label: 'privacy-audit',+ issueLabel: 'privacy',+ labelDescription: 'Proposed from a privacy/data-governance audit',+ noun: 'privacy finding(s)',+ }),+ },+ 'cost-efficiency': {+ quotaBurnId: null,+ label: 'Cost & resource efficiency',+ description: 'Metered-spend audit (paid API calls, unbounded scans, storage tiers, over-provisioning) — configurable: file issues (default) or implement fixes',+ defaultFileIssues: true,+ filing: filing({+ slugPrefix: 'cost-',+ label: 'cost-efficiency-audit',+ // Spend is a performance-family concern; the metric label `cost` keeps+ // it filterable apart from latency work.+ issueLabel: 'performance',+ labelDescription: 'Proposed from a cost/resource-efficiency audit',+ noun: 'cost finding(s)',+ }),+ },});export const AUDIT_TASK_TYPES = new Set(Object.keys(AUDIT_DEFINITIONS));@@ -658,12 +739,12 @@ export function applyAuditModeWrapper(promptTemplate, modeInstructions) {* labels fails at the source boundary.*/export const DO_BETTER_SCOPE_COVERAGE = Object.freeze({- security: ['security'],+ security: ['security', 'privacy'],'code-quality': ['code-quality', 'observability'],dry: ['simplify'],architecture: ['module-hygiene', 'api-contract'],- 'bugs-perf': ['better-runtime-safety', 'performance', 'error-handling', 'observability'],- 'stack-specific': ['ui-lifecycle', 'accessibility', 'data-safety', 'security'],+ 'bugs-perf': ['better-runtime-safety', 'performance', 'error-handling', 'observability', 'reliability', 'cost-efficiency'],+ 'stack-specific': ['ui-lifecycle', 'accessibility', 'data-safety', 'security', 'infrastructure', 'data-integrity'],deps: ['better-dependency-freedom', 'security'],tests: ['test-coverage', 'better-test-quality'],ux: ['ux', 'mobile-responsive', 'copy'],@@ -728,6 +809,12 @@ export const AUDIT_SUGGESTED_AFTER = Object.freeze({// Measure and describe the shape that survived the ladder.performance: Object.freeze(['better-complexity']),documentation: Object.freeze(['performance', 'better-cognitive-load']),+ // Service lenses: deployment config after the code-level security pass it+ // shares findings with; system-level reliability after call-level failure+ // handling; spend after latency, since a performance fix often moves cost.+ infrastructure: Object.freeze(['security']),+ reliability: Object.freeze(['error-handling']),+ 'cost-efficiency': Object.freeze(['performance']),});// WHY each audit sits where it does in the order above — rationale only. The@@ -750,4 +837,9 @@ export const AUDIT_RUN_GUIDANCE = Object.freeze({'code-quality': 'Broad triage that points at the focused audit worth running; avoid overlapping fixes in the same slice.',documentation: 'Describes the final result, so it runs once behavior and structure have settled.',performance: 'Measure a real bottleneck before optimizing, and remeasure after structural and complexity changes.',+ 'data-integrity': 'Head of the order — duplicated, dropped, or silently wrong data compounds with every run, so it is fixed before code moves around it.',+ privacy: 'Head of the order — exposed personal data is a harm already happening, whatever cleanup is queued.',+ infrastructure: 'Follows the code-level security pass, so deployment findings (exposure, credentials, unpinned images) do not duplicate what it already filed.',+ reliability: 'Follows call-level failure handling: once each call fails safely, look at how the service as a whole restarts, drains, and sheds load.',+ 'cost-efficiency': 'Follows performance, because a latency fix often changes what the path costs; measure spend on the shape that survived.',});diff --git a/server/lib/auditQuality.js b/server/lib/auditQuality.jsindex 400930936a..ddb227da60 100644--- a/server/lib/auditQuality.js+++ b/server/lib/auditQuality.js@@ -31,6 +31,11 @@ export const AUDIT_DISCOVERY = Object.freeze({'better-runtime-safety': 'Scan asynchronous callbacks, resource cleanup, nullable access and process lifecycles across source roots; rank reachable crashes, corrupted state and leaked resources.','better-dependency-freedom': 'Inventory manifests and actual imports across packages; rank dependency cost, advisory exposure and removable surface against the complexity of a concrete replacement.','better-test-quality': 'Inventory suites and public boundaries; search assertion-free tests, overmocking, tautologies and redundant cases, prioritizing suites that falsely protect critical behavior.',+ infrastructure: 'Inventory infrastructure-as-code, container, orchestration, deployment and CI files; scan exposure, identity grants, secrets, pinning, resource limits and probes, ranking reachable production exposure and irreproducible deploys first.',+ 'data-integrity': 'Inventory every write path, ingestion entry point, consumer, batch/backfill job and stored data format; trace retry and redelivery behavior and multi-step writes, ranking silent duplication, loss and wrong results first.',+ reliability: 'Inventory process entry points, signal handling, health endpoints, queues, workers and scheduled jobs; trace shutdown, restart, overload and multi-instance behavior, ranking dropped work and outage amplification first.',+ privacy: 'Inventory personal and sensitive fields in schemas and payloads, then trace them to logs, errors, analytics, caches, exports, third-party calls and deletion paths; rank exposure already happening over missing governance.',+ 'cost-efficiency': 'Inventory metered dependencies (paid APIs, model providers, cloud storage/query/compute, egress) and their call sites, schedules and retry paths; rank spend by frequency times unit cost and growth with usage.',});export function auditQualityInstructions(taskType) {@@ -85,7 +90,19 @@ export function parseAuditQualityReport(summary, category) {export const AUDIT_FRESHNESS_MS = 30 * 24 * 60 * 60 * 1000;-export function summarizeAppQuality(records = [], now = Date.now()) {+/**+ * Roll the newest measurement per category into the app's quality summary.+ *+ * `inapplicable` maps category → reason for categories this repository cannot+ * have findings for (from `resolveQualityChecks`; the caller supplies it only+ * where it can afford the repository scan). A category is inapplicable when that+ * map names it OR its own fresh report says `not-applicable` — unless it holds+ * a fresh rated assessment anyway, which is evidence that it does apply.+ * `applicableCategories` is the honest denominator: a backend API is not+ * "3 of 30 rated" because seven UI audits have nothing to look at.+ * `totalCategories` keeps its catalog-size meaning for existing readers.+ */+export function summarizeAppQuality(records = [], now = Date.now(), { inapplicable = {} } = {}) {const normalizedRecords = records.map(record => ({...record,category: normalizeAuditTaskType(record.category),@@ -97,14 +114,21 @@ export function summarizeAppQuality(records = [], now = Date.now()) {const assessedAt = record?.assessedAt;const age = now - Date.parse(assessedAt);const stale = valid && (!Number.isFinite(age) || age < 0 || age > AUDIT_FRESHNESS_MS);- return { id, label: definition.label, ...(valid ? report.data : { score: null, coverage: 'unavailable' }), assessedAt: assessedAt || null, agentId: record?.agentId || null, sourcePeerId: record?.sourcePeerId || null, sourcePeerName: record?.sourcePeerName || null, stale };+ const contributes = valid && !stale && report.data.coverage === 'broad' && report.data.confidence !== 'low' && report.data.score !== null;+ const reportedNotApplicable = valid && !stale && report.data.coverage === 'not-applicable';+ const detectedReason = Object.hasOwn(inapplicable, id) ? inapplicable[id] : null;+ const applicable = contributes || !(reportedNotApplicable || detectedReason);+ const inapplicableReason = applicable ? null+ : detectedReason || 'the latest audit reported this category as not applicable';+ return { id, label: definition.label, ...(valid ? report.data : { score: null, coverage: 'unavailable' }), assessedAt: assessedAt || null, agentId: record?.agentId || null, sourcePeerId: record?.sourcePeerId || null, sourcePeerName: record?.sourcePeerName || null, stale, contributes, applicable, inapplicableReason };});- const rated = categories.filter(c => !c.stale && c.coverage === 'broad' && c.confidence !== 'low' && c.score !== null);+ const rated = categories.filter(c => c.contributes);return {score: rated.length ? Math.round(rated.reduce((sum, c) => sum + c.score, 0) / rated.length) : null,ratedCategories: rated.length,totalCategories: categories.length,- categories,+ applicableCategories: categories.filter(c => c.applicable).length,+ categories: categories.map(({ contributes: _contributes, ...category }) => category),};}diff --git a/server/lib/qualitySchedulePlan.js b/server/lib/qualitySchedulePlan.jsindex 3db5e062c7..153d7158e5 100644--- a/server/lib/qualitySchedulePlan.js+++ b/server/lib/qualitySchedulePlan.js@@ -181,6 +181,28 @@ function findFreeHourForward(target, { busy, taken }) {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());+/**+ * Which (weekday, daily-slot) cell each ordered check takes, day-major so a+ * check never runs earlier in the week than one ordered before it.+ *+ * With no explicit checks-per-day the checks are spread as evenly as the week+ * allows — 30 checks at 5 slots a day run 5,5,4,4,4,4,4, not 5×6 with an empty+ * Sunday. An explicit per-day count packs each day full first, which is what+ * asking for "N a day" means. More checks than cells wrap onto earlier cells+ * (the planner warns about that).+ */+function weeklyCells(count, perDay, pack) {+ if (pack || count > perDay * 7) {+ return Array.from({ length: count }, (_, index) => ({ dayIndex: Math.floor(index / perDay) % 7, hourIndex: index % perDay }));+ }+ const cells = [];+ for (let dayIndex = 0; dayIndex < 7; dayIndex += 1) {+ const today = Math.floor(count / 7) + (dayIndex < count % 7 ? 1 : 0);+ for (let hourIndex = 0; hourIndex < today; hourIndex += 1) cells.push({ dayIndex, hourIndex });+ }+ return cells;+}+/*** Plan the week.*@@ -266,11 +288,12 @@ export function planQualitySchedule({ taskTypes = [], fileIssuesByType = {}, busreturn { checksPerDay: 0, slots: [], claim: null, warnings, options: settings };}+ const cells = weeklyCells(ordered.length, auditHours.length, Number.isInteger(requested) && requested > 0);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 day = (1 + cells[index].dayIndex) % 7;+ const hour = auditHours[cells[index].hourIndex];const fileIssues = typeof fileIssuesByType[taskType] === 'boolean'? fileIssuesByType[taskType]: (typeof settings.fileIssues === 'boolean' ? settings.fileIssues : defaultFileIssuesFor(taskType));diff --git a/server/lib/qualitySchedulePlan.test.js b/server/lib/qualitySchedulePlan.test.jsindex bd6b51e66b..1662604296 100644--- a/server/lib/qualitySchedulePlan.test.js+++ b/server/lib/qualitySchedulePlan.test.js@@ -134,7 +134,7 @@ describe('planQualitySchedule', () => {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/);+ expect(plan.warnings.join(' ')).toMatch(new RegExp(`1 a day was raised to ${Math.ceil(AUDIT_TASK_TYPE_LIST.length / 7)}`));});it('says so when an overnight window is collapsed rather than planning a window nobody chose', () => {@@ -156,7 +156,7 @@ describe('planQualitySchedule', () => {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.cron).toBe('0 3,8,13,17,22 * * *');expect(plan.claim.hours).toHaveLength(plan.checksPerDay);expect(plan.claim.taskType).toBe('claim-work');});diff --git a/server/lib/scheduledTaskTypes.js b/server/lib/scheduledTaskTypes.jsindex ad3ad56ad3..c0c04615b2 100644--- a/server/lib/scheduledTaskTypes.js+++ b/server/lib/scheduledTaskTypes.js@@ -93,6 +93,28 @@ export const SELF_IMPROVEMENT_TASK_TYPES = [// `test-coverage`, which owns the GAPS. Files under `tests` plus the// `test-quality` metric label.'better-test-quality',+ // Service and data-platform lenses — what a backend API, data platform, or+ // infrastructure repository is judged on that the UI-shaped audits above+ // do not own. `infrastructure` is gated on IaC/container/CI files; the rest+ // apply to any service and report `not-applicable` when they do not.+ // Deployment configuration: exposure, identity grants, secrets, pinning,+ // resource limits and probes, CI supply chain. Distinct from `security`+ // (application code) and `dependency-updates` (package bumps).+ 'infrastructure',+ // Runtime data correctness: idempotent ingestion under redelivery, atomic+ // multi-step writes, consistency, schema evolution of stored data. Distinct+ // from `data-safety`, which owns upgrade/migration/destructive-default risk.+ 'data-integrity',+ // System-level behavior under restart, overload and multi-instance runs.+ // Distinct from `error-handling`, which owns per-call timeouts and retries.+ 'reliability',+ // Personal and sensitive data: exposure through logs/exports/third parties,+ // minimization, retention and erasure. Distinct from `security` (authz,+ // injection) — honors the project's documented data-sharing model.+ 'privacy',+ // Metered spend: paid API/model calls, unbounded cloud scans, storage tiers,+ // over-provisioning. Distinct from `performance` (latency and throughput).+ 'cost-efficiency',// Audits `git stash list` for {appName} and drops entries already superseded// by (or a subset of) current `main`/HEAD, or that are stale/abandoned scratch// work — without discarding real unlanded work. On-demand only (no cadencediff --git a/server/routes/apps/crud.js b/server/routes/apps/crud.jsindex 74508bb76c..edf7f38773 100644--- a/server/routes/apps/crud.js+++ b/server/routes/apps/crud.js@@ -136,7 +136,13 @@ router.get('/:id', loadApp, asyncHandler(async (req, res) => {hasSubmodules = gitmodules;}- const [enrichedApp] = includeQuality === 'true' ? await enrichAppsWithQuality([app]) : [app];+ // The detail read alone scans the checkout for applicability (cached per repo),+ // so the Quality tab's denominator and runner skip audits that cannot apply.+ const [enrichedApp] = includeQuality === 'true'+ ? await enrichAppsWithQuality([app], {+ resolveApplicability: async (target) => (await import('../../services/appQualitySchedule.js')).inapplicableAuditReasons(target),+ })+ : [app];res.json({ ...enrichedApp, uiPort, devUiPort, apiPort, overallStatus, degraded, pm2Status: statuses, appVersion, hasSubmodules, hasDeployScript: hasDeployScript(app), xcodeScripts: checkScripts(app) });}));diff --git a/server/services/appQuality.js b/server/services/appQuality.jsindex 8679a6b427..95a2c957a7 100644--- a/server/services/appQuality.js+++ b/server/services/appQuality.js@@ -31,6 +31,12 @@ export async function recordAuditQuality({ task, taskType, agentId, workspacePatreturn true;}+/**+ * @param {object[]} apps - Managed app records+ * @param {object} [deps] - Injectable seams. `resolveApplicability(app)` →+ * `{ [category]: reason }` adds repository-scan applicability; only the+ * single-app detail read passes it, so a list read never walks N checkouts.+ */export async function enrichAppsWithQuality(apps, deps = {}) {if (!apps.length) return apps;// One app-scoped query per list, not one per tile or transcript scan.@@ -47,13 +53,15 @@ export async function enrichAppsWithQuality(apps, deps = {}) {// records, never the whole list — same posture as the peer collect below.const releases = await Promise.all(apps.map(app => readReleaseQuality(deps, app).catch(() => [])));return Promise.all(apps.map(async (app, index) => {- const shared = await collectAppQuality(app, 30, deps)- .catch(() => ({ records: [], federation: { failed: true } }));+ const [shared, inapplicable] = await Promise.all([+ collectAppQuality(app, 30, deps).catch(() => ({ records: [], federation: { failed: true } })),+ deps.resolveApplicability ? deps.resolveApplicability(app).catch(() => ({})) : {},+ ]);return { ...app,quality: result ? { ...summarizeAppQuality(latestQualityRecords([...result.rows.filter(row => row.app_id === app.id).map(qualityRecord),...shared.records, ...releases[index],- ]), deps.now ?? Date.now()), federation: shared.federation }+ ]), deps.now ?? Date.now(), { inapplicable }), federation: shared.federation }: { ...summarizeAppQuality(), unavailable: true },};}));diff --git a/server/services/appQuality.test.js b/server/services/appQuality.test.jsindex d2b6026aa3..a67bd24f25 100644--- a/server/services/appQuality.test.js+++ b/server/services/appQuality.test.js@@ -73,11 +73,30 @@ describe('scheduled audit measurement workflow', () => {['performance', 100, 'broad', 'low', now],].map(([category, score, coverage, confidence, date]) => ({ category, report: report({ category, score, coverage, confidence }), assessedAt: new Date(date).toISOString() }));const quality = summarizeAppQuality(records, now);- expect(quality).toMatchObject({ score: 40, ratedCategories: 2, totalCategories: 25 });+ expect(quality).toMatchObject({ score: 40, ratedCategories: 2, totalCategories: Object.keys(AUDIT_DEFINITIONS).length });expect(quality.categories.find(c => c.id === 'ux')).toMatchObject({ score: 100, stale: true });expect(summarizeAppQuality().score).toBeNull();});+ // The regression: a backend API was reported as "2 of 30 categories" because+ // seven UI audits it cannot have findings for sat in the denominator.+ it('drops categories that cannot apply from the denominator, unless rated evidence says they do', () => {+ const now = Date.now();+ const records = [+ ['code-quality', 80, 'broad', 'high'],+ ['typing', null, 'not-applicable', 'low'],+ ['mobile-responsive', 60, 'broad', 'high'],+ ].map(([category, score, coverage, confidence]) => ({ category, report: report({ category, score, coverage, confidence }), assessedAt: new Date(now).toISOString() }));+ const quality = summarizeAppQuality(records, now, { inapplicable: { accessibility: 'no user interface found', 'mobile-responsive': 'no user interface found' } });+ const byId = Object.fromEntries(quality.categories.map(c => [c.id, c]));+ expect(byId.accessibility).toMatchObject({ applicable: false, inapplicableReason: 'no user interface found' });+ expect(byId.typing).toMatchObject({ applicable: false, inapplicableReason: expect.stringMatching(/not applicable/) });+ // Detected as UI-less, but a fresh broad assessment exists: it counts.+ expect(byId['mobile-responsive']).toMatchObject({ applicable: true, inapplicableReason: null });+ expect(quality.applicableCategories).toBe(Object.keys(AUDIT_DEFINITIONS).length - 2);+ expect(quality.score).toBe(70);+ });+it('surfaces previously stored lifecycle scores under the renamed category', () => {const now = Date.now();const legacy = {diff --git a/server/services/appQualityFederation.js b/server/services/appQualityFederation.jsindex 260d5c9862..11ceb4a882 100644--- a/server/services/appQualityFederation.js+++ b/server/services/appQualityFederation.js@@ -145,7 +145,8 @@ async function releasePayload(deps, app) {if (!repoPath) return null;const { readStoredQualitySnapshot } = await import('./appQualitySnapshotFile.js');const stored = await readStoredQualitySnapshot(repoPath, deps);- return stored.status === 'v1' || stored.status === 'v2' ? stored : null;+ // 'future-categories': a newer install's snapshot — its known rows still count.+ return ['v1', 'v2', 'future-categories'].includes(stored.status) ? stored : null;}/** Shipped evidence is read-only and never re-exported as a local audit. */diff --git a/server/services/appQualitySchedule.js b/server/services/appQualitySchedule.jsindex 962b876e2b..2466bbfd4a 100644--- a/server/services/appQualitySchedule.js+++ b/server/services/appQualitySchedule.js@@ -36,7 +36,8 @@ import {resolveQualityScheduleOptions,} from '../lib/qualitySchedulePlan.js';import { cronWeekdayHours } from '../lib/cronFields.js';-import { getAppTaskTypeOverrides, updateAppTaskTypeOverrides } from './apps.js';+import { AUDIT_FRESHNESS_MS } from '../lib/auditQuality.js';+import { getAppById, 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';@@ -53,6 +54,15 @@ const CAPABILITY_PATTERNS = {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],+ // Deployment described in the repository: IaC, containers and orchestration,+ // platform manifests, process managers, and CI pipelines (a CI workflow is a+ // deployment surface with its own supply-chain risk).+ infrastructure: [+ /\.(tf|tfvars|bicep)$/i, /(^|\/)(terraform|pulumi|cdk|k8s|kubernetes|helm|charts|ansible|infra|infrastructure|deploy|deployment)\//i,+ /(^|\/)(Dockerfile|Containerfile)[^/]*$/i, /(^|\/)(docker-)?compose[^/]*\.ya?ml$/i, /(^|\/)Chart\.yaml$/, /(^|\/)(Pulumi|serverless)[^/]*\.ya?ml$/i,+ /(^|\/)(cdk|vercel|firebase)\.json$/i, /(^|\/)(fly|netlify|wrangler)\.toml$/i, /(^|\/)(Procfile|Jenkinsfile)$/, /(^|\/)ecosystem\.config\.[cm]?js$/i,+ /(^|\/)\.github\/workflows\/[^/]+\.ya?ml$/i, /(^|\/)\.gitlab-ci\.ya?ml$/i, /(^|\/)\.circleci\//i, /(^|\/)azure-pipelines\.ya?ml$/i, /(^|\/)cloudformation\//i,+ ],};/**@@ -138,20 +148,24 @@ async function scanRepoCapabilities(repoPath) {}/**- * Categories a past audit of THIS app reported as not applicable. The auditing+ * Categories a recent 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.+ * above — but only while it is fresh: a repository that later gains a UI or a+ * deployment manifest must get the audit back, so a ruling older than the+ * quality freshness window (the same 30 days after which a score goes stale)+ * no longer counts. 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) {+async function loadNotApplicableCategories(appId, now = Date.now()) {const result = await query(- `SELECT DISTINCT ON (category) category, report FROM app_quality_measurements+ `SELECT DISTINCT ON (category) category, assessed_at, report FROM app_quality_measurementsWHERE 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')+ return new Set(result.rows.filter(row => row.report?.coverage === 'not-applicable'+ && now - Date.parse(row.assessed_at) <= AUDIT_FRESHNESS_MS).map(row => normalizeAuditTaskType(row.category)));}@@ -190,6 +204,61 @@ export async function resolveQualityChecks(app) {return { checks, capabilities, scanned, complete };}+/**+ * Whether ONE audit is worth dispatching for this app — the programmatic+ * bail-out every dispatch lane consults before an agent is spawned, so a+ * mobile-responsive audit of a repository with no client code costs a+ * `git ls-files` (cached) instead of a provider call. Same verdict as the+ * schedule form's, by construction: both read `resolveQualityChecks`.+ *+ * Non-audit task types and apps with no checkout always apply — the gate only+ * ever REMOVES work it has evidence against.+ *+ * @param {object} app - The managed app record+ * @param {string} taskType - Scheduled task type+ * @returns {Promise<{ applicable: boolean, reason: string|null }>}+ */+export async function resolveAuditApplicability(app, taskType) {+ const category = normalizeAuditTaskType(taskType);+ if (!app?.id || !app.repoPath || !Object.hasOwn(AUDIT_DEFINITIONS, category)) return { applicable: true, reason: null };+ const { checks } = await resolveQualityChecks(app);+ const check = checks.find(entry => entry.taskType === category);+ return { applicable: check?.applicable !== false, reason: check?.reason || null };+}++/**+ * Every category this app's repository cannot have findings for, as+ * `{ [category]: reason }` — the shape `summarizeAppQuality` takes, so the+ * Quality tab's denominator and runner agree with the dispatch gate.+ *+ * @param {object} app - The managed app record+ * @returns {Promise<Record<string, string>>}+ */+export async function inapplicableAuditReasons(app) {+ const { checks } = await resolveQualityChecks(app);+ return Object.fromEntries(checks.filter(check => !check.applicable).map(check => [check.taskType, check.reason]));+}++/**+ * The same verdict keyed by app id, for the sequencing lanes (maintenance runs,+ * quota-burn steps) that hold an id rather than a record. Returns WHY the audit+ * does not apply, or null when it does — or when that cannot be determined, so+ * an unreadable app or a failed detection never blocks work.+ *+ * @param {string|null} appId - Managed app id+ * @param {string} taskType - Scheduled task type+ * @returns {Promise<string|null>}+ */+export async function inapplicableAuditReason(appId, taskType) {+ if (!appId || !Object.hasOwn(AUDIT_DEFINITIONS, normalizeAuditTaskType(taskType))) return null;+ // `.then` rather than a direct call, so even a synchronous throw from the+ // app lookup lands in the fail-open catch instead of the caller's lane.+ const verdict = await Promise.resolve(appId).then(id => getAppById(id))+ .then(app => (app ? resolveAuditApplicability(app, taskType) : null))+ .catch(() => null);+ return verdict && !verdict.applicable ? verdict.reason || 'not applicable to this repository' : null;+}+/*** The weekday/hour cells already claimed by something else on this app.*diff --git a/server/services/appQualitySchedule.test.js b/server/services/appQualitySchedule.test.jsindex 5f9c7f3e39..9287839e3f 100644--- a/server/services/appQualitySchedule.test.js+++ b/server/services/appQualitySchedule.test.js@@ -6,11 +6,13 @@ const query = vi.fn();const getAppTaskTypeOverrides = vi.fn();const updateAppTaskTypeOverrides = vi.fn();const loadSchedule = vi.fn();+const getAppById = 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', () => ({+ getAppById: (...args) => getAppById(...args),getAppTaskTypeOverrides: (...args) => getAppTaskTypeOverrides(...args),updateAppTaskTypeOverrides: (...args) => updateAppTaskTypeOverrides(...args),}));@@ -21,6 +23,8 @@ const {buildQualitySchedulePlan,collectBusyOccupancies,detectRepoCapabilities,+ inapplicableAuditReason,+ resolveAuditApplicability,resolveQualityChecks,} = await import('./appQualitySchedule.js');@@ -45,6 +49,38 @@ beforeEach(() => {vi.spyOn(console, 'log').mockImplementation(() => {});});+describe('audit applicability gate', () => {+ it('bails out of a UI audit for a pure API repository, keeps the service lenses', async () => {+ const app = appWith(NODE_SERVICE);+ expect(await resolveAuditApplicability(app, 'mobile-responsive')).toEqual({ applicable: false, reason: expect.stringMatching(/no user interface/) });+ expect(await resolveAuditApplicability(app, 'reliability')).toEqual({ applicable: true, reason: null });+ // Infrastructure needs deployment config, which this service lacks.+ expect((await resolveAuditApplicability(app, 'infrastructure')).applicable).toBe(false);+ });++ it('recognizes deployment configuration as infrastructure', async () => {+ for (const file of ['infra/main.tf', 'Dockerfile', 'deploy/values.yaml', '.github/workflows/ci.yml', 'ecosystem.config.cjs', 'charts/api/Chart.yaml']) {+ const { capabilities } = await detectRepoCapabilities(appWith(['package.json', file]));+ expect(capabilities.infrastructure, file).toBe(true);+ }+ });++ it('never gates non-audit work or an app without a checkout', async () => {+ expect(await resolveAuditApplicability(appWith(NODE_SERVICE), 'claim-issue')).toEqual({ applicable: true, reason: null });+ expect(await resolveAuditApplicability({ id: 'x', name: 'X' }, 'accessibility')).toEqual({ applicable: true, reason: null });+ expect(execGit).not.toHaveBeenCalled();+ });++ it('answers by app id for the sequencing lanes, and fails open when the app is unreadable', async () => {+ const app = appWith(NODE_SERVICE);+ getAppById.mockResolvedValueOnce(app);+ expect(await inapplicableAuditReason(app.id, 'accessibility')).toMatch(/no user interface/);+ getAppById.mockRejectedValueOnce(new Error('boom'));+ expect(await inapplicableAuditReason(app.id, 'accessibility')).toBeNull();+ expect(await inapplicableAuditReason(null, 'accessibility')).toBeNull();+ });+});+describe('resolveQualityChecks', () => {it('skips the UI audits for a repository that ships no interface', async () => {const { checks, capabilities } = await resolveQualityChecks(appWith(NODE_SERVICE));@@ -76,15 +112,23 @@ describe('resolveQualityChecks', () => {});it('lets an auditing agent that reported not-applicable overrule the path heuristics', async () => {- query.mockResolvedValue({ rows: [{ category: 'security', report: { coverage: 'not-applicable' } }] });+ query.mockResolvedValue({ rows: [{ category: 'security', assessed_at: new Date().toISOString(), 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/);});+ // A repository that gained a UI (or a deployment manifest) since the ruling+ // must get the audit back once the ruling ages out.+ it('stops honoring a not-applicable ruling once it is older than the freshness window', async () => {+ query.mockResolvedValue({ rows: [{ category: 'security', assessed_at: new Date(Date.now() - 31 * 86400000).toISOString(), report: { coverage: 'not-applicable' } }] });+ const { checks } = await resolveQualityChecks(appWith(NODE_SERVICE));+ expect(checks.find(check => check.taskType === 'security').applicable).toBe(true);+ });+it('recognizes a retired lifecycle category in stored applicability results', async () => {- query.mockResolvedValue({ rows: [{ category: 'react-lifecycle', report: { coverage: 'not-applicable' } }] });+ query.mockResolvedValue({ rows: [{ category: 'react-lifecycle', assessed_at: new Date().toISOString(), report: { coverage: 'not-applicable' } }] });const { checks } = await resolveQualityChecks(appWith(['package.json', 'src/App.jsx']));expect(checks.find(check => check.taskType === 'ui-lifecycle')).toMatchObject({applicable: false,diff --git a/server/services/appQualitySnapshotFile.js b/server/services/appQualitySnapshotFile.jsindex 4ca04c6cbc..081c96a84c 100644--- a/server/services/appQualitySnapshotFile.js+++ b/server/services/appQualitySnapshotFile.js@@ -34,7 +34,9 @@ export const APP_QUALITY_SNAPSHOT_MAX_BYTES = 4 * 1024 * 1024;export const QUALITY_SNAPSHOT_BRANCH = 'portos/quality-snapshot';const snapshotPath = (repoPath, filename = APP_QUALITY_SNAPSHOT_FILENAME) => join(repoPath, filename);-const REWRITE_BLOCKED = new Set(['future', 'unrecognized', 'malformed', 'oversize', 'unreadable']);+// 'future-categories' is readable (known rows are used) but was written by a+// newer install whose categories this one would drop on rewrite.+const REWRITE_BLOCKED = new Set(['future', 'future-categories', 'unrecognized', 'malformed', 'oversize', 'unreadable']);const QUALITY_PR_TITLE = 'chore: publish quality snapshot';const QUALITY_PR_BODY = `## Summarydiff --git a/server/services/appQualitySnapshotFormat.js b/server/services/appQualitySnapshotFormat.jsindex 8a108611a2..90045a6c00 100644--- a/server/services/appQualitySnapshotFormat.js+++ b/server/services/appQualitySnapshotFormat.js@@ -165,6 +165,21 @@ export function serializeQualitySnapshot(repository, records) {return canonicalize(repository, normalized);}+/**+ * The category dictionary may name categories a NEWER install added — the+ * catalog grows, and a snapshot committed by an upgraded peer reaches installs+ * that have not upgraded yet. Accept any well-formed name here; rows that use+ * an unknown one are set aside by `parseV2` instead of failing the whole file.+ */+const MAX_CATEGORY_NAMES = 256;+const CATEGORY_NAME = /^[a-z][a-z0-9-]{0,63}$/;+function parseCategoryDictionary(values) {+ if (!Array.isArray(values) || values.length > MAX_CATEGORY_NAMES) return null;+ if (values.some(value => typeof value !== 'string' || !CATEGORY_NAME.test(value))) return null;+ if (new Set(values).size !== values.length) return null;+ return values;+}+function parseDictionary(values, allowed) {if (!Array.isArray(values) || values.length > allowed.size) return null;if (values.some(value => typeof value !== 'string' || !allowed.has(value))) return null;@@ -198,6 +213,9 @@ function parseV1(value) {: { status: 'malformed' };}+/** A well-formed row naming a category this install does not know yet. */+const UNKNOWN_CATEGORY_ROW = Symbol('unknown-category-row');+function parseV2Row(row, categories, coverage, confidence) {if (!Array.isArray(row) || row.length !== 8) return null;const [assessedAt, categoryIndex, score, worstSeverity, coverageIndex, confidenceIndex, scannedFiles, totalFiles] = row;@@ -208,6 +226,7 @@ function parseV2Row(row, categories, coverage, confidence) {if (!isInt(coverageIndex, 0, Math.max(coverage.length - 1, 0)) || coverageIndex >= coverage.length) return null;if (!isInt(confidenceIndex, 0, Math.max(confidence.length - 1, 0)) || confidenceIndex >= confidence.length) return null;if (!isInt(scannedFiles, 0, Number.MAX_SAFE_INTEGER) || !isInt(totalFiles, 0, Number.MAX_SAFE_INTEGER)) return null;+ if (!READABLE_CATEGORIES.has(categories[categoryIndex])) return UNKNOWN_CATEGORY_ROW;return normalizeRecord({assessedAt,category: categories[categoryIndex],@@ -225,7 +244,7 @@ function parseV2(value) {return { status: 'malformed' };}if (typeof value.repository !== 'string' || !REPOSITORY.test(value.repository)) return { status: 'malformed' };- const categories = parseDictionary(value.categories, READABLE_CATEGORIES);+ const categories = parseCategoryDictionary(value.categories);const coverage = parseDictionary(value.coverage, COVERAGE);const confidence = parseDictionary(value.confidence, CONFIDENCE);if (!categories || !coverage || !confidence) return { status: 'malformed' };@@ -234,12 +253,20 @@ function parseV2(value) {return { status: 'malformed' };}const records = [];+ let unknownRows = 0;for (const row of value.measurements) {const record = parseV2Row(row, categories, coverage, confidence);if (!record) return { status: 'malformed' };+ if (record === UNKNOWN_CATEGORY_ROW) {+ unknownRows += 1;+ continue;+ }records.push(record);}if (duplicateDays(records)) return { status: 'malformed' };+ // Readable, but not ours to rewrite: canonicalizing would drop the rows a+ // newer install wrote. Readers use the known records; writers leave the file.+ if (unknownRows) return { status: 'future-categories', repository: value.repository, records, canonical: null };const canonical = canonicalize(value.repository, records);return canonical? { status: 'v2', repository: value.repository, records, canonical }diff --git a/server/services/appQualitySnapshotFormat.test.js b/server/services/appQualitySnapshotFormat.test.jsindex 16a99193e0..d07b035e80 100644--- a/server/services/appQualitySnapshotFormat.test.js+++ b/server/services/appQualitySnapshotFormat.test.js@@ -200,3 +200,27 @@ it('keeps a full 30-day category window under the cap and materially smaller tha.toHaveLength(JSON.parse(serializeQualitySnapshot(repository, oneCategory)).measurements.length * categories.length);expect(JSON.parse(classifyQualitySnapshot(v2).canonical).measurements).toHaveLength(rows.length);});++// A snapshot committed by an upgraded peer names categories this install's+// catalog does not have yet. Before, that marked the whole file malformed, so+// the older install lost every release score it COULD read.+it('reads the known rows of a newer install’s snapshot and refuses to rewrite it', () => {+ const stored = classifyQualitySnapshot(JSON.stringify({+ schemaVersion: 2, repository, reportVersion: 1,+ categories: ['security', 'example-future-lens'], coverage: [...QUALITY_COVERAGE_VALUES], confidence: [...QUALITY_CONFIDENCE_VALUES],+ measurements: [+ ['2026-09-20T00:00:00.000Z', 0, 82, 5, 0, 2, 120, 120],+ ['2026-09-20T00:00:00.000Z', 1, 64, 3, 0, 2, 40, 40],+ ],+ }));+ expect(stored.status).toBe('future-categories');+ expect(stored.records.map(record => record.category)).toEqual(['security']);+ // No canonical form: rewriting would drop the newer install's rows.+ expect(stored.canonical).toBeNull();+ const malformedName = classifyQualitySnapshot(JSON.stringify({+ schemaVersion: 2, repository, reportVersion: 1,+ categories: ['Not A Category!'], coverage: [...QUALITY_COVERAGE_VALUES], confidence: [...QUALITY_CONFIDENCE_VALUES],+ measurements: [],+ }));+ expect(malformedName.status).toBe('malformed');+});diff --git a/server/services/cosTaskGenerator.auditMode.test.js b/server/services/cosTaskGenerator.auditMode.test.jsindex 9e5d23487c..a7cec0fcce 100644--- a/server/services/cosTaskGenerator.auditMode.test.js+++ b/server/services/cosTaskGenerator.auditMode.test.js@@ -49,6 +49,14 @@ const AUDIT_TEMPLATE_WITH_TOKEN = [].join('\n');const promptTemplate = vi.hoisted(() => ({ body: null }));+// Per-type applicability verdicts; absent = applies. The repository scan that+// produces them is covered in appQualitySchedule.test.js.+const applicability = vi.hoisted(() => ({ inapplicable: {} }));+vi.mock('./appQualitySchedule.js', () => ({+ resolveAuditApplicability: vi.fn(async (_app, taskType) => (applicability.inapplicable[taskType]+ ? { applicable: false, reason: applicability.inapplicable[taskType] }+ : { applicable: true, reason: null })),+}));vi.mock('./taskPromptService.js', () => ({getTaskPrompt: vi.fn(async () => promptTemplate.body),@@ -165,6 +173,16 @@ describe('issues-only audit dispatch never acquires code-shipping instructions (beforeEach(() => {vi.clearAllMocks();promptTemplate.body = AUDIT_TEMPLATE;+ applicability.inapplicable = {};+ });++ it('bails out before generating an audit that cannot apply, advancing the cadence', async () => {+ applicability.inapplicable = { 'mobile-responsive': 'no user interface found in this repository' };+ const { recordExecution } = await import('./taskSchedule.js');+ expect(await generate('mobile-responsive')).toBeNull();+ expect(recordExecution).toHaveBeenCalledWith('mobile-responsive', 'app-1');+ // A sibling audit that does apply still generates.+ expect(await generate('reliability')).not.toBeNull();});it.each(AUDIT_TYPES)('%s — file-issues mode renders no commit/push/PR/auto-merge directive', async (taskType) => {diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 31aacec509..671ea8806e 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -2274,8 +2274,8 @@ export async function emitOnDemandEmpty({ taskScheduleMod, request, targetApp, tconst app = await getAppById(appId).catch(() => null);reason = app?.layeredIntelligence?.lastRunReason || null;}- if (outcome === 'idle' && request.taskType === 'pr-reviewer') {- reason = takePerpetualTransient('pr-reviewer', appId)?.reason ?? null;+ if (outcome === 'idle' && (request.taskType === 'pr-reviewer' || isAuditTaskType(request.taskType))) {+ reason = takePerpetualTransient(request.taskType, appId)?.reason ?? null;}// 'transient' says "the forge probe failed, try again shortly" — only true when@@ -2397,6 +2397,27 @@ function buildImprovementTaskMetadata(taskType, app, interval, taskSchedule, appreturn metadata;}+/**+ * The dispatch-side half of audit applicability (see `resolveAuditApplicability`).+ * A detection failure never blocks work — the gate only removes what it has+ * evidence against. The verdict is parked as a transient so a manual Run's+ * "produced nothing" notice can say WHY (`emitOnDemandEmpty`).+ *+ * @returns {Promise<boolean>} true when the dispatch must be skipped+ */+async function skipInapplicableAudit(app, taskType, taskSchedule) {+ const { resolveAuditApplicability } = await import('./appQualitySchedule.js');+ const verdict = await resolveAuditApplicability(app, taskType).catch((err) => {+ emitLog('warn', `Audit applicability check failed for ${taskType}/${app.name}: ${err.message}`, { appId: app.id, analysisType: taskType });+ return { applicable: true, reason: null };+ });+ if (verdict.applicable) return false;+ emitLog('info', `⏭️ Skipping ${taskType} for ${app.name}: not applicable — ${verdict.reason}`, { appId: app.id, analysisType: taskType });+ recordPerpetualTransient(taskType, app.id, { reason: `Not applicable to this repository: ${verdict.reason}` });+ await taskSchedule.recordExecution(taskType, app.id);+ return true;+}+/*** Run a task type's registered buildTaskInput hook (taskTypeHooks.js) for* deterministic pre-agent data collection. Returns `{ skip: true }` when the@@ -2728,6 +2749,15 @@ export async function prepareManagedAppImprovementTask(taskType, app, state, {// Also protect requests queued before the target-scope gate was installed.if (requiresInstallWideTarget(taskType)) return null;+ // Audit applicability bail-out — before metadata, preflights, or a spawn slot.+ // A quality audit this repository cannot have findings for (a mobile audit of+ // a pure API, an infrastructure audit of a repo with no deployment config) is+ // skipped with a logged reason instead of paying a provider call to be told+ // "not applicable". Covers every lane that reaches this generator: the clock,+ // a manual Run, a maintenance run, and a quota-burn step. Execution is+ // recorded so the cadence advances rather than retrying every tick.+ if (isAuditTaskType(taskType) && await skipInapplicableAudit(app, taskType, taskSchedule)) return null;+// NOTE: `updateAppActivity` + the "Generating improvement task" log are// intentionally deferred until AFTER every gate returns non-null (see end// of function). The original code stamped both eagerly, which was tolerablediff --git a/server/services/maintenanceRun.js b/server/services/maintenanceRun.jsindex e3f9e5bf37..5cb7a0b5d7 100644--- a/server/services/maintenanceRun.js+++ b/server/services/maintenanceRun.js@@ -318,10 +318,22 @@ async function evaluate(id, { ignoreTaskId }) {const catalog = await getQuotaBurnTaskCatalog({ manual: true });const completed = { ...run.completed };+ const skippedSteps = {};for (const step of run.steps) {if (completed[step.id]) continue;const shape = sequenceStepShapeReason(step);if (shape) return hold(shape);+ // An audit this repository cannot have findings for is COMPLETED as+ // skipped, not dispatched: the generator would refuse it anyway, and a+ // refused request would leave the step pending — re-dispatched on every+ // evaluation. Checked here so the run moves straight to the next step.+ const inapplicable = step.drain ? null : await (await import('./appQualitySchedule.js')).inapplicableAuditReason(run.appId, step.taskRef?.taskType);+ if (inapplicable) {+ completed[step.id] = new Date().toISOString();+ skippedSteps[step.id] = inapplicable;+ console.log(`⏭️ Maintenance run ${id}: skipped ${step.taskRef.taskType} (${step.id}) — not applicable: ${inapplicable}`);+ continue;+ }if (step.drain) {const probe = await probeSequenceDrain(step, { catalog, ignoreTaskId });if (probe.drained) {@@ -331,10 +343,11 @@ async function evaluate(id, { ignoreTaskId }) {if (!probe.job) return hold(probe.reason);}const result = await invokeQuotaBurnStep({ step, family: stepBurnFamily(step, run), catalog, maintenanceRunId: id });- if (!result.dispatched) return hold(result.reason, { completed });+ if (!result.dispatched) return hold(result.reason, { completed, ...skippedPatch(run, skippedSteps) });const taskType = step.taskRef.taskType;await patchRun(id, {completed,+ ...skippedPatch(run, skippedSteps),steps: run.steps.map(entry => entry.id === step.id ? { ...entry, startedAt: entry.startedAt || new Date().toISOString() } : entry),reason: null,active: { stepId: step.id, taskType, status: 'queued', requestId: result.awaiting?.requestId ?? null, at: new Date().toISOString() },@@ -343,13 +356,18 @@ async function evaluate(id, { ignoreTaskId }) {return { dispatched: true, stepId: step.id, taskType, summary: result.summary };}await patchRun(id, {- completed, active: null, reason: 'maintenance sequence complete',+ completed, ...skippedPatch(run, skippedSteps), active: null, reason: 'maintenance sequence complete',status: MAINTENANCE_RUN_STATUS.COMPLETED, finishedAt: new Date().toISOString(),});console.log(`🧹 Maintenance run ${id} complete for ${run.appId}`);return { dispatched: false, completed: true, reason: 'maintenance sequence complete' };}+/** Merge newly skipped steps into the run's `skipped` map (step id → reason), or add nothing. */+const skippedPatch = (run, skippedSteps) => (Object.keys(skippedSteps).length+ ? { skipped: { ...(run.skipped || {}), ...skippedSteps } }+ : {});+/*** Continuation. An audit step is done when its agent SUCCEEDS; a failed agent* leaves its task blocked, which the next evaluation reports as a hold untildiff --git a/server/services/maintenanceRun.test.js b/server/services/maintenanceRun.test.jsindex 5be493dc12..5acb87d12a 100644--- a/server/services/maintenanceRun.test.js+++ b/server/services/maintenanceRun.test.js@@ -7,7 +7,10 @@ import { MAINTENANCE_SEQUENCE_TYPES, MAINTENANCE_TASK_ORDER } from '../lib/maintconst { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-maintenance-run-' });vi.mock('../lib/fileUtils.js', async () => makeProxy(await vi.importActual('../lib/fileUtils.js')));-const state = vi.hoisted(() => ({ tasks: [], requests: [], invoked: [], dispatch: null, probe: null }));+const state = vi.hoisted(() => ({ tasks: [], requests: [], invoked: [], dispatch: null, probe: null, inapplicable: {} }));+// Applicability is decided by the repository scan (covered in+// appQualitySchedule.test.js); here only the run's reaction to a verdict matters.+vi.mock('./appQualitySchedule.js', () => ({ inapplicableAuditReason: vi.fn(async (_appId, taskType) => state.inapplicable[taskType] || null) }));vi.mock('./cosState.js', () => ({ loadState: vi.fn(async () => ({ agents: {} })) }));vi.mock('./cosTaskStore.js', () => ({ getAllTasks: vi.fn(async () => ({ cos: { tasks: state.tasks }, user: { tasks: [] } })) }));vi.mock('./taskSchedule.js', () => ({ getOnDemandRequests: vi.fn(async () => state.requests) }));@@ -62,11 +65,24 @@ beforeEach(async () => {vi.clearAllMocks();__resetMaintenanceRunScheduler();await rm(join(tempRoot, 'cos', 'maintenance-runs.json'), { force: true });- Object.assign(state, { tasks: [], requests: [], invoked: [], dispatch: null, probe: null });+ Object.assign(state, { tasks: [], requests: [], invoked: [], dispatch: null, probe: null, inapplicable: {} });});afterAll(cleanup);describe('manual maintenance run', () => {+ // The regression: a refused request would leave the step pending, so the run+ // re-dispatched an audit that could never apply on every evaluation.+ it('completes an inapplicable audit as skipped without dispatching it, then moves on', async () => {+ state.inapplicable = { 'mobile-responsive': 'no user interface found in this repository' };+ const { run } = await startMaintenanceRun({ appId: 'app-1', providerId: 'codex', model: 'gpt-5', taskTypes: ['mobile-responsive', 'security'] });+ expect(dispatchedTypes()).toEqual(['security']);+ const stored = await getMaintenanceRun(run.id);+ expect(stored.completed[run.steps[0].id]).toBeTruthy();+ expect(stored.skipped).toEqual({ [run.steps[0].id]: 'no user interface found in this repository' });+ await __onMaintenanceAgentCompleted(agentFor(run, 1));+ expect((await getMaintenanceRun(run.id)).status).toBe('completed');+ });+it.each(['file-issues', 'fix'])('runs only selected quality checks in %s mode with pinned overrides', async (mode) => {const { run } = await startMaintenanceRun({ appId: 'app-1', providerId: 'codex', model: 'gpt-5', effort: 'high', mode, taskTypes: ['security', 'documentation'] });expect(run.steps.map(step => step.taskRef.taskType)).toEqual(['security', 'documentation']);diff --git a/server/services/quotaBurnInvoke.js b/server/services/quotaBurnInvoke.jsindex 7a058afb8e..1d559d8f54 100644--- a/server/services/quotaBurnInvoke.js+++ b/server/services/quotaBurnInvoke.js@@ -450,6 +450,13 @@ async function runBuiltinTaskStep({ resolved, step, family, candidate, maintenanconst queued = await queuedOnDemandReason(resolved.catalog?.queued, resolved.ref.taskType, resolved.ref.appId);if (queued) return declined(queued);+ // An audit that cannot apply to the target repository is declined HERE, so+ // the burn moves on to work that can spend the window. The generator would+ // refuse it too, but only after the request consumed the step's turn.+ const { inapplicableAuditReason } = await import('./appQualitySchedule.js');+ const inapplicable = await inapplicableAuditReason(resolved.ref.appId, resolved.ref.taskType);+ if (inapplicable) return declined(`"${resolved.ref.taskType}" does not apply to this app: ${inapplicable}`);+const picked = await resolveStepProvider(resolved.effective, family);if (picked.error) return declined(picked.error);diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.jsonindex 8c95e3ae20..a5b57584b6 100644--- a/server/services/taskPromptDefaults/integrity.snapshot.json+++ b/server/services/taskPromptDefaults/integrity.snapshot.json@@ -1,7 +1,7 @@{"DEFAULT_TASK_PROMPTS": {"accessibility": "46f628a44a919bb788de8761e86ca0e1",- "api-contract": "cf02b10a5993baf473e0d320771f26b6",+ "api-contract": "d52e00ec53eb5618df1a769efccc08f3","better-cognitive-load": "a1fe22f6ef936131456c55a6b0623204","better-complexity": "c99f67b43ff54a1c8cf0176c721d9c06","better-dependency-freedom": "8a79c8be829f926bbc7720ee29818d53",@@ -18,20 +18,23 @@"code-reviewer-review": "27ded42013f28e7d327d8f1cc624aac1","console-errors": "5a7f6fd0b119db9d0e01c7f44a7a061c","copy": "6a0959e898d37fb4d4d7445dfc8008c9",- "data-safety": "86b07f51abdbcbe7016f840b5bb0cd9b",+ "cost-efficiency": "239bad18c51b50c80599d30b2fb0ad15",+ "data-integrity": "5fcc4f5044101e89da5bbf4890c11a1c",+ "data-safety": "eb97988dfc16d4c655f1834acc91d665","dependency-updates": "44de787b45e037fbce281efc87706873","do-replan": "35660eb7b43e4259a6a9253ed288a1db","documentation": "a30e3bfba8cd13369ccaf806a3534a79","error-handling": "137b371f38398042c0a2c7e2279c92ce","feature-ideas": "804f62f1dadadbfa8a0bcd4aff16b2e8",+ "infrastructure": "b4ad755eb115b82679c601a0df1ffd7b","issue-reconcile": "541afc6566aa012ebc400ccff391ce2b","jira-sprint-manager": "3e63c8a3bdf0d5a05a30faaa2dc07980","jira-status-report": "9d374a9d8ccb92c5c8fd0aa9899e79a5","mobile-responsive": "eb7f6b307bccd15199c74d7aff5c21c3","model-comparison-refresh": "7de58f49e5cea22a4282fb37bc9f37ab","module-hygiene": "3b7671cd44f719d4b2116b96a279e6d0",- "observability": "fdb4d77df5891cfb653a5da2553ecf8a",- "performance": "b69bf4cbd2b3c272b5650608c62cede3",+ "observability": "243e58bcfae2759f82caf3ff6c8fc9c5",+ "performance": "8b297d723f9f39154c9cf6d501738494","plan-feature": "7f859397ff16889ffc0cf5a8ba6bddab","plan-task": "8a53a518714cc4029d751fdad92f9b05","plan-task-claim": "ac25c5c94a1e5ba5fb728abcb2e0aadb",@@ -40,11 +43,13 @@"pr-reviewer-review": "a4b35a1dc44e03b3d0ecf1a4e1bae6df","pr-reviewer-security": "d1e99626b12939ee39ab38eaa7d23f59","pr-watcher": "5246968aa90bb2bbf7957dcd9ae13a51",+ "privacy": "ecf3c57c064e3c4ab662d70252c686fb","reference-watch": "57221102b6245d40852ac258fbf9ebbf","refresh-local-llm-catalog": "9741ca6a8419fcdea2743e3b64781a8b","release-check": "cd936b9a4fb76273b36ec54c3ed6d5ba",+ "reliability": "2a99be77b8f34653f4b926db0a773ea5","repo-sync": "0a648d35d43b023b758226b9c709c8ea",- "security": "c5e35a12eeb06e6afe4617f4428fa1ab",+ "security": "4bd26243a5792a39040da0b49321ca27","simplify": "2a048214d1dd3b75bee9ae1a38fa1589","stash-cleanup": "1c12bac5aac6bb27008c40981e7db08c","test-coverage": "36beffc0c2959be5d818ded54b3fe298",@@ -56,7 +61,7 @@},"PROMPT_VERSIONS": {"accessibility": 5,- "api-contract": 1,+ "api-contract": 2,"better-cognitive-load": 1,"better-complexity": 2,"better-dependency-freedom": 1,@@ -72,29 +77,34 @@"code-reviewer-b": 1,"console-errors": 4,"copy": 1,- "data-safety": 1,+ "cost-efficiency": 1,+ "data-integrity": 1,+ "data-safety": 2,"dependency-updates": 6,"do-replan": 2,"documentation": 7,"error-handling": 3,"feature-ideas": 11,+ "infrastructure": 1,"issue-reconcile": 7,"jira-sprint-manager": 1,"jira-status-report": 1,"mobile-responsive": 3,"model-comparison-refresh": 2,"module-hygiene": 1,- "observability": 1,- "performance": 4,+ "observability": 2,+ "performance": 5,"plan-feature": 6,"plan-task": 19,"pr-reviewer": 5,"pr-watcher": 2,+ "privacy": 1,"reference-watch": 4,"refresh-local-llm-catalog": 4,"release-check": 14,+ "reliability": 1,"repo-sync": 1,- "security": 3,+ "security": 4,"simplify": 1,"stash-cleanup": 2,"test-coverage": 3,@@ -113,6 +123,9 @@"76cfcab471c1a555767b71b8b9932ae0","762506421c793074d172d3eb794fe866"],+ "api-contract": [+ "cf02b10a5993baf473e0d320771f26b6"+ ],"better-complexity": ["c92b99080d0453d70bb26a412fb48ce9"],@@ -227,6 +240,9 @@"2b6ed595287f0742bed9ecba6788afe6","eec33a9293f9393019917a6632dd964e"],+ "data-safety": [+ "86b07f51abdbcbe7016f840b5bb0cd9b"+ ],"dependency-updates": ["020d66b93698341c556eca1eee851bee","640a7c4214e6bdba2bbd5b9061d9d425",@@ -278,11 +294,15 @@"model-comparison-refresh": ["dc1702b07c7fb8be6165feb776d5acb6"],+ "observability": [+ "fdb4d77df5891cfb653a5da2553ecf8a"+ ],"performance": ["c8224243c15f6897ee04be25d172f021","4fea5eb3585bdc150980934b289016bc","672bd3958b12afb0f382bcebb6dc3b33",- "d7e3a80f42903fbf90be0efc9b559c0b"+ "d7e3a80f42903fbf90be0efc9b559c0b",+ "b69bf4cbd2b3c272b5650608c62cede3"],"plan-feature": ["9fbc2a2ded8f4533d1f0f6b9cb780b34",@@ -346,7 +366,8 @@"security": ["b199739b21a8c45ed3778b2339ebf55f","d0f54c1fbe62d067b1a23ee0a9f3528c",- "8e58c1305a391ac765b0b13ab9615eb3"+ "8e58c1305a391ac765b0b13ab9615eb3",+ "c5e35a12eeb06e6afe4617f4428fa1ab"],"stash-cleanup": ["f9de8b10937919ceb6656fbdb70179c4"diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.jsindex 2e71d1a09a..b487130f2b 100644--- a/server/services/taskPromptDefaults/prompts.js+++ b/server/services/taskPromptDefaults/prompts.js@@ -134,6 +134,16 @@ an explicitly closed concern is worse than a window spent idle.intended root, including through symlinks and encoded separators.- **Missing authorization** — an endpoint or action that checks who you are butnot whether you may do this, or checks neither.+- **Broken resource or tenant isolation** — where the application serves more+ than one principal, a query, object-store key, or cache entry not scoped to+ the caller's owner or tenant, so one caller can read or change another's data+ by guessing or iterating an id.+- **Server-side request forgery** — a URL, host, or webhook target supplied by a+ caller that the server fetches, letting it reach internal services, cloud+ metadata endpoints, or local files.+- **Unsafe deserialization and parsing** — untrusted bytes handed to a+ deserializer, template engine, archive extractor, or XML parser that can+ execute code, write outside its target, or exhaust memory.- **Unvalidated trust boundaries that are actually crossed** — data arrivingfrom another machine, a third-party API, or a model response, used withoutvalidation where a malformed or hostile value would do damage.@@ -306,13 +316,36 @@ scale the code actually sees. Say which one you have.- **Cache misuse** — a cache that never invalidates, one that never hits becauseits key varies, or an unbounded one that is really a leak.+## Required service and data-path coverage++For services, APIs, workers, and data pipelines, inspect the heaviest request+and job paths as well as any UI:++- **Query plans** — read the plan (EXPLAIN or the engine's equivalent) for the+ most frequent and the most expensive queries rather than inferring index use+ from the schema; watch for sequential scans, sorts spilling to disk, and plans+ that change with data volume.+- **Buffering instead of streaming** — a whole file, object, result set, or+ response body loaded into memory when it could be streamed or paged.+- **Batch shape** — bulk operations done one row or one request at a time, or+ batches so large they time out or hold locks for seconds.+- **Connection and concurrency limits** — pools sized below the concurrency the+ service accepts, work serialized behind one connection, or unbounded parallel+ fan-out that saturates a downstream.+- **Data layout for analytical reads** — reads that cannot prune partitions or+ push predicates down, many small files, row-oriented formats scanned for a+ few columns.+- **Serialization and startup cost** — repeated encode/decode of the same+ payload, and cold-start work on a serverless or per-request path.+## Required UI load and idle-network coverageFor apps with a UI, inspect the shared shell and at least one high-volumecollection route, plus a sibling tab that does not use that collection. Traceinitial reads, mounted hidden panels, polling timers, websocket invalidations,-and reconnect recovery. Include Brain inbox/memory, CoS history, and media-history when those surfaces exist; follow the app's collection-loading standard.+and reconnect recovery. Include the app's largest growing collections (inboxes,+histories, media libraries, logs) when they exist; follow the app's+collection-loading standard.When browser tooling is available, capture a cold route load, navigation to thesibling tab, and at least 60 seconds of idle network activity. Report request@@ -332,6 +365,9 @@ file a deduplicated coverage-gap issue with the missing check and next step.Never copy live personal records, hostnames, tokens, or raw private HAR bodiesinto reports; report redacted endpoint patterns and aggregate measurements.+Money and metered-quota spend belong to the cost-efficiency work; stay on+latency, throughput, and resource use.+## Do not trade correctness or clarity for a gain you cannot measureReject micro-optimizations with no measured effect, and any change that makes@@ -864,8 +900,8 @@ keyboard-inaccessible icon") — and file it as the UX finding, not as the a11y'data-safety': `[Improvement: {appName}] Data and upgrade-safety audit-Audit {appName} for changes that could corrupt, lose, or strand user data-across upgrades and machines.+Audit {appName} for changes and operations that could corrupt, lose, or strand+data across upgrades, deployments, environments, and machines.Repository: {repoPath}@@ -889,9 +925,23 @@ Hunt specifically for:field it never read.- **Read-modify-write races between two paths** that mutate the same record orfile and can drop one another's changes.--State the upgrade scenario explicitly for each finding: which install, holding-what, upgrading to what, and what breaks. Cross-version and cross-install+- **Backups that would not restore** — a backup that omits a store the+ application needs, has never been restored by any script or test, or restores+ into a shape the current code rejects.+- **Bulk and backfill operations without a safety net** — a mass update, delete,+ reprocessing, or backfill job with no dry run, no bounded scope, no batching,+ and no way to resume or undo when it stops halfway.+- **Retention and lifecycle rules that reach live data** — an expiry,+ compaction, or cleanup rule whose predicate or path can match data that is+ still in use.+- **Long-lived data formats** — datasets, archives, or exported files written in+ a shape the next version cannot read, with no version marker or reader for+ the old shape.++State the scenario explicitly for each finding: which install, environment, or+dataset, holding what, upgrading or running what, and what breaks. Runtime data+correctness (duplicates under retry, partial writes, lost updates) belongs to+the data-integrity work. Cross-version and cross-installcompatibility code is NOT dead code — read the project's rules on migrationsand version gates before proposing any such removal.`,@@ -1039,32 +1089,49 @@ coverage.`,'api-contract': `[Improvement: {appName}] API and route-contract audit-Audit {appName}'s API endpoints and route handlers for contract drift,-validation gaps, and error traps.+Audit {appName}'s API surface — HTTP routes, RPC services, GraphQL resolvers,+event and message contracts, and any published SDK or client — for contract+drift, validation gaps, and error traps.Repository: {repoPath}{modeInstructions}-Trace client callers through to server routes and schemas, hunting for:+Identify the framework and the project's own conventions (validation library,+error envelope, async wrapper, versioning scheme) before judging anything. Trace+callers — in-repo clients, SDKs, consumers of a published spec — through to the+handlers and schemas, hunting for:-- **Unvalidated inputs** — endpoints reading \`req.body\`/\`query\`/\`params\`- directly with no validation schema, letting malformed types into domain logic.-- **Client/server drift** — a client service sending a field no route reads, a- route requiring one the caller omits, or a caller awaiting a key the response+- **Unvalidated inputs** — handlers reading the request body, query, params, or+ message payload directly with no schema, letting malformed types into domain+ logic.+- **Caller/handler drift** — a caller sending a field no handler reads, a+ handler requiring one the caller omits, or a caller reading a key the responsenever carries.-- **Status and envelope errors** — a 200 carrying \`{ error }\`, a raw 500 for- bad client input, or a bare string where the app's \`{ error: message }\`- envelope is expected.-- **Async traps** — a route handler not wrapped in \`asyncHandler\`, where a- rejected promise hangs the request socket instead of reaching the error- middleware.-- **Loose schemas** — unbounded strings (no \`.max()\`), arbitrary keys (no- \`.strict()\`), or an enum accepting values downstream code cannot handle.-- **Method mismatch** — a mutation behind \`GET\`, or a non-idempotent \`PUT\`.--For each finding, name the caller AND the route with \`file.js:LINE\`, the shape-that gets through, and the concrete failure it produces.`,+- **Spec drift** — an OpenAPI, protobuf, GraphQL, or event schema that no longer+ matches the implementation, so generated clients and documentation are wrong.+- **Breaking changes to a published contract** — a renamed, removed, or retyped+ field, a changed default, or a reused protobuf field number on an API other+ systems consume, with no new version or deprecation path.+- **Status and envelope errors** — success statuses carrying errors, a server+ error for bad client input, or responses that break the project's own error+ envelope, so callers cannot tell retryable failures from permanent ones.+- **Async traps** — a handler whose rejected promise or thrown error bypasses+ the framework's error path (for example an Express handler missing the+ project's async wrapper), hanging the request instead of failing it.+- **Unsafe mutation semantics** — a mutation behind a safe method, a+ non-idempotent PUT or DELETE, or a create endpoint clients will retry with no+ idempotency key, producing duplicates on a timeout.+- **Unbounded or unstable collections** — list endpoints with no limit, no+ maximum page size, or offset pagination over data that changes underneath the+ caller.+- **Long work on a synchronous request** — an endpoint that does minutes of work+ inline where the contract should accept the job and report status.+- **Loose schemas** — unbounded strings, arbitrary extra keys, or an enum+ accepting values downstream code cannot handle.++For each finding, name the caller AND the handler with \`file:LINE\`, the shape+that gets through, and the concrete failure it produces for a consumer.`,'ui-lifecycle': `[Improvement: {appName}] UI lifecycle and state audit@@ -1126,10 +1193,23 @@ Hunt specifically for:- **Uninstrumented workflows** — a multi-step background pipeline or agenttransition with no progress logging, so a stuck job looks identical to a slowone.--For each finding, name the catch block or uninstrumented step and state the-operational blind spot it creates: what breaks, and how long before anyone-notices.`,+- **Lost correlation** — a request, job, or message id that is not carried+ across a service, queue, or thread boundary, so one failure's log lines cannot+ be joined together.+- **Nothing to alert on** — a critical path (request latency and error rate,+ queue depth or consumer lag, job success and duration, data freshness) with no+ metric or countable signal, so a degradation is only discovered by a user.+- **Health signals that do not reflect health** — a status or health endpoint+ that reports OK while a dependency the service needs is down, or that never+ reports degraded states.+- **No trail for consequential actions** — destructive, administrative, or+ permission-changing operations with no record of who did what and when,+ where the domain needs one.++Match the project's scale: a single-process tool needs good logs and a truthful+status view, not a tracing stack. For each finding, name the catch block,+uninstrumented step, or missing signal and state the operational blind spot it+creates: what breaks, and how long before anyone notices.`,'copy': `[Improvement: {appName}] Copy and text-clarity audit@@ -1573,6 +1653,284 @@ practical public boundary instead of deleting it.Cite the test file and case name with \`file:LINE\`, the source it claims tocover, and the probe result.`,+ 'infrastructure': `[Improvement: {appName}] Infrastructure and deployment audit++Audit how {appName} is built, packaged, deployed, and run, as described by the+configuration in its repository.++Repository: {repoPath}++{modeInstructions}++Inventory the infrastructure-as-code, container, orchestration, platform, process+manager, and CI/CD files first. Judge each against the environment it actually+targets — a local development compose file is not a production manifest, and+the project's documented deployment model decides which exposure is intended.++## Hunt for++- **Exposure beyond intent** — a storage bucket, database, admin port, or+ service reachable from a wider network than the design calls for: public ACLs,+ \`0.0.0.0/0\` ingress, a load balancer in front of an internal endpoint, a+ debug port published by a container.+- **Over-broad identity** — a role, service account, token, or CI permission+ granted wildcard actions or resources, or more than the workload uses; a+ long-lived static credential where the platform offers a short-lived one.+- **Secrets in configuration** — a credential committed in a manifest, a+ variables file, a CI file, or a baked-in image layer; a secret passed where it+ lands in logs or process listings.+- **Irreproducible builds and deploys** — an unpinned base image (\`latest\`), an+ unpinned CI action or provider plugin, a build step that fetches whatever is+ newest, a deploy that depends on state only one machine has.+- **Missing runtime guardrails** — no resource requests/limits, no health or+ readiness probe where the orchestrator uses one, a container running as root+ with a writable root filesystem it does not need, no restart policy for a+ long-running service.+- **Unsafe state and data configuration** — IaC state with no locking or no+ encryption, a storage resource with no encryption at rest, no versioning or+ deletion protection on data that cannot be regenerated, no backup policy.+- **CI/CD supply-chain and injection risk** — untrusted pull-request content+ reaching a privileged workflow context, script injection through+ interpolated event fields, artifacts published without provenance.+- **Environment drift** — two environments (or a manifest and the code that+ reads it) that disagree about a port, a variable, or a resource, so the first+ deploy to the other one fails.++## Not yours++Application-code vulnerabilities belong to the security work; package version+bumps to dependency updates; per-call timeouts and retries to the failure-path+work; process shutdown and health-endpoint behavior inside the code to the+reliability work. Name the overlap if it is the cause, then leave it to its owner.++## The bar++Every finding names the file and line, the environment it affects, and the+concrete consequence: who can reach what, what a leaked credential grants, or+which deploy breaks. Redact before you publish — describe a secret's location+and shape, never its value, and never paste account ids, hostnames, or addresses.`,++ 'data-integrity': `[Improvement: {appName}] Data integrity and pipeline audit++Audit whether the data {appName} ingests, transforms, stores, and serves stays+correct — no duplicates, no silent loss, no quietly wrong results — under the+retries, redeliveries, crashes, and concurrency it will actually see.++Repository: {repoPath}++{modeInstructions}++Inventory every write path first: request handlers that persist, ingestion and+import entry points, queue and stream consumers, batch, backfill, and+compaction jobs, and the formats data is stored in. Then trace what happens+when each one runs twice, stops halfway, or runs concurrently with itself.++## Hunt for++- **Non-idempotent writes under retry or redelivery** — a consumer on an+ at-least-once queue, a retried request, or a re-run job that inserts again+ instead of upserting by a natural or idempotency key, producing duplicates.+- **Partial writes visible to readers** — a multi-object or multi-table write+ with no transaction, commit protocol, manifest, or atomic rename, so a crash+ or a concurrent reader sees half a batch as if it were whole.+- **Lost updates** — read-modify-write on shared records with no transaction,+ row version, conditional write, or serialization, where two writers race.+- **Validation missing at the boundary** — records accepted from an upstream+ source with no schema check, so one malformed batch poisons everything+ downstream of it.+- **Schema evolution that breaks old data** — a stored format (table, column+ family, Parquet/Avro/JSON document, event payload) changed in a way readers+ of already-written data cannot handle: a renamed or retyped field, a new+ required field with no default, a partition layout change with no rewrite.+- **Semantic corruption** — time zones and naive timestamps mixed, floating+ point for money, NULL collapsed into empty or zero, truncation or precision+ loss on conversion, a join or aggregation that double-counts.+- **Unstable pagination and incremental reads** — offset pagination over data+ that changes underneath it, a high-water mark that skips late or equal+ timestamps, a sync cursor that loses records written during a read.+- **Deletion and retention that miss or overreach** — a retention job whose+ range or predicate can match live data, or a delete that leaves derived+ copies (indexes, caches, aggregates, replicas) inconsistent with the source.+- **Missing integrity checks on transfer** — a copy, upload, or replication with+ no checksum or row-count reconciliation, so truncation goes unnoticed.++## Not yours++Stored-format changes that need an upgrade migration, destructive defaults,+and backup/restore belong to the data-safety work; personal-data retention+obligations to the privacy work; call-level retries to the failure-path work.++## The bar++State the scenario for every finding: which write path, which failure or+interleaving (a retry, a crash between steps, two concurrent writers, a late+record), and exactly what the stored data looks like afterward. Cite+\`file:LINE\` for the write and for the caller that can trigger the scenario.`,++ 'reliability': `[Improvement: {appName}] Reliability and operability audit++Audit how {appName} behaves as a running service: when it starts, when it is+stopped or restarted, when load exceeds capacity, when it runs as more than one+instance, and when a deploy puts old and new versions side by side.++Repository: {repoPath}++{modeInstructions}++Inventory the process entry points, signal handling, health endpoints, queues+and worker pools, scheduled and background jobs, and the deployment shape the+repository describes (single process, replicas, serverless, a process manager).+Judge against that shape — a single-user tool on one machine does not need+leader election, and the project's documented deployment model is binding.++## Hunt for++- **Work dropped on shutdown** — no SIGTERM handling, or a handler that exits+ without draining in-flight requests, finishing or checkpointing jobs, and+ flushing buffered writes, so every deploy or restart loses work.+- **Health checks that lie or amplify** — a readiness check that reports ready+ before dependencies are usable, or a liveness check that fails when a+ dependency is down, so the orchestrator restart-loops a healthy process.+- **Unbounded intake** — an in-memory queue, buffer, fan-out, or worker pool+ with no bound or backpressure, so a burst turns into memory exhaustion instead+ of rejected or delayed work.+- **Jobs that run twice or never resume** — a scheduled job with no lock or+ lease when more than one instance can run it, or a long job with no+ checkpoint, so a crash restarts it from zero or leaves it half-done.+- **Startup fragility** — a process that crashes permanently when a dependency+ is briefly unavailable at boot instead of retrying, or that starts with+ invalid configuration and fails on the first request instead of at startup.+- **Mixed-version hazards** — a message, job payload, cache entry, or stored+ record whose shape changed such that the old and new versions running during a+ rolling deploy (or a rollback) misread each other.+- **Single points of failure the design did not choose** — process-local state+ (sessions, locks, rate counters, caches treated as truth) in a service that+ is deployed or scaled as multiple instances.+- **Self-inflicted overload** — synchronized timers or cron jobs that all fire+ at once, a thundering herd after a restart, a cache stampede on expiry.++## Not yours++Per-call timeouts, retry ceilings, and degraded-dependency fallbacks belong to+the failure-path work; latent code defects (missing awaits, leaks) to the+runtime-safety work; health-probe and resource-limit configuration in+manifests to the infrastructure work; missing metrics to the observability work.++## The bar++Every finding names the event (a deploy, a crash, a burst, a second instance),+the code path with \`file:LINE\`, and what is lost, duplicated, or unavailable+as a result. A resilience pattern the design does not need is not a finding.`,++ 'privacy': `[Improvement: {appName}] Privacy and data-governance audit++Audit how {appName} handles personal and sensitive data: where it goes, who and+what can see it, how long it stays, and whether it can be removed.++Repository: {repoPath}++{modeInstructions}++**Read the project's documented data model and sharing rules first and treat+them as binding.** A flow the project deliberately supports — syncing a user's+own data to machines they control, say — is not a finding because the data is+personal. The question is whether data reaches a place, audience, or lifetime+the design did not choose.++Inventory the personal and sensitive fields first (identity, contact, location,+health, financial, credentials, free-text a user wrote about themselves or+others), then trace each to every sink.++## Hunt for++- **Exposure in operational output** — personal data or secrets in log lines,+ error messages, crash reports, analytics events, URLs and query strings,+ cache keys, or file names, where far more people and systems can read them.+- **Over-sharing to third parties** — full records sent to an external API,+ model provider, telemetry service, or webhook when the task needed a field or+ a summary; no minimization or redaction before an outbound call.+- **API over-exposure** — responses that return fields the caller has no use+ for or no right to see, because a whole record is serialized instead of a+ projection.+- **Retention without an end** — personal data kept indefinitely with no+ retention rule, or temporary copies (exports, uploads, scratch files, debug+ dumps) that are never cleaned up.+- **Erasure that does not reach every copy** — a delete that removes the+ primary record but leaves derived datasets, search indexes, caches, backups+ the design says are prunable, or replicas holding it.+- **Real data in the wrong place** — production or personal records copied into+ test fixtures, seed files, documentation examples, or lower environments.+- **Unprotected sensitive stores** — sensitive data at rest with no encryption+ where the platform expects it, or access to it with no audit trail when the+ domain requires one.++## Not yours++Authentication, authorization, and injection belong to the security work; data+correctness to the data-integrity work; storage encryption flags in+infrastructure manifests to the infrastructure work. Name the overlap if it is+the cause.++## The bar++For each finding, name the field or data class, the source, the sink with+\`file:LINE\`, and the audience or lifetime it should not have. Never paste a+real personal value into a finding — describe the field, not its contents.`,++ 'cost-efficiency': `[Improvement: {appName}] Cost and resource-efficiency audit++Find where {appName} spends money or metered quota it does not need to: paid+API and model calls, cloud storage, query, compute, and egress.++Repository: {repoPath}++{modeInstructions}++Inventory the metered dependencies first — paid third-party APIs, AI model+providers, cloud object storage, warehouse or lake query engines, serverless+or managed compute, message services, and cross-region or internet egress —+then every call site, schedule, and retry path that reaches them.++## Estimate, never guess++A cost finding needs a rough quantity: how often the path runs, the unit cost+or what the bill scales with (calls, bytes scanned, bytes stored, GB-hours), and+how that grows with usage. State the estimate and its assumptions. "This could+be expensive" is not a finding.++## Hunt for++- **Paid calls repeated for the same answer** — a model or API call with no+ cache for identical inputs, a call re-made on every render, poll, or retry+ when the result could be reused.+- **Paid work nobody asked for** — calls on startup, background pre-generation,+ or batch fills the user did not trigger; honor the project's documented rules+ about when provider calls are allowed.+- **Retries that multiply spend** — retry loops around paid calls with no+ ceiling, or retries of errors that can never succeed.+- **Unbounded scans of metered stores** — listing an entire bucket, a query+ without a partition or date filter, \`SELECT *\` against a columnar store, a+ full-table scan where an index or predicate pushdown was available.+- **Storage that only grows** — no lifecycle rule moving cold data to a cheaper+ tier or expiring it, unbounded log or artifact retention, many small files+ where the engine charges or slows per file.+- **Over-provisioning** — always-on resources sized for peak, idle capacity+ that could scale to zero, a larger instance or model tier than the workload+ uses (a cheaper model would do the job).+- **Avoidable egress** — data moved across regions or out of the provider on a+ hot path when it could be processed in place.++## Not yours++Latency and throughput belong to the performance work, even when a fix also+saves money; resource limits in manifests belong to the infrastructure work.++## The bar++For each finding give \`file:LINE\`, the cost driver, the estimate with its+assumptions, the proposed change, and the expected saving. Reject changes that+save pennies at the cost of correctness or clarity.`,+'feature-ideas': `[Improvement: {appName}] Implement Next Planned FeatureYour goal is to implement the next planned item from PLAN.md, or brainstorm a new feature if no plan exists.diff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.jsindex 04f25a91da..f68882fcff 100644--- a/server/services/taskPromptDefaults/versions.js+++ b/server/services/taskPromptDefaults/versions.js@@ -33,10 +33,10 @@ export const PROMPT_VERSIONS = {// default persisted, sometimes mis-flagged promptCustomized) auto-upgrade to the// current {appName} body. See the retired-hash history in// integrity.snapshot.json + the self-heal in taskScheduleStore.js readSchedule().- 'security': 3, // v3: carries {modeInstructions} (the pre-v3 body had no placeholder, so its own "fix and commit" steps fought a file-issues dispatch) and defers to the project's documented threat model, requiring an attacker-or-accident story per finding instead of a generic OWASP checklist walk. Previously v2: generic {appName} body (older default hardcoded "PortOS"/"server/routes" paths)+ 'security': 4, // v4: adds tenant/resource isolation, SSRF, and unsafe deserialization — the service and data-API defects the v3 list (written for a web app) did not name. v3: carries {modeInstructions} (the pre-v3 body had no placeholder, so its own "fix and commit" steps fought a file-issues dispatch) and defers to the project's documented threat model, requiring an attacker-or-accident story per finding instead of a generic OWASP checklist walk. Previously v2: generic {appName} body (older default hardcoded "PortOS"/"server/routes" paths)'code-quality': 4, // v4: hands generated-artifact/hand-synced-registry/layout-coupling drift to the better-structural-drift lane and counted branching + reader cost to better-complexity / better-cognitive-load, keeping conventional maintainability defects — the split across PortOS's specialist tasks. Previously v3: inventory structural drift, duplicate sources of truth, volatile generated artifacts, and incidental-layout coupling before conventional maintainability checks. v2: generic {appName} body (older default hardcoded "PortOS")'test-coverage': 3, // v3: carries {modeInstructions}, ranks gaps by consequence rather than percentage, tests at the highest practical public boundary, requires naming the regression a new test uniquely catches, and hands existing-test quality to better-test-quality. Previously v2: generic {appName} body (older default hardcoded "PortOS")- 'performance': 4, // v4: requires UI route-load, idle-network and large-collection evidence; missing measurements are explicitly unverified.+ 'performance': 5, // v5: adds required service/data-path coverage (query plans, streaming vs buffering, batch shape, pools, partition pruning, cold start), hands spend to cost-efficiency, and replaces PortOS-specific collection names with generic ones — the prompt runs against every managed app. v4: requires UI route-load, idle-network and large-collection evidence; missing measurements are explicitly unverified.'accessibility': 5, // v5: the "skip what static analysis already covers" list now also names keyboard-trap/unreachable-control and faked-semantics findings, matching Biome's `useKeyWithClickEvents`, `noNoninteractiveElementToInteractiveRole`, `useFocusableInteractive`, and `noAriaHiddenOnFocusable` a11y rules (enabled in `client/biome.jsonc` alongside the four from v4) — the live-agent budget shifts further to focus-order/live-region/contrast/zoom issues static analysis still can't establish. Previously v4: checks for an existing JSX a11y linter (Biome's a11y group, jsx-a11y) first and skips findings it already catches deterministically (missing alt/labels, invalid/unsupported ARIA), so the live-agent budget goes to keyboard/focus/live-region/contrast/zoom issues static analysis can't establish. Previously v3: carries {modeInstructions}, names who is blocked and how far they get, and prefers a native element over a custom control with patched attributes. Previously v2: generic {appName} + the app UI (older default hardcoded "PortOS" + http://localhost:5555)'console-errors': 4, // v4: refer to framework-neutral UI lifecycle audit. v3: carries {modeInstructions}, collects real emitted output before diagnosing, groups duplicates by cause, and forbids "fixing" an error by suppressing it. Previously v2: unified `[Improvement: {appName}]` body (pre-unification defaults shipped separate self- and app-improvement bodies)'error-handling': 3, // v3: carries {modeInstructions} and covers resilience (timeouts, retry ceilings, degraded-dependency fallback, cleanup on the error path, actionable user-facing text) while handing swallowed errors and log context to observability. Previously v2: unified `[Improvement: {appName}]` body (older default used the `[App Improvement: {appName}]` header)@@ -47,12 +47,12 @@ export const PROMPT_VERSIONS = {'mobile-responsive': 3, // v3: carries {modeInstructions} and requires the viewport width plus what a user cannot do there, rather than flagging any layout that merely looks different. Previously v2: generic {appName} app-UI body (older default hardcoded "PortOS" + http://localhost:5555)'ux': 4, // v4: forge issues use plain human-readable titles and tracker-defined IDs; filing syntax/identity comes from {trackerInstructions}. v3: audits narrow monitors and widget containers, including clipped overflow and sidebar/zoom states.// v2: replaces the hardcoded "Read-only on source / no branches, no PRs" paragraph with {modeInstructions} — the audit is registered as file-issues-capable, so a do-work dispatch previously got a mode banner that its own body contradicted in two places. Previously v1: walk the running UI with Playwright MCP against a 7-item named UX checklist and file ONE tracker item per finding via {trackerInstructions} — read-only on source, no branches/PRs. Mode (file-issues vs implement) is injected at dispatch via {modeInstructions} / applyAuditModeWrapper — no prompt bump required.- 'data-safety': 1, // v1: data/upgrade-safety audit (migrations, schema parity, version gates). Mode injected at dispatch.+ 'data-safety': 2, // v2: generalizes beyond installs to deployments/environments/datasets and adds backup restorability, bulk/backfill safety, retention reach, and long-lived data formats; hands runtime data correctness to data-integrity. v1: data/upgrade-safety audit (migrations, schema parity, version gates). Mode injected at dispatch.'simplify': 1, // v1: dead-code/duplication audit. Mode injected at dispatch.'module-hygiene': 1, // v1: evidence-led complexity, responsibility, reuse, and reusable-surface discoverability audit. Mode injected at dispatch.- 'api-contract': 1, // v1: API/route-contract audit (validation gaps, client/server drift, status envelopes, asyncHandler). Net-new type (no retired-hash history needed). Mode injected at dispatch.+ 'api-contract': 2, // v2: framework-neutral (RPC, GraphQL, event contracts, SDKs — not only Express routes) and adds spec drift, breaking changes to published contracts, idempotency keys, pagination bounds, and long synchronous work. v1: API/route-contract audit (validation gaps, client/server drift, status envelopes, asyncHandler). Net-new type (no retired-hash history needed). Mode injected at dispatch.'ui-lifecycle': 2, // v2: framework-neutral UI lifecycle and state correctness. v1: lifecycle/state audit limited to React effects, stale closures, unmounted setState, and derived state. Mode injected at dispatch.- 'observability': 1, // v1: logging/observability audit (silent catches, log noise, missing error context, uninstrumented pipelines). Net-new type. Mode injected at dispatch.+ 'observability': 2, // v2: adds correlation across boundaries, alertable metrics for critical paths, truthful health signals, and audit trails, scaled to the project. v1: logging/observability audit (silent catches, log noise, missing error context, uninstrumented pipelines). Net-new type. Mode injected at dispatch.'copy': 1, // v1: copy/text-clarity audit (jargon, ambiguous action verbs, dead-end errors, pluralization). Net-new type. Mode injected at dispatch.// The `better-*` lanes are PortOS-owned specialist missions associated with@@ -66,6 +66,11 @@ export const PROMPT_VERSIONS = {'better-structural-drift': 1, // v1: derived artifacts as a second source of truth, position-keyed records, hand-synced registries, incidental-layout coupling — carved out of code-quality v3.'better-runtime-safety': 2, // Framework-neutral UI lifecycle overlap. Previous version: v1: latent defects (floating promises, unowned rejections, unguarded access, sentinel confusion, races, leaks) requiring a concrete failure scenario.'better-dependency-freedom': 1, // v1: dependency NECESSITY (the do:depfree lens) — classify, prove usage, size the replacement. Distinct from dependency-updates, which bumps what stays.+ 'infrastructure': 1, // v1: IaC/container/orchestration/CI audit — exposure, identity grants, secrets, pinning, runtime guardrails, state config, CI supply chain, environment drift. Net-new type. Mode injected at dispatch.+ 'data-integrity': 1, // v1: runtime data-correctness audit — idempotency under redelivery, partial writes, lost updates, boundary validation, schema evolution, semantic corruption, pagination, retention, transfer checks. Net-new type.+ 'reliability': 1, // v1: service reliability audit — shutdown draining, truthful health checks, backpressure, job leasing/checkpoints, startup fragility, mixed-version deploys. Net-new type.+ 'privacy': 1, // v1: personal/sensitive-data audit — operational exposure, third-party minimization, API over-exposure, retention, erasure reach, real data in fixtures. Honors the project's documented sharing model. Net-new type.+ 'cost-efficiency': 1, // v1: metered-spend audit — repeated paid calls, unrequested provider work, retry multiplication, unbounded scans, storage growth, over-provisioning, egress. Net-new type.'better-test-quality': 1, // v1: vacuous/weak/redundant existing tests, proven with a mutation probe. Distinct from test-coverage, which owns the gaps.'stash-cleanup': 2, // v2: the STALE/ABANDONED heuristic names `AGENTS.md` (or `CLAUDE.md`) as the policy file to check before assuming a stash contradicts current architecture (#4852). v1: triage git stash list — supersession check against main, drop superseded/stale entries, leave real unlanded work in place. Net-new type (no retired-hash history needed).'repo-sync': 1, // v1: verify + finish the deterministic install-wide origin-sync sweep (services/repoSync.js) — resolve mid-flight merges/rebases, decide what to do with uncommitted work, land or report unpushed branches, triage the stashes it could not prove redundant. Net-new type (no retired-hash history needed).diff --git a/server/services/taskScheduleRegistry.js b/server/services/taskScheduleRegistry.jsindex 036813842b..92ef4b1507 100644--- a/server/services/taskScheduleRegistry.js+++ b/server/services/taskScheduleRegistry.js@@ -349,6 +349,14 @@ export const DEFAULT_TASK_INTERVALS = {'better-runtime-safety': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, dataInputs: ['open-issues', 'open-pull-requests'], taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },'better-dependency-freedom': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, dataInputs: ['open-issues', 'open-pull-requests'], taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },'better-test-quality': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, dataInputs: ['open-issues', 'open-pull-requests'], taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },+ // Service and data-platform lenses (see AUDIT_DEFINITIONS). File-issues by+ // default — their findings usually touch production configuration — with+ // open issues + PRs preloaded for dedup like the do:better lanes above.+ 'infrastructure': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, dataInputs: ['open-issues', 'open-pull-requests'], taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },+ 'data-integrity': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, dataInputs: ['open-issues', 'open-pull-requests'], taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },+ 'reliability': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, dataInputs: ['open-issues', 'open-pull-requests'], taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },+ 'privacy': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, dataInputs: ['open-issues', 'open-pull-requests'], taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },+ 'cost-efficiency': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, dataInputs: ['open-issues', 'open-pull-requests'], taskMetadata: { fileIssues: true, useWorktree: false, openPR: false } },// Trusted remediation is separate from external intake. Legacy author// filter settings cannot widen this lane into untrusted contributor PRs.'pr-watcher': { type: INTERVAL_TYPES.ON_DEMAND, intervalMs: 1800000, enabled: true, providerId: null, model: null, prompt: null, taskMetadata: { prAuthorFilter: 'trusted', readOnly: false } },@@ -551,6 +559,11 @@ export const TASK_TYPE_DESCRIPTIONS = {'better-runtime-safety': 'Runtime safety — missing awaits, unhandled rejections, unguarded nulls, leaks, races; file issues (default) or implement fixes','better-dependency-freedom': 'Dependency freedom — replace micro-packages and native-API wrappers with in-repo code; file issues (default) or implement one removal','better-test-quality': 'Test quality — vacuous, weak, or redundant tests; file issues (default) or implement one cleanup',+ 'infrastructure': 'Infrastructure & deployment — IaC, containers, orchestration and CI: exposure, identity grants, secrets, pinning, limits; file issues (default) or implement fixes',+ 'data-integrity': 'Data integrity — idempotent ingestion, atomic writes, consistency, schema evolution of stored data; file issues (default) or implement fixes',+ 'reliability': 'Reliability — graceful shutdown, health/readiness, backpressure, job leasing, mixed-version deploys; file issues (default) or implement fixes',+ 'privacy': 'Privacy & data governance — personal data in logs/exports/third parties, minimization, retention and erasure; file issues (default) or implement fixes',+ 'cost-efficiency': 'Cost efficiency — metered API/model calls, unbounded scans, storage tiers, over-provisioning; file issues (default) or implement fixes','model-comparison-refresh': 'Research sourced model quality, effort, price, latency and quota evidence for Models Comparison','stash-cleanup': 'Triage git stash list — drop entries superseded by or stale relative to main, leave real unlanded work in place','repo-sync': 'Sync every managed app with origin — back on the default branch, pushed and pulled, merged branches/worktrees and redundant stashes cleared',