Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: prioritize worst audit findings and report app quality scores

[._.]/ Adam Eivy196e5c4e3977
diff --git a/client/src/components/AppTile.jsx b/client/src/components/AppTile.jsx
index 6ad3ab3f9b..4c0b03ef4d 100644
--- a/client/src/components/AppTile.jsx
+++ b/client/src/components/AppTile.jsx
@@ -1,3 +1,4 @@
+import AppQuality from './apps/AppQuality';
import { useState, memo } from 'react';
import { Link } from 'react-router';
import StatusBadge from './StatusBadge';
@@ -69,6 +70,7 @@ const AppTile = memo(function AppTile({ app, onUpdate }) {
<StatusBadge status={app.overallStatus} size="sm" />
</div>
+ <div className="mb-2"><AppQuality app={app} /></div>
{/* Ports */}
<div className="mb-2 flex flex-wrap gap-1">
{app.uiPort && (
diff --git a/client/src/components/apps/AppQuality.jsx b/client/src/components/apps/AppQuality.jsx
new file mode 100644
index 0000000000..5a83587024
--- /dev/null
+++ b/client/src/components/apps/AppQuality.jsx
@@ -0,0 +1,47 @@
+import { Link } from 'react-router';
+import { formatDateShort } from '../../utils/formatters';
+
+export default function AppQuality({ app, detail = false }) {
+ const quality = app.quality;
+ const score = quality?.score;
+ const label = quality?.unavailable ? 'Quality unavailable'
+ : score == null ? 'Quality: not assessed' : `Quality: ${score}/100`;
+ if (!detail) return (
+ <Link to={`/apps/${app.id}/overview`} className="text-xs text-port-accent hover:underline" title="View audit scores and coverage">
+ {label}{score != null && ` · ${quality.ratedCategories}/${quality.totalCategories} categories`}
+ </Link>
+ );
+ return (
+ <section aria-label="App quality" className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">
+ <h3 className="font-semibold text-white">{label}</h3>
+ <p className="text-xs text-gray-400">
+ Assessments describe the code before fixes. The overall score is the equal-weight mean of broad, medium/high-confidence assessments from the last 30 days.
+ {' '}{quality?.ratedCategories ?? 0}/{quality?.totalCategories ?? 0} categories contribute. Missing, partial, low-confidence and stale assessments are excluded, not counted as perfect.
+ </p>
+ <Link to={`/apps/${app.id}/tasks`} className="inline-block text-sm text-port-accent hover:underline">Configure or run scheduled audits</Link>
+ {!!quality?.categories?.length && (
+ <details>
+ <summary className="cursor-pointer text-sm text-port-accent">Category breakdown</summary>
+ <div className="overflow-x-auto">
+ <table className="w-full text-sm text-left">
+ <thead className="text-gray-400"><tr><th className="py-2 pr-3">Category</th><th className="pr-3">Score</th><th>Evidence</th></tr></thead>
+ <tbody>{quality.categories.map(category => (
+ <tr key={category.id} className="border-t border-port-border align-top">
+ <th scope="row" className="py-2 pr-3 font-medium">{category.label}</th>
+ <td className="py-2 pr-3 whitespace-nowrap">{category.score == null ? '—' : `${category.score}/100`}</td>
+ <td className="py-2 text-xs text-gray-400">
+ <div>{category.stale ? 'Stale · ' : ''}{category.coverage}{category.confidence && ` · ${category.confidence} confidence`}
+ {category.assessedAt && ` · ${formatDateShort(category.assessedAt)}`}</div>
+ {category.summary && <p className="mt-1 break-words">{category.summary}</p>}
+ {category.totalFiles > 0 && <div>{category.scannedFiles}/{category.totalFiles} files scanned · Worst severity: {category.worstSeverity}/10</div>}
+ {category.agentId && <Link className="text-port-accent hover:underline" to={`/cos/agents/${category.agentId}`}>Audit run</Link>}
+ </td>
+ </tr>
+ ))}</tbody>
+ </table>
+ </div>
+ </details>
+ )}
+ </section>
+ );
+}
diff --git a/client/src/components/apps/AppQuality.test.jsx b/client/src/components/apps/AppQuality.test.jsx
new file mode 100644
index 0000000000..4ac67481f3
--- /dev/null
+++ b/client/src/components/apps/AppQuality.test.jsx
@@ -0,0 +1,21 @@
+import { render, screen } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+import { it, expect } from 'vitest';
+import AppQuality from './AppQuality';
+
+it('shows zero as a real score and explains excluded categories in the breakdown', () => {
+ const app = { id: 'portos-default', quality: { score: 0, ratedCategories: 1, totalCategories: 25, 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' },
+ ] } };
+ render(<MemoryRouter><AppQuality app={app} detail /></MemoryRouter>);
+ expect(screen.getByRole('heading', { name: 'Quality: 0/100' })).toBeInTheDocument();
+ expect(screen.getByText('Stale · partial')).toBeInTheDocument();
+ expect(screen.getByText(/1\/25 categories contribute/)).toBeInTheDocument();
+ expect(screen.getByRole('link', { name: /Configure/ })).toHaveAttribute('href', '/apps/portos-default/tasks');
+});
+
+it('links an unassessed tile to its app overview without inventing a score', () => {
+ render(<MemoryRouter><AppQuality app={{ id: 'other' }} /></MemoryRouter>);
+ expect(screen.getByRole('link', { name: 'Quality: not assessed' })).toHaveAttribute('href', '/apps/other/overview');
+});
diff --git a/client/src/components/apps/tabs/OverviewTab.jsx b/client/src/components/apps/tabs/OverviewTab.jsx
index 0dd04aca34..40c5387bc7 100644
--- a/client/src/components/apps/tabs/OverviewTab.jsx
+++ b/client/src/components/apps/tabs/OverviewTab.jsx
@@ -1,3 +1,4 @@
+import AppQuality from '../AppQuality';
import { useState, useEffect, useMemo } from 'react';
import { Link, useNavigate } from 'react-router';
import { FolderOpen, Gamepad2, Terminal, Code, RefreshCw, Wrench, Archive, ArchiveRestore, Download, Tag, AlertTriangle, Rocket, Camera, Image, Sparkles, Trash2 } from 'lucide-react';
@@ -124,6 +125,7 @@ export default function OverviewTab({ app, onRefresh }) {
Kanban board, which needed the full page width, now live on the app's
own JIRA tab.) */}
<div className="space-y-6 max-w-5xl">
+ <AppQuality app={app} detail />
{/* Details Grid */}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
<div>
diff --git a/client/src/pages/Apps.jsx b/client/src/pages/Apps.jsx
index 4efc77e134..c0509f0956 100644
--- a/client/src/pages/Apps.jsx
+++ b/client/src/pages/Apps.jsx
@@ -1,3 +1,4 @@
+import AppQuality from '../components/apps/AppQuality';
import { useState, useEffect, useCallback, useRef } from 'react';
import { Link } from 'react-router';
import { ExternalLink, Gamepad2, Play, Square, RotateCcw, FolderOpen, Terminal, Code, RefreshCw, Wrench, Archive, ArchiveRestore, Ticket, Download, Hammer, Smartphone, Trash2, AlertTriangle } from 'lucide-react';
@@ -348,6 +349,7 @@ export default function Apps() {
<StatusBadge status={app.overallStatus} size="sm" />
)}
</div>
+ <AppQuality app={app} />
<div className="text-xs text-gray-500 flex flex-wrap gap-x-2 mt-1">
{isNonPm2 ? (
<span className="text-gray-500">{app.repoPath}</span>
diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.js
index b03ba2e13b..b47ba547e6 100644
--- a/client/src/services/apiApps.js
+++ b/client/src/services/apiApps.js
@@ -2,8 +2,8 @@ import toast from '../components/ui/Toast';
import { request, API_BASE } from './apiCore.js';
// Apps
-export const getApps = (options) => request('/apps', options);
-export const getApp = (id, options) => request(`/apps/${id}`, options);
+export const getApps = (options) => request('/apps?includeQuality=true', options);
+export const getApp = (id, options) => request(`/apps/${id}?includeQuality=true`, options);
// Managed checkout topology: returns sanitized local/fork/upstream revision
// state without exposing machine-local repo paths.
export const getAppRepositorySources = (id, options = {}) =>
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index bb88d42b04..da4912ee45 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -379,3 +379,16 @@ Timeline render ID, so restart can reconcile output without new provider work.
Project sync v10 gates cut validation and explicit audio semantics. Older Video
audio settings default to native clip audio when read; new drafts explicitly
select a contract. No new store, seed or data-rewriting migration is required.
+
+### Managed app quality assessments
+
+`app_quality_assessments` is `db-primary`: one latest assessment per managed
+app/category, queried together for the dashboard and management pages. The app
+registry is still file-backed, so app ids are opaque scoped keys; reads select
+only currently registered apps. PostgreSQL stores the bounded JSON report and
+agent provenance; no asset bytes or new JSON store. Additive `CREATE TABLE IF
+NOT EXISTS` in boot schema and init-db.sql provisions both existing and new
+installs without transforming existing records. No seed or backfill fabricates
+scores. The mandatory Postgres backup includes the table. These assessments
+remain machine-local: they describe this install's checkout and agent evidence,
+and are not included in peer sync or capability/status payloads.
diff --git a/docs/features/app-quality.md b/docs/features/app-quality.md
new file mode 100644
index 0000000000..541359d660
--- /dev/null
+++ b/docs/features/app-quality.md
@@ -0,0 +1,75 @@
+# App quality assessments
+
+The dashboard app tiles, Apps list, and each app's Overview show a quality score.
+Open **Category breakdown** in Overview to see the evidence, coverage, date,
+confidence, worst-finding severity and originating CoS run. This includes PortOS's
+baseline app. **Configure or run scheduled audits** opens that app's Tasks tab.
+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
+for 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
+verified exemption or an existing issue. Existing unresolved issues still affect
+the assessment. Low churn alone does not exempt a severe hotspot. Each category
+has its own discovery strategy in `server/lib/auditQuality.js`; these instructions
+are injected at dispatch even when an install customized its stored prompt.
+File-only versus fix mode remains authoritative.
+
+## Scoring
+
+Auditors assess the **pre-fix** category from 0–100, where higher is healthier:
+
+| Score | Meaning |
+| --- | --- |
+| 90–100 | No material defect found after broad evidence |
+| 70–89 | Localized moderate debt |
+| 40–69 | Significant recurring or widespread problems |
+| 10–39 | Severe defects in core workflows |
+| 0–9 | Pervasive critical failure |
+
+Worst-finding severity is a separate 0–10 value (higher is worse; 0 means no
+material finding verified). An issue being filed, or one fix being made, is not
+an automatic score improvement. Scores express an auditor's judgment supported
+by the scan and inspection, not a certification or an exhaustive proof.
+
+The overall score is the rounded, equal-weight average of the latest eligible
+category assessments: **broad** discovery coverage, medium/high confidence, and
+at most 30 days old. Broad means the signal scan covered the entire declared
+eligible inventory; deep investigation still stays bounded. Partial, stale,
+low-confidence, unavailable and inapplicable assessments remain visible but do
+not contribute. Missing categories do not count as 100. The contributing category
+count 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.
+Database failures show **unavailable** while app management stays usable.
+
+The completion sentinel summary contains one `QUALITY_AUDIT_JSON: {...}` line
+with the versioned report described in the dispatch prompt. The parser rejects
+out-of-range scores, wrong categories, contradictory coverage counts, duplicate
+markers and malformed JSON. Missing/invalid output never invents a score or
+replaces a previous valid measurement; the prior measurement keeps its original
+date and expires normally. Assessment collection does not relax commit/PR gates.
+The run's recorded start time orders measurements so delayed recovery cannot
+replace newer evidence. PostgreSQL stores the latest report per app/category,
+locally and within the ordinary database backup; no old runs are guessed into
+scores and no extra audit batch is enabled automatically.
+
+## Coverage review
+
+The existing catalog already separates conventional quality, cyclomatic
+complexity, cognitive load, structural drift, module hygiene, dead code and
+duplication, dependencies, typing, API contracts, runtime safety, error handling,
+observability, performance, test coverage, test quality and documentation.
+Security and data/upgrade safety cover their respective trust and persistence
+boundaries. Product-facing coverage comes from UX (including onboarding and
+successful task completion), UI bugs, console errors, accessibility,
+mobile/responsive behavior and copy clarity.
+
+This change keeps those 25 lenses rather than adding overlapping tasks.
+Real-user product outcomes such as retention or satisfaction cannot be inferred
+reliably from a source audit and are not fabricated into this codebase score.
+A future distinct category must register both its scheduled prompt and a
+repository discovery strategy; the catalog parity test prevents an auditor
+without a search strategy.
diff --git a/server/lib/README.md b/server/lib/README.md
index 945bfd0ba5..c58bb3c92e 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -631,3 +631,5 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `videoTimelineFades.js` | Browser-safe `fitFades()` proportionally fits a fade pair to its visible duration. Shared by timeline normalization/export and the editor preview/trim controls; legacy import paths re-export it. |
| `voiceEngines.js` | Shared TTS engine IDs, display metadata, supported-engine set, and persisted configuration keys. |
+
+| `auditQuality.js` | Category discovery strategies, assessment prompt and strict schema, sentinel parsing, and freshness-aware app quality aggregation. |
diff --git a/server/lib/auditCatalog.js b/server/lib/auditCatalog.js
index 4f39db9cd8..bf80abe2b9 100644
--- a/server/lib/auditCatalog.js
+++ b/server/lib/auditCatalog.js
@@ -36,7 +36,7 @@ Your deliverable is tracker items, not code. The run must end with the same \`gi
## How to run this audit
-1. **Pick a bounded slice and say so first.** Do NOT attempt the whole repository. Choose one coherent area (a feature directory, a route group, a handful of related screens) — prefer one that recent audit issues have not already covered — and open your report by naming the slice in one line.
+1. **Scan broadly, then bound the investigation.** Follow the repository-wide discovery and ranking contract below BEFORE choosing a slice. Deep-review the strongest candidates in one coherent area; do not attempt to deeply read the whole repository.
2. **Complete a substantive review before filing.** Spend most of the available run budget investigating and validating candidates, reserving time for de-duplication, filing, and the final report. Within the bounded slice, inventory at least three distinct relevant paths or components (or all of them if fewer exist), then inspect their callers, consumers, tests, and relevant history. Finding or filing the first issue is NOT a stopping condition: continue through the remaining inventory, including when the first candidate is a duplicate or rejected. Stop when the inventory is reviewed, the configured run budget is nearly exhausted, or a concrete blocker prevents further review; do not idle to fill time or exceed the run budget.
3. **Read the actual code.** Every finding must cite \`path/to/file.js:LINE\` and describe a concrete, reproducible impact: a reachable runtime/data failure, a CI or release failure, or recurring manual churn demonstrated by repository history. Delete subjective style preferences and any finding whose consequence you cannot prove.
4. **De-duplicate before filing.** Follow the Inventory step under "Where to record findings" above. If it is already filed, skip it; comment on the existing item only when you have genuinely new evidence.
@@ -54,7 +54,7 @@ export const DO_WORK_MODE_CONTRACT = `## Mode: implement the highest-value fix
This banner OVERRIDES any later instruction to file issues, leave source unchanged, or skip commits. Pick ONE coherent, high-value finding from the mission below and implement it this run. Do not boil the ocean.
-1. **Pick a bounded slice** and say so first.
+1. **Scan broadly, rank candidates, then pick a bounded slice** containing the highest-impact actionable finding. Follow the discovery contract below before choosing.
2. **Read the actual code** and the project's \`AGENTS.md\` / conventions. Honor documented non-issues.
3. **Implement the fix** — the smallest change that actually solves the concrete problem. If the only obstacle was a design choice, make the call and state it.
4. **Verify** with the project's tests (or a focused new test when the path is untested and a silent break would cost data, money, or quota).
diff --git a/server/lib/auditQuality.js b/server/lib/auditQuality.js
new file mode 100644
index 0000000000..5bfd42c6e9
--- /dev/null
+++ b/server/lib/auditQuality.js
@@ -0,0 +1,95 @@
+import { z } from 'zod';
+import { AUDIT_DEFINITIONS } from './auditCatalog.js';
+import { safeJSONParse } from './jsonIo.js';
+
+const REPORT_PREFIX = 'QUALITY_AUDIT_JSON: ';
+
+// Each lens must explain how to find candidates before choosing a slice.
+export const AUDIT_DISCOVERY = Object.freeze({
+ security: 'Inventory trust boundaries, credential handling, process execution and input-to-sink paths; rank reachable exploit impact under the documented trust model.',
+ 'code-quality': 'Inventory source directories and convention violations; search brittle conditions, duplicated policy and magic values, ranking demonstrated defects and recurring maintenance cost.',
+ 'test-coverage': 'Map public routes, workflows and destructive actions to integration tests; rank untested high-impact outcomes, not uncovered line counts.',
+ performance: 'Inventory hot routes, loops, queries and large payloads; use existing profiling or bounded measurements to rank latency, memory and repeated work.',
+ accessibility: 'Inventory shared controls and screens; scan semantic roles, labels, focus and contrast, then verify the most reused controls and critical keyboard journeys.',
+ documentation: 'Compare setup, upgrade and public API documentation against scripts and implementations; rank instructions that break installation or cause data loss first.',
+ 'ui-bugs': 'Inventory routes and shared components; trace primary actions, loading/error/empty states and navigation, then reproduce the highest-reach broken workflows.',
+ 'mobile-responsive': 'Scan all layouts for fixed widths, grids, overflow and touch targets; test the most reused layouts and primary journeys at narrow widths.',
+ 'error-handling': 'Inventory external I/O and failure boundaries; search swallowed rejections and missing recovery, ranking data loss and stranded user operations first.',
+ typing: 'Inventory unsafe casts, any, nullable values and external schemas; rank mismatches at public and persistence boundaries by reachable failure.',
+ 'console-errors': 'Inventory startup and critical routes, inspect available browser/server diagnostics, then reproduce recurring errors with the widest user impact.',
+ ux: 'Inventory primary user goals and route flows; rank blocked task completion, onboarding friction, navigation dead ends and missing recovery, then walk the worst journeys.',
+ 'data-safety': 'Inventory destructive writes, migrations, backup/restore and cross-version payloads; rank irreversible data loss and incompatible upgrades first.',
+ simplify: 'Scan source exports, callers and repeated blocks across the repository; rank proven dead subsystems and duplicated behavior by maintenance cost and drift.',
+ 'module-hygiene': 'Inventory module sizes, imports, responsibilities and catalogs across source roots; inspect the largest responsibility tangles and most reused missing abstractions.',
+ 'api-contract': 'Inventory all routes, schemas and clients; compare request/response and version contracts, prioritizing destructive writes and widely consumed APIs.',
+ 'react-lifecycle': 'Scan effects, subscriptions, async state updates and shared hooks across components; rank resource leaks, stale writes and corrupted user state.',
+ observability: 'Inventory critical workflows and their failure/status signals; rank invisible data loss, silent failures and operations that cannot be diagnosed.',
+ copy: 'Inventory shared messages, destructive confirmations, setup and empty/error screens; rank wording that causes wrong actions or prevents task completion.',
+ 'better-complexity': 'Run an available language-aware complexity analyzer over all first-party source roots. Otherwise use repository-wide branching searches to shortlist functions, then count decision points manually. Publish the top measured functions and counts; file length is only a discovery hint.',
+ 'better-cognitive-load': 'Scan deeply nested control flow, boolean flags, mixed abstraction levels and misleading names across source roots; rank reader cost in critical, widely used workflows.',
+ 'better-structural-drift': 'Inventory generators, duplicated registries and derived artifacts; inspect independently edited sources of truth and position-keyed records, ranking demonstrated drift and merge churn.',
+ '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.',
+});
+
+export function auditQualityInstructions(taskType) {
+ if (!Object.hasOwn(AUDIT_DEFINITIONS, taskType)) return '';
+ return `## Repository-wide discovery, worst offender first, and quality assessment
+
+This contract overrides narrower slice-selection or ranking advice in the mission, including customized prompts. Preserve the selected file-issues/fix mode and documented non-issues.
+1. Inventory all first-party source roots with git ls-files or rg --files, excluding vendored/generated/build/dependency output. Do a cheap repository-wide signal scan BEFORE choosing where to investigate. Do not deep-read the entire repository.
+2. Category search: ${AUDIT_DISCOVERY[taskType]}
+3. Rank at least the top five candidates (or all if fewer), with paths, measured signals, impact, reach, confidence and why higher candidates win. Validate the top candidates through callers, tests and relevant history before filing or fixing. Severity and user impact outrank ease, small scope and recency. Churn and fan-in break ties; inactivity alone never dismisses a severe offender. If the raw worst is exempt, already filed or not actionable, report why and continue down the ranking. Existing unresolved issues still count against quality. Never pick a nit while a verified major problem remains actionable.
+4. Keep investigation bounded after this scan. Report scanned roots, tools/commands, candidate ranking, exclusions, reviewed paths, unreviewed inventory and stopping reason. If tools or budget prevent broad discovery, report partial coverage, never claim a global worst or a clean repository.
+5. Assess the PRE-FIX codebase for this category on 0–100 (higher is healthier): 90–100 no material defect found after broad evidence; 70–89 localized moderate debt; 40–69 significant recurring or widespread problems; 10–39 severe/core-workflow defects; 0–9 pervasive critical failure. Score the category, not the agent's performance or issue count. Explain the score using severity, prevalence and concrete evidence. Do not award points merely for filing or fixing this run. Use score:null for unavailable or inapplicable assessment; zero is a real score.
+6. Score the worst finding's severity separately on 1–10: 1–3 minor localized impact, 4–6 material recurring cost, 7–8 major workflow/reliability impact, 9–10 critical data/security/availability failure. Use 0 only when no material finding was verified. List this severity for every finding in the narrative.
+7. Include exactly one single-line QUALITY_AUDIT_JSON: {...} in your completion sentinel summary AND final response, with no secrets or personal data. Replace the example values with observed evidence. The category is fixed to this task; do not rate other categories. Keep ordinary completion/PR instructions and summaries too.
+QUALITY_AUDIT_JSON: {"version":1,"category":"${taskType}","score":null,"worstSeverity":0,"coverage":"unavailable","confidence":"low","summary":"Explain the assessment and strongest evidence","scannedFiles":0,"totalFiles":0}
+Allowed coverage: broad, partial, unavailable, not-applicable. Allowed confidence: low, medium, high. scannedFiles counts files actually included in the category signal scan; totalFiles is the eligible inventory. Broad requires the whole inventory to be scanned (deep review remains bounded). Partial scores are provisional and excluded from the overall score. If unavailable or not-applicable, score must be null and explain why. Even a zero-finding audit returns this assessment.`;
+}
+
+export const appQualityQuerySchema = z.object({ includeQuality: z.enum(['true', 'false']).optional() });
+
+export const auditQualityReportSchema = z.object({
+ version: z.literal(1),
+ category: z.string().refine(value => Object.hasOwn(AUDIT_DEFINITIONS, value)),
+ score: z.number().int().min(0).max(100).nullable(),
+ worstSeverity: z.number().int().min(0).max(10),
+ coverage: z.enum(['broad', 'partial', 'unavailable', 'not-applicable']),
+ confidence: z.enum(['low', 'medium', 'high']),
+ summary: z.string().trim().min(1).max(2000),
+ scannedFiles: z.number().int().nonnegative(),
+ totalFiles: z.number().int().nonnegative(),
+}).strict().refine(r => r.scannedFiles <= r.totalFiles)
+ .refine(r => ['unavailable', 'not-applicable'].includes(r.coverage) ? r.score === null : r.score !== null && r.scannedFiles > 0)
+ .refine(r => r.coverage !== 'broad' || (r.totalFiles > 0 && r.scannedFiles === r.totalFiles));
+
+export function parseAuditQualityReport(summary, category) {
+ if (typeof summary !== 'string') return null;
+ const lines = summary.split(/\r?\n/).filter(line => line.startsWith(REPORT_PREFIX));
+ if (lines.length !== 1) return null;
+ const parsed = auditQualityReportSchema.safeParse(safeJSONParse(lines[0].slice(REPORT_PREFIX.length), null));
+ return parsed.success && parsed.data.category === category ? parsed.data : null;
+}
+
+export const AUDIT_FRESHNESS_MS = 30 * 24 * 60 * 60 * 1000;
+
+export function summarizeAppQuality(records = [], now = Date.now()) {
+ const categories = Object.entries(AUDIT_DEFINITIONS).map(([id, definition]) => {
+ const record = records.find(row => row.category === id);
+ const report = auditQualityReportSchema.safeParse(record?.report);
+ const valid = report.success && report.data.category === id;
+ 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, stale };
+ });
+ const rated = categories.filter(c => !c.stale && c.coverage === 'broad' && c.confidence !== 'low' && c.score !== null);
+ return {
+ score: rated.length ? Math.round(rated.reduce((sum, c) => sum + c.score, 0) / rated.length) : null,
+ ratedCategories: rated.length,
+ totalCategories: categories.length,
+ categories,
+ };
+}
diff --git a/server/lib/db.catalogDdlParity.test.js b/server/lib/db.catalogDdlParity.test.js
index 44d4e03996..6b8499f506 100644
--- a/server/lib/db.catalogDdlParity.test.js
+++ b/server/lib/db.catalogDdlParity.test.js
@@ -37,6 +37,7 @@ const DB_JS = [
].join('\n');
const CATALOG_TABLES = [
+ 'app_quality_assessments',
'catalog_scraps',
'catalog_ingredients',
'catalog_ingredient_sources',
diff --git a/server/lib/db/schema/core.js b/server/lib/db/schema/core.js
index 742cb2dc4f..115539d238 100644
--- a/server/lib/db/schema/core.js
+++ b/server/lib/db/schema/core.js
@@ -3,6 +3,14 @@
// zero behavior change; every statement is idempotent and runs on every boot.
// Parity-locked against server/scripts/init-db.sql by db.catalogDdlParity.test.js.
export const coreDdl = [
+ `CREATE TABLE IF NOT EXISTS app_quality_assessments (
+ app_id TEXT NOT NULL,
+ category TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ assessed_at TIMESTAMPTZ NOT NULL,
+ report JSONB NOT NULL,
+ PRIMARY KEY (app_id, category)
+ )`,
`ALTER TABLE memories ADD COLUMN IF NOT EXISTS sync_sequence BIGSERIAL`,
`ALTER TABLE memories ADD COLUMN IF NOT EXISTS origin_instance_id VARCHAR(36)`,
`CREATE INDEX IF NOT EXISTS idx_memories_origin_instance ON memories (origin_instance_id)`,
diff --git a/server/lib/index.js b/server/lib/index.js
index 1e061ae3ea..f61c37bded 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -611,3 +611,5 @@ export * from './providerTypes.js';
export * from './notificationTypes.js';
export * from './videoTimelineFades.js';
export * from './voiceEngines.js';
+
+export * from './auditQuality.js';
diff --git a/server/routes/apps/crud.js b/server/routes/apps/crud.js
index 3b05684c26..7e8fb3df5d 100644
--- a/server/routes/apps/crud.js
+++ b/server/routes/apps/crud.js
@@ -1,3 +1,5 @@
+import { appQualityQuerySchema } from '../../lib/auditQuality.js';
+import { enrichAppsWithQuality } from '../../services/appQuality.js';
/**
* App CRUD + status enrichment + archive lifecycle.
*
@@ -31,13 +33,17 @@ const router = Router();
// GET /api/apps - List all apps. The route fetches the raw records; the
// appListEnrichment service owns the PM2 status/port/process enrichment.
router.get('/', asyncHandler(async (req, res) => {
- const apps = await appsService.getAllApps();
- res.json(await enrichAppsWithPm2Status(apps));
+ const { includeQuality } = validateRequest(appQualityQuerySchema, req.query);
+ const apps = await enrichAppsWithPm2Status(await appsService.getAllApps());
+ // The bare list is the frozen peer-probe contract. Local UI opts into
+ // assessment prose explicitly so it never rides automatic federation probes.
+ res.json(includeQuality === 'true' ? await enrichAppsWithQuality(apps) : apps);
}));
// GET /api/apps/:id - Get single app
router.get('/:id', loadApp, asyncHandler(async (req, res) => {
const app = req.loadedApp;
+ const { includeQuality } = validateRequest(appQualityQuerySchema, req.query);
// Non-PM2 apps skip PM2 status
let statuses = {};
@@ -88,7 +94,8 @@ router.get('/:id', loadApp, asyncHandler(async (req, res) => {
hasSubmodules = gitmodules;
}
- res.json({ ...app, uiPort, devUiPort, apiPort, overallStatus, degraded, pm2Status: statuses, appVersion, hasSubmodules, hasDeployScript: hasDeployScript(app), xcodeScripts: checkScripts(app) });
+ const [enrichedApp] = includeQuality === 'true' ? await enrichAppsWithQuality([app]) : [app];
+ res.json({ ...enrichedApp, uiPort, devUiPort, apiPort, overallStatus, degraded, pm2Status: statuses, appVersion, hasSubmodules, hasDeployScript: hasDeployScript(app), xcodeScripts: checkScripts(app) });
}));
// POST /api/apps - Create new app
diff --git a/server/routes/apps/crud.test.js b/server/routes/apps/crud.test.js
index 046840dc8c..457299561d 100644
--- a/server/routes/apps/crud.test.js
+++ b/server/routes/apps/crud.test.js
@@ -1,7 +1,9 @@
+vi.mock('../../services/appQuality.js', () => ({ enrichAppsWithQuality: vi.fn(async apps => apps.map(app => ({ ...app, quality: { score: 75 } }))) }));
import { describe, it, expect, vi, beforeEach } from 'vitest';
import express from 'express';
import { request } from '../../lib/testHelper.js';
import crudRoutes from './crud.js';
+import { enrichAppsWithQuality } from '../../services/appQuality.js';
// Mock the services this router (and its port-config service) touch.
vi.mock('../../services/apps.js', () => ({
@@ -74,6 +76,20 @@ describe('Apps CRUD Routes', () => {
expect(response.body[0].overallStatus).toBe('online');
});
+ it('keeps quality reports off peer probes and returns them only for explicit local UI reads', async () => {
+ appsService.getAllApps.mockResolvedValue([{ id: 'portos-default', name: 'PortOS', type: 'ios-native', repoPath: '/tmp/test' }]);
+ const peer = await request(app).get('/api/apps');
+ expect(peer.body[0].quality).toBeUndefined();
+ expect(enrichAppsWithQuality).not.toHaveBeenCalled();
+ const local = await request(app).get('/api/apps?includeQuality=true');
+ expect(local.body[0].quality).toEqual({ score: 75 });
+ const invalid = await request(app).get('/api/apps?includeQuality=anything');
+ expect(invalid.status).toBe(400);
+ appsService.getAppById.mockResolvedValue({ id: 'portos-default', name: 'PortOS', type: 'ios-native' });
+ const detail = await request(app).get('/api/apps/portos-default?includeQuality=true');
+ expect(detail.body.quality).toEqual({ score: 75 });
+ });
+
it('should handle apps with no PM2 processes', async () => {
const mockApps = [
{ id: 'app-001', name: 'Test App', pm2ProcessNames: [], repoPath: '/tmp/test' }
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 9c9a20a689..4ed87440ae 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -1944,3 +1944,13 @@ DROP TRIGGER IF EXISTS trg_tribe_touchpoints_audit ON tribe_touchpoints;
CREATE TRIGGER trg_tribe_touchpoints_audit AFTER UPDATE OR DELETE ON tribe_touchpoints FOR EACH ROW EXECUTE FUNCTION record_audit_log();
DROP TRIGGER IF EXISTS trg_tribe_identities_audit ON tribe_identities;
CREATE TRIGGER trg_tribe_identities_audit AFTER UPDATE OR DELETE ON tribe_identities FOR EACH ROW EXECUTE FUNCTION record_audit_log();
+
+-- Latest machine-local scheduled audit assessment per managed app/category.
+CREATE TABLE IF NOT EXISTS app_quality_assessments (
+ app_id TEXT NOT NULL,
+ category TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ assessed_at TIMESTAMPTZ NOT NULL,
+ report JSONB NOT NULL,
+ PRIMARY KEY (app_id, category)
+ );
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index b94e2f4b5a..150c4ec559 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -1,3 +1,4 @@
+import { isAuditTaskType } from '../lib/auditCatalog.js';
import { isPrivateSecurityTask } from '../lib/privateSecurityPolicy.js';
/**
* Agent Finalization
@@ -700,6 +701,7 @@ export function dispatchTaskOutputHookOnce({
}
const hookDispatch = dispatchTaskOutputHook({
+ assessedAt: agent?.startedAt,
agentId,
task,
success,
@@ -1373,11 +1375,19 @@ async function recoverBareSentinelPayload(contents, taskType) {
* task types (no hook). The hook receives `{ appId, success, payload, ... }` and
* loads its own app/config — finalizeAgent stays domain-agnostic.
*/
-async function dispatchTaskOutputHook({ agentId, task, success, workspacePath, readPayload = true, recovery = false }) {
+async function dispatchTaskOutputHook({ agentId, task, success, workspacePath, assessedAt, readPayload = true, recovery = false }) {
// Shared resolver with evaluateSuccessCriteria's gate — "runs a hook" and "gets
// the programmatic-I/O criterion" must stay the same question (#2727).
const taskType = resolveTaskHookType(task);
if (!taskType) return { ran: false };
+ if (isAuditTaskType(taskType)) {
+ const { recordAuditQuality } = await import('./appQuality.js');
+ await recordAuditQuality({ task, taskType, agentId, success, assessedAt,
+ workspacePath: readPayload ? (workspacePath || task?.metadata?.repoPath) : null })
+ .catch(err => emitLog('warn', `⚠️ Audit quality was not saved for ${agentId}: ${err.message}`, { agentId }));
+ // Assessment telemetry never waives commit/PR success criteria for fix mode.
+ return { ran: false };
+ }
const { getTaskOutputHook } = await import('./taskTypeHooks.js');
const hook = await getTaskOutputHook(taskType);
if (!hook) return { ran: false };
diff --git a/server/services/agentFinalization.outputHooks.test.js b/server/services/agentFinalization.outputHooks.test.js
index 1a73f08e5c..0208c64023 100644
--- a/server/services/agentFinalization.outputHooks.test.js
+++ b/server/services/agentFinalization.outputHooks.test.js
@@ -1,3 +1,5 @@
+vi.mock('./appQuality.js', () => ({ recordAuditQuality: vi.fn(async () => true) }));
+import { recordAuditQuality } from './appQuality.js';
// The goal-fidelity gate (#5994) reaches a local model at completion. Pinned OFF
// here so these tests exercise the path they are about without depending on the
// developer's own reviewer settings — and so a machine that HAS a local reviewer
@@ -58,6 +60,7 @@ describe('recovery output-hook dispatch (#3182)', () => {
persistedAgent = {
id: 'agent-example',
status: 'running',
+ startedAt: '2026-09-10T00:00:00Z',
metadata: {},
};
getAgent.mockImplementation(async () => persistedAgent);
@@ -72,6 +75,15 @@ describe('recovery output-hook dispatch (#3182)', () => {
getTaskOutputHook.mockResolvedValue(hook);
});
+ it('captures audit telemetry on the shared completion path without waiving fix-mode delivery criteria', async () => {
+ const task = { ...TASK, metadata: { ...TASK.metadata, analysisType: 'better-complexity' } };
+ await expect(dispatchTaskOutputHookOnce({ agentId: 'agent-audit', task, success: true, workspacePath: '/worktree' }))
+ .resolves.toEqual({ ran: false });
+ expect(recordAuditQuality).toHaveBeenCalledWith({ task, taskType: 'better-complexity', agentId: 'agent-audit', success: true, workspacePath: '/worktree', assessedAt: persistedAgent.startedAt });
+ expect(hook).not.toHaveBeenCalled();
+ expect(updateAgent).not.toHaveBeenCalled();
+ });
+
it.each([
['orphan cleanup', false],
['post-restart completion', true],
diff --git a/server/services/appQuality.db.test.js b/server/services/appQuality.db.test.js
new file mode 100644
index 0000000000..11892c100f
--- /dev/null
+++ b/server/services/appQuality.db.test.js
@@ -0,0 +1,38 @@
+// Only npm run test:db (portos_test); each run owns its scoped rows.
+import { afterAll, describe, expect, it } from 'vitest';
+import { checkHealth, ensureSchema, query, close } from '../lib/db.js';
+import { requireDbOrSkip } from '../lib/dbTestGate.js';
+import { recordAuditQuality, enrichAppsWithQuality } from './appQuality.js';
+
+const health = await checkHealth().catch(error => ({ connected: false, error: error.message }));
+const runDb = requireDbOrSkip('appQuality', health.connected, health.error);
+const appId = `test-quality-${process.pid}-${Date.now()}`;
+
+afterAll(async () => {
+ if (runDb) await query('DELETE FROM app_quality_assessments WHERE app_id = $1', [appId]);
+ await close();
+});
+
+describe.skipIf(!runDb)('app quality persistence', () => {
+ it('keeps the newest assessment across duplicate completion and delayed recovery, isolated by app', async () => {
+ await ensureSchema();
+ const now = Date.now();
+ const write = (offset, score, success = true) => recordAuditQuality({
+ task: { metadata: { app: appId } }, taskType: 'better-complexity',
+ agentId: `agent-${offset}`, workspacePath: '/test-repo', success,
+ assessedAt: new Date(now + offset).toISOString(),
+ }, { readFile: async () => `QUALITY_AUDIT_JSON: ${JSON.stringify({
+ version: 1, category: 'better-complexity', score, worstSeverity: 7,
+ coverage: 'broad', confidence: 'high', summary: 'Measured dispatcher branching.', scannedFiles: 50, totalFiles: 50,
+ })}` });
+ await write(-2000, 30);
+ await write(-1000, 65);
+ await write(-1000, 10); // repeated completion cannot rewrite its assessment
+ await write(-2000, 5); // recovery of an older run cannot supersede it
+ await write(0, 99, false); // failed run cannot overwrite measured evidence
+ const [app, other] = await enrichAppsWithQuality([{ id: appId }, { id: `${appId}-other` }]);
+ expect(app.quality).toMatchObject({ score: 65, ratedCategories: 1 });
+ expect(other.quality.score).toBeNull();
+ expect(app.quality.categories.find(category => category.id === 'better-complexity')).toMatchObject({ agentId: 'agent--1000', score: 65 });
+ });
+});
diff --git a/server/services/appQuality.js b/server/services/appQuality.js
new file mode 100644
index 0000000000..211eba3301
--- /dev/null
+++ b/server/services/appQuality.js
@@ -0,0 +1,45 @@
+/** Machine-local, DB-primary audit measurements. Reads never dispatch AI work. */
+import { ensureSchema, query } from '../lib/db.js';
+import { doneSentinelPath, parseSentinelPayload } from '../lib/agentSentinel.js';
+import { tryReadFile } from '../lib/fileCore.js';
+import { parseAuditQualityReport, summarizeAppQuality } from '../lib/auditQuality.js';
+
+export async function recordAuditQuality({ task, taskType, agentId, workspacePath, success, assessedAt }, deps = {}) {
+ if (!success || !workspacePath || !task?.metadata?.app || !agentId) return false;
+ const contents = await (deps.readFile || tryReadFile)(doneSentinelPath(workspacePath, agentId));
+ const { summary } = parseSentinelPayload(contents);
+ const report = parseAuditQualityReport(summary, taskType);
+ if (!report) return false;
+ // Latest measurement per category, idempotent for repeated completion. A
+ // delayed recovery of an older task must not replace a newer assessment.
+ if (!Number.isFinite(Date.parse(assessedAt))) return false;
+ await (deps.ensureSchema || ensureSchema)();
+ await (deps.query || query)(
+ `INSERT INTO app_quality_assessments (app_id, category, agent_id, assessed_at, report)
+ VALUES ($1, $2, $3, $4, $5::jsonb)
+ ON CONFLICT (app_id, category) DO UPDATE SET
+ agent_id = EXCLUDED.agent_id, assessed_at = EXCLUDED.assessed_at, report = EXCLUDED.report
+ WHERE app_quality_assessments.assessed_at < EXCLUDED.assessed_at`,
+ [task.metadata.app, taskType, agentId, assessedAt, JSON.stringify(report)]
+ );
+ return true;
+}
+
+export async function enrichAppsWithQuality(apps, deps = {}) {
+ if (!apps.length) return apps;
+ // One indexed query per list, not one per tile, and no history/log scans.
+ const result = await (deps.query || query)(
+ `SELECT app_id, category, agent_id, assessed_at, report FROM app_quality_assessments WHERE app_id = ANY($1::text[])`,
+ [apps.map(app => app.id)]
+ ).catch(err => {
+ console.error(`❌ App quality unavailable: ${err.message}`);
+ return null;
+ });
+ return apps.map(app => ({
+ ...app,
+ quality: result ? summarizeAppQuality(result.rows.filter(row => row.app_id === app.id).map(row => ({
+ category: row.category, agentId: row.agent_id,
+ assessedAt: new Date(row.assessed_at).toISOString(), report: row.report,
+ }))) : { ...summarizeAppQuality(), unavailable: true },
+ }));
+}
diff --git a/server/services/appQuality.test.js b/server/services/appQuality.test.js
new file mode 100644
index 0000000000..5d92e1a8de
--- /dev/null
+++ b/server/services/appQuality.test.js
@@ -0,0 +1,67 @@
+import { describe, it, expect, vi } from 'vitest';
+import { recordAuditQuality, enrichAppsWithQuality } from './appQuality.js';
+import { AUDIT_DEFINITIONS } from '../lib/auditCatalog.js';
+import { AUDIT_DISCOVERY, auditQualityInstructions, parseAuditQualityReport, summarizeAppQuality, AUDIT_FRESHNESS_MS } from '../lib/auditQuality.js';
+
+const report = (overrides = {}) => ({ version: 1, category: 'better-complexity', score: 35, worstSeverity: 8,
+ coverage: 'broad', confidence: 'high', summary: 'The checkout has a major branching hotspot in the job dispatcher.', scannedFiles: 100, totalFiles: 100, ...overrides });
+const sentinel = value => `Completed audit.\nQUALITY_AUDIT_JSON: ${JSON.stringify(value)}\n`;
+const task = { metadata: { app: 'portos-default' } };
+const assessedAt = '2026-09-10T00:00:00Z';
+
+// Unique regression: audits must persist a validated, app-scoped measurement
+// without turning a missing/malformed report into a perfect score.
+describe('scheduled audit measurement workflow', () => {
+ it('covers every scheduled audit lens with a discovery strategy and score contract', () => {
+ expect(Object.keys(AUDIT_DISCOVERY).sort()).toEqual(Object.keys(AUDIT_DEFINITIONS).sort());
+ for (const category of Object.keys(AUDIT_DEFINITIONS)) {
+ expect(auditQualityInstructions(category)).toContain(AUDIT_DISCOVERY[category]);
+ expect(auditQualityInstructions(category)).toContain(`"category":"${category}"`);
+ }
+ expect(auditQualityInstructions('claim-issue')).toBe('');
+ });
+
+ it('accepts the structured sentinel envelope and uses server-owned app, category and run provenance', async () => {
+ const query = vi.fn().mockResolvedValue({ rows: [] });
+ const ensureSchema = vi.fn();
+ await expect(recordAuditQuality({ task, taskType: 'better-complexity', agentId: 'agent-1', workspacePath: '/repo', success: true, assessedAt }, {
+ readFile: vi.fn().mockResolvedValue(JSON.stringify({ summary: sentinel(report()), payload: null })), query, ensureSchema,
+ })).resolves.toBe(true);
+ expect(query.mock.calls[0][1]).toEqual(['portos-default', 'better-complexity', 'agent-1', assessedAt, JSON.stringify(report())]);
+
+ });
+
+ it('rejects malformed, cross-category, duplicate and dishonest coverage reports and failed runs without writing', async () => {
+ const query = vi.fn();
+ const run = { task, taskType: 'better-complexity', agentId: 'agent-1', workspacePath: '/repo', success: true, assessedAt };
+ for (const contents of ['', sentinel(report({ score: 101 })), sentinel(report({ score: '35' })), sentinel(report({ category: 'security' })), sentinel(report({ scannedFiles: 3 })), sentinel(report({ coverage: 'unavailable' })), sentinel(report()) + sentinel(report())]) {
+ expect(await recordAuditQuality(run, { readFile: async () => contents, query })).toBe(false);
+ }
+ expect(await recordAuditQuality({ ...run, success: false }, { readFile: async () => sentinel(report()), query })).toBe(false);
+ expect(query).not.toHaveBeenCalled();
+ expect(parseAuditQualityReport(sentinel(report({ score: 0 })), 'better-complexity')?.score).toBe(0);
+ });
+
+ it('excludes stale, partial, low-confidence and inapplicable assessments while retaining their breakdown', () => {
+ const now = Date.now();
+ const records = [
+ ['better-complexity', 0, 'broad', 'high', now],
+ ['code-quality', 80, 'broad', 'medium', now],
+ ['security', 100, 'partial', 'high', now],
+ ['ux', 100, 'broad', 'high', now - AUDIT_FRESHNESS_MS - 1],
+ ['typing', null, 'not-applicable', 'low', now],
+ ['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.categories.find(c => c.id === 'ux')).toMatchObject({ score: 100, stale: true });
+ expect(summarizeAppQuality().score).toBeNull();
+ });
+
+ it('makes database unavailability explicit without failing app management', async () => {
+ const log = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const [app] = await enrichAppsWithQuality([{ id: 'app' }], { query: vi.fn().mockRejectedValue(new Error('offline')) });
+ expect(app.quality).toMatchObject({ unavailable: true, score: null });
+ log.mockRestore();
+ });
+});
diff --git a/server/services/cosTaskGenerator.auditMode.test.js b/server/services/cosTaskGenerator.auditMode.test.js
index 106b37f5bf..e0ffdac3fc 100644
--- a/server/services/cosTaskGenerator.auditMode.test.js
+++ b/server/services/cosTaskGenerator.auditMode.test.js
@@ -180,6 +180,8 @@ describe('issues-only audit dispatch never acquires code-shipping instructions (
// Positive control: the file-issues contract IS what rendered, so the
// negatives above are not passing on an empty or truncated prompt.
expect(prompt).toContain('Mode: file issues, change nothing');
+ expect(prompt).toContain('Repository-wide discovery, worst offender first');
+ expect(prompt).toContain(`"category":"${taskType}"`);
expect(prompt).toContain('## Completion (No Code Output)');
expect(prompt).not.toContain('{modeInstructions}');
expect(prompt).not.toContain('{trackerInstructions}');
@@ -209,6 +211,8 @@ describe('issues-only audit dispatch never acquires code-shipping instructions (
const prompt = renderPrompt(task);
expect(prompt).toContain('Mode: implement the highest-value fix');
+ expect(prompt).toContain('Repository-wide discovery, worst offender first');
+ expect(prompt).toContain(`"category":"${taskType}"`);
expect(prompt).toMatch(/^## Completion Workflow$/m);
expect(prompt).toMatch(/^\s*\d+\.\s+`\/do:push/m);
});
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index a2e912f6c6..438520fb95 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -1,3 +1,4 @@
+import { auditQualityInstructions } from '../lib/auditQuality.js';
import { isPrivateSecurityTask, PRIVATE_SECURITY_DELIVERY } from '../lib/privateSecurityPolicy.js';
/**
* CoS Task Generator Module
@@ -2722,7 +2723,9 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st
}
const planConstraintBlock = buildPlanConstraintBlock(metadata.planId);
- const modeInstructions = isAuditTaskType(taskType) ? modeContractFor(fileIssues) : '';
+ const modeInstructions = isAuditTaskType(taskType)
+ ? `${modeContractFor(fileIssues)}\n\n${auditQualityInstructions(taskType)}`
+ : '';
const baseDescription = await buildImprovementTaskDescription({
promptTemplate: applyAuditModeWrapper(promptTemplate, modeInstructions),
app, promptTaskType, metadata,
diff --git a/server/services/taskPromptDefaults.test.js b/server/services/taskPromptDefaults.test.js
index 1d18d9c5af..867030e154 100644
--- a/server/services/taskPromptDefaults.test.js
+++ b/server/services/taskPromptDefaults.test.js
@@ -118,7 +118,7 @@ describe('taskPromptDefaults integrity snapshot', () => {
['better-test-quality', ['Vacuous', 'mutation probe', 'Deletion is a valid outcome', 'Missing coverage is separate work']],
])('%s states the discipline that makes it its own lane', (key, markers) => {
const current = DEFAULT_TASK_PROMPTS[key];
- expect(PROMPT_VERSIONS[key]).toBe(1);
+ expect(PROMPT_VERSIONS[key]).toBe(key === 'better-complexity' ? 2 : 1);
for (const marker of markers) expect(current, key).toContain(marker);
});
diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.json
index 639d21b649..8b30975326 100644
--- a/server/services/taskPromptDefaults/integrity.snapshot.json
+++ b/server/services/taskPromptDefaults/integrity.snapshot.json
@@ -3,7 +3,7 @@
"accessibility": "76cfcab471c1a555767b71b8b9932ae0",
"api-contract": "cf02b10a5993baf473e0d320771f26b6",
"better-cognitive-load": "a1fe22f6ef936131456c55a6b0623204",
- "better-complexity": "c92b99080d0453d70bb26a412fb48ce9",
+ "better-complexity": "c99f67b43ff54a1c8cf0176c721d9c06",
"better-dependency-freedom": "8a79c8be829f926bbc7720ee29818d53",
"better-runtime-safety": "4259ab85dd3eaf8efb16a250187bd857",
"better-structural-drift": "941389a1f1c8983eef4f87af1241fbf9",
@@ -58,7 +58,7 @@
"accessibility": 3,
"api-contract": 1,
"better-cognitive-load": 1,
- "better-complexity": 1,
+ "better-complexity": 2,
"better-dependency-freedom": 1,
"better-runtime-safety": 1,
"better-structural-drift": 1,
@@ -111,6 +111,9 @@
"b07cfe1e367411036ef1d4cc4b6e9d2e",
"372916803f32b82da38a5b2130a54baf"
],
+ "better-complexity": [
+ "c92b99080d0453d70bb26a412fb48ce9"
+ ],
"branch-reconcile": [
"7ef2b5f7d8f05937d4912b26ad45f42e",
"ecb0621588a751b1383ecd89cf514382",
diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.js
index 6455d8261f..ef66176ac9 100644
--- a/server/services/taskPromptDefaults/prompts.js
+++ b/server/services/taskPromptDefaults/prompts.js
@@ -1091,10 +1091,11 @@ changes, and by how many callers depend on it:
git log --since='90 days ago' --name-only --format='' | sort | uniq -c | sort -rn | head -40
\`\`\`
-A high-complexity function in a file nothing has touched in a year is stable by
-revealed preference — record that you found it and move on. A high-complexity
-function inside the top churn files is where defects are actively being
-introduced.
+Low churn is a ranking factor, never an automatic exclusion. A severe complexity
+hotspot can still dominate risk in stable code. Compare the highest measured
+counts across the repository before selecting a fix; explain with evidence if
+you pass over the raw worst offender. Recent churn and caller reach increase
+priority when the measured complexity and impact are otherwise similar.
## Reject these — high branching is correct here
diff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.js
index 0da2180c3b..8b4da163a4 100644
--- a/server/services/taskPromptDefaults/versions.js
+++ b/server/services/taskPromptDefaults/versions.js
@@ -62,7 +62,7 @@ export const PROMPT_VERSIONS = {
// (DO_BETTER_LENS_COVERAGE in lib/auditCatalog.js), so an improvement here is
// a candidate to push upstream rather than to diverge silently. Net-new types
// (no retired-hash history needed). Mode injected at dispatch.
- 'better-complexity': 1, // v1: counted branching per function, ranked by churn/fan-in, with a named transformation and a behavior-preservation contract.
+ 'better-complexity': 2, // v2: compare repository-wide worst offenders; low churn is not an exclusion. v1: counted branching per function, ranked by churn/fan-in, with a named transformation and a behavior-preservation contract.
'better-cognitive-load': 1, // v1: reader cost (mixed abstraction, flag arguments, lying names, action at a distance) — explicitly NOT the size/nesting thresholds its siblings own.
'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': 1, // v1: latent defects (floating promises, unowned rejections, unguarded access, sentinel confusion, races, leaks) requiring a concrete failure scenario.
diff --git a/server/vitest.config.db.js b/server/vitest.config.db.js
index d7653c01fb..10ebf2daf3 100644
--- a/server/vitest.config.db.js
+++ b/server/vitest.config.db.js
@@ -15,6 +15,7 @@ process.env.NODE_ENV = 'test';
* listed explicitly below (the drift guard fails the build if you forget).
*/
export const DB_TEST_INCLUDE = [
+ 'services/appQuality.db.test.js',
'**/db.test.js',
'services/catalogDB.test.js',
'services/catalogDB.facets.db.test.js',