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: retain audit measurements and chart app quality over time
[._.]/ Adam Eivyce866d7c55f1
diff --git a/client/src/components/apps/AppQuality.jsx b/client/src/components/apps/AppQuality.jsxindex 5a83587024..a233dee208 100644--- a/client/src/components/apps/AppQuality.jsx+++ b/client/src/components/apps/AppQuality.jsx@@ -1,3 +1,4 @@+import AppQualityHistory from './AppQualityHistory';import { Link } from 'react-router';import { formatDateShort } from '../../utils/formatters';@@ -19,6 +20,7 @@ export default function AppQuality({ app, detail = false }) {{' '}{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>+ <AppQualityHistory appId={app.id} categories={quality?.categories} />{!!quality?.categories?.length && (<details><summary className="cursor-pointer text-sm text-port-accent">Category breakdown</summary>diff --git a/client/src/components/apps/AppQuality.test.jsx b/client/src/components/apps/AppQuality.test.jsxindex 4ac67481f3..a4b2ce8ca3 100644--- a/client/src/components/apps/AppQuality.test.jsx+++ b/client/src/components/apps/AppQuality.test.jsx@@ -1,14 +1,16 @@import { render, screen } from '@testing-library/react';import { MemoryRouter } from 'react-router';-import { it, expect } from 'vitest';+import { it, expect, vi } from 'vitest';import AppQuality from './AppQuality';+vi.mock('../../services/apiApps', () => ({ getAppQualityHistory: vi.fn().mockResolvedValue({ points: [], totalCategories: 25 }) }));-it('shows zero as a real score and explains excluded categories in the breakdown', () => {+it('shows zero as a real score and explains excluded categories in the breakdown', async () => {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>);+ await screen.findByText(/No scored assessments/);expect(screen.getByRole('heading', { name: 'Quality: 0/100' })).toBeInTheDocument();expect(screen.getByText('Stale · partial')).toBeInTheDocument();expect(screen.getByText(/1\/25 categories contribute/)).toBeInTheDocument();diff --git a/client/src/components/apps/AppQualityHistory.jsx b/client/src/components/apps/AppQualityHistory.jsxnew file mode 100644index 0000000000..e2a23806a0--- /dev/null+++ b/client/src/components/apps/AppQualityHistory.jsx@@ -0,0 +1,67 @@+import { useEffect, useState } from 'react';+import { useSearchParams } from 'react-router';+import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';+import { getAppQualityHistory } from '../../services/apiApps';++export default function AppQualityHistory({ appId, categories = [] }) {+ const [params, setParams] = useSearchParams();+ const days = ['30', '90', '365'].includes(params.get('qualityDays')) ? params.get('qualityDays') : '90';+ const category = categories.some(c => c.id === params.get('qualityCategory')) ? params.get('qualityCategory') : 'overall';+ const [state, setState] = useState({ loading: true });+ const [refresh, setRefresh] = useState(0);+ useEffect(() => {+ let active = true;+ setState({ loading: true });+ getAppQualityHistory(appId, days).then(data => {+ if (active) setState({ data });+ }).catch(() => {+ if (active) setState({ error: true });+ });+ return () => { active = false; };+ }, [appId, days, refresh]);+ const change = (key, value) => setParams(previous => {+ const next = new URLSearchParams(previous);+ next.set(key, value);+ return next;+ });+ const points = (state.data?.points || []).map(point => ({ ...point,+ value: category === 'overall' ? point.score : point.categories[category]?.score ?? null,+ evidence: category === 'overall' ? `${point.ratedCategories}/${state.data.totalCategories} categories` :+ `${point.categories[category]?.coverage ?? 'unavailable'} · ${point.categories[category]?.confidence ?? 'unknown'} confidence`,+ }));+ const measured = points.filter(p => p.value !== null);+ return (+ <div className="space-y-3">+ <h4 className="text-sm font-medium">Quality over time</h4>+ <div className="flex flex-wrap gap-3 text-sm">+ <label>Period <select className="bg-port-bg border border-port-border rounded p-1" value={days} onChange={e => change('qualityDays', e.target.value)}>+ <option value="30">30 days</option><option value="90">90 days</option><option value="365">1 year</option>+ </select></label>+ <label>Category <select className="bg-port-bg border border-port-border rounded p-1 max-w-full" value={category} onChange={e => change('qualityCategory', e.target.value)}>+ <option value="overall">Overall</option>{categories.map(c => <option key={c.id} value={c.id}>{c.label}</option>)}+ </select></label>+ <button type="button" className="text-port-accent hover:underline" onClick={() => setRefresh(n => n + 1)}>Refresh history</button>+ </div>+ <p className="text-xs text-gray-400">Daily snapshots (UTC), higher is healthier. Scores carry forward for up to 30 days; gaps mean no fresh evidence. Coverage changes can move the overall mean. Category views include provisional assessments.</p>+ {state.loading ? <p role="status">Loading quality history…</p> : state.error ? <p role="alert">Quality history could not be loaded. Use Refresh history to retry.</p> : !measured.length ? <p className="text-sm text-gray-400">No scored assessments in this period. Run an audit to start the history.</p> : <>+ <div className="h-56 w-full" role="img" aria-label="Daily quality scores from 0 to 100; values and evidence are available in the history table below">+ <ResponsiveContainer width="100%" height="100%">+ <LineChart data={points} margin={{ top: 8, right: 12, bottom: 8, left: 0 }}>+ <CartesianGrid strokeDasharray="3 3" stroke="#374151" />+ <XAxis dataKey="date" tick={{ fill: '#9ca3af', fontSize: 11 }} minTickGap={40} />+ <YAxis domain={[0, 100]} tick={{ fill: '#9ca3af', fontSize: 11 }} width={35} />+ <Tooltip contentStyle={{ backgroundColor: '#111827', borderColor: '#374151' }} formatter={(value, _name, item) => [`${value}/100 · ${item.payload.evidence}`, 'Quality']} />+ <Line type="stepAfter" dataKey="value" name="Quality" stroke="#60a5fa" strokeWidth={2} connectNulls={false} dot={measured.length === 1} isAnimationActive={false} />+ </LineChart>+ </ResponsiveContainer>+ </div>+ <details><summary className="cursor-pointer text-sm text-port-accent">History values and coverage</summary>+ <div className="max-h-64 overflow-auto"><table className="w-full text-left text-xs">+ <thead><tr><th>Date (UTC)</th><th>Score</th><th>Evidence</th></tr></thead>+ <tbody>{points.map(point => <tr key={point.date}><th scope="row" className="py-1 font-normal">{point.date}</th><td>{point.value == null ? '—' : `${point.value}/100`}</td><td>{point.evidence}</td></tr>)}</tbody>+ </table></div>+ </details>+ </>}+ </div>+ );+}diff --git a/client/src/components/apps/AppQualityHistory.test.jsx b/client/src/components/apps/AppQualityHistory.test.jsxnew file mode 100644index 0000000000..a45e82ee85--- /dev/null+++ b/client/src/components/apps/AppQualityHistory.test.jsx@@ -0,0 +1,22 @@+import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import { MemoryRouter, useLocation } from 'react-router';+import { it, expect, vi } from 'vitest';+import AppQualityHistory from './AppQualityHistory';+import { getAppQualityHistory } from '../../services/apiApps';+vi.mock('../../services/apiApps', () => ({ getAppQualityHistory: vi.fn() }));+vi.mock('recharts', () => ({ ResponsiveContainer: () => <div>Chart</div>, LineChart: () => null, Line: () => null, XAxis: () => null, YAxis: () => null, CartesianGrid: () => null, Tooltip: () => null }));+function Location() { return <output>{useLocation().search}</output>; }+it('loads shared filters, displays category evidence, and recovers after a failed range change', async () => {+ getAppQualityHistory.mockResolvedValueOnce({ totalCategories: 25, points: [{ date: '2026-09-10', score: 80, ratedCategories: 2, categories: { security: { score: 40, coverage: 'partial', confidence: 'medium' } } }] });+ render(<MemoryRouter initialEntries={['/?qualityDays=30&qualityCategory=security&tab=overview']}><AppQualityHistory appId="portos-default" categories={[{ id: 'security', label: 'Security' }]} /><Location /></MemoryRouter>);+ expect(await screen.findByText('40/100')).toBeInTheDocument();+ expect(screen.getByText('partial · medium confidence')).toBeInTheDocument();+ expect(getAppQualityHistory).toHaveBeenCalledWith('portos-default', '30');+ getAppQualityHistory.mockRejectedValueOnce(new Error('offline'));+ fireEvent.change(screen.getByLabelText('Period'), { target: { value: '365' } });+ expect(await screen.findByRole('alert')).toHaveTextContent('could not be loaded');+ expect(screen.getByRole('status')).toHaveTextContent('qualityDays=365&qualityCategory=security&tab=overview');+ getAppQualityHistory.mockResolvedValueOnce({ points: [] });+ fireEvent.click(screen.getByRole('button', { name: 'Refresh history' }));+ await waitFor(() => expect(screen.getByText(/No scored assessments/)).toBeInTheDocument());+});diff --git a/client/src/components/apps/tabs/OverviewTab.test.jsx b/client/src/components/apps/tabs/OverviewTab.test.jsxindex b1c68db293..21d1f28b8a 100644--- a/client/src/components/apps/tabs/OverviewTab.test.jsx+++ b/client/src/components/apps/tabs/OverviewTab.test.jsx@@ -3,6 +3,8 @@ import { render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { MemoryRouter } from 'react-router';+vi.mock('../../../services/apiApps', () => ({ getAppQualityHistory: vi.fn().mockResolvedValue({ points: [] }) }));+vi.mock('../../../services/api', () => ({PORTOS_APP_ID: 'portos-default',getAppSpriteBindings: vi.fn(() => Promise.resolve({ bindings: [] })),diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.jsindex b47ba547e6..f3426c2d74 100644--- a/client/src/services/apiApps.js+++ b/client/src/services/apiApps.js@@ -4,6 +4,7 @@ import { request, API_BASE } from './apiCore.js';// Appsexport const getApps = (options) => request('/apps?includeQuality=true', options);export const getApp = (id, options) => request(`/apps/${id}?includeQuality=true`, options);+export const getAppQualityHistory = (id, days, options) => request(`/apps/${id}/quality-history?days=${days}`, { silent: true, ...options });// Managed checkout topology: returns sanitized local/fork/upstream revision// state without exposing machine-local repo paths.export const getAppRepositorySources = (id, options = {}) =>diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex da4912ee45..1d8f3eff02 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -382,8 +382,8 @@ 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+`app_quality_measurements` is `db-primary`: immutable assessments per managed+app/category/run, with the latest per category queried together for the dashboard and management pages. The appregistry is still file-backed, so app ids are opaque scoped keys; reads selectonly currently registered apps. PostgreSQL stores the bounded JSON report andagent provenance; no asset bytes or new JSON store. Additive `CREATE TABLE IFdiff --git a/docs/features/app-quality.md b/docs/features/app-quality.mdindex 541359d660..a077c5b761 100644--- a/docs/features/app-quality.md+++ b/docs/features/app-quality.md@@ -52,7 +52,7 @@ markers and malformed JSON. Missing/invalid output never invents a score orreplaces a previous valid measurement; the prior measurement keeps its originaldate 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,+replace newer evidence. PostgreSQL retains each run measurement and projects the latest per app/category,locally and within the ordinary database backup; no old runs are guessed intoscores and no extra audit batch is enabled automatically.@@ -73,3 +73,21 @@ reliably from a source audit and are not fabricated into this codebase score.A future distinct category must register both its scheduled prompt and arepository discovery strategy; the catalog parity test prevents an auditorwithout a search strategy.++## Quality history++Each app Overview includes a daily UTC chart with 30-day, 90-day and one-year+ranges and an overall/category selector. Both selections are shareable URL+parameters. The expandable history table provides dates, values and coverage+without relying on color or hover. Refresh history reloads measurements.++Daily snapshots use the latest assessment available on that date, carrying it+forward for at most 30 days. Missing or expired evidence creates a gap. The+current day ends at the request time. Category charts include provisional+partial/low-confidence scores; the overall chart applies the same eligibility+rules as today's score. Coverage is shown with each value because adding or+losing a category can change the mean without same-category improvement.+History begins with newly reported assessments; no scores are invented for old+runs. The local detail endpoint `/api/apps/:id/quality-history?days=90` reads only+that app's measurements and bounds results to the last measurement per UTC day+and category, including a 30-day lookback to seed the selected range.diff --git a/server/lib/auditQuality.js b/server/lib/auditQuality.jsindex 5bfd42c6e9..153c45b69a 100644--- a/server/lib/auditQuality.js+++ b/server/lib/auditQuality.js@@ -93,3 +93,30 @@ export function summarizeAppQuality(records = [], now = Date.now()) {categories,};}++export const appQualityHistoryQuerySchema = z.object({ days: z.enum(['30', '90', '365']).default('90').transform(Number) });++/** Daily UTC snapshots of evidence available then; never backfill past scores. */+export function buildAppQualityHistory(records, days, now = Date.now()) {+ const dayMs = 86400000;+ const today = Math.floor(now / dayMs) * dayMs;+ const sorted = records.filter(r => Number.isFinite(Date.parse(r.assessedAt)))+ .sort((a, b) => Date.parse(a.assessedAt) - Date.parse(b.assessedAt));+ const latest = new Map();+ let cursor = 0;+ const points = [];+ for (let day = today - (days - 1) * dayMs; day <= today; day += dayMs) {+ const asOf = Math.min(day + dayMs - 1, now);+ while (cursor < sorted.length && Date.parse(sorted[cursor].assessedAt) <= asOf) {+ const record = sorted[cursor++];+ latest.set(record.category, record);+ }+ const summary = summarizeAppQuality([...latest.values()], asOf);+ points.push({ date: new Date(day).toISOString().slice(0, 10), score: summary.score,+ ratedCategories: summary.ratedCategories,+ categories: Object.fromEntries(summary.categories.map(c => [c.id, {+ score: c.stale ? null : c.score, coverage: c.coverage, confidence: c.confidence ?? null,+ }])) });+ }+ return { days, totalCategories: Object.keys(AUDIT_DEFINITIONS).length, points };+}diff --git a/server/lib/db.catalogDdlParity.test.js b/server/lib/db.catalogDdlParity.test.jsindex 6b8499f506..0b7d4232fa 100644--- a/server/lib/db.catalogDdlParity.test.js+++ b/server/lib/db.catalogDdlParity.test.js@@ -37,7 +37,7 @@ const DB_JS = [].join('\n');const CATALOG_TABLES = [- 'app_quality_assessments',+ 'app_quality_measurements','catalog_scraps','catalog_ingredients','catalog_ingredient_sources',diff --git a/server/lib/db/schema/core.js b/server/lib/db/schema/core.jsindex 115539d238..48f575abb8 100644--- a/server/lib/db/schema/core.js+++ b/server/lib/db/schema/core.js@@ -3,14 +3,15 @@// 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 (+ `CREATE TABLE IF NOT EXISTS app_quality_measurements (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)+ PRIMARY KEY (app_id, category, agent_id))`,+ `CREATE INDEX IF NOT EXISTS idx_app_quality_history ON app_quality_measurements (app_id, assessed_at DESC)`,`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/routes/apps/crud.js b/server/routes/apps/crud.jsindex 7e8fb3df5d..53e9b8b8fb 100644--- a/server/routes/apps/crud.js+++ b/server/routes/apps/crud.js@@ -1,5 +1,5 @@-import { appQualityQuerySchema } from '../../lib/auditQuality.js';-import { enrichAppsWithQuality } from '../../services/appQuality.js';+import { appQualityQuerySchema, appQualityHistoryQuerySchema } from '../../lib/auditQuality.js';+import { enrichAppsWithQuality, getAppQualityHistory } from '../../services/appQuality.js';/*** App CRUD + status enrichment + archive lifecycle.*@@ -40,6 +40,11 @@ router.get('/', asyncHandler(async (req, res) => {res.json(includeQuality === 'true' ? await enrichAppsWithQuality(apps) : apps);}));+router.get('/:id/quality-history', loadApp, asyncHandler(async (req, res) => {+ const { days } = validateRequest(appQualityHistoryQuerySchema, req.query);+ res.json(await getAppQualityHistory(req.loadedApp.id, days));+}));+// GET /api/apps/:id - Get single approuter.get('/:id', loadApp, asyncHandler(async (req, res) => {const app = req.loadedApp;diff --git a/server/routes/apps/crud.test.js b/server/routes/apps/crud.test.jsindex 457299561d..940b012ec7 100644--- a/server/routes/apps/crud.test.js+++ b/server/routes/apps/crud.test.js@@ -1,9 +1,9 @@-vi.mock('../../services/appQuality.js', () => ({ enrichAppsWithQuality: vi.fn(async apps => apps.map(app => ({ ...app, quality: { score: 75 } }))) }));+vi.mock('../../services/appQuality.js', () => ({ getAppQualityHistory: vi.fn(async () => ({ points: [], days: 90 })), 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';+import { enrichAppsWithQuality, getAppQualityHistory } from '../../services/appQuality.js';// Mock the services this router (and its port-config service) touch.vi.mock('../../services/apps.js', () => ({@@ -88,6 +88,10 @@ describe('Apps CRUD Routes', () => {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 });+ const history = await request(app).get('/api/apps/portos-default/quality-history?days=90');+ expect(history.status).toBe(200);+ expect(getAppQualityHistory).toHaveBeenCalledWith('portos-default', 90);+ expect((await request(app).get('/api/apps/portos-default/quality-history?days=9999')).status).toBe(400);});it('should handle apps with no PM2 processes', async () => {diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex 4ed87440ae..2e211d4a07 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -1945,12 +1945,14 @@ CREATE TRIGGER trg_tribe_touchpoints_audit AFTER UPDATE OR DELETE ON tribe_touchDROP 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 (+-- Immutable machine-local scheduled audit measurements per app/category/run.+CREATE TABLE IF NOT EXISTS app_quality_measurements (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)+ PRIMARY KEY (app_id, category, agent_id));++CREATE INDEX IF NOT EXISTS idx_app_quality_history ON app_quality_measurements (app_id, assessed_at DESC);diff --git a/server/services/appQuality.db.test.js b/server/services/appQuality.db.test.jsindex 11892c100f..37ca35f559 100644--- a/server/services/appQuality.db.test.js+++ b/server/services/appQuality.db.test.js@@ -2,14 +2,14 @@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';+import { recordAuditQuality, enrichAppsWithQuality, getAppQualityHistory } 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]);+ if (runDb) await query('DELETE FROM app_quality_measurements WHERE app_id = $1', [appId]);await close();});@@ -32,6 +32,10 @@ describe.skipIf(!runDb)('app quality persistence', () => {await write(0, 99, false); // failed run cannot overwrite measured evidenceconst [app, other] = await enrichAppsWithQuality([{ id: appId }, { id: `${appId}-other` }]);expect(app.quality).toMatchObject({ score: 65, ratedCategories: 1 });+ const history = await getAppQualityHistory(appId, 30);+ expect(history.points.at(-1)).toMatchObject({ score: 65, ratedCategories: 1 });+ const retained = await query('SELECT report FROM app_quality_measurements WHERE app_id = $1 ORDER BY assessed_at', [appId]);+ expect(retained.rows.map(row => row.report.score)).toEqual([30, 65]);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.jsindex 211eba3301..2a1033cacf 100644--- a/server/services/appQuality.js+++ b/server/services/appQuality.js@@ -2,7 +2,7 @@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';+import { parseAuditQualityReport, summarizeAppQuality, buildAppQualityHistory, AUDIT_FRESHNESS_MS } from '../lib/auditQuality.js';export async function recordAuditQuality({ task, taskType, agentId, workspacePath, success, assessedAt }, deps = {}) {if (!success || !workspacePath || !task?.metadata?.app || !agentId) return false;@@ -10,16 +10,13 @@ export async function recordAuditQuality({ task, taskType, agentId, workspacePatconst { 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.+ // Immutable run measurements make completion replay idempotent.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)+ `INSERT INTO app_quality_measurements (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`,+ ON CONFLICT (app_id, category, agent_id) DO NOTHING`,[task.metadata.app, taskType, agentId, assessedAt, JSON.stringify(report)]);return true;@@ -27,9 +24,9 @@ export async function recordAuditQuality({ task, taskType, agentId, workspacePatexport async function enrichAppsWithQuality(apps, deps = {}) {if (!apps.length) return apps;- // One indexed query per list, not one per tile, and no history/log scans.+ // One app-scoped query per list, not one per tile or transcript scan.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[])`,+ `SELECT DISTINCT ON (app_id, category) app_id, category, agent_id, assessed_at, report FROM app_quality_measurements WHERE app_id = ANY($1::text[]) ORDER BY app_id, category, assessed_at DESC, agent_id DESC`,[apps.map(app => app.id)]).catch(err => {console.error(`❌ App quality unavailable: ${err.message}`);@@ -43,3 +40,21 @@ export async function enrichAppsWithQuality(apps, deps = {}) {}))) : { ...summarizeAppQuality(), unavailable: true },}));}++export async function getAppQualityHistory(appId, days, deps = {}) {+ const now = deps.now ?? Date.now();+ const start = new Date(now);+ start.setUTCHours(0, 0, 0, 0);+ start.setUTCDate(start.getUTCDate() - days + 1);+ // Last measurement per UTC day/category bounds the payload regardless of run frequency.+ const result = await (deps.query || query)(+ `SELECT DISTINCT ON (category, (assessed_at AT TIME ZONE 'UTC')::date)+ category, agent_id, assessed_at, report FROM app_quality_measurements+ WHERE app_id = $1 AND assessed_at >= $2 AND assessed_at <= $3+ ORDER BY category, (assessed_at AT TIME ZONE 'UTC')::date, assessed_at DESC, agent_id DESC`,+ [appId, new Date(start.getTime() - AUDIT_FRESHNESS_MS), new Date(now)]+ );+ return buildAppQualityHistory(result.rows.map(row => ({ category: row.category,+ agentId: row.agent_id, assessedAt: new Date(row.assessed_at).toISOString(), report: row.report,+ })), days, now);+}diff --git a/server/services/appQuality.test.js b/server/services/appQuality.test.jsindex 5d92e1a8de..da9480c767 100644--- a/server/services/appQuality.test.js+++ b/server/services/appQuality.test.js@@ -1,7 +1,7 @@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';+import { AUDIT_DISCOVERY, auditQualityInstructions, parseAuditQualityReport, summarizeAppQuality, AUDIT_FRESHNESS_MS, buildAppQualityHistory } 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 });@@ -65,3 +65,18 @@ describe('scheduled audit measurement workflow', () => {log.mockRestore();});});++it('retains historical scores without hindsight, expires old evidence and exposes changed coverage', () => {+ const now = Date.parse('2026-09-10T12:00:00Z');+ const rows = [+ { category: 'better-complexity', assessedAt: '2026-08-01T12:00:00Z', report: report({ score: 20 }) },+ { category: 'better-complexity', assessedAt: '2026-09-09T12:00:00Z', report: report({ score: 70 }) },+ { category: 'security', assessedAt: '2026-09-10T10:00:00Z', report: report({ category: 'security', score: 90 }) },+ ];+ const { points } = buildAppQualityHistory(rows, 90, now);+ expect(points.find(p => p.date === '2026-07-31').score).toBeNull();+ expect(points.find(p => p.date === '2026-08-01')).toMatchObject({ score: 20, ratedCategories: 1 });+ expect(points.find(p => p.date === '2026-09-01').score).toBeNull();+ expect(points.find(p => p.date === '2026-09-09')).toMatchObject({ score: 70, ratedCategories: 1 });+ expect(points.at(-1)).toMatchObject({ score: 80, ratedCategories: 2 });+});