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

fix: share quality across matching managed apps and publish release scores

[._.]/ Adam Eivyf2dea518f7cb
diff --git a/AGENTS.md b/AGENTS.md
index ab0923c348..91bf318b5a 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -248,6 +248,7 @@ This complements the Security Model (which governs the deployed product) — thi
- **main**: active development. **release**: push `main` to `release` to trigger the GitHub Release workflow.
- **Push pattern**: `git pull --rebase --autostash && git push`
- **No per-branch changelog entries.** Individual PRs do not write a changelog file or fragment — commit messages are the record. `/do:release` synthesizes the release notes from the commit log since the last tag (grouped by feature/theme) when it runs, and writes the result to `.changelog/v{version}.md`. This replaced an earlier per-branch fragment workflow (`.changelog/next/*.md` + `npm run changelog:add`), which existed to avoid parallel branches conflicting on a shared `NEXT.md` — deriving notes from commits at release time sidesteps that problem entirely, since no branch writes to `.changelog/` anymore. Consequence: **write commit subjects/bodies for a human release-note reader**, not just for `git log` — see "Git commits and PRs" in the global instructions. Full rationale: `.changelog/README.md`.
+- **Release quality snapshot**: Before a release, run `npm run quality:snapshot` on the install holding PortOS audit evidence and include `quality-snapshot.json` in the release commit. This publishes numeric local assessments only; no provider calls or private run prose. If no local evidence exists, retain the existing snapshot and report that it was not refreshed.
- **Versioning**: the version in `package.json` reflects the last release. Do not bump during development — `/do:release` handles it.
- After each feature or bug fix, run `/simplify`, then commit and push.
- **Capture deferred work, and decide rather than park it.** Deferred refactors/cleanups go into a filed GitHub issue labeled `plan`, specific enough to pick up cold — never left only in chat. When the sole obstacle is an undecided design choice, **make the call yourself** and file it ready-to-work; `future` / `needs-input` are last resorts. Invoke the `portos-file-issue` skill for the full labeling contract. Add independent slashdo dispatch hints (`model:light|medium|heavy`, `effort:low|medium|high|xhigh|max`) and contributor labels (`good first issue`, `help wanted`) only when the work you just inspected justifies them — omit an axis rather than guessing, never stamp `medium` on both, and never mark a wide mechanical sweep as a good first issue. Also stamp `planner:<model>` — a third, independent axis naming the model that WROTE the plan — taking the value verbatim from the "Planner Attribution" section of your own prompt (PortOS resolves it from the provider/model it dispatched you with); never guess it from what you believe you are, and omit it when your run was given none. Create missing labels lazily with slashdo/GitHub colors before `gh issue create`, use repeated `--label` flags, and keep category labels (`plan`, `ux`, `bug`, `tests`) intact.
diff --git a/client/src/components/apps/AppQuality.jsx b/client/src/components/apps/AppQuality.jsx
index 1ed747fc77..5d0e04db48 100644
--- a/client/src/components/apps/AppQuality.jsx
+++ b/client/src/components/apps/AppQuality.jsx
@@ -32,7 +32,7 @@ export default function AppQuality({ app, detail = false }) {
</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.
+ Unified app score: newest assessment per category across this install and {quality.federation.available ?? 0} available 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.`}
@@ -66,6 +66,7 @@ export default function AppQuality({ app, detail = false }) {
<Link to={runnerLink(category.id)} aria-label={`Configure and run ${category.label}`} className="block mt-1 text-port-accent hover:underline">Configure and run</Link>
{category.summary && <details className="mt-1"><summary className="cursor-pointer text-port-accent">Assessment details</summary><p className="break-words">{category.summary}</p></details>}
{category.totalFiles > 0 && <div>{category.scannedFiles}/{category.totalFiles} files scanned · Worst severity: {category.worstSeverity}/10</div>}
+ {category.sourcePeerName && !category.sourcePeerId && <div>Source: {category.sourcePeerName}</div>}
{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>
diff --git a/docs/decisions/2026-09-10-portos-quality-federation.md b/docs/decisions/2026-09-10-portos-quality-federation.md
index f74098e165..4ae3c5185d 100644
--- a/docs/decisions/2026-09-10-portos-quality-federation.md
+++ b/docs/decisions/2026-09-10-portos-quality-federation.md
@@ -1,8 +1,8 @@
-# Numeric PortOS quality federation
+# Numeric app 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.
+history combine measurements for matching managed repositories across this install
+and directly registered sync peers. Local app IDs, names and paths need not match.
The newest assessment per category wins (run hash breaks timestamp ties), then
the existing equal-weight category mean applies: broad coverage, medium/high
@@ -11,7 +11,7 @@ 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
+Only peers with 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
@@ -35,9 +35,35 @@ 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.
+each analysis install as an enabled 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.
+
+## September 11: matching apps and release snapshots
+
+Full-sync was an unintended additional gate: configured selective-sync peers
+(including Void) could exchange their selected records but received 403 for
+quality. Numeric assessments now follow the enabled outbound relationship and
+master sync switch, independently of private record categories. Turning off sync
+or disabling/removing the peer stops sharing. The local app must have the same
+normalized Git origin; matching a display name alone never exports evidence.
+The optional `repository` query is a hash, retaining the v1 response shape and
+PortOS default for older clients. Older servers may reject selective peers or
+return PortOS for that query; repository validation excludes mismatches.
+
+Before each release, run `npm run quality:snapshot` on the install holding local
+PortOS assessments, then include `quality-snapshot.json` in the release commit.
+The command reads the existing DB, sanitizes the same numeric projection, and
+refuses to replace a snapshot when no evidence is available. It invokes no AI
+and includes neither peer contributions nor source narratives. CI publishes the
+committed file with the source release; it does not need the private database.
+
+Every matching PortOS checkout reads that file alongside local and peer evidence.
+Original assessment dates and the 30-day freshness rule remain intact, so an old
+release cannot masquerade as a fresh assessment. Forks with a different origin
+ignore the upstream snapshot. Shipped evidence is labeled "Release snapshot"
+and is never re-exported as a local run. Full run logs and transcripts remain
+machine-local; only numeric run assessments cross instances.
diff --git a/package.json b/package.json
index 208b243703..96e1167b83 100644
--- a/package.json
+++ b/package.json
@@ -43,6 +43,7 @@
"setup:hooks": "bash scripts/setup-git-hooks.sh",
"update": "node -e \"const{spawnSync:s}=require('child_process');const w=process.platform==='win32';const r=s(w?'powershell':'bash',w?['-NoProfile','-ExecutionPolicy','Bypass','-File','update.ps1']:['update.sh'],{stdio:'inherit'});process.exit(r.status??1)\"",
"test": "npm test --prefix server && npm test --prefix client",
+ "quality:snapshot": "node scripts/publish-quality-snapshot.js",
"theme:check": "node scripts/check-themes.js",
"smoke": "node scripts/smoke-boot.js"
},
diff --git a/quality-snapshot.json b/quality-snapshot.json
new file mode 100644
index 0000000000..a6f84fa7b3
--- /dev/null
+++ b/quality-snapshot.json
@@ -0,0 +1,272 @@
+{
+ "schemaVersion": 1,
+ "repository": "2d5f6a24e05573259a136bc8e83f04c18bb1438c4f1d96cbe0ac73f6ffc4e0a0",
+ "measurements": [
+ {
+ "measurementId": "25118a56c4a70f291ee6874211cf97dda1284c57643d6702daae80bbface0013",
+ "assessedAt": "2026-09-11T02:09:13.557Z",
+ "report": {
+ "version": 1,
+ "category": "accessibility",
+ "score": 68,
+ "worstSeverity": 8,
+ "coverage": "broad",
+ "confidence": "high",
+ "scannedFiles": 1713,
+ "totalFiles": 1713
+ }
+ },
+ {
+ "measurementId": "d980eee1b0165473e654a6ebe0b21bd03d11ba3315c93ae187a6af0271732982",
+ "assessedAt": "2026-09-11T05:26:14.358Z",
+ "report": {
+ "version": 1,
+ "category": "api-contract",
+ "score": 72,
+ "worstSeverity": 7,
+ "coverage": "broad",
+ "confidence": "medium",
+ "scannedFiles": 371,
+ "totalFiles": 371
+ }
+ },
+ {
+ "measurementId": "b36acd4091a03da1b874f2be54fc585b79a5dc66ee7d797c4de5db592ce3e7f5",
+ "assessedAt": "2026-09-10T17:06:43.676Z",
+ "report": {
+ "version": 1,
+ "category": "better-cognitive-load",
+ "score": 64,
+ "worstSeverity": 7,
+ "coverage": "broad",
+ "confidence": "medium",
+ "scannedFiles": 4185,
+ "totalFiles": 4185
+ }
+ },
+ {
+ "measurementId": "1eebdf14e81a8c4f46f3804d9711e68676a0f0cec96c2e87a1fa399c57ba4372",
+ "assessedAt": "2026-09-10T12:38:20.981Z",
+ "report": {
+ "version": 1,
+ "category": "better-complexity",
+ "score": 58,
+ "worstSeverity": 6,
+ "coverage": "broad",
+ "confidence": "medium",
+ "scannedFiles": 4185,
+ "totalFiles": 4185
+ }
+ },
+ {
+ "measurementId": "d36486ed4648dea977bd49f02948b071bd36c28e9c14a37f8072c2a634a35cd2",
+ "assessedAt": "2026-09-10T06:14:17.032Z",
+ "report": {
+ "version": 1,
+ "category": "better-structural-drift",
+ "score": 68,
+ "worstSeverity": 5,
+ "coverage": "broad",
+ "confidence": "medium",
+ "scannedFiles": 4175,
+ "totalFiles": 4175
+ }
+ },
+ {
+ "measurementId": "6298c049fb4772b9ff13c3a5a13905015dfe15b99c51609db929c13bc7bea959",
+ "assessedAt": "2026-09-11T00:11:45.376Z",
+ "report": {
+ "version": 1,
+ "category": "code-quality",
+ "score": 82,
+ "worstSeverity": 6,
+ "coverage": "broad",
+ "confidence": "high",
+ "scannedFiles": 7367,
+ "totalFiles": 7367
+ }
+ },
+ {
+ "measurementId": "2ce67bce3c70db90fa8379b41b9314c05e9f5916323ca7f93d01c1d628adfad4",
+ "assessedAt": "2026-09-11T06:13:55.436Z",
+ "report": {
+ "version": 1,
+ "category": "data-safety",
+ "score": 68,
+ "worstSeverity": 8,
+ "coverage": "broad",
+ "confidence": "medium",
+ "scannedFiles": 7364,
+ "totalFiles": 7364
+ }
+ },
+ {
+ "measurementId": "0102e6409ec8d5ad1b2fde2c78e6f945f2dc5455036f406c1ee86ae26445488b",
+ "assessedAt": "2026-09-10T19:06:38.953Z",
+ "report": {
+ "version": 1,
+ "category": "documentation",
+ "score": 76,
+ "worstSeverity": 5,
+ "coverage": "broad",
+ "confidence": "medium",
+ "scannedFiles": 239,
+ "totalFiles": 239
+ }
+ },
+ {
+ "measurementId": "107b9748fdbfac4d640ab9627ab16e0a4b84965dbc81d77ce41448452d417efd",
+ "assessedAt": "2026-09-11T05:25:58.268Z",
+ "report": {
+ "version": 1,
+ "category": "error-handling",
+ "score": 71,
+ "worstSeverity": 8,
+ "coverage": "broad",
+ "confidence": "high",
+ "scannedFiles": 4188,
+ "totalFiles": 4188
+ }
+ },
+ {
+ "measurementId": "64fce5882bb11a4f2671b66dd08046de1bd908788f9c88850355ada9cd20795e",
+ "assessedAt": "2026-09-11T04:48:25.502Z",
+ "report": {
+ "version": 1,
+ "category": "mobile-responsive",
+ "score": 86,
+ "worstSeverity": 4,
+ "coverage": "broad",
+ "confidence": "medium",
+ "scannedFiles": 7334,
+ "totalFiles": 7334
+ }
+ },
+ {
+ "measurementId": "7a6e4d04609546cea27e075014bdb4cf5d8b027586e194526539b55cb663bf93",
+ "assessedAt": "2026-09-10T10:25:44.286Z",
+ "report": {
+ "version": 1,
+ "category": "module-hygiene",
+ "score": 72,
+ "worstSeverity": 5,
+ "coverage": "broad",
+ "confidence": "high",
+ "scannedFiles": 3763,
+ "totalFiles": 3763
+ }
+ },
+ {
+ "measurementId": "79e6da253105d7801fe4848611a988089553c2c0ffc9dbef51163d09f896cd42",
+ "assessedAt": "2026-09-11T05:26:52.844Z",
+ "report": {
+ "version": 1,
+ "category": "observability",
+ "score": 62,
+ "worstSeverity": 6,
+ "coverage": "broad",
+ "confidence": "high",
+ "scannedFiles": 4191,
+ "totalFiles": 4191
+ }
+ },
+ {
+ "measurementId": "602a4a5ff34bc32378a90e9a236befa87b739e6601ce623820a2b59bb77f77a8",
+ "assessedAt": "2026-09-10T14:41:26.439Z",
+ "report": {
+ "version": 1,
+ "category": "performance",
+ "score": 68,
+ "worstSeverity": 5,
+ "coverage": "broad",
+ "confidence": "medium",
+ "scannedFiles": 4186,
+ "totalFiles": 4186
+ }
+ },
+ {
+ "measurementId": "6f77d6fc832e35e026784e818f6d2f0c964f531e01fb9a167e2a7cb2d97b266d",
+ "assessedAt": "2026-09-10T23:59:42.485Z",
+ "report": {
+ "version": 1,
+ "category": "security",
+ "score": 94,
+ "worstSeverity": 0,
+ "coverage": "broad",
+ "confidence": "high",
+ "scannedFiles": 7462,
+ "totalFiles": 7462
+ }
+ },
+ {
+ "measurementId": "bc16212799340eb771074e1a0132ce007f1716ed816b8e9cbf926dbcb85b89dc",
+ "assessedAt": "2026-09-10T08:32:49.922Z",
+ "report": {
+ "version": 1,
+ "category": "simplify",
+ "score": 70,
+ "worstSeverity": 5,
+ "coverage": "broad",
+ "confidence": "medium",
+ "scannedFiles": 7278,
+ "totalFiles": 7278
+ }
+ },
+ {
+ "measurementId": "8c4861377fe30e010fbc9c5e6bd14c48b85208536631420e0a6d79f7603e722e",
+ "assessedAt": "2026-09-11T00:19:27.463Z",
+ "report": {
+ "version": 1,
+ "category": "test-coverage",
+ "score": 82,
+ "worstSeverity": 8,
+ "coverage": "broad",
+ "confidence": "high",
+ "scannedFiles": 7291,
+ "totalFiles": 7291
+ }
+ },
+ {
+ "measurementId": "4196f433e31368a49b853d97c0c599425ee139438697c99b432873a0ca0ddbde",
+ "assessedAt": "2026-09-11T19:44:53.227Z",
+ "report": {
+ "version": 1,
+ "category": "typing",
+ "score": null,
+ "worstSeverity": 0,
+ "coverage": "not-applicable",
+ "confidence": "high",
+ "scannedFiles": 8140,
+ "totalFiles": 8140
+ }
+ },
+ {
+ "measurementId": "b158c04331799a56444f7b9ffb47caa2886c8edd19fb9ff10572461661c26564",
+ "assessedAt": "2026-09-11T02:45:28.794Z",
+ "report": {
+ "version": 1,
+ "category": "ui-bugs",
+ "score": 82,
+ "worstSeverity": 6,
+ "coverage": "broad",
+ "confidence": "high",
+ "scannedFiles": 2541,
+ "totalFiles": 2541
+ }
+ },
+ {
+ "measurementId": "2ad2c4ced2c2584972be16efd674a6b60ab5b8576eb645b5cb39d39528461c81",
+ "assessedAt": "2026-09-11T05:26:04.263Z",
+ "report": {
+ "version": 1,
+ "category": "ux",
+ "score": 58,
+ "worstSeverity": 8,
+ "coverage": "broad",
+ "confidence": "high",
+ "scannedFiles": 1598,
+ "totalFiles": 1598
+ }
+ }
+ ]
+}
diff --git a/scripts/publish-quality-snapshot.js b/scripts/publish-quality-snapshot.js
new file mode 100644
index 0000000000..964d5c7a08
--- /dev/null
+++ b/scripts/publish-quality-snapshot.js
@@ -0,0 +1,13 @@
+/** Explicit, local-only release step: no provider calls and no peer evidence. */
+import { writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { PATHS } from '../server/lib/paths.js';
+import { buildQualitySnapshot } from '../server/services/appQualityFederation.js';
+
+const { close } = await import('../server/lib/db.js');
+await (async () => {
+ const snapshot = await buildQualitySnapshot();
+ if (!snapshot?.measurements.length) throw new Error('No local quality evidence to publish; existing snapshot preserved');
+ await writeFile(join(PATHS.root, 'quality-snapshot.json'), `${JSON.stringify(snapshot, null, 2)}\n`);
+ console.log(`Published ${snapshot.measurements.length} numeric assessments to quality-snapshot.json`);
+})().finally(close);
diff --git a/server/lib/auditQuality.js b/server/lib/auditQuality.js
index c9e5db31ec..c796578f58 100644
--- a/server/lib/auditQuality.js
+++ b/server/lib/auditQuality.js
@@ -132,3 +132,7 @@ export function compareQualityRecords(a, b) {
return Date.parse(a.assessedAt) - Date.parse(b.assessedAt)
|| (a.measurementId || a.agentId || '').localeCompare(b.measurementId || b.agentId || '');
}
+
+export const appQualityFederationQuerySchema = appQualityHistoryQuerySchema.extend({
+ repository: z.string().regex(/^[a-f0-9]{64}$/).optional(),
+});
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 1667b84ad7..dbd76634a9 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -748,7 +748,7 @@ export const RECORD_KIND_SCHEMA_CATEGORIES = Object.freeze({
* no RECORD_KIND_SCHEMA_CATEGORIES entry.
*
* `appQuality`: numeric-only local evidence at GET /api/apps/quality-federation,
- * validated against its exact wire version by collectPortosQuality; never written or pushed.
+ * validated against its exact wire version by collectAppQuality; never written or pushed.
*
* 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/routes/apps/crud.js b/server/routes/apps/crud.js
index bc3d234321..aad03ed216 100644
--- a/server/routes/apps/crud.js
+++ b/server/routes/apps/crud.js
@@ -1,4 +1,4 @@
-import { appQualityQuerySchema, appQualityHistoryQuerySchema } from '../../lib/auditQuality.js';
+import { appQualityQuerySchema, appQualityHistoryQuerySchema, appQualityFederationQuerySchema } from '../../lib/auditQuality.js';
import { exportPortosQuality } from '../../services/appQualityFederation.js';
import { enrichAppsWithQuality, getAppQualityHistory } from '../../services/appQuality.js';
/**
@@ -33,9 +33,9 @@ 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 });
+ const { days, repository } = validateRequest(appQualityFederationQuerySchema, req.query);
+ const payload = await exportPortosQuality(req.get('X-PortOS-Instance-Id'), days, {}, repository);
+ if (!payload) throw new ServerError('Quality sharing requires a registered enabled sync peer and a known repository', { status: 403 });
res.json(payload);
}));
diff --git a/server/routes/apps/crud.test.js b/server/routes/apps/crud.test.js
index bb314c4b8c..3bbb1b1a41 100644
--- a/server/routes/apps/crud.test.js
+++ b/server/routes/apps/crud.test.js
@@ -62,8 +62,12 @@ describe('Apps CRUD Routes', () => {
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(exportPortosQuality).toHaveBeenCalledWith('peer', 30, {}, undefined);
expect(appsService.getAppById).not.toHaveBeenCalled();
+ const repository = 'a'.repeat(64);
+ expect((await request(app).get(`/api/apps/quality-federation?repository=${repository}`).set('X-PortOS-Instance-Id', 'peer')).status).toBe(200);
+ expect(exportPortosQuality).toHaveBeenLastCalledWith('peer', 90, {}, repository);
+ expect((await request(app).get('/api/apps/quality-federation?repository=invalid')).status).toBe(400);
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);
diff --git a/server/services/appQuality.js b/server/services/appQuality.js
index fc8d4c0efb..bfea7913bd 100644
--- a/server/services/appQuality.js
+++ b/server/services/appQuality.js
@@ -1,10 +1,10 @@
-/** DB-primary audit measurements with read-through PortOS federation. Reads never dispatch AI work. */
+/** DB-primary audit measurements with read-through app 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, latestQualityRecords } from '../lib/auditQuality.js';
import { PORTOS_APP_ID } from '../lib/appIdentity.js';
-import { collectPortosQuality, qualityRecord, readQualityRecords } from './appQualityFederation.js';
+import { collectAppQuality, qualityRecord, readQualityRecords, readReleaseQuality } from './appQualityFederation.js';
export async function recordAuditQuality({ task, taskType, agentId, workspacePath, success, assessedAt }, deps = {}) {
if (!success || !workspacePath || !task?.metadata?.app || !agentId) return false;
@@ -40,23 +40,28 @@ 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(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 },
+ const release = apps.some(app => app.id === PORTOS_APP_ID) ? await readReleaseQuality(deps) : [];
+ return Promise.all(apps.map(async app => {
+ const shared = await collectAppQuality(app, 30, deps)
+ .catch(() => ({ records: [], federation: { failed: true } }));
+ return { ...app,
+ quality: result ? { ...summarizeAppQuality(latestQualityRecords([
+ ...result.rows.filter(row => row.app_id === app.id).map(qualityRecord),
+ ...shared.records, ...(app.id === PORTOS_APP_ID ? release : []),
+ ]), deps.now ?? Date.now()), federation: shared.federation }
+ : { ...summarizeAppQuality(), unavailable: true },
+ };
}));
}
export async function getAppQualityHistory(appId, days, deps = {}) {
const now = deps.now ?? Date.now();
const records = await readQualityRecords(appId, days, now, deps);
- const shared = appId === PORTOS_APP_ID ? await collectPortosQuality(days, deps)
+ const app = appId === PORTOS_APP_ID ? { id: appId }
+ : await (deps.getAppById || (await import('./apps.js')).getAppById)(appId);
+ const shared = app ? await collectAppQuality(app, days, deps)
.catch(() => ({ records: [], federation: { failed: true } })) : null;
- return { ...buildAppQualityHistory([...records, ...(shared?.records || [])], days, now),
+ const release = appId === PORTOS_APP_ID ? await readReleaseQuality(deps) : [];
+ return { ...buildAppQualityHistory([...records, ...(shared?.records || []), ...release], days, now),
...(shared ? { federation: shared.federation } : {}) };
}
diff --git a/server/services/appQualityFederation.js b/server/services/appQualityFederation.js
index 5d7330125c..888ad5c91d 100644
--- a/server/services/appQualityFederation.js
+++ b/server/services/appQualityFederation.js
@@ -1,4 +1,7 @@
-/** Read-through federation of numeric PortOS audit evidence; never exports prose or relays peers. */
+/** Read-through federation of numeric app audit evidence; never exports prose or relays peers. */
+import { readFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { PATHS } from '../lib/paths.js';
import { createHash } from 'node:crypto';
import { z } from 'zod';
import { query } from '../lib/db.js';
@@ -29,15 +32,16 @@ const payloadSchema = z.object({
// 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)();
+async function repositoryKey(deps, app = { id: PORTOS_APP_ID }) {
+ if (app.id !== PORTOS_APP_ID && !app.repoPath) return null;
+ const origin = await (deps.getOriginInfo || getOriginInfo)(app.repoPath);
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));
+ return (await getPeers()).filter(peer => peerAllowsOutbound(peer));
}
export function qualityRecord(row) {
@@ -61,12 +65,26 @@ export async function readQualityRecords(appId, days, now, deps = {}) {
}
/** New endpoint always enforces peer sharing consent, even without instance-password auth. */
-export async function exportPortosQuality(callerId, days, deps = {}) {
+export async function exportPortosQuality(callerId, days, deps = {}, requestedRepository) {
const peers = await eligiblePeers(deps);
if (!callerId || !peers.some(peer => peer.instanceId === callerId)) return null;
- const repository = await repositoryKey(deps);
+ let app = { id: PORTOS_APP_ID };
+ if (requestedRepository) {
+ const { getAllApps } = deps.getAllApps ? deps : await import('./apps.js');
+ const candidates = await Promise.all((await getAllApps()).map(async candidate => ({
+ app: candidate, repository: await repositoryKey(deps, candidate),
+ })));
+ app = candidates.find(candidate => candidate.repository === requestedRepository)?.app;
+ if (!app) return null;
+ }
+ return buildQualitySnapshot(app, days, deps);
+}
+
+/** Sanitized local evidence, also used by the explicit release snapshot command. */
+export async function buildQualitySnapshot(app = { id: PORTOS_APP_ID }, days = 30, deps = {}) {
+ const repository = await repositoryKey(deps, app);
if (!repository) return null;
- const records = await readQualityRecords(PORTOS_APP_ID, days, deps.now ?? Date.now(), deps);
+ const records = await readQualityRecords(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 });
@@ -77,14 +95,18 @@ export async function exportPortosQuality(callerId, days, deps = {}) {
/** No persistence or forwarding: disabled/offline peers cannot leave a hidden stale contribution. */
export async function collectPortosQuality(days, deps = {}) {
+ return collectAppQuality({ id: PORTOS_APP_ID }, days, deps);
+}
+
+export async function collectAppQuality(app, 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 repository = await repositoryKey(deps, app);
+ if (!repository) return { records: [], federation: { peers: 0, available: 0, unavailable: 0 } };
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}`,
+ `${peerBaseUrl(peer)}/api/apps/quality-federation?days=${days}${app.id === PORTOS_APP_ID ? '' : `&repository=${repository}`}`,
{ signal: AbortSignal.timeout(3000), redirect: 'error', maxBytes: MAX_PAYLOAD_BYTES }, peer);
if (!response.ok) {
await response.body?.cancel?.();
@@ -106,3 +128,15 @@ export async function collectPortosQuality(days, deps = {}) {
federation: { peers: peers.length, available: results.filter(r => r.status === 'fulfilled').length,
unavailable: results.filter(r => r.status === 'rejected').length } };
}
+
+/** Shipped evidence is read-only and never re-exported as a local audit. */
+export async function readReleaseQuality(deps = {}) {
+ const body = await (deps.readSnapshot || (() => readFile(join(PATHS.root, 'quality-snapshot.json'), 'utf8')))().catch(() => null);
+ if (!body || Buffer.byteLength(body) > MAX_PAYLOAD_BYTES) return [];
+ const payload = await Promise.resolve().then(() => payloadSchema.parse(JSON.parse(body))).catch(() => null);
+ if (!payload || payload.repository !== await repositoryKey(deps)) 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.' },
+ }));
+}
diff --git a/server/services/appQualityFederation.test.js b/server/services/appQualityFederation.test.js
index 146783eac4..8a81f6c0b4 100644
--- a/server/services/appQualityFederation.test.js
+++ b/server/services/appQualityFederation.test.js
@@ -1,21 +1,21 @@
import { it, expect, vi } from 'vitest';
import { mockNoPeers } from '../lib/mockPathsDataRoot.js';
-import { exportPortosQuality, collectPortosQuality } from './appQualityFederation.js';
+import { exportPortosQuality, collectPortosQuality, collectAppQuality, buildQualitySnapshot, readReleaseQuality } 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 peer = { id: 'peer-a', instanceId: 'instance-a', enabled: 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 deps = rows => ({ now, getOriginInfo, readSnapshot: async () => null, 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 () => {
+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(payload).toMatchObject({ schemaVersion: 1, measurements: [{ report: { category: 'security', score: 40 } }] });
@@ -23,7 +23,7 @@ it('exports only validated local numeric evidence to approved full-sync peers',
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'] }]) {
+ for (const disabled of [{ enabled: 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 } });
@@ -84,3 +84,30 @@ it('lets newer partial evidence supersede older broad scores and breaks ties con
}
expect(new Set(scores).size).toBe(1);
});
+
+it('matches managed repositories with different local ids and excludes other origins', async () => {
+ const getOriginInfo = async path => ({ host: 'github.com', fullName: path === '/unrelated' ? 'owner/other' : 'owner/app' });
+ const source = { ...deps([row('security', 88)]), getOriginInfo };
+ const payload = await buildQualitySnapshot({ id: 'remote-id', repoPath: '/remote/app' }, 30, source);
+ const local = { ...deps([]), getOriginInfo, peerFetch: vi.fn(async () => response(payload)),
+ getAppById: async id => ({ id, repoPath: '/local/app' }) };
+ const [app] = await enrichAppsWithQuality([{ id: 'local-id', repoPath: '/local/app' }], local);
+ expect(app.quality).toMatchObject({ score: 88, federation: { available: 1 } });
+ expect(local.peerFetch.mock.calls[0][0]).toContain(`&repository=${payload.repository}`);
+ expect((await getAppQualityHistory('local-id', 30, local)).points.at(-1).score).toBe(88);
+ expect((await collectAppQuality({ id: 'other', repoPath: '/unrelated' }, 30, local)).records).toEqual([]);
+ source.getAllApps = async () => [{ id: 'remote-id', repoPath: '/remote/app' }];
+ expect(await exportPortosQuality(peer.instanceId, 30, source, payload.repository)).toEqual(payload);
+ expect(source.query.mock.calls.at(-1)[1][0]).toBe('remote-id');
+ expect(await exportPortosQuality(peer.instanceId, 30, source, '0'.repeat(64))).toBeNull();
+});
+
+it('loads release evidence without peers and never re-exports it', async () => {
+ const payload = await buildQualitySnapshot(undefined, 30, deps([row('security', 82)]));
+ const local = { ...deps([]), getPeers: async () => [], readSnapshot: async () => JSON.stringify(payload) };
+ expect((await enrichAppsWithQuality([{ id: 'portos-default' }], local))[0].quality.score).toBe(82);
+ expect((await getAppQualityHistory('portos-default', 30, local)).points.at(-1).score).toBe(82);
+ expect((await buildQualitySnapshot(undefined, 30, local)).measurements).toEqual([]);
+ expect(await readReleaseQuality({ ...local, getOriginInfo: async () => ({ host: 'github.com', fullName: 'fork/PortOS' }) })).toEqual([]);
+ expect(await readReleaseQuality({ ...local, readSnapshot: async () => 'broken' })).toEqual([]);
+});