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: store quality snapshots as compact schema v2 (#8038)

[._.]/ Adam Eivy0a4d2d7325b7
diff --git a/client/src/components/apps/AppQuality.jsx b/client/src/components/apps/AppQuality.jsx
index 30b25ff2fd..294b10a4f8 100644
--- a/client/src/components/apps/AppQuality.jsx
+++ b/client/src/components/apps/AppQuality.jsx
@@ -17,6 +17,8 @@ const PUBLISH_SKIPPED = {
'no-remote': 'App repo has no origin remote to open a pull request against',
'no-default-branch': 'Could not resolve the repository default branch',
'pr-failed': 'Could not open a quality snapshot pull request',
+ 'unsupported-format': 'The committed quality file is in an unsupported format. Publish left it in place.',
+ 'invalid-evidence': 'The current measurements could not be written as a snapshot. Publish left the file in place.',
};
export default function AppQuality({ app, detail = false }) {
diff --git a/client/src/components/apps/AppQuality.test.jsx b/client/src/components/apps/AppQuality.test.jsx
index 3ddfe287df..746ad93e34 100644
--- a/client/src/components/apps/AppQuality.test.jsx
+++ b/client/src/components/apps/AppQuality.test.jsx
@@ -143,4 +143,16 @@ describe('AppQuality snapshot publishing', () => {
await waitFor(() => expect(toast).toHaveBeenCalledWith('Snapshot already up to date in .quality.json'));
expect(toast.success).not.toHaveBeenCalled();
});
+
+ it('says an unsupported snapshot file was left in place', async () => {
+ publishAppQualitySnapshot.mockResolvedValue({ success: true, published: false, reason: 'unsupported-format', path: '.quality.json' });
+ render(<MemoryRouter><AppQuality app={publishingApp} detail /></MemoryRouter>);
+ await screen.findByText(/No scored assessments/);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Publish snapshot now' }));
+
+ await waitFor(() => expect(toast).toHaveBeenCalledWith(
+ 'The committed quality file is in an unsupported format. Publish left it in place.'));
+ expect(toast.success).not.toHaveBeenCalled();
+ });
});
diff --git a/docs/API.md b/docs/API.md
index 7c51d8609b..c17b5fb57c 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -101,7 +101,7 @@ legacy list for local Apps/Dashboard views.
| GET | `/apps/:id/status` | Get PM2 status |
| GET | `/apps/:id/logs` | Get recent logs |
| POST | `/apps/:id/refresh-config` | Re-parse ecosystem config |
-| POST | `/apps/:id/quality-snapshot` | Rebuild the app's numeric quality snapshot and land `.quality.json` through a merge-on-green pull request on `portos/quality-snapshot` (scoped to that one path; the live checkout is not committed). Answers `{ success, published, path }` plus the commit `hash`, `prUrl`, and `prNumber`, or a `reason` of `no-repo-path` / `not-a-repo` / `no-evidence` / `no-changes` / `no-remote` / `no-default-branch` / `pr-failed` when nothing was written. Not gated on the app's `publishQualitySnapshot` toggle — that toggle only automates the same publish after each audit. Any app's committed `.quality.json` is read back as a "Release snapshot" quality source, PortOS's own checkout included (`npm run quality:snapshot` is the same publish, run from the release step). |
+| POST | `/apps/:id/quality-snapshot` | Rebuild the app's numeric quality snapshot and land canonical schema v2 `.quality.json` through a merge-on-green pull request on `portos/quality-snapshot` (scoped to that one path; the live checkout is not committed). The file is not the peer wire payload (`PORTOS_SCHEMA_VERSIONS.appQuality` stays 1). A v1 file is rewritten when current evidence exists. Answers `{ success, published, path }` plus the commit `hash`, `prUrl`, and `prNumber`, or a `reason` of `no-repo-path` / `not-a-repo` / `no-evidence` / `no-changes` / `no-remote` / `no-default-branch` / `pr-failed` / `unsupported-format` / `invalid-evidence` when nothing was written. `unsupported-format` means a future, unrecognized, malformed, or oversize file was left in place. Not gated on the app's `publishQualitySnapshot` toggle — that toggle only automates the same publish after each audit. Any app's committed `.quality.json` (or a historical `quality-snapshot.json` when `.quality.json` is absent) is read back as a "Release snapshot" quality source, PortOS's own checkout included (`npm run quality:snapshot` is the same publish, run from the release step; `npm run quality:snapshot -- --migrate` converts an old file without reading the database). |
| GET | `/apps/:id/quality-schedule` | The Quality tab's weekly-schedule form: every audit check with its applicability verdict and reason, the repository shapes that verdict came from, the cron expressions already occupied on this app, and the plan the shipped defaults produce. Read-only — no LLM call, no write. |
| POST | `/apps/:id/quality-schedule/preview` | Re-plan for an edited form (selection, per-check delivery mode, checks per day, hour window, claim-drain task and offset). Still read-only; a POST only because the option bag carries a per-check map. |
| POST | `/apps/:id/quality-schedule/apply` | Persist the plan as ordinary per-app task-type overrides: the selected checks enabled with their weekly cron and `fileIssues` mode, the audit types left out disabled with their interval cleared, and — when at least one selected check files issues — one daily cron for the issue-claim drain (one an earlier plan planted is retired when it is switched off or replaced). Other task types are untouched. |
diff --git a/docs/decisions/2026-09-10-portos-quality-federation.md b/docs/decisions/2026-09-10-portos-quality-federation.md
index 8180e234eb..9a38f88bfb 100644
--- a/docs/decisions/2026-09-10-portos-quality-federation.md
+++ b/docs/decisions/2026-09-10-portos-quality-federation.md
@@ -137,3 +137,51 @@ pull request, and queues the existing merge-on-green sweep (`queuePendingMerge`
on GitHub; GitLab auto-merge when the pipeline succeeds). No review is requested.
The live checkout is not committed, staged, or switched. An unchanged snapshot
still skips git entirely.
+
+## September 22: compact file schema v2
+
+The sections above coupled the checked-in file to the federation object
+(`{ schemaVersion, repository, measurements }`). A file-format change would have
+forced a peer wire rollout. Those are now two adapters over one normalized
+record. `PORTOS_SCHEMA_VERSIONS.appQuality` stays 1, and peers still exchange
+the v1 object payload. The checked-in file is schema v2.
+
+v2 keeps the opaque origin fingerprint and replaces per-row objects with sorted
+dictionaries plus fixed rows:
+
+`[assessedAt, categoryIndex, score, worstSeverity, coverageIndex, confidenceIndex, scannedFiles, totalFiles]`
+
+`reportVersion` is 1. Category dictionaries list the categories that appear, in
+order. Coverage and confidence dictionaries are the full enums in their declared
+order. Scores stay nullable. Timestamps stay ISO instants, not midnight dates.
+`measurementId` is not stored. While a v1 file still carries that id, release
+reads keep it for same-timestamp ordering. v2 reads use a transient digest of
+the normalized row. The digest is not written. Database provenance fields are
+unchanged.
+
+The canonical artifact stays JSON. An append-only TSV, CSV, or NDJSON log was
+rejected: the database is already the immutable history, and a checked-in append
+log would be unbounded, harder to validate, and more conflict-prone. The file
+remains the bounded release projection: one row per UTC day and category, the
+30-day lookback, and the 4 MiB cap. PostgreSQL retention is unchanged. No
+`scripts/migrations/` entry is involved; those migrations own `data/` paths.
+
+Readers accept v1 `.quality.json` and, only when that file is absent, the
+historical `quality-snapshot.json` filename. A read never mutates the checkout.
+Malformed rows, unknown keys, invalid dictionary indexes, duplicate UTC
+day/category winners, a mismatched origin fingerprint, and oversize files fail
+closed. A future `schemaVersion` is recognized and left unparsed.
+
+`npm run quality:snapshot` writes canonical v2 whenever the database has current
+evidence, including when the committed file is still valid v1. It does not
+invent rows the database does not have, and it does not replace a non-empty
+file when evidence is absent. A future schema, an unrecognized document, a
+malformed snapshot, or an oversize file is left untouched and reported as
+`unsupported-format`. A second publish whose normalized v2 bytes are already on
+the default branch or the snapshot branch does not open another pull request.
+
+`npm run quality:snapshot -- --migrate` converts a v1 file, or the historical
+filename, through the same temporary worktree, scoped commit, and
+merge-on-green pull request. It uses only rows already in the file. When the
+historical filename is the source, the commit also removes it. Unknown future
+formats stay in place.
diff --git a/docs/features/app-quality.md b/docs/features/app-quality.md
index 49284988b8..a366cafdf5 100644
--- a/docs/features/app-quality.md
+++ b/docs/features/app-quality.md
@@ -92,6 +92,40 @@ runs. The local detail endpoint `/api/apps/:id/quality-history?days=90` reads on
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.
+## Release snapshot file
+
+A managed app can publish its recent numeric scores into `.quality.json` at the
+repository root. The file is a bounded projection, not the audit history:
+PostgreSQL keeps every measurement, and the file keeps one row per UTC day and
+category for the same 30-day window the quality panel uses, capped at 4 MiB.
+Publish opens a merge-on-green pull request on `portos/quality-snapshot` and
+does not commit the live checkout. With no local evidence, a non-empty file is
+left as it is.
+
+The checked-in schema is v2. It stores an opaque origin fingerprint, sorted
+category and enum dictionaries, and fixed rows
+`[assessedAt, categoryIndex, score, worstSeverity, coverageIndex, confidenceIndex, scannedFiles, totalFiles]`.
+Scores stay nullable. Timestamps stay ISO instants. The file does not store
+summaries, paths, app names, agent ids, or `measurementId`. Same-timestamp
+ordering uses a transient digest of the row, computed when the file is read.
+
+That file is not the peer federation payload. Peers still exchange schema v1
+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
+canonical artifact: an append-only text log would grow without a bound and would
+be harder to validate, while the database is already the history.
+
+`npm run quality:snapshot` writes canonical v2 from local evidence, including
+when the committed file is still v1. `npm run quality:snapshot -- --migrate`
+converts a v1 file or the historical filename to canonical v2 using only the
+rows already stored, through the same pull request. A second publish of the
+same normalized v2 snapshot does not open another pull request. Duplicate rows
+for one UTC day and category are rejected rather than silently dropped.
+
## Weekly quality schedule
The app's Quality tab carries a **Weekly quality schedule** form that configures
diff --git a/docs/plans/2026-09-22-quality-snapshot-format.md b/docs/plans/2026-09-22-quality-snapshot-format.md
index 21b10e3afb..b16cdeb0f0 100644
--- a/docs/plans/2026-09-22-quality-snapshot-format.md
+++ b/docs/plans/2026-09-22-quality-snapshot-format.md
@@ -1,6 +1,7 @@
# Compact, versioned quality snapshots
-Status: proposed design for the managed-app quality snapshot format. Tracked by
+Status: implemented. The file schema lives in
+`server/services/appQualitySnapshotFormat.js`. Tracked by
[#8038](https://github.com/atomantic/PortOS/issues/8038).
## Context
diff --git a/scripts/publish-quality-snapshot.js b/scripts/publish-quality-snapshot.js
index 322ac2cca9..c1989f22f5 100644
--- a/scripts/publish-quality-snapshot.js
+++ b/scripts/publish-quality-snapshot.js
@@ -5,17 +5,26 @@
* managed app uses — this command is the manual trigger, equivalent to the audit
* hook the app's `publishQualitySnapshot` toggle automates. The publisher opens
* a merge-on-green pull request rather than committing on the live checkout.
+ *
+ * `--migrate` rewrites a v1 file, or a historical `quality-snapshot.json`, to
+ * canonical schema v2 using only the rows already in the file. It does not read
+ * audit measurements and does not invent any.
*/
import { getAppById, PORTOS_APP_ID } from '../server/services/apps.js';
-import { publishAppQualitySnapshot, APP_QUALITY_SNAPSHOT_FILENAME } from '../server/services/appQualitySnapshotFile.js';
+import {
+ publishAppQualitySnapshot, migrateAppQualitySnapshot, APP_QUALITY_SNAPSHOT_FILENAME,
+} from '../server/services/appQualitySnapshotFile.js';
+const migrate = process.argv.includes('--migrate');
const { close } = await import('../server/lib/db.js');
await (async () => {
const app = await getAppById(PORTOS_APP_ID);
if (!app) throw new Error('PortOS app record not found; cannot publish a quality snapshot');
- const result = await publishAppQualitySnapshot(app);
- // `no-changes` is a success: the committed snapshot already matches the evidence.
- if (!result.published && result.reason !== 'no-changes') {
+ const result = migrate ? await migrateAppQualitySnapshot(app) : await publishAppQualitySnapshot(app);
+ // `no-changes` is a success: the committed snapshot already matches.
+ // `no-legacy-file` is a success for `--migrate`: there was nothing to convert.
+ const quiet = new Set(['no-changes', 'no-legacy-file']);
+ if (!result.published && !quiet.has(result.reason)) {
throw new Error(`Nothing published (${result.reason}); existing ${APP_QUALITY_SNAPSHOT_FILENAME} preserved`);
}
})().finally(close);
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index df083698ef..38b40a1e5c 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -32,7 +32,8 @@ import { join } from 'path';
import { PATHS, tryReadFile, safeJSONParse } from './fileUtils.js';
export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
- // Numeric-only PortOS audit evidence; read-through, never imported into local records.
+ // Numeric-only peer wire payload (v1); read-through, never imported into local records.
+ // Checked-in `.quality.json` is file schema v2 and must not bump this number.
appQuality: 1,
// Type-level (storage layout) version for `data/universes/{id}/index.json`.
// v5 = post-split. Migration 034 introduced it. The independent per-record
@@ -827,6 +828,8 @@ export const RECORD_KIND_SCHEMA_CATEGORIES = Object.freeze({
*
* `appQuality`: numeric-only local evidence at GET /api/apps/quality-federation,
* validated against its exact wire version by collectAppQuality; never written or pushed.
+ * The repository file format is versioned separately (`appQualitySnapshotFormat.js`)
+ * and a file-schema change must not bump this wire version.
*
* Do NOT add a real record-push category here to silence the guard — that would
* leave its push transfers ungated (silent cross-install corruption). Only
diff --git a/server/services/appQuality.js b/server/services/appQuality.js
index 3c9df2e779..efdce58a69 100644
--- a/server/services/appQuality.js
+++ b/server/services/appQuality.js
@@ -39,7 +39,8 @@ export async function enrichAppsWithQuality(apps, deps = {}) {
console.error(`❌ App quality unavailable: ${err.message}`);
return null;
});
- // Shipped evidence: any app's committed `.quality.json`.
+ // Shipped evidence: `.quality.json`, or a historical `quality-snapshot.json`
+ // when the canonical file is absent.
// One unreadable checkout (git spawn failure, timeout) must cost that app its release
// records, never the whole list — same posture as the peer collect below.
const releases = await Promise.all(apps.map(app => readReleaseQuality(deps, app).catch(() => [])));
diff --git a/server/services/appQualityFederation.js b/server/services/appQualityFederation.js
index 23502d53af..073578cc3f 100644
--- a/server/services/appQualityFederation.js
+++ b/server/services/appQualityFederation.js
@@ -10,6 +10,7 @@ import { getOriginInfo } from '../lib/gitRemote.js';
import { peerBaseUrl } from '../lib/peerUrl.js';
import { readBodyCapped } from '../lib/safeUrlFetch.js';
import { peerFetch } from '../lib/peerHttpClient.js';
+import { releaseTieId } from './appQualitySnapshotFormat.js';
const MAX_PAYLOAD_BYTES = 4 * 1024 * 1024;
const sharedSummary = 'Numeric assessment shared by a federated instance; evidence remains on the source machine.';
@@ -133,23 +134,39 @@ export async function collectAppQuality(app, days, deps = {}) {
}
/**
- * Every app — PortOS's own checkout included — reads the `.quality.json` at its
- * repo root, under the same guards: repository match, no future dates, 4 MiB cap.
+ * Every app — PortOS's own checkout included — reads `.quality.json` (or the
+ * historical `quality-snapshot.json` when the canonical file is absent). v1 and
+ * v2 both normalize. The read never writes. Repository match, future dates, and
+ * the 4 MiB cap still apply. The peer wire schema is not used here.
*/
async function releasePayload(deps, app) {
const repoPath = appRepoPath(app);
if (!repoPath) return null;
- const { readAppQualitySnapshotFile } = await import('./appQualitySnapshotFile.js');
- const parsed = payloadSchema.safeParse(await readAppQualitySnapshotFile(repoPath, deps));
- return parsed.success ? parsed.data : null;
+ const { readStoredQualitySnapshot } = await import('./appQualitySnapshotFile.js');
+ const stored = await readStoredQualitySnapshot(repoPath, deps);
+ return stored.status === 'v1' || stored.status === 'v2' ? stored : null;
}
/** Shipped evidence is read-only and never re-exported as a local audit. */
export async function readReleaseQuality(deps = {}, app = { id: PORTOS_APP_ID }) {
const payload = await releasePayload(deps, app);
if (!payload || payload.repository !== await repositoryKey(deps, app)) return [];
- return payload.measurements.filter(row => Date.parse(row.assessedAt) <= (deps.now ?? Date.now())).map(row => ({
- ...row, category: row.report.category, sourcePeerName: 'Release snapshot',
- report: { ...row.report, summary: 'Published release assessment; original assessment date and freshness rules apply.' },
+ const now = deps.now ?? Date.now();
+ return payload.records.filter(row => Date.parse(row.assessedAt) <= now).map(row => ({
+ measurementId: releaseTieId(row),
+ assessedAt: row.assessedAt,
+ category: row.category,
+ sourcePeerName: 'Release snapshot',
+ report: {
+ version: 1,
+ category: row.category,
+ score: row.score,
+ worstSeverity: row.worstSeverity,
+ coverage: row.coverage,
+ confidence: row.confidence,
+ summary: 'Published release assessment; original assessment date and freshness rules apply.',
+ scannedFiles: row.scannedFiles,
+ totalFiles: row.totalFiles,
+ },
}));
}
diff --git a/server/services/appQualityFederation.test.js b/server/services/appQualityFederation.test.js
index 4b8b1395e3..acebd21fe5 100644
--- a/server/services/appQualityFederation.test.js
+++ b/server/services/appQualityFederation.test.js
@@ -2,6 +2,8 @@ import { it, expect, vi } from 'vitest';
import { mockNoPeers } from '../lib/mockPathsDataRoot.js';
import { exportPortosQuality, collectPortosQuality, collectAppQuality, buildQualitySnapshot, readReleaseQuality } from './appQualityFederation.js';
import { enrichAppsWithQuality, getAppQualityHistory } from './appQuality.js';
+import { PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';
+import { qualityFileFromWireSnapshot } from './appQualitySnapshotFormat.js';
vi.mock('./instances.js', () => mockNoPeers());
const now = Date.parse('2026-09-10T12:00:00Z');
const peer = { id: 'peer-a', instanceId: 'instance-a', enabled: true, address: '192.0.2.1', port: 5555 };
@@ -18,6 +20,7 @@ const response = payload => new Response(JSON.stringify(payload), { status: 200
it('exports only validated local numeric evidence to approved sync peers', async () => {
const local = deps([row('security', 40)]);
const payload = await exportPortosQuality(peer.instanceId, 30, local);
+ expect(PORTOS_SCHEMA_VERSIONS.appQuality).toBe(1);
expect(payload).toMatchObject({ schemaVersion: 1, measurements: [{ report: { category: 'security', score: 40 } }] });
expect(JSON.stringify(payload)).not.toMatch(/Private|Users|agent-security|summary|app_id|github/);
expect(local.query.mock.calls[0][1][0]).toBe('portos-default');
@@ -139,6 +142,42 @@ it('reads a managed app\'s committed .quality.json as release evidence and rejec
expect(await readReleaseQuality(local, { id: 'local-id' })).toEqual([]);
});
+it('reads v2 and legacy snapshot files without writing, and drops future dates', async () => {
+ const getOriginInfo = async () => ({ host: 'github.com', fullName: 'owner/app' });
+ const managed = { id: 'local-id', repoPath: '/repo/example-app' };
+ const published = await buildQualitySnapshot(managed, 30, { ...deps([row('security', 76)]), getOriginInfo });
+ const v2 = qualityFileFromWireSnapshot(published);
+ const writes = [];
+ const file = bodyFor => ({
+ ...deps([]), getOriginInfo, getPeers: async () => [],
+ writeFile: async () => { writes.push('write'); },
+ readFile: async path => bodyFor(path),
+ });
+
+ const records = await readReleaseQuality(file(() => v2), managed);
+ expect(records).toMatchObject([{ category: 'security', sourcePeerName: 'Release snapshot', report: { score: 76 } }]);
+ expect(writes).toEqual([]);
+ expect(v2).not.toContain('measurementId');
+ expect(v2).not.toContain(published.measurements[0].measurementId);
+ expect(JSON.stringify(records)).not.toMatch(/Users|agent-security|app_id|github/);
+
+ const legacy = await readReleaseQuality(file(path => {
+ if (path.endsWith('.quality.json')) throw new Error('ENOENT');
+ return JSON.stringify(published);
+ }), managed);
+ expect(legacy).toMatchObject([{ report: { score: 76 } }]);
+
+ const occupied = await readReleaseQuality(file(path => {
+ if (path.endsWith('.quality.json')) return JSON.stringify({ schemaVersion: 3 });
+ return JSON.stringify(published);
+ }), managed);
+ expect(occupied).toEqual([]);
+
+ const future = JSON.parse(v2);
+ future.measurements.push(['2026-09-11T00:00:00.000Z', 0, 10, 1, 0, 2, 12, 12]);
+ expect(await readReleaseQuality(file(() => JSON.stringify(future)), managed)).toMatchObject([{ report: { score: 76 } }]);
+});
+
it('keeps one broken checkout from failing the whole list or its own history read', async () => {
// execGit rejecting inside repositoryKey (spawn failure, timeout) used to
// escape both release reads and 500 GET /api/apps?includeQuality=true.
diff --git a/server/services/appQualitySnapshotFile.js b/server/services/appQualitySnapshotFile.js
index 21629f43cf..03fd1dc9bd 100644
--- a/server/services/appQualitySnapshotFile.js
+++ b/server/services/appQualitySnapshotFile.js
@@ -1,7 +1,8 @@
/**
* `.quality.json` — the numeric quality snapshot a repository carries at its
- * root. The file IS a `buildQualitySnapshot` result verbatim
- * (`{ schemaVersion, repository, measurements }`).
+ * root. Writers emit canonical file schema v2 (`appQualitySnapshotFormat.js`).
+ * That file is not the peer wire payload: federation stays on
+ * `PORTOS_SCHEMA_VERSIONS.appQuality` v1.
*
* PortOS's own checkout is not special: it is a managed app like any other, so
* its release snapshot is this same file, written by this same publisher, under
@@ -12,20 +13,25 @@
* (`publishQualitySnapshot`), commits only this one path on a dedicated branch,
* and lands it through a merge-on-green pull request so the live checkout never
* diverges from origin and repos that block pushes to the default branch still
- * receive the file.
+ * receive the file. Reads never write. A v1 file or historical
+ * `quality-snapshot.json` is explicit legacy input.
*/
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { atomicWrite } from '../lib/fileCore.js';
+import {
+ APP_QUALITY_LEGACY_SNAPSHOT_FILENAME,
+ classifyQualitySnapshot,
+ qualityFileFromWireSnapshot,
+} from './appQualitySnapshotFormat.js';
export const APP_QUALITY_SNAPSHOT_FILENAME = '.quality.json';
export const APP_QUALITY_SNAPSHOT_MAX_BYTES = 4 * 1024 * 1024;
export const QUALITY_SNAPSHOT_BRANCH = 'portos/quality-snapshot';
-const snapshotPath = repoPath => join(repoPath, APP_QUALITY_SNAPSHOT_FILENAME);
-// Byte-identical across every publisher so two files of the same snapshot compare equal.
-const serialize = snapshot => `${JSON.stringify(snapshot, null, 2)}\n`;
+const snapshotPath = (repoPath, filename = APP_QUALITY_SNAPSHOT_FILENAME) => join(repoPath, filename);
+const REWRITE_BLOCKED = new Set(['future', 'unrecognized', 'malformed', 'oversize', 'unreadable']);
const QUALITY_PR_TITLE = 'chore: publish quality snapshot';
const QUALITY_PR_BODY = `## Summary
@@ -36,25 +42,66 @@ Update the repository \`.quality.json\` numeric quality snapshot generated by Po
- Merge when required CI is green; no code review required
`;
-/** Raw bytes, or null when absent/unreadable/oversize. The publish path needs the
- * exact text so an unchanged snapshot can skip git entirely. */
-async function readSnapshotText(repoPath, deps = {}) {
- if (!repoPath) return null;
- const body = await (deps.readFile || readFile)(snapshotPath(repoPath), 'utf8').catch(() => null);
- if (typeof body !== 'string' || Buffer.byteLength(body) > APP_QUALITY_SNAPSHOT_MAX_BYTES) return null;
- return body;
+async function readSnapshotEntry(repoPath, filename, deps = {}) {
+ try {
+ const body = await (deps.readFile || readFile)(join(repoPath, filename), 'utf8');
+ if (typeof body !== 'string') return { status: 'absent' };
+ if (Buffer.byteLength(body) > APP_QUALITY_SNAPSHOT_MAX_BYTES) return { status: 'oversize' };
+ return { status: 'text', body };
+ } catch {
+ return { status: 'absent' };
+ }
}
-/** Parsed `.quality.json`, or null for every failure mode. Never throws. */
+/** Parsed `.quality.json`, or null for every failure mode. Never throws.
+ * Legacy filename resolution lives in `readQualitySnapshotSource`. */
export async function readAppQualitySnapshotFile(repoPath, deps = {}) {
- const body = await readSnapshotText(repoPath, deps);
- if (!body) return null;
+ if (!repoPath) return null;
+ const entry = await readSnapshotEntry(repoPath, APP_QUALITY_SNAPSHOT_FILENAME, deps);
+ if (entry.status !== 'text') return null;
// Inline rather than jsonIo.safeJSONParse: routes/apps/crud.js reaches this
// module statically, so a lib import here lands in the suite import budget.
- const parsed = await Promise.resolve().then(() => JSON.parse(body)).catch(() => null);
+ const parsed = await Promise.resolve().then(() => JSON.parse(entry.body)).catch(() => null);
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
}
+/** `.quality.json`, or the legacy filename only when that file is absent.
+ * Oversize and unreadable primary files do not fall through. */
+export async function readQualitySnapshotSource(repoPath, deps = {}) {
+ if (!repoPath) return null;
+ const primary = await readSnapshotEntry(repoPath, APP_QUALITY_SNAPSHOT_FILENAME, deps);
+ if (primary.status === 'text') return { filename: APP_QUALITY_SNAPSHOT_FILENAME, text: primary.body };
+ if (primary.status === 'oversize') return { filename: APP_QUALITY_SNAPSHOT_FILENAME, oversize: true, text: null };
+ const legacy = await readSnapshotEntry(repoPath, LEGACY_QUALITY_SNAPSHOT_FILENAME, deps);
+ if (legacy.status === 'text') return { filename: LEGACY_QUALITY_SNAPSHOT_FILENAME, text: legacy.body };
+ if (legacy.status === 'oversize') return { filename: LEGACY_QUALITY_SNAPSHOT_FILENAME, oversize: true, text: null };
+ return null;
+}
+
+async function readClassified(repoPath, filename, deps) {
+ if (!repoPath) return { status: 'absent' };
+ let body;
+ try {
+ body = await (deps.readFile || readFile)(snapshotPath(repoPath, filename), 'utf8');
+ } catch {
+ return { status: 'absent' };
+ }
+ if (typeof body !== 'string') return { status: 'absent' };
+ if (Buffer.byteLength(body) > APP_QUALITY_SNAPSHOT_MAX_BYTES) return { status: 'oversize' };
+ return { body, filename, ...classifyQualitySnapshot(body) };
+}
+
+/**
+ * `.quality.json` when it exists, otherwise the historical `quality-snapshot.json`.
+ * A present canonical file is never replaced by the legacy name. Never writes.
+ */
+export async function readStoredQualitySnapshot(repoPath, deps = {}) {
+ const primary = await readClassified(repoPath, APP_QUALITY_SNAPSHOT_FILENAME, deps);
+ if (primary.status !== 'absent') return primary;
+ const legacy = await readClassified(repoPath, APP_QUALITY_LEGACY_SNAPSHOT_FILENAME, deps);
+ return legacy.status === 'absent' ? { status: 'absent', filename: null } : legacy;
+}
+
function skipped(app, reason) {
console.log(`📊 Quality snapshot skipped for app ${app?.id}: ${reason}`);
return { published: false, reason, path: APP_QUALITY_SNAPSHOT_FILENAME };
@@ -77,17 +124,8 @@ export function __resetQualitySnapshotPublishState() {
lastPublishedBody.clear();
}
-/**
- * Rebuild the app's numeric snapshot and land it as `.quality.json` through a
- * merge-on-green pull request. An empty snapshot never overwrites a populated
- * file, and an unchanged snapshot never reaches git — an audit that moved
- * nothing leaves no commit.
- */
-export async function publishAppQualitySnapshot(app, deps = {}) {
- if (!app?.repoPath) return skipped(app, 'no-repo-path');
- const { repoPath } = app;
- const run = (publishTails.get(repoPath) ?? Promise.resolve())
- .then(() => publishNow(app, deps), () => publishNow(app, deps));
+function enqueue(repoPath, task) {
+ const run = (publishTails.get(repoPath) ?? Promise.resolve()).then(task, task);
// The queued value never rejects, so one failed publish cannot poison the tail.
const queued = run.then(() => {}, () => {});
publishTails.set(repoPath, queued);
@@ -96,12 +134,62 @@ export async function publishAppQualitySnapshot(app, deps = {}) {
return run;
}
-async function showRefFile(git, repoPath, spec) {
- const result = await git.execGit(['show', spec], repoPath, { ignoreExitCode: true }).catch(() => null);
- if (!result || result.exitCode !== 0) return null;
+/**
+ * Rebuild the app's numeric snapshot and land it as canonical v2 `.quality.json`
+ * through a merge-on-green pull request. An empty snapshot never overwrites a
+ * populated file. A v1 file is rewritten when current evidence exists. An
+ * already-canonical v2 snapshot with the same records never reaches git.
+ */
+export async function publishAppQualitySnapshot(app, deps = {}) {
+ if (!app?.repoPath) return skipped(app, 'no-repo-path');
+ return enqueue(app.repoPath, () => publishNow(app, deps));
+}
+
+/**
+ * Convert a v1 `.quality.json` or historical `quality-snapshot.json` to canonical
+ * v2 using only the rows already in the file. Same isolated worktree and pull
+ * request as publication. Does not read the database and does not invent rows.
+ */
+export async function migrateAppQualitySnapshot(app, deps = {}) {
+ if (!app?.repoPath) return skipped(app, 'no-repo-path');
+ return enqueue(app.repoPath, () => migrateNow(app, deps));
+}
+
+async function readGitSnapshot(git, repoPath, spec) {
+ let result;
+ try {
+ result = await git.execGit(['show', spec], repoPath, {
+ ignoreExitCode: true,
+ maxBuffer: APP_QUALITY_SNAPSHOT_MAX_BYTES + 1,
+ });
+ } catch {
+ return { status: 'unreadable' };
+ }
+ if (!result || result.exitCode !== 0) return { status: 'absent' };
const body = result.stdout;
- if (typeof body !== 'string' || Buffer.byteLength(body) > APP_QUALITY_SNAPSHOT_MAX_BYTES) return null;
- return body;
+ if (typeof body !== 'string') return { status: 'absent' };
+ if (Buffer.byteLength(body) > APP_QUALITY_SNAPSHOT_MAX_BYTES) return { status: 'oversize' };
+ return { body, ...classifyQualitySnapshot(body) };
+}
+
+function untouched(app, status) {
+ console.log(`📊 Quality snapshot left untouched for app ${app?.id}: ${status}`);
+ return { published: false, reason: 'unsupported-format', path: APP_QUALITY_SNAPSHOT_FILENAME };
+}
+
+function sameSnapshot(stored, next) {
+ if (!stored || stored.status === 'absent' || stored.status === 'unreadable') return false;
+ if (stored.body === next) return true;
+ return stored.status === 'v2' && stored.canonical === next;
+}
+
+async function repoBase(app, git) {
+ if (!await git.isRepo(app.repoPath)) return { skip: skipped(app, 'not-a-repo') };
+ if (!hasOrigin(await git.getRemote(app.repoPath))) return { skip: skipped(app, 'no-remote') };
+ await git.fetchOrigin(app.repoPath).catch(() => {});
+ const defaultBranch = await git.getDefaultBranch(app.repoPath);
+ if (!defaultBranch) return { skip: skipped(app, 'no-default-branch') };
+ return { defaultBranch };
}
function hasOrigin(remote) {
@@ -110,35 +198,80 @@ function hasOrigin(remote) {
async function publishNow(app, deps) {
const git = deps.git || await import('./git.js');
+ // Evidence is resolved before any remote check so a repo that is not a
+ // checkout never builds, and an empty projection never reaches git.
if (!await git.isRepo(app.repoPath)) return skipped(app, 'not-a-repo');
const build = deps.buildQualitySnapshot || (await import('./appQualityFederation.js')).buildQualitySnapshot;
const snapshot = await build(app, 30, deps);
if (!snapshot?.measurements?.length) return skipped(app, 'no-evidence');
- const next = serialize(snapshot);
+ const next = qualityFileFromWireSnapshot(snapshot);
+ if (!next) return skipped(app, 'invalid-evidence');
if (lastPublishedBody.get(app.repoPath) === next) return skipped(app, 'no-changes');
- if (!hasOrigin(await git.getRemote(app.repoPath))) return skipped(app, 'no-remote');
+ const base = await repoBase(app, git);
+ if (base.skip) return base.skip;
+ const onDefault = await readGitSnapshot(
+ git, app.repoPath, `origin/${base.defaultBranch}:${APP_QUALITY_SNAPSHOT_FILENAME}`,
+ );
+ if (REWRITE_BLOCKED.has(onDefault.status)) return untouched(app, onDefault.status);
+ // v1 bytes are a real migration even when the scores match. Only v2 that
+ // already canonicalizes to `next` is "no changes".
+ if (sameSnapshot(onDefault, next)) {
+ lastPublishedBody.set(app.repoPath, next);
+ return skipped(app, 'no-changes');
+ }
+ return landOrReuse(app, git, base.defaultBranch, deps, next, snapshot.measurements.length);
+}
+
+async function migrateNow(app, deps) {
+ const git = deps.git || await import('./git.js');
+ if (!await git.isRepo(app.repoPath)) return skipped(app, 'not-a-repo');
+ const base = await repoBase(app, git);
+ if (base.skip) return base.skip;
- await git.fetchOrigin(app.repoPath).catch(() => {});
- const defaultBranch = await git.getDefaultBranch(app.repoPath);
- if (!defaultBranch) return skipped(app, 'no-default-branch');
+ let source = await readGitSnapshot(
+ git, app.repoPath, `origin/${base.defaultBranch}:${APP_QUALITY_SNAPSHOT_FILENAME}`,
+ );
+ let removeLegacy = false;
+ if (source.status === 'absent') {
+ source = await readGitSnapshot(
+ git, app.repoPath, `origin/${base.defaultBranch}:${APP_QUALITY_LEGACY_SNAPSHOT_FILENAME}`,
+ );
+ removeLegacy = source.status === 'v1' || source.status === 'v2';
+ }
+ if (source.status === 'absent') return skipped(app, 'no-legacy-file');
+ if (REWRITE_BLOCKED.has(source.status)) return untouched(app, source.status);
+ if (!source.records?.length || !source.canonical) return skipped(app, 'no-evidence');
- const fromDefault = await showRefFile(git, app.repoPath, `origin/${defaultBranch}:${APP_QUALITY_SNAPSHOT_FILENAME}`);
- if (fromDefault === next) {
+ const next = source.canonical;
+ if (!removeLegacy && source.status === 'v2' && source.body === next) {
lastPublishedBody.set(app.repoPath, next);
return skipped(app, 'no-changes');
}
+ if (lastPublishedBody.get(app.repoPath) === next && !removeLegacy) return skipped(app, 'no-changes');
+ return landOrReuse(app, git, base.defaultBranch, deps, next, source.records.length, {
+ removeLegacy,
+ message: `chore: migrate quality snapshot to schema v2 (${source.records.length} measurements)`,
+ });
+}
- const fromBranch = await showRefFile(git, app.repoPath, `origin/${QUALITY_SNAPSHOT_BRANCH}:${APP_QUALITY_SNAPSHOT_FILENAME}`);
- if (fromBranch === next) {
+async function landOrReuse(app, git, defaultBranch, deps, next, count, options = {}) {
+ const onBranch = await readGitSnapshot(
+ git, app.repoPath, `origin/${QUALITY_SNAPSHOT_BRANCH}:${APP_QUALITY_SNAPSHOT_FILENAME}`,
+ );
+ const legacyOnBranch = options.removeLegacy
+ ? await readGitSnapshot(git, app.repoPath, `origin/${QUALITY_SNAPSHOT_BRANCH}:${APP_QUALITY_LEGACY_SNAPSHOT_FILENAME}`)
+ : { status: 'absent' };
+ if (sameSnapshot(onBranch, next) && legacyOnBranch.status === 'absent') {
const reused = await reuseOpenSnapshotPr(app, git, defaultBranch, deps);
if (reused.published) lastPublishedBody.set(app.repoPath, next);
return reused;
}
-
- const count = snapshot.measurements.length;
- const result = await landSnapshotPr(app, { body: next, count, defaultBranch, git, deps });
+ const result = await landSnapshotPr(app, {
+ body: next, count, defaultBranch, git, deps,
+ message: options.message, removeLegacy: options.removeLegacy === true,
+ });
lastPublishedBody.set(app.repoPath, next);
return result;
}
@@ -174,7 +307,7 @@ async function landExistingBranchPr(app, git, defaultBranch, deps) {
};
}
-async function landSnapshotPr(app, { body, count, defaultBranch, git, deps }) {
+async function landSnapshotPr(app, { body, count, defaultBranch, git, deps, message, removeLegacy = false }) {
const makeTemp = deps.mkdtemp || mkdtemp;
const worktreePath = await makeTemp(join(tmpdir(), 'portos-quality-'));
const addWorktree = deps.addWorktree || (async (args, repo) => {
@@ -182,6 +315,10 @@ async function landSnapshotPr(app, { body, count, defaultBranch, git, deps }) {
return addWorktreeWithRetry(args, repo);
});
const removeTemp = deps.rm || rm;
+ const commitPaths = removeLegacy
+ ? [APP_QUALITY_SNAPSHOT_FILENAME, APP_QUALITY_LEGACY_SNAPSHOT_FILENAME]
+ : [APP_QUALITY_SNAPSHOT_FILENAME];
+ const commitMessage = message || `chore: publish PortOS quality snapshot (${count} measurements)`;
const run = async () => {
const baseRef = `origin/${defaultBranch}`;
@@ -193,12 +330,15 @@ async function landSnapshotPr(app, { body, count, defaultBranch, git, deps }) {
app.repoPath,
);
await (deps.writeFile || atomicWrite)(join(worktreePath, APP_QUALITY_SNAPSHOT_FILENAME), body);
+ if (removeLegacy) {
+ await git.execGit(['rm', '-f', '--', APP_QUALITY_LEGACY_SNAPSHOT_FILENAME], worktreePath);
+ }
await git.stageFiles(worktreePath, [APP_QUALITY_SNAPSHOT_FILENAME]);
const { hash } = await git.commit(
worktreePath,
- `chore: publish PortOS quality snapshot (${count} measurements)`,
- { paths: [APP_QUALITY_SNAPSHOT_FILENAME] },
- ).catch(err => git.unstageFiles(worktreePath, [APP_QUALITY_SNAPSHOT_FILENAME])
+ commitMessage,
+ { paths: commitPaths },
+ ).catch(err => git.unstageFiles(worktreePath, commitPaths)
.catch(() => {}).then(() => Promise.reject(err)));
await pushSnapshotBranch(git, app.repoPath, worktreePath);
diff --git a/server/services/appQualitySnapshotFile.test.js b/server/services/appQualitySnapshotFile.test.js
index 5ca60daa09..cd5a7e991e 100644
--- a/server/services/appQualitySnapshotFile.test.js
+++ b/server/services/appQualitySnapshotFile.test.js
@@ -2,8 +2,12 @@ import { it, expect, vi, beforeEach, afterEach } from 'vitest';
import { join } from 'node:path';
import {
APP_QUALITY_SNAPSHOT_FILENAME, APP_QUALITY_SNAPSHOT_MAX_BYTES, QUALITY_SNAPSHOT_BRANCH,
- readAppQualitySnapshotFile, publishAppQualitySnapshot, __resetQualitySnapshotPublishState,
+ readAppQualitySnapshotFile, readStoredQualitySnapshot, publishAppQualitySnapshot,
+ migrateAppQualitySnapshot, __resetQualitySnapshotPublishState,
} from './appQualitySnapshotFile.js';
+import {
+ APP_QUALITY_LEGACY_SNAPSHOT_FILENAME, qualityFileFromWireSnapshot,
+} from './appQualitySnapshotFormat.js';
const app = { id: 'example-id', repoPath: '/repo/example-app' };
const worktreePath = '/tmp/portos-quality-test';
@@ -19,6 +23,7 @@ const snapshot = (count = 1) => ({
})),
});
const serialized = body => `${JSON.stringify(body, null, 2)}\n`;
+const canonical = () => qualityFileFromWireSnapshot(snapshot());
const missingShow = { exitCode: 1, stdout: '', stderr: 'exists' };
const gitDouble = (overrides = {}) => ({
isRepo: vi.fn(async () => true),
@@ -80,9 +85,16 @@ it('lands a changed snapshot from a detached worktree so the PR branch stays att
});
const [path, body] = deps.writeFile.mock.calls[0];
expect(path).toBe(join(worktreePath, '.quality.json'));
- expect(JSON.parse(body)).toEqual(snapshot());
+ expect(body).toBe(canonical());
+ expect(JSON.parse(body)).toMatchObject({
+ schemaVersion: 2,
+ reportVersion: 1,
+ categories: ['security'],
+ measurements: [['2026-09-10T10:00:00Z', 0, 82, 5, 0, 2, 12, 12]],
+ });
expect(body.endsWith('\n')).toBe(true);
- expect(body).not.toMatch(/Users|summary|app_id|agent-|github/);
+ expect(body).not.toMatch(/measurementId|Users|summary|app_id|agent-|github/);
+ expect(deps.buildQualitySnapshot).toHaveBeenCalledWith(app, 30, deps);
expect(deps.addWorktree).toHaveBeenCalledWith(
['worktree', 'add', '--detach', worktreePath, 'origin/main'],
'/repo/example-app',
@@ -116,7 +128,7 @@ it('lands a changed snapshot from a detached worktree so the PR branch stays att
});
it('skips when origin already has the snapshot and does not write the live checkout', async () => {
- const body = serialized(snapshot());
+ const body = canonical();
const deps = testDeps({
git: gitDouble({
execGit: vi.fn(async (args) => args[0] === 'show' && String(args[1]).startsWith('origin/main:')
@@ -133,7 +145,7 @@ it('skips when origin already has the snapshot and does not write the live check
});
it('re-queues an already-open snapshot PR whose branch already has the same bytes', async () => {
- const body = serialized(snapshot());
+ const body = canonical();
const deps = testDeps({
git: gitDouble({
execGit: vi.fn(async (args) => args[0] === 'show' && String(args[1]).includes(QUALITY_SNAPSHOT_BRANCH)
@@ -259,3 +271,105 @@ it('enables GitLab auto-merge instead of the GitHub pending-merge queue', async
'/repo/example-app', undefined, { rejectOnError: true },
);
});
+
+const showFiles = files => vi.fn(async (args) => {
+ if (args[0] !== 'show') return missingShow;
+ const spec = String(args[1]);
+ const name = spec.slice(spec.lastIndexOf(':') + 1);
+ return Object.hasOwn(files, name)
+ ? { exitCode: 0, stdout: files[name], stderr: '' }
+ : missingShow;
+});
+
+it('rewrites a v1 snapshot to canonical v2 and leaves a semantically identical v2 untouched', async () => {
+ const upgrade = testDeps({ git: gitDouble({ execGit: showFiles({ '.quality.json': serialized(snapshot()) }) }) });
+ expect(await publishAppQualitySnapshot(app, upgrade)).toMatchObject({ published: true, prUrl });
+ expect(upgrade.writeFile.mock.calls[0][1]).toBe(canonical());
+ expect(upgrade.writeFile.mock.calls[0][0]).toBe(join(worktreePath, '.quality.json'));
+
+ __resetQualitySnapshotPublishState();
+ const compact = JSON.stringify(JSON.parse(canonical()));
+ const identical = testDeps({ git: gitDouble({ execGit: showFiles({ '.quality.json': compact }) }) });
+ expect(await publishAppQualitySnapshot(app, identical)).toEqual({
+ published: false, reason: 'no-changes', path: '.quality.json',
+ });
+ expect(identical.writeFile).not.toHaveBeenCalled();
+ expect(identical.addWorktree).not.toHaveBeenCalled();
+});
+
+it('leaves a future, unrecognized, or unreadable snapshot in place', async () => {
+ const future = testDeps({
+ git: gitDouble({ execGit: showFiles({ '.quality.json': JSON.stringify({ schemaVersion: 3, repository: 'a'.repeat(64) }) }) }),
+ });
+ expect(await publishAppQualitySnapshot(app, future)).toEqual({
+ published: false, reason: 'unsupported-format', path: '.quality.json',
+ });
+ expect(future.writeFile).not.toHaveBeenCalled();
+
+ const tsv = testDeps({
+ git: gitDouble({ execGit: showFiles({ '.quality.json': 'category\tscore\nsecurity\t80\n' }) }),
+ });
+ expect((await publishAppQualitySnapshot(app, tsv)).reason).toBe('unsupported-format');
+ expect(tsv.writeFile).not.toHaveBeenCalled();
+
+ const unreadable = testDeps({
+ git: gitDouble({ execGit: vi.fn(async (args) => {
+ if (args[0] === 'show') throw new Error('git output exceeded maxBuffer');
+ return { exitCode: 0, stdout: '', stderr: '' };
+ }) }),
+ });
+ expect((await publishAppQualitySnapshot(app, unreadable)).reason).toBe('unsupported-format');
+ expect(unreadable.writeFile).not.toHaveBeenCalled();
+ expect(log).toHaveBeenCalledWith('📊 Quality snapshot left untouched for app example-id: future');
+});
+
+it('migrates a legacy file to v2 without inventing measurements or writing the live checkout', async () => {
+ const legacyBody = serialized(snapshot());
+ const deps = testDeps({
+ git: gitDouble({ execGit: showFiles({ [APP_QUALITY_LEGACY_SNAPSHOT_FILENAME]: legacyBody }) }),
+ buildQualitySnapshot: vi.fn(async () => snapshot(3)),
+ });
+ expect(await migrateAppQualitySnapshot(app, deps)).toMatchObject({ published: true, prUrl, hash: 'abc1234' });
+ expect(deps.buildQualitySnapshot).not.toHaveBeenCalled();
+ const [path, body] = deps.writeFile.mock.calls[0];
+ expect(path).toBe(join(worktreePath, '.quality.json'));
+ expect(path.startsWith(app.repoPath)).toBe(false);
+ expect(JSON.parse(body).measurements).toEqual([['2026-09-10T10:00:00Z', 0, 82, 5, 0, 2, 12, 12]]);
+ expect(deps.git.execGit).toHaveBeenCalledWith(
+ ['rm', '-f', '--', APP_QUALITY_LEGACY_SNAPSHOT_FILENAME], worktreePath);
+ expect(deps.git.commit).toHaveBeenCalledWith(worktreePath,
+ 'chore: migrate quality snapshot to schema v2 (1 measurements)',
+ { paths: ['.quality.json', APP_QUALITY_LEGACY_SNAPSHOT_FILENAME] });
+
+ __resetQualitySnapshotPublishState();
+ const again = testDeps({
+ git: gitDouble({ execGit: showFiles({ '.quality.json': body }) }),
+ buildQualitySnapshot: vi.fn(async () => { throw new Error('database must stay unread'); }),
+ });
+ expect(await migrateAppQualitySnapshot(app, again)).toEqual({
+ published: false, reason: 'no-changes', path: '.quality.json',
+ });
+ expect(again.writeFile).not.toHaveBeenCalled();
+ expect(again.addWorktree).not.toHaveBeenCalled();
+});
+
+it('reads v1, v2, and the legacy filename without falling past a canonical file', async () => {
+ const v1 = serialized(snapshot());
+ const v2 = canonical();
+ const read = files => readStoredQualitySnapshot('/repo/example-app', {
+ readFile: async path => {
+ const name = path.slice(path.lastIndexOf('/') + 1);
+ if (!Object.hasOwn(files, name)) throw new Error('ENOENT');
+ return files[name];
+ },
+ });
+ expect(APP_QUALITY_LEGACY_SNAPSHOT_FILENAME).toBe('quality-snapshot.json');
+ expect((await read({ '.quality.json': v1 })).status).toBe('v1');
+ expect((await read({ '.quality.json': v2 })).status).toBe('v2');
+ expect((await read({ [APP_QUALITY_LEGACY_SNAPSHOT_FILENAME]: v1 })).filename).toBe(APP_QUALITY_LEGACY_SNAPSHOT_FILENAME);
+ const both = await read({ '.quality.json': v2, [APP_QUALITY_LEGACY_SNAPSHOT_FILENAME]: v1 });
+ expect(both.filename).toBe('.quality.json');
+ expect(both.status).toBe('v2');
+ expect((await read({ '.quality.json': 'not-json', [APP_QUALITY_LEGACY_SNAPSHOT_FILENAME]: v1 })).status).toBe('unrecognized');
+ expect((await read({ '.quality.json': ' '.repeat(APP_QUALITY_SNAPSHOT_MAX_BYTES + 1) })).status).toBe('oversize');
+});
diff --git a/server/services/appQualitySnapshotFormat.js b/server/services/appQualitySnapshotFormat.js
new file mode 100644
index 0000000000..cc48c98973
--- /dev/null
+++ b/server/services/appQualitySnapshotFormat.js
@@ -0,0 +1,285 @@
+/**
+ * Checked-in `.quality.json` schema. This is not the peer wire payload.
+ *
+ * `PORTOS_SCHEMA_VERSIONS.appQuality` stays the v1 federation object. Writers
+ * emit only canonical file schema v2. v1 JSON and a historical
+ * `quality-snapshot.json` body normalize to the same records; a future schema
+ * is recognized and left for the publisher to report, not reinterpreted.
+ *
+ * Rows are `[assessedAt, categoryIndex, score, worstSeverity, coverageIndex,
+ * confidenceIndex, scannedFiles, totalFiles]`. `measurementId` is not stored.
+ * Same-timestamp selection uses the v1 id while a file still has one, otherwise
+ * a transient digest of the normalized row (`releaseTieId`). The digest is not
+ * written. PostgreSQL remains the history; this file is only the bounded
+ * projection the publisher already built.
+ */
+import { createHash } from 'node:crypto';
+import { z } from 'zod';
+import { AUDIT_DEFINITIONS } from '../lib/auditCatalog.js';
+import { auditQualityReportSchema } from '../lib/auditQuality.js';
+
+export const APP_QUALITY_FILE_SCHEMA_VERSION = 2;
+export const APP_QUALITY_REPORT_VERSION = 1;
+export const APP_QUALITY_LEGACY_SNAPSHOT_FILENAME = 'quality-snapshot.json';
+export const QUALITY_COVERAGE_VALUES = Object.freeze(['broad', 'partial', 'unavailable', 'not-applicable']);
+export const QUALITY_CONFIDENCE_VALUES = Object.freeze(['low', 'medium', 'high']);
+export const MAX_QUALITY_SNAPSHOT_ROWS = 10000;
+
+const REPOSITORY = /^[a-f0-9]{64}$/;
+const CATEGORIES = new Set(Object.keys(AUDIT_DEFINITIONS));
+const COVERAGE = new Set(QUALITY_COVERAGE_VALUES);
+const CONFIDENCE = new Set(QUALITY_CONFIDENCE_VALUES);
+const V1_KEYS = new Set(['schemaVersion', 'repository', 'measurements']);
+const V2_KEYS = new Set(['schemaVersion', 'repository', 'reportVersion', 'categories', 'coverage', 'confidence', 'measurements']);
+const MEASUREMENT_KEYS = new Set(['measurementId', 'assessedAt', 'report']);
+const REPORT_KEYS = new Set(['version', 'category', 'score', 'worstSeverity', 'coverage', 'confidence', 'summary', 'scannedFiles', 'totalFiles']);
+const PLACEHOLDER_SUMMARY = 'Numeric assessment';
+// Z and numeric offsets are both ISO instants. Zod's default datetime() rejects
+// offsets, which would treat one UTC day as two when the date prefix differs.
+const timestampSchema = z.iso.datetime({ offset: true });
+
+function compareText(a, b) {
+ if (a < b) return -1;
+ if (a > b) return 1;
+ return 0;
+}
+
+function plainObject(value) {
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
+}
+
+function allowedKeys(value, keys) {
+ return plainObject(value) && Object.keys(value).every(key => keys.has(key));
+}
+
+function utcDay(iso) {
+ const time = Date.parse(iso);
+ return Number.isFinite(time) ? new Date(time).toISOString().slice(0, 10) : null;
+}
+
+function isInt(value, min, max) {
+ return typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max;
+}
+
+function duplicateDays(records) {
+ const seen = new Set();
+ for (const record of records) {
+ const day = utcDay(record.assessedAt);
+ if (!day) return true;
+ const key = `${day}|${record.category}`;
+ if (seen.has(key)) return true;
+ seen.add(key);
+ }
+ return false;
+}
+
+function numericReport(report) {
+ if (!allowedKeys(report, REPORT_KEYS)) return null;
+ const parsed = auditQualityReportSchema.safeParse({ ...report, summary: PLACEHOLDER_SUMMARY });
+ if (!parsed.success) return null;
+ const { summary: _summary, ...kept } = parsed.data;
+ return kept;
+}
+
+function normalizeRecord(record, measurementId = null) {
+ if (!plainObject(record) || !timestampSchema.safeParse(record.assessedAt).success) return null;
+ const report = numericReport({
+ version: 1,
+ category: record.category,
+ score: record.score,
+ worstSeverity: record.worstSeverity,
+ coverage: record.coverage,
+ confidence: record.confidence,
+ scannedFiles: record.scannedFiles,
+ totalFiles: record.totalFiles,
+ });
+ if (!report) return null;
+ return {
+ assessedAt: record.assessedAt,
+ category: report.category,
+ score: report.score,
+ worstSeverity: report.worstSeverity,
+ coverage: report.coverage,
+ confidence: report.confidence,
+ scannedFiles: report.scannedFiles,
+ totalFiles: report.totalFiles,
+ measurementId,
+ };
+}
+
+function compareRecords(a, b) {
+ return Date.parse(a.assessedAt) - Date.parse(b.assessedAt)
+ || compareText(a.assessedAt, b.assessedAt)
+ || compareText(a.category, b.category);
+}
+
+function canonicalize(repository, records) {
+ const categories = [...new Set(records.map(record => record.category))].sort(compareText);
+ const categoryIndex = new Map(categories.map((category, index) => [category, index]));
+ const coverageIndex = new Map(QUALITY_COVERAGE_VALUES.map((value, index) => [value, index]));
+ const confidenceIndex = new Map(QUALITY_CONFIDENCE_VALUES.map((value, index) => [value, index]));
+ const measurements = [...records].sort(compareRecords).map(record => [
+ record.assessedAt,
+ categoryIndex.get(record.category),
+ record.score,
+ record.worstSeverity,
+ coverageIndex.get(record.coverage),
+ confidenceIndex.get(record.confidence),
+ record.scannedFiles,
+ record.totalFiles,
+ ]);
+ return `${JSON.stringify({
+ schemaVersion: APP_QUALITY_FILE_SCHEMA_VERSION,
+ repository,
+ reportVersion: APP_QUALITY_REPORT_VERSION,
+ categories,
+ coverage: [...QUALITY_COVERAGE_VALUES],
+ confidence: [...QUALITY_CONFIDENCE_VALUES],
+ measurements,
+ }, null, 2)}\n`;
+}
+
+/** Canonical v2 text, or null when the records are not a valid projection. */
+export function serializeQualitySnapshot(repository, records) {
+ if (typeof repository !== 'string' || !REPOSITORY.test(repository) || !Array.isArray(records)) return null;
+ if (records.length > MAX_QUALITY_SNAPSHOT_ROWS) return null;
+ const normalized = [];
+ for (const record of records) {
+ const measurementId = typeof record?.measurementId === 'string' && REPOSITORY.test(record.measurementId)
+ ? record.measurementId : null;
+ const next = normalizeRecord(record, measurementId);
+ if (!next) return null;
+ normalized.push(next);
+ }
+ if (duplicateDays(normalized)) return null;
+ return canonicalize(repository, normalized);
+}
+
+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;
+ if (new Set(values).size !== values.length) return null;
+ return values;
+}
+
+function parseV1Measurement(measurement) {
+ if (!allowedKeys(measurement, MEASUREMENT_KEYS)) return null;
+ if (typeof measurement.measurementId !== 'string' || !REPOSITORY.test(measurement.measurementId)) return null;
+ if (!timestampSchema.safeParse(measurement.assessedAt).success) return null;
+ const report = numericReport(measurement.report);
+ if (!report) return null;
+ return normalizeRecord({ assessedAt: measurement.assessedAt, ...report }, measurement.measurementId);
+}
+
+function parseV1(value) {
+ if (!allowedKeys(value, V1_KEYS) || value.schemaVersion !== 1) return { status: 'malformed' };
+ if (typeof value.repository !== 'string' || !REPOSITORY.test(value.repository)) return { status: 'malformed' };
+ if (!Array.isArray(value.measurements) || value.measurements.length > MAX_QUALITY_SNAPSHOT_ROWS) return { status: 'malformed' };
+ const records = [];
+ for (const measurement of value.measurements) {
+ const record = parseV1Measurement(measurement);
+ if (!record) return { status: 'malformed' };
+ records.push(record);
+ }
+ if (duplicateDays(records)) return { status: 'malformed' };
+ const canonical = canonicalize(value.repository, records);
+ return canonical
+ ? { status: 'v1', repository: value.repository, records, canonical }
+ : { status: 'malformed' };
+}
+
+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;
+ if (!timestampSchema.safeParse(assessedAt).success) return null;
+ if (!isInt(categoryIndex, 0, Math.max(categories.length - 1, 0)) || categoryIndex >= categories.length) return null;
+ if (!(score === null || isInt(score, 0, 100))) return null;
+ if (!isInt(worstSeverity, 0, 10)) return null;
+ 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;
+ return normalizeRecord({
+ assessedAt,
+ category: categories[categoryIndex],
+ score,
+ worstSeverity,
+ coverage: coverage[coverageIndex],
+ confidence: confidence[confidenceIndex],
+ scannedFiles,
+ totalFiles,
+ });
+}
+
+function parseV2(value) {
+ if (!allowedKeys(value, V2_KEYS) || value.schemaVersion !== 2 || value.reportVersion !== APP_QUALITY_REPORT_VERSION) {
+ return { status: 'malformed' };
+ }
+ if (typeof value.repository !== 'string' || !REPOSITORY.test(value.repository)) return { status: 'malformed' };
+ const categories = parseDictionary(value.categories, CATEGORIES);
+ const coverage = parseDictionary(value.coverage, COVERAGE);
+ const confidence = parseDictionary(value.confidence, CONFIDENCE);
+ if (!categories || !coverage || !confidence) return { status: 'malformed' };
+ if (!Array.isArray(value.measurements) || value.measurements.length > MAX_QUALITY_SNAPSHOT_ROWS) return { status: 'malformed' };
+ if (value.measurements.length > 0 && (categories.length === 0 || coverage.length === 0 || confidence.length === 0)) {
+ return { status: 'malformed' };
+ }
+ const records = [];
+ for (const row of value.measurements) {
+ const record = parseV2Row(row, categories, coverage, confidence);
+ if (!record) return { status: 'malformed' };
+ records.push(record);
+ }
+ if (duplicateDays(records)) return { status: 'malformed' };
+ const canonical = canonicalize(value.repository, records);
+ return canonical
+ ? { status: 'v2', repository: value.repository, records, canonical }
+ : { status: 'malformed' };
+}
+
+/**
+ * Classify a snapshot document. `canonical` is the only byte sequence writers
+ * emit for that repository and those records. Future schemas stay unparsed.
+ */
+export function classifyQualitySnapshot(body) {
+ if (typeof body !== 'string') return { status: 'unrecognized' };
+ let parsed;
+ try {
+ parsed = JSON.parse(body);
+ } catch {
+ return { status: 'unrecognized' };
+ }
+ if (!plainObject(parsed) || !Object.hasOwn(parsed, 'schemaVersion')) return { status: 'unrecognized' };
+ if (parsed.schemaVersion === 1) return parseV1(parsed);
+ if (parsed.schemaVersion === 2) return parseV2(parsed);
+ if (Number.isInteger(parsed.schemaVersion) && parsed.schemaVersion > APP_QUALITY_FILE_SCHEMA_VERSION) {
+ return { status: 'future' };
+ }
+ return { status: 'unrecognized' };
+}
+
+/** v1 wire object or v2 file object → canonical v2 text, or null. */
+export function qualityFileFromWireSnapshot(snapshot) {
+ const classified = classifyQualitySnapshot(JSON.stringify(snapshot ?? null));
+ return classified.status === 'v1' || classified.status === 'v2' ? classified.canonical : null;
+}
+
+/** Digest of the scoring row. Not stored in v2; used only to order timestamp ties. */
+export function snapshotTieKey(record) {
+ return createHash('sha256').update(JSON.stringify([
+ record.assessedAt,
+ record.category,
+ record.score,
+ record.worstSeverity,
+ record.coverage,
+ record.confidence,
+ record.scannedFiles,
+ record.totalFiles,
+ ])).digest('hex');
+}
+
+/** v1 files keep their stored id. v2 rows get the transient digest. */
+export function releaseTieId(record) {
+ return typeof record?.measurementId === 'string' && REPOSITORY.test(record.measurementId)
+ ? record.measurementId
+ : snapshotTieKey(record);
+}
diff --git a/server/services/appQualitySnapshotFormat.test.js b/server/services/appQualitySnapshotFormat.test.js
new file mode 100644
index 0000000000..a8d5036942
--- /dev/null
+++ b/server/services/appQualitySnapshotFormat.test.js
@@ -0,0 +1,157 @@
+import { it, expect } from 'vitest';
+import { AUDIT_DEFINITIONS } from '../lib/auditCatalog.js';
+import { compareQualityRecords } from '../lib/auditQuality.js';
+import { APP_QUALITY_SNAPSHOT_MAX_BYTES } from './appQualitySnapshotFile.js';
+import {
+ APP_QUALITY_FILE_SCHEMA_VERSION, QUALITY_COVERAGE_VALUES, QUALITY_CONFIDENCE_VALUES,
+ classifyQualitySnapshot, qualityFileFromWireSnapshot, releaseTieId, serializeQualitySnapshot,
+ snapshotTieKey,
+} from './appQualitySnapshotFormat.js';
+
+const repository = 'a'.repeat(64);
+const measurementId = 'b'.repeat(64);
+const security = {
+ assessedAt: '2026-09-20T00:00:00.000Z',
+ category: 'security',
+ score: 82,
+ worstSeverity: 5,
+ coverage: 'broad',
+ confidence: 'high',
+ scannedFiles: 120,
+ totalFiles: 120,
+};
+const typing = {
+ assessedAt: '2026-09-21T00:00:00.000Z',
+ category: 'typing',
+ score: null,
+ worstSeverity: 0,
+ coverage: 'not-applicable',
+ confidence: 'low',
+ scannedFiles: 0,
+ totalFiles: 4,
+};
+
+function v1Document(measurements) {
+ return {
+ schemaVersion: 1,
+ repository,
+ measurements: measurements.map(record => ({
+ measurementId: record.measurementId || measurementId,
+ assessedAt: record.assessedAt,
+ report: {
+ version: 1,
+ category: record.category,
+ score: record.score,
+ worstSeverity: record.worstSeverity,
+ coverage: record.coverage,
+ confidence: record.confidence,
+ summary: 'private narrative for example-user and agent-example',
+ scannedFiles: record.scannedFiles,
+ totalFiles: record.totalFiles,
+ },
+ })),
+ };
+}
+
+it('serializes canonical v2 rows with stable indexes and no provenance', () => {
+ const text = serializeQualitySnapshot(repository, [{ ...typing }, { ...security, measurementId }]);
+ const parsed = JSON.parse(text);
+ expect(APP_QUALITY_FILE_SCHEMA_VERSION).toBe(2);
+ expect(parsed).toEqual({
+ schemaVersion: 2,
+ repository,
+ reportVersion: 1,
+ categories: ['security', 'typing'],
+ coverage: [...QUALITY_COVERAGE_VALUES],
+ confidence: [...QUALITY_CONFIDENCE_VALUES],
+ measurements: [
+ ['2026-09-20T00:00:00.000Z', 0, 82, 5, 0, 2, 120, 120],
+ ['2026-09-21T00:00:00.000Z', 1, null, 0, 3, 0, 0, 4],
+ ],
+ });
+ expect(text.endsWith('\n')).toBe(true);
+ expect(text).not.toMatch(/measurementId|example-user|agent-example|summary/);
+ expect(classifyQualitySnapshot(text).canonical).toBe(text);
+ const reversed = serializeQualitySnapshot(repository, [typing, security]);
+ expect(reversed).toBe(text);
+});
+
+it('normalizes v1 JSON idempotently and keeps its measurement id off the v2 bytes', () => {
+ const wire = v1Document([security, typing]);
+ const first = classifyQualitySnapshot(JSON.stringify(wire));
+ expect(first.status).toBe('v1');
+ expect(first.records.map(record => record.measurementId)).toEqual([measurementId, measurementId]);
+ expect(first.records.map(record => record.score)).toEqual([82, null]);
+ expect(JSON.stringify(first.records)).not.toMatch(/example-user|agent-example/);
+ const second = classifyQualitySnapshot(first.canonical);
+ expect(second.status).toBe('v2');
+ expect(second.canonical).toBe(first.canonical);
+ expect(second.records.map(record => record.measurementId)).toEqual([null, null]);
+ expect(qualityFileFromWireSnapshot(wire)).toBe(first.canonical);
+ expect(first.canonical).not.toContain(measurementId);
+});
+
+it('rejects future, unrecognized, malformed, duplicate-day, and invalid-index documents', () => {
+ expect(classifyQualitySnapshot('category\tscore\n').status).toBe('unrecognized');
+ expect(classifyQualitySnapshot('{"quality":true}').status).toBe('unrecognized');
+ expect(classifyQualitySnapshot(JSON.stringify({ schemaVersion: 3, repository })).status).toBe('future');
+ expect(classifyQualitySnapshot(JSON.stringify({ ...v1Document([security]), schemaVersion: 2 })).status).toBe('malformed');
+ expect(classifyQualitySnapshot(JSON.stringify({ ...v1Document([security]), note: true })).status).toBe('malformed');
+
+ const sameDay = v1Document([
+ security,
+ { ...security, assessedAt: '2026-09-19T22:30:00-04:00', score: 10 },
+ ]);
+ expect(classifyQualitySnapshot(JSON.stringify(sameDay)).status).toBe('malformed');
+ const nextDay = v1Document([
+ security,
+ { ...security, assessedAt: '2026-09-20T20:30:00-04:00', score: 70 },
+ ]);
+ expect(classifyQualitySnapshot(JSON.stringify(nextDay)).status).toBe('v1');
+
+ const badIndex = classifyQualitySnapshot(JSON.stringify({
+ schemaVersion: 2, repository, reportVersion: 1,
+ categories: ['security'], coverage: [...QUALITY_COVERAGE_VALUES], confidence: [...QUALITY_CONFIDENCE_VALUES],
+ measurements: [['2026-09-20T00:00:00.000Z', 4, 82, 5, 0, 2, 120, 120]],
+ }));
+ expect(badIndex.status).toBe('malformed');
+ expect(serializeQualitySnapshot(repository, [security, { ...security, score: 1 }])).toBeNull();
+});
+
+it('keeps v1 tie ids and orders v2 rows with a transient digest', () => {
+ const low = { ...security, score: 25 };
+ const high = { ...security, score: 75 };
+ expect(snapshotTieKey(low)).not.toBe(snapshotTieKey(high));
+ expect(snapshotTieKey({ ...low, measurementId: 'c'.repeat(64) })).toBe(snapshotTieKey(low));
+ expect(releaseTieId({ ...low, measurementId })).toBe(measurementId);
+ expect(releaseTieId({ ...low, measurementId: null })).toBe(snapshotTieKey(low));
+ const winner = rows => [...rows].sort(compareQualityRecords).at(-1).score;
+ const keyed = record => ({ ...record, measurementId: snapshotTieKey(record) });
+ expect(winner([keyed(low), keyed(high)])).toBe(winner([keyed(high), keyed(low)]));
+ expect(classifyQualitySnapshot(serializeQualitySnapshot(repository, [low])).canonical).not.toContain(snapshotTieKey(low));
+});
+
+it('keeps a full 30-day category window under the cap and materially smaller than v1', () => {
+ const categories = Object.keys(AUDIT_DEFINITIONS);
+ const start = Date.parse('2026-08-01T00:00:00.000Z');
+ const records = [];
+ for (let day = 0; day < 30; day += 1) {
+ const assessedAt = new Date(start + day * 86400000).toISOString();
+ for (const category of categories) {
+ records.push({
+ assessedAt, category, score: 80, worstSeverity: 3,
+ coverage: 'broad', confidence: 'high', scannedFiles: 10, totalFiles: 10,
+ });
+ }
+ }
+ const v2 = serializeQualitySnapshot(repository, records);
+ const v1 = `${JSON.stringify(v1Document(records), null, 2)}\n`;
+ const rows = JSON.parse(v2).measurements;
+ expect(rows).toHaveLength(30 * categories.length);
+ expect(Buffer.byteLength(v2)).toBeLessThan(APP_QUALITY_SNAPSHOT_MAX_BYTES);
+ expect(Buffer.byteLength(v2)).toBeLessThan(Buffer.byteLength(v1) * 0.5);
+ const oneCategory = records.filter(record => record.category === categories[0]);
+ expect(JSON.parse(serializeQualitySnapshot(repository, records)).measurements)
+ .toHaveLength(JSON.parse(serializeQualitySnapshot(repository, oneCategory)).measurements.length * categories.length);
+ expect(JSON.parse(classifyQualitySnapshot(v2).canonical).measurements).toHaveLength(rows.length);
+});