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: unify PortOS quality scores across full-sync peers

Adam Eivy99451030ccea
diff --git a/client/src/components/apps/AppQuality.jsx b/client/src/components/apps/AppQuality.jsx
index d7aaaf8663..a3157b7139 100644
--- a/client/src/components/apps/AppQuality.jsx
+++ b/client/src/components/apps/AppQuality.jsx
@@ -21,6 +21,14 @@ export default function AppQuality({ app, detail = false }) {
Assessments describe the code before fixes. The overall score is the equal-weight mean of broad, medium/high-confidence assessments from the last 30 days.
{' '}{quality?.ratedCategories ?? 0}/{quality?.totalCategories ?? 0} categories contribute. Missing, partial, low-confidence and stale assessments are excluded, not counted as perfect.
</p>
+ {quality?.federation && (
+ <p className="text-xs text-gray-400">
+ Unified PortOS score: newest assessment per category across this install and {quality.federation.available ?? 0} available full-sync peers with the same repository. Versions may differ.
+ {' '}Peer evidence is fetched when viewed; offline peers do not contribute.
+ {quality.federation.failed && ' Peer quality could not be loaded; the score may be incomplete.'}
+ {quality.federation.unavailable > 0 && ` ${quality.federation.unavailable} peers unavailable or incompatible; the score may be incomplete.`}
+ </p>
+ )}
{score == null && !quality?.unavailable && (
<p className="text-sm text-gray-400">
{hasAssessments
@@ -45,7 +53,8 @@ export default function AppQuality({ app, detail = false }) {
{category.assessedAt && ` · ${formatDateShort(category.assessedAt)}`}</div>
{category.summary && <p className="mt-1 break-words">{category.summary}</p>}
{category.totalFiles > 0 && <div>{category.scannedFiles}/{category.totalFiles} files scanned · Worst severity: {category.worstSeverity}/10</div>}
- {category.agentId && <Link className="text-port-accent hover:underline" to={`/cos/agents/${category.agentId}`}>Audit run</Link>}
+ {category.sourcePeerId && <div>Source: {category.sourcePeerName || 'federated peer'} · <Link className="text-port-accent hover:underline" to="/instances">View instances</Link></div>}
+ {!category.sourcePeerId && category.agentId && <Link className="text-port-accent hover:underline" to={`/cos/agents/${category.agentId}`}>Audit run</Link>}
</td>
</tr>
))}</tbody>
diff --git a/client/src/components/apps/AppQuality.test.jsx b/client/src/components/apps/AppQuality.test.jsx
index bd1066a606..c73337200a 100644
--- a/client/src/components/apps/AppQuality.test.jsx
+++ b/client/src/components/apps/AppQuality.test.jsx
@@ -40,3 +40,14 @@ it('distinguishes saved but excluded evidence from an app that was never assesse
expect(screen.getByText(/Saved assessments do not currently qualify/)).toBeInTheDocument();
expect(screen.getByText('60/100')).toBeInTheDocument();
});
+
+it('identifies federated evidence and incomplete scores without linking to a local audit run', async () => {
+ const app = { id: 'portos-default', quality: { score: 80, federation: { available: 1, unavailable: 1 }, categories: [
+ { id: 'security', label: 'Security', score: 80, coverage: 'broad', sourcePeerId: 'peer-a', agentId: 'remote-run' },
+ ] } };
+ render(<MemoryRouter><AppQuality app={app} detail /></MemoryRouter>);
+ await screen.findByText(/No scored assessments/);
+ expect(screen.getByText(/1 peers unavailable or incompatible/)).toBeInTheDocument();
+ expect(screen.getByRole('link', { name: 'View instances' })).toHaveAttribute('href', '/instances');
+ expect(screen.queryByRole('link', { name: 'Audit run' })).not.toBeInTheDocument();
+});
diff --git a/client/src/components/apps/AppQualityHistory.jsx b/client/src/components/apps/AppQualityHistory.jsx
index e2a23806a0..87d6d410c0 100644
--- a/client/src/components/apps/AppQualityHistory.jsx
+++ b/client/src/components/apps/AppQualityHistory.jsx
@@ -43,6 +43,7 @@ export default function AppQualityHistory({ appId, categories = [] }) {
<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.data?.federation && <p className="text-xs text-gray-400">Unified history includes {state.data.federation.available ?? 0} available full-sync peers. {state.data.federation.failed ? 'Peer quality could not be loaded; history may be incomplete.' : state.data.federation.unavailable > 0 ? `${state.data.federation.unavailable} peers unavailable or incompatible; history may be incomplete.` : 'Peer availability can change historical coverage.'}</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%">
diff --git a/docs/README.md b/docs/README.md
index 007cd2c2a6..deab2928b6 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -54,7 +54,7 @@ Comms & voice: [beeper](./features/beeper.md) · [openclaw-operator-chat](./feat
## Point-in-time records
- **[plans/](./plans/README.md)** — dated design plans (`YYYY-MM-DD-<slug>.md`), archived on approval before implementation. Historical records, not living docs. See [provider connections and harnesses](./plans/2026-09-06-provider-connections-and-harnesses.md) for stable executable routes, migration and management flows.
-- **decisions/** — ADRs (`YYYY-MM-DD-<slug>.md`), e.g. the [Postgres-as-primary-datastore decision](./decisions/2026-06-07-postgres-as-primary-datastore.md) and what may cross the federation layer ([privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md), [federated visual prompts](./decisions/2026-08-20-federated-visual-prompts.md), [conditioning crosses to an allowlisted peer](./decisions/2026-08-22-federated-media-input-assets.md), [AI usage metrics federate on by default](./decisions/2026-09-01-federated-usage-metrics.md)), and why H3 [ships the draft-decode gates without an asset](./decisions/2026-08-30-h3-draft-decoder-asset.md).
+- **decisions/** — ADRs (`YYYY-MM-DD-<slug>.md`), e.g. the [Postgres-as-primary-datastore decision](./decisions/2026-06-07-postgres-as-primary-datastore.md) and what may cross the federation layer ([privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md), [federated visual prompts](./decisions/2026-08-20-federated-visual-prompts.md), [conditioning crosses to an allowlisted peer](./decisions/2026-08-22-federated-media-input-assets.md), [AI usage metrics federate on by default](./decisions/2026-09-01-federated-usage-metrics.md), [numeric PortOS quality federation](./decisions/2026-09-10-portos-quality-federation.md)), and why H3 [ships the draft-decode gates without an asset](./decisions/2026-08-30-h3-draft-decoder-asset.md).
- **research/** — dated investigation and incident write-ups (e.g. the [mflux GPU-watchdog panic](./research/2026-06-13-mflux-training-watchdog-panic.md) and the [local LLM performance audit](./research/2026-08-22-local-llm-performance-audit.md)).
- **superpowers/** — plan/spec pairs from superpowers-driven builds: `specs/<date>-<slug>-design.md` (design) + `plans/<date>-<slug>.md` (implementation plan).
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 1d8f3eff02..f7a392d3ee 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -389,6 +389,8 @@ only currently registered apps. PostgreSQL stores the bounded JSON report and
agent provenance; no asset bytes or new JSON store. Additive `CREATE TABLE IF
NOT EXISTS` in boot schema and init-db.sql provisions both existing and new
installs without transforming existing records. No seed or backfill fabricates
-scores. The mandatory Postgres backup includes the table. These assessments
-remain machine-local: they describe this install's checkout and agent evidence,
-and are not included in peer sync or capability/status payloads.
+scores. The mandatory Postgres backup includes the table. Assessment rows and their prose remain machine-local. The PortOS baseline app
+also exposes a numeric-only projection through `GET /api/apps/quality-federation`
+(`days=30|90|365`), gated on an identified, registered, enabled full-sync peer
+with outbound sharing allowed. The ordinary app list and capability/status
+payloads still carry no assessment data. See [quality federation](decisions/2026-09-10-portos-quality-federation.md).
diff --git a/docs/decisions/2026-09-10-portos-quality-federation.md b/docs/decisions/2026-09-10-portos-quality-federation.md
new file mode 100644
index 0000000000..f74098e165
--- /dev/null
+++ b/docs/decisions/2026-09-10-portos-quality-federation.md
@@ -0,0 +1,43 @@
+# Numeric PortOS quality federation
+
+PortOS audits may run on several federated installs. The quality panel and its
+history combine measurements for the baseline PortOS app across this install
+and directly registered full-sync peers. Other managed apps remain local.
+
+The newest assessment per category wins (run hash breaks timestamp ties), then
+the existing equal-weight category mean applies: broad coverage, medium/high
+confidence and no older than 30 days. Partial or unavailable newer assessments
+supersede older evidence without manufacturing a qualifying score. Repeated
+reads and repeated runs do not give a machine extra weight. UTC history uses
+only evidence available by each day's end, with the same freshness rules.
+
+Only peers with full sync enabled, sync not disabled, and an outbound-approved
+relationship are queried or served. The receiving endpoint always enforces this
+sharing policy, regardless of the legacy strict-pull ramp. The instance-id header
+identifies the configured peer; it is not authentication. Optional instance
+passwords continue to be sent through the existing peer HTTP client.
+
+The wire contract is versioned in `PORTOS_SCHEMA_VERSIONS.appQuality`. It exports
+only validated category enums, numeric scores/severity/inventory counts,
+coverage/confidence enums, timestamps and opaque run hashes. It never exports
+assessment summaries, transcripts, app paths, raw run IDs or private records.
+Only locally recorded measurements are served, so a read cannot recursively fan
+out or relay another peer's data. A hash of the normalized Git origin host and
+repository name scopes the exchange; raw remote URLs and credentials never
+travel. Unknown origins and different forks do not combine. Versions of the same
+repository intentionally combine: this is a distributed maintenance assessment,
+not a claim that every installed commit has identical code quality.
+
+Reads fetch existing data, never AI work. Each peer has a three-second deadline
+and a 4 MiB response cap. At most one row per UTC day/category is transferred,
+including a 30-day lookback for history. Old peers (404), unauthorized peers,
+incompatible schemas, malformed responses, differing repositories and offline
+peers are excluded and counted as unavailable in the UI. Local scores remain
+usable. This is read-through aggregation, not durable replication: history and
+scores may change with peer availability. It covers direct peers only; configure
+each analysis install as a full-sync peer to obtain the same complete view.
+
+The existing `app_quality_measurements` DB-primary store is unchanged and covered
+by normal PostgreSQL backup. No migration, seed, background job, persistent peer
+cache or new record-sync category is needed. This numeric projection does not
+relax the machine-local privacy rule for source evidence or other records.
diff --git a/server/lib/README.md b/server/lib/README.md
index 68e12d4594..430a51d6d2 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -632,4 +632,4 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `videoTimelineFades.js` | Browser-safe `fitFades()` proportionally fits a fade pair to its visible duration. Shared by timeline normalization/export and the editor preview/trim controls; legacy import paths re-export it. |
| `voiceEngines.js` | Shared TTS engine IDs, display metadata, supported-engine set, and persisted configuration keys. |
-| `auditQuality.js` | Category discovery strategies, assessment prompt and strict schema, sentinel parsing, and freshness-aware app quality aggregation. |
+| `auditQuality.js` | Category discovery strategies, assessment prompt and strict schema, sentinel parsing, and freshness-aware app quality aggregation with deterministic latest-per-category selection across peers. |
diff --git a/server/lib/auditQuality.js b/server/lib/auditQuality.js
index 153c45b69a..33fc54f494 100644
--- a/server/lib/auditQuality.js
+++ b/server/lib/auditQuality.js
@@ -83,7 +83,7 @@ export function summarizeAppQuality(records = [], now = Date.now()) {
const assessedAt = record?.assessedAt;
const age = now - Date.parse(assessedAt);
const stale = valid && (!Number.isFinite(age) || age < 0 || age > AUDIT_FRESHNESS_MS);
- return { id, label: definition.label, ...(valid ? report.data : { score: null, coverage: 'unavailable' }), assessedAt: assessedAt || null, agentId: record?.agentId || null, stale };
+ return { id, label: definition.label, ...(valid ? report.data : { score: null, coverage: 'unavailable' }), assessedAt: assessedAt || null, agentId: record?.agentId || null, sourcePeerId: record?.sourcePeerId || null, sourcePeerName: record?.sourcePeerName || null, stale };
});
const rated = categories.filter(c => !c.stale && c.coverage === 'broad' && c.confidence !== 'low' && c.score !== null);
return {
@@ -101,7 +101,7 @@ 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));
+ .sort(compareQualityRecords);
const latest = new Map();
let cursor = 0;
const points = [];
@@ -120,3 +120,15 @@ export function buildAppQualityHistory(records, days, now = Date.now()) {
}
return { days, totalCategories: Object.keys(AUDIT_DEFINITIONS).length, points };
}
+
+/** One newest measurement per category, with a stable run tie-break across all installs. */
+export function latestQualityRecords(records) {
+ const latest = new Map();
+ for (const record of [...records].sort(compareQualityRecords)) latest.set(record.category, record);
+ return [...latest.values()];
+}
+
+export function compareQualityRecords(a, b) {
+ return Date.parse(a.assessedAt) - Date.parse(b.assessedAt)
+ || (a.measurementId || a.agentId || '').localeCompare(b.measurementId || b.agentId || '');
+}
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 68feae5fe7..c7f8724cf6 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -32,6 +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.
+ appQuality: 1,
// Type-level (storage layout) version for `data/universes/{id}/index.json`.
// v5 = post-split. Migration 034 introduced it. The independent per-record
// shape is currently v5 (stamped inside each record by `sanitizeTemplate`).
diff --git a/server/routes/apps/crud.js b/server/routes/apps/crud.js
index 53e9b8b8fb..bc3d234321 100644
--- a/server/routes/apps/crud.js
+++ b/server/routes/apps/crud.js
@@ -1,4 +1,5 @@
import { appQualityQuerySchema, appQualityHistoryQuerySchema } from '../../lib/auditQuality.js';
+import { exportPortosQuality } from '../../services/appQualityFederation.js';
import { enrichAppsWithQuality, getAppQualityHistory } from '../../services/appQuality.js';
/**
* App CRUD + status enrichment + archive lifecycle.
@@ -30,6 +31,14 @@ import { loadApp, pathExists, deriveAppPorts, computeOverallStatus } from './sha
const router = Router();
+// Numeric local evidence only. This endpoint never invokes aggregate reads or forwards peer data.
+router.get('/quality-federation', asyncHandler(async (req, res) => {
+ const { days } = validateRequest(appQualityHistoryQuerySchema, req.query);
+ const payload = await exportPortosQuality(req.get('X-PortOS-Instance-Id'), days);
+ if (!payload) throw new ServerError('Quality sharing requires a registered enabled full-sync peer and a known repository', { status: 403 });
+ res.json(payload);
+}));
+
// GET /api/apps - List all apps. The route fetches the raw records; the
// appListEnrichment service owns the PM2 status/port/process enrichment.
router.get('/', asyncHandler(async (req, res) => {
diff --git a/server/routes/apps/crud.test.js b/server/routes/apps/crud.test.js
index 940b012ec7..bb314c4b8c 100644
--- a/server/routes/apps/crud.test.js
+++ b/server/routes/apps/crud.test.js
@@ -1,3 +1,5 @@
+vi.mock('../../services/appQualityFederation.js', () => ({ exportPortosQuality: vi.fn() }));
+import { exportPortosQuality } from '../../services/appQualityFederation.js';
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';
@@ -56,6 +58,17 @@ describe('Apps CRUD Routes', () => {
vi.clearAllMocks();
});
+ it('serves numeric federation before app lookup, validates days and refuses unapproved peers', async () => {
+ exportPortosQuality.mockResolvedValue({ schemaVersion: 1, measurements: [] });
+ const result = await request(app).get('/api/apps/quality-federation?days=30').set('X-PortOS-Instance-Id', 'peer');
+ expect(result.status).toBe(200);
+ expect(exportPortosQuality).toHaveBeenCalledWith('peer', 30);
+ expect(appsService.getAppById).not.toHaveBeenCalled();
+ expect((await request(app).get('/api/apps/quality-federation?days=999')).status).toBe(400);
+ exportPortosQuality.mockResolvedValue(null);
+ expect((await request(app).get('/api/apps/quality-federation')).status).toBe(403);
+ });
+
describe('GET /api/apps', () => {
it('should return list of apps with PM2 status', async () => {
const mockApps = [
diff --git a/server/services/appQuality.js b/server/services/appQuality.js
index a3c321f812..fc8d4c0efb 100644
--- a/server/services/appQuality.js
+++ b/server/services/appQuality.js
@@ -1,8 +1,10 @@
-/** Machine-local, DB-primary audit measurements. Reads never dispatch AI work. */
+/** DB-primary audit measurements with read-through PortOS federation. Reads never dispatch AI work. */
import { ensureSchema, query } from '../lib/db.js';
import { doneSentinelPath, parseSentinelPayload } from '../lib/agentSentinel.js';
import { tryReadFile } from '../lib/jsonIo.js';
-import { parseAuditQualityReport, summarizeAppQuality, buildAppQualityHistory, AUDIT_FRESHNESS_MS } from '../lib/auditQuality.js';
+import { parseAuditQualityReport, summarizeAppQuality, buildAppQualityHistory, latestQualityRecords } from '../lib/auditQuality.js';
+import { PORTOS_APP_ID } from '../lib/appIdentity.js';
+import { collectPortosQuality, qualityRecord, readQualityRecords } from './appQualityFederation.js';
export async function recordAuditQuality({ task, taskType, agentId, workspacePath, success, assessedAt }, deps = {}) {
if (!success || !workspacePath || !task?.metadata?.app || !agentId) return false;
@@ -38,29 +40,23 @@ export async function enrichAppsWithQuality(apps, deps = {}) {
console.error(`❌ App quality unavailable: ${err.message}`);
return null;
});
+ const shared = apps.some(app => app.id === PORTOS_APP_ID)
+ ? await collectPortosQuality(30, deps).catch(() => ({ records: [], federation: { failed: true } })) : null;
return apps.map(app => ({
...app,
- quality: result ? summarizeAppQuality(result.rows.filter(row => row.app_id === app.id).map(row => ({
- category: row.category, agentId: row.agent_id,
- assessedAt: new Date(row.assessed_at).toISOString(), report: row.report,
- }))) : { ...summarizeAppQuality(), unavailable: true },
+ quality: result ? { ...summarizeAppQuality(latestQualityRecords([
+ ...result.rows.filter(row => row.app_id === app.id).map(qualityRecord),
+ ...(app.id === PORTOS_APP_ID ? shared.records : []),
+ ]), deps.now ?? Date.now()), ...(app.id === PORTOS_APP_ID ? { federation: shared.federation } : {}) }
+ : { ...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);
+ const records = await readQualityRecords(appId, days, now, deps);
+ const shared = appId === PORTOS_APP_ID ? await collectPortosQuality(days, deps)
+ .catch(() => ({ records: [], federation: { failed: true } })) : null;
+ return { ...buildAppQualityHistory([...records, ...(shared?.records || [])], days, now),
+ ...(shared ? { federation: shared.federation } : {}) };
}
diff --git a/server/services/appQualityFederation.js b/server/services/appQualityFederation.js
new file mode 100644
index 0000000000..5d7330125c
--- /dev/null
+++ b/server/services/appQualityFederation.js
@@ -0,0 +1,108 @@
+/** Read-through federation of numeric PortOS audit evidence; never exports prose or relays peers. */
+import { createHash } from 'node:crypto';
+import { z } from 'zod';
+import { query } from '../lib/db.js';
+import { PORTOS_APP_ID } from '../lib/appIdentity.js';
+import { auditQualityReportSchema, AUDIT_FRESHNESS_MS } from '../lib/auditQuality.js';
+import { PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';
+import { getOriginInfo } from '../lib/gitRemote.js';
+import { peerBaseUrl } from '../lib/peerUrl.js';
+import { readBodyCapped } from '../lib/safeUrlFetch.js';
+import { peerFetch } from '../lib/peerHttpClient.js';
+
+const MAX_PAYLOAD_BYTES = 4 * 1024 * 1024;
+const sharedSummary = 'Numeric assessment shared by a federated instance; evidence remains on the source machine.';
+const hash = value => createHash('sha256').update(value).digest('hex');
+const numericReportSchema = z.preprocess(value => value && typeof value === 'object'
+ ? { ...value, summary: sharedSummary } : value, auditQualityReportSchema)
+ .transform(({ summary: _summary, ...report }) => report);
+const measurementSchema = z.object({
+ measurementId: z.string().regex(/^[a-f0-9]{64}$/),
+ assessedAt: z.string().datetime(),
+ report: numericReportSchema,
+}).strict();
+const payloadSchema = z.object({
+ schemaVersion: z.literal(PORTOS_SCHEMA_VERSIONS.appQuality),
+ repository: z.string().regex(/^[a-f0-9]{64}$/),
+ measurements: z.array(measurementSchema).max(10000),
+}).strict();
+
+// Match repositories without sharing remote URLs, names, credentials or local paths.
+// Independent versions of the same repository intentionally contribute to one score.
+async function repositoryKey(deps) {
+ const origin = await (deps.getOriginInfo || getOriginInfo)();
+ return origin.host && origin.fullName ? hash(`${origin.host}/${origin.fullName}`.toLowerCase()) : null;
+}
+
+async function eligiblePeers(deps) {
+ const { getPeers } = deps.getPeers ? deps : await import('./instances.js');
+ const { peerAllowsOutbound } = await import('./sharing/peerSyncShared.js');
+ return (await getPeers()).filter(peer => peer.fullSync === true && peerAllowsOutbound(peer));
+}
+
+export function qualityRecord(row) {
+ return { category: row.category, agentId: row.agent_id,
+ measurementId: hash(row.agent_id), assessedAt: new Date(row.assessed_at).toISOString(), report: row.report };
+}
+
+/** Daily category winners include the freshness lookback required for historical snapshots. */
+export async function readQualityRecords(appId, days, now, deps = {}) {
+ const start = new Date(now);
+ start.setUTCHours(0, 0, 0, 0);
+ start.setUTCDate(start.getUTCDate() - days + 1);
+ 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 result.rows.map(qualityRecord);
+}
+
+/** New endpoint always enforces peer sharing consent, even without instance-password auth. */
+export async function exportPortosQuality(callerId, days, deps = {}) {
+ const peers = await eligiblePeers(deps);
+ if (!callerId || !peers.some(peer => peer.instanceId === callerId)) return null;
+ const repository = await repositoryKey(deps);
+ if (!repository) return null;
+ const records = await readQualityRecords(PORTOS_APP_ID, days, deps.now ?? Date.now(), deps);
+ const measurements = records.flatMap(record => {
+ const parsed = measurementSchema.safeParse({ measurementId: record.measurementId,
+ assessedAt: record.assessedAt, report: record.report });
+ return parsed.success && parsed.data.report.category === record.category ? [parsed.data] : [];
+ });
+ return { schemaVersion: PORTOS_SCHEMA_VERSIONS.appQuality, repository, measurements };
+}
+
+/** No persistence or forwarding: disabled/offline peers cannot leave a hidden stale contribution. */
+export async function collectPortosQuality(days, deps = {}) {
+ const peers = await eligiblePeers(deps);
+ if (!peers.length) return { records: [], federation: { peers: 0, available: 0, unavailable: 0 } };
+ const repository = await repositoryKey(deps);
+ const now = deps.now ?? Date.now();
+ const results = await Promise.allSettled(peers.map(async peer => {
+ if (!repository) throw new Error('Repository identity unavailable');
+ const response = await (deps.peerFetch || peerFetch)(
+ `${peerBaseUrl(peer)}/api/apps/quality-federation?days=${days}`,
+ { signal: AbortSignal.timeout(3000), redirect: 'error', maxBytes: MAX_PAYLOAD_BYTES }, peer);
+ if (!response.ok) {
+ await response.body?.cancel?.();
+ throw new Error('Peer quality unavailable');
+ }
+ const body = await readBodyCapped(response, MAX_PAYLOAD_BYTES);
+ if (!body) {
+ await response.body?.cancel?.();
+ throw new Error('Peer quality payload too large');
+ }
+ const payload = payloadSchema.parse(JSON.parse(body.toString('utf8')));
+ if (payload.repository !== repository) throw new Error('Different repository');
+ return payload.measurements.filter(row => Date.parse(row.assessedAt) <= now).map(row => ({
+ ...row, category: row.report.category, sourcePeerId: peer.id, sourcePeerName: peer.name || peer.id,
+ report: { ...row.report, summary: sharedSummary },
+ }));
+ }));
+ return { records: results.flatMap(result => result.status === 'fulfilled' ? result.value : []),
+ federation: { peers: peers.length, available: results.filter(r => r.status === 'fulfilled').length,
+ unavailable: results.filter(r => r.status === 'rejected').length } };
+}
diff --git a/server/services/appQualityFederation.test.js b/server/services/appQualityFederation.test.js
new file mode 100644
index 0000000000..146783eac4
--- /dev/null
+++ b/server/services/appQualityFederation.test.js
@@ -0,0 +1,86 @@
+import { it, expect, vi } from 'vitest';
+import { mockNoPeers } from '../lib/mockPathsDataRoot.js';
+import { exportPortosQuality, collectPortosQuality } from './appQualityFederation.js';
+import { enrichAppsWithQuality, getAppQualityHistory } from './appQuality.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, fullSync: true, address: '192.0.2.1', port: 5555 };
+const getOriginInfo = async () => ({ host: 'github.com', fullName: 'atomantic/PortOS' });
+const row = (category, score, assessed_at = '2026-09-10T10:00:00Z', extra = {}) => ({
+ app_id: 'portos-default', category, agent_id: `agent-${category}`, assessed_at,
+ report: { version: 1, category, score, worstSeverity: 5, coverage: 'broad', confidence: 'high',
+ summary: 'Private paths /Users/person/project and audit narrative', scannedFiles: 12, totalFiles: 12 }, ...extra,
+});
+const deps = rows => ({ now, getOriginInfo, getPeers: async () => [peer], query: vi.fn(async () => ({ rows })) });
+const response = payload => new Response(JSON.stringify(payload), { status: 200 });
+
+// Uniquely pins numeric-only privacy, peer consent and cross-install score convergence.
+it('exports only validated local numeric evidence to approved full-sync peers', async () => {
+ const local = deps([row('security', 40)]);
+ const payload = await exportPortosQuality(peer.instanceId, 30, local);
+ 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');
+ expect(local.query.mock.calls[0][1][1].toISOString()).toBe('2026-07-13T00:00:00.000Z');
+ for (const caller of [undefined, 'unknown']) expect(await exportPortosQuality(caller, 30, local)).toBeNull();
+ for (const disabled of [{ enabled: false }, { fullSync: false }, { syncEnabled: false }, { directions: ['inbound'] }]) {
+ const blocked = { ...local, getPeers: async () => [{ ...peer, ...disabled }] };
+ expect(await exportPortosQuality(peer.instanceId, 30, blocked)).toBeNull();
+ expect(await collectPortosQuality(30, blocked)).toMatchObject({ records: [], federation: { peers: 0 } });
+ }
+ expect(await exportPortosQuality(peer.instanceId, 30, { ...local, getOriginInfo: async () => ({}) })).toBeNull();
+});
+
+it('combines newest categories in app view and UTC history without changing other apps or forwarding evidence', async () => {
+ const remote = await exportPortosQuality(peer.instanceId, 30, deps([row('security', 80), row('performance', 60)]));
+ const local = { ...deps([row('security', 20, '2026-09-09T10:00:00Z')]), peerFetch: vi.fn(async () => response(remote)) };
+ const apps = await enrichAppsWithQuality([{ id: 'portos-default' }, { id: 'other' }], local);
+ expect(apps[0].quality).toMatchObject({ score: 70, ratedCategories: 2, federation: { peers: 1, available: 1, unavailable: 0 } });
+ expect(apps[0].quality.categories.find(c => c.id === 'security')).toMatchObject({ sourcePeerId: 'peer-a', agentId: null });
+ expect(apps[1].quality.score).toBeNull();
+ expect(local.peerFetch.mock.calls[0]).toEqual(['http://192.0.2.1:5555/api/apps/quality-federation?days=30',
+ expect.objectContaining({ signal: expect.any(AbortSignal), redirect: 'error', maxBytes: 4194304 }), peer]);
+ const history = await getAppQualityHistory('portos-default', 30, local);
+ expect(history.points.find(p => p.date === '2026-09-09').score).toBe(20);
+ expect(history.points.at(-1)).toMatchObject({ score: 70, ratedCategories: 2 });
+ expect((await enrichAppsWithQuality([{ id: 'portos-default' }], local))[0].quality.score).toBe(70);
+ expect((await exportPortosQuality(peer.instanceId, 30, local)).measurements.map(m => m.report.score)).toEqual([20]);
+});
+
+it('keeps local scores on old, offline, malformed, oversize or mismatched peers and rejects future evidence', async () => {
+ const payload = await exportPortosQuality(peer.instanceId, 30, deps([row('security', 90)]));
+ const local = deps([row('security', 20)]);
+ for (const fetch of [
+ async () => new Response('', { status: 404 }),
+ async () => { throw new Error('offline'); },
+ async () => response({ ...payload, schemaVersion: 2 }),
+ async () => response({ ...payload, repository: '0'.repeat(64) }),
+ async () => response({ ...payload, measurements: [{ ...payload.measurements[0], report: { ...payload.measurements[0].report, score: 101 } }] }),
+ async () => new Response('too large', { headers: { 'content-length': '4194305' } }),
+ ]) {
+ const [app] = await enrichAppsWithQuality([{ id: 'portos-default' }], { ...local, peerFetch: fetch });
+ expect(app.quality).toMatchObject({ score: 20, federation: { available: 0, unavailable: 1 } });
+ }
+ const future = { ...payload, measurements: [{ ...payload.measurements[0], assessedAt: '2026-09-11T00:00:00Z' }] };
+ expect((await collectPortosQuality(30, { ...local, peerFetch: async () => response(future) })).records).toEqual([]);
+});
+
+it('lets newer partial evidence supersede older broad scores and breaks ties consistently', async () => {
+ const partial = row('security', 80);
+ partial.report.coverage = 'partial';
+ partial.report.scannedFiles = 1;
+ const payload = await exportPortosQuality(peer.instanceId, 30, deps([partial]));
+ const partialDeps = { ...deps([row('security', 20, '2026-09-09T10:00:00Z')]), peerFetch: async () => response(payload) };
+ expect((await enrichAppsWithQuality([{ id: 'portos-default' }], partialDeps))[0].quality.score).toBeNull();
+ expect((await getAppQualityHistory('portos-default', 30, partialDeps)).points.at(-1).score).toBeNull();
+ const a = row('security', 25, undefined, { agent_id: 'run-a' });
+ const b = row('security', 75, undefined, { agent_id: 'run-b' });
+ const scores = [];
+ for (const [here, there] of [[a, b], [b, a]]) {
+ const shared = await exportPortosQuality(peer.instanceId, 30, deps([there]));
+ const combined = { ...deps([here]), peerFetch: async () => response(shared) };
+ scores.push((await enrichAppsWithQuality([{ id: 'portos-default' }], combined))[0].quality.score);
+ scores.push((await getAppQualityHistory('portos-default', 30, combined)).points.at(-1).score);
+ }
+ expect(new Set(scores).size).toBe(1);
+});