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: managed apps can commit their quality snapshot to .quality.json

Adam Eivye422233570c0
diff --git a/client/src/components/apps/AppQuality.jsx b/client/src/components/apps/AppQuality.jsx
index 010d0d671a..742fb7ef93 100644
--- a/client/src/components/apps/AppQuality.jsx
+++ b/client/src/components/apps/AppQuality.jsx
@@ -1,11 +1,35 @@
import AppQualityRunner from './AppQualityRunner';
import AppQualityHistory from './AppQualityHistory';
-import { Fragment } from 'react';
+import { Fragment, useState } from 'react';
import { Link, useSearchParams } from 'react-router';
import { formatDateShort } from '../../utils/formatters';
+import { publishAppQualitySnapshot } from '../../services/apiApps';
+import toast from '../ui/Toast';
+
+// The server refuses rather than fails when there is nothing to publish, so each
+// `published: false` reason gets its own plain-language explanation.
+const PUBLISH_SKIPPED = {
+ 'no-changes': 'Snapshot already up to date in .quality.json',
+ 'no-evidence': 'No quality evidence yet — run an audit first',
+ 'no-repo-path': 'App repo path is not a git repository',
+ 'not-a-repo': 'App repo path is not a git repository',
+};
export default function AppQuality({ app, detail = false }) {
const [params] = useSearchParams();
+ const [publishing, setPublishing] = useState(false);
+ // User-initiated, so every outcome toasts (the wrapper is silent).
+ const publishSnapshot = async () => {
+ setPublishing(true);
+ const result = await publishAppQualitySnapshot(app.id).catch(err => ({ failure: err }));
+ setPublishing(false);
+ if (result?.failure) return toast.error(result.failure.message || 'Could not publish the quality snapshot');
+ if (result?.published) {
+ const shortHash = result.hash ? ` (${result.hash.slice(0, 7)})` : '';
+ return toast.success(`Quality snapshot committed to .quality.json${shortHash}`);
+ }
+ toast(PUBLISH_SKIPPED[result?.reason] || 'Nothing to publish to .quality.json');
+ };
const quality = app.quality;
const selectedCategory = quality?.categories?.find(category => category.id === params.get('qualityCheck'));
const runnerLink = categoryId => {
@@ -59,7 +83,11 @@ export default function AppQuality({ app, detail = false }) {
: 'No audit assessment has been saved. Completed maintenance tasks only supply a score when they return a valid quality report. Earlier runs are not scored retroactively; run a scheduled audit to collect an assessment.'}
</p>
)}
- <div className="flex flex-wrap gap-4 text-sm text-port-accent"><Link to="/cos/schedule" className="hover:underline">Scheduled audit runners</Link><Link to="/cos/agents" className="hover:underline">View agents</Link></div>
+ <div className="flex flex-wrap items-center gap-4 text-sm text-port-accent"><Link to="/cos/schedule" className="hover:underline">Scheduled audit runners</Link><Link to="/cos/agents" className="hover:underline">View agents</Link>{app.publishQualitySnapshot === true && (
+ <button type="button" onClick={publishSnapshot} disabled={publishing} className="hover:underline disabled:opacity-40 disabled:no-underline">
+ {publishing ? 'Publishing snapshot…' : 'Publish snapshot now'}
+ </button>
+ )}</div>
<div className="grid grid-cols-1 xl:grid-cols-2 gap-5 items-start">
<div className="min-w-0 space-y-4">
{!selectedCategory && runner}
diff --git a/client/src/components/apps/AppQuality.test.jsx b/client/src/components/apps/AppQuality.test.jsx
index 19efeb7827..a42131c187 100644
--- a/client/src/components/apps/AppQuality.test.jsx
+++ b/client/src/components/apps/AppQuality.test.jsx
@@ -1,9 +1,16 @@
-import { fireEvent, render, screen, within } from '@testing-library/react';
+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
-import { it, expect, vi } from 'vitest';
+import { describe, it, expect, vi } from 'vitest';
import AppQuality from './AppQuality';
vi.mock('./AppQualityRunner', () => ({ default: ({ children }) => children(<div>Runner</div>) }));
-vi.mock('../../services/apiApps', () => ({ getAppQualityHistory: vi.fn().mockResolvedValue({ points: [], totalCategories: 25 }) }));
+vi.mock('../../services/apiApps', () => ({
+ getAppQualityHistory: vi.fn().mockResolvedValue({ points: [], totalCategories: 25 }),
+ publishAppQualitySnapshot: vi.fn(),
+}));
+vi.mock('../ui/Toast', () => ({ default: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }) }));
+
+import { publishAppQualitySnapshot } from '../../services/apiApps';
+import toast from '../ui/Toast';
it('shows zero as a real score and explains excluded categories in the breakdown', async () => {
const app = { id: 'portos-default', quality: { score: 0, ratedCategories: 1, totalCategories: 25, categories: [
@@ -92,3 +99,38 @@ it('opens the shared runner beside unavailable category evidence while preservin
expect(screen.getAllByText('Runner')).toHaveLength(1);
expect(screen.getAllByText('unavailable')).toHaveLength(2);
});
+
+describe('AppQuality snapshot publishing', () => {
+ const publishingApp = { id: 'example', publishQualitySnapshot: true, quality: { score: 80, categories: [] } };
+
+ it('offers the publish action only for an app that opted in', async () => {
+ const { rerender } = render(<MemoryRouter><AppQuality app={{ ...publishingApp, publishQualitySnapshot: false }} detail /></MemoryRouter>);
+ await screen.findByText(/No scored assessments/);
+ expect(screen.queryByRole('button', { name: 'Publish snapshot now' })).not.toBeInTheDocument();
+
+ rerender(<MemoryRouter><AppQuality app={publishingApp} detail /></MemoryRouter>);
+ expect(screen.getByRole('button', { name: 'Publish snapshot now' })).toBeInTheDocument();
+ });
+
+ it('reports the commit that carried the snapshot into the repo', async () => {
+ publishAppQualitySnapshot.mockResolvedValue({ success: true, published: true, hash: 'abc1234def', 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(publishAppQualitySnapshot).toHaveBeenCalledWith('example'));
+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Quality snapshot committed to .quality.json (abc1234)'));
+ });
+
+ it('explains a refusal instead of claiming a commit that never happened', async () => {
+ publishAppQualitySnapshot.mockResolvedValue({ success: true, published: false, reason: 'no-changes', 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('Snapshot already up to date in .quality.json'));
+ expect(toast.success).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/apps/EditAppDrawer.jsx b/client/src/components/apps/EditAppDrawer.jsx
index 887ed03255..5c294ce95a 100644
--- a/client/src/components/apps/EditAppDrawer.jsx
+++ b/client/src/components/apps/EditAppDrawer.jsx
@@ -1,6 +1,6 @@
import { useState, useEffect, useCallback } from 'react';
import { Link } from 'react-router';
-import { GitBranch, GitPullRequest, Lock, Copy, ShieldCheck } from 'lucide-react';
+import { BarChart3, GitBranch, GitPullRequest, Lock, Copy, ShieldCheck } from 'lucide-react';
import IconPicker from '../IconPicker';
import * as api from '../../services/api';
import { PORTOS_APP_ID } from '../../services/apiCore';
@@ -70,6 +70,9 @@ export default function EditAppDrawer({ app, onClose, onSave }) {
defaultUseWorktree: app.defaultUseWorktree || app.defaultOpenPR || false,
// Unset means ON server-side, so an app that has never been saved shows checked.
verifyRepoStateOnCompletion: app.verifyRepoStateOnCompletion !== false,
+ // Opt-in: publishing writes to the app's own repo, so an app that has never
+ // been saved must render unchecked.
+ publishQualitySnapshot: app.publishQualitySnapshot === true,
featureOverrides: Object.fromEntries(
APP_FEATURE_IDS.map(featureId => [featureId, getAppFeatureOverride(app, featureId)])
),
@@ -271,6 +274,7 @@ export default function EditAppDrawer({ app, onClose, onSave }) {
defaultOpenPR: formData.defaultOpenPR,
defaultPrCompletion: formData.defaultPrCompletion,
verifyRepoStateOnCompletion: formData.verifyRepoStateOnCompletion,
+ publishQualitySnapshot: formData.publishQualitySnapshot,
};
// Do not stamp an all-null map during an unrelated edit. Leaving the map
@@ -704,6 +708,20 @@ export default function EditAppDrawer({ app, onClose, onSave }) {
<p className="ml-6 text-xs text-gray-500">
Audits git and the forge once an agent completes. A leftover worktree, an undeleted branch, or an unmerged PR files a recovery task instead of being silently left behind.
</p>
+ <label htmlFor="edit-app-publish-quality-snapshot" className="flex items-center gap-2 cursor-pointer">
+ <input
+ id="edit-app-publish-quality-snapshot"
+ type="checkbox"
+ checked={formData.publishQualitySnapshot}
+ onChange={e => setFormData(prev => ({ ...prev, publishQualitySnapshot: e.target.checked }))}
+ className="rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"
+ />
+ <BarChart3 size={14} className="text-emerald-400" />
+ <span className="text-sm text-white">Publish quality snapshot to repo</span>
+ </label>
+ <p className="ml-6 text-xs text-gray-500">
+ After each audit, PortOS writes the app’s numeric quality scores to .quality.json at the repo root and commits it, so other PortOS installs running this app start with the latest scores. Off by default; nothing is pushed.
+ </p>
</div>
)}
diff --git a/client/src/components/apps/EditAppDrawer.test.jsx b/client/src/components/apps/EditAppDrawer.test.jsx
index 8451cac0cd..a74758e58b 100644
--- a/client/src/components/apps/EditAppDrawer.test.jsx
+++ b/client/src/components/apps/EditAppDrawer.test.jsx
@@ -211,6 +211,29 @@ describe('EditAppDrawer work tracker selector', () => {
await waitFor(() => expect(api.updateApp).toHaveBeenCalled());
expect(api.updateApp.mock.calls[0][1].verifyRepoStateOnCompletion).toBe(false);
});
+
+ // Publishing writes to the app's own repo, so the stored value must round-trip
+ // exactly: an app that opted in stays checked, and turning it back off has to
+ // reach the server as `false` rather than being dropped from the payload.
+ it('round-trips the opt-in repo quality snapshot toggle', async () => {
+ renderDrawer({ app: { ...APP, publishQualitySnapshot: true } });
+ await openTab('Workflow');
+
+ const toggle = await screen.findByLabelText(/Publish quality snapshot to repo/);
+ expect(toggle).toBeChecked();
+ fireEvent.click(toggle);
+ fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }));
+
+ await waitFor(() => expect(api.updateApp).toHaveBeenCalled());
+ expect(api.updateApp.mock.calls[0][1].publishQualitySnapshot).toBe(false);
+ });
+
+ it('leaves repo snapshot publishing off for an app that never opted in', async () => {
+ renderDrawer();
+ await openTab('Workflow');
+
+ expect(await screen.findByLabelText(/Publish quality snapshot to repo/)).not.toBeChecked();
+ });
});
describe('EditAppDrawer native launch target', () => {
diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.js
index 254b948816..1d83570b9d 100644
--- a/client/src/services/apiApps.js
+++ b/client/src/services/apiApps.js
@@ -12,6 +12,13 @@ export const getApps = ({ includeQuality = false, view, ...options } = {}) => {
};
export const getApp = (id, { includeQuality = false, ...options } = {}) => request(includeQuality ? `/apps/${id}?includeQuality=true` : `/apps/${id}`, options);
export const getAppQualityHistory = (id, days, options) => request(`/apps/${id}/quality-history?days=${days}`, { silent: true, ...options });
+// Write the app's numeric quality scores to `.quality.json` at the repo root and
+// commit them, so other PortOS installs running this app start with the latest
+// scores. Opt-in per app (`publishQualitySnapshot`) and user-initiated from the
+// Quality tab, which toasts every outcome itself — so default to silent.
+// Response: { success, published, reason?, hash?, path }.
+export const publishAppQualitySnapshot = (id, options = {}) =>
+ request(`/apps/${id}/quality-snapshot`, { method: 'POST', silent: true, ...options });
// Managed checkout topology: returns sanitized local/fork/upstream revision
// state without exposing machine-local repo paths.
export const getAppRepositorySources = (id, options = {}) =>
diff --git a/docs/API.md b/docs/API.md
index 816e5e8fe7..26d84df574 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -100,6 +100,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 commit it to `.quality.json` at its repo root (staged and committed as that one path; never pushed). Answers `{ success, published, path }` plus the commit `hash`, or a `reason` of `no-repo-path` / `not-a-repo` / `no-evidence` / `no-changes` when nothing was written. Not gated on the app's `publishQualitySnapshot` toggle — that toggle only automates the same publish after each audit. Any managed app's committed `.quality.json` is read back as a "Release snapshot" quality source. |
### Processes & Logs
diff --git a/docs/decisions/2026-09-10-portos-quality-federation.md b/docs/decisions/2026-09-10-portos-quality-federation.md
index 4ae3c5185d..fc4b6795b7 100644
--- a/docs/decisions/2026-09-10-portos-quality-federation.md
+++ b/docs/decisions/2026-09-10-portos-quality-federation.md
@@ -67,3 +67,43 @@ 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.
+
+## September 14: managed-app snapshots (`.quality.json`)
+
+The release snapshot above was PortOS-only: every other managed app's numeric
+evidence stayed in the database of whichever install ran the audit, so a second
+machine that had never audited the app showed no score for it. Managed apps now
+get the same shipped-evidence path.
+
+Each app carries an opt-in `publishQualitySnapshot` setting (unset/false = off).
+When it is on, every audit that records a measurement for the app rebuilds the
+app's numeric snapshot and commits it to `.quality.json` at the app's repo root.
+`POST /api/apps/:id/quality-snapshot` does the same on demand and is deliberately
+not gated on the toggle — a manual call is explicit intent.
+
+The file IS a snapshot, not a wrapper: the exact `{ schemaVersion, repository,
+measurements }` a federation export carries, serialized the same way as PortOS's
+own root `quality-snapshot.json`. The filename is generic and PortOS-agnostic on
+purpose — it is generated data any tool can read. If PortOS ever needs a config
+manifest inside a managed repo, that is a separate, hand-editable file; generated
+evidence and configuration do not share one path. **PortOS's own root
+`quality-snapshot.json` is unchanged** — same name, same publisher, same reader.
+
+Publishing is conservative. An app with no repo path, a repo path that is not a
+git checkout, or a snapshot with zero measurements is skipped, so an empty
+snapshot can never overwrite a populated file. A rebuild whose bytes match the
+committed file skips git entirely, so an audit that moved nothing leaves no
+commit. The commit is scoped with `git commit -- :(literal).quality.json`, so an
+automated write can never sweep in whatever the user had staged, and nothing is
+ever pushed. The audit-completion hook runs outside the request lifecycle and
+swallows every failure: a locked index never fails a completion.
+
+Reading is not gated on the toggle. PortOS reads a `.quality.json` in ANY managed
+app's repo as a "Release snapshot" quality source, with exactly the guards the
+PortOS snapshot already gets: schema validation, the normalized-origin repository
+hash must match, future assessment dates are dropped, the 30-day freshness rule
+and original dates still apply, a 4 MiB cap, and the records are labeled
+"Release snapshot" and never re-exported as local runs. A checkout of a different
+fork ignores the file. The content stays numeric-only — no summaries, paths, run
+ids or app names — so committing it to a public repository leaks nothing the
+federation wire contract would not already carry.
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.js
index 20de01a245..5163731edc 100644
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@ -574,7 +574,15 @@ describe('deferred imports stay deferred (#6156)', () => {
// image-gen dispatcher and is NOT in this number: checkConnection reaches it
// through a memoized call-site await import(), so the ~110 suites that never
// probe a local runtime do not pay for it.
-const MAX_STATIC_INSTANTIATIONS = 104552;
+// The managed-app `.quality.json` publisher raises this by a further 38, all of
+// it in two new suites, none of it a new edge into a widely-reached module:
+// `services/git.commit.test.js` pays git.js's closure (~34) to pin that an
+// automated commit is scoped to literal pathspecs, and
+// `services/appQualitySnapshotFile.test.js` plus crud.js's static import of that
+// dependency-free module account for the rest. The publisher itself reaches
+// git.js and appQualityFederation.js through `await import()`, and the audit
+// hook reaches the publisher the same way, so neither is in any closure.
+const MAX_STATIC_INSTANTIATIONS = 104590;
const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);
diff --git a/server/lib/validation.js b/server/lib/validation.js
index fe525a3544..84f4ca19d1 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -288,6 +288,8 @@ export const appSchema = z.object({
// task when it diverges. See lib/repoStateExpectations.js. Unset = ON: an install
// that never hears about a leaked branch just accumulates them.
verifyRepoStateOnCompletion: z.boolean().optional(),
+ // Unset/false = off (default); true = commit a `.quality.json` quality snapshot into the app repo after each audit.
+ publishQualitySnapshot: z.boolean().optional(),
featureOverrides: appFeatureOverridesSchema.optional(),
jira: jiraConfigSchema.optional().nullable(),
datadog: datadogConfigSchema.optional().nullable(),
diff --git a/server/routes/apps/crud.js b/server/routes/apps/crud.js
index 6df958ddcc..d35814c285 100644
--- a/server/routes/apps/crud.js
+++ b/server/routes/apps/crud.js
@@ -1,16 +1,18 @@
import { appListQuerySchema, appQualityQuerySchema, appQualityHistoryQuerySchema, appQualityFederationQuerySchema } from '../../lib/auditQuality.js';
import { exportPortosQuality } from '../../services/appQualityFederation.js';
import { enrichAppsWithQuality, getAppQualityHistory } from '../../services/appQuality.js';
+import { publishAppQualitySnapshot } from '../../services/appQualitySnapshotFile.js';
/**
* App CRUD + status enrichment + archive lifecycle.
*
- * GET / → App[] (PM2-status-enriched)
- * GET /:id → App (PM2-status-enriched, + appVersion)
- * POST / → App
- * PUT /:id → App (ports written back to ecosystem config)
- * DELETE /:id → 204 (removes the PortOS registry association only)
- * POST /:id/archive → App
- * POST /:id/unarchive → App
+ * GET / → App[] (PM2-status-enriched)
+ * GET /:id → App (PM2-status-enriched, + appVersion)
+ * POST / → App
+ * PUT /:id → App (ports written back to ecosystem config)
+ * DELETE /:id → 204 (removes the PortOS registry association only)
+ * POST /:id/archive → App
+ * POST /:id/unarchive → App
+ * POST /:id/quality-snapshot → commits the app's `.quality.json` snapshot
*/
import { Router } from 'express';
@@ -69,7 +71,14 @@ router.get('/', asyncHandler(async (req, res) => {
router.get('/:id/quality-history', loadApp, asyncHandler(async (req, res) => {
const { days } = validateRequest(appQualityHistoryQuerySchema, req.query);
- res.json(await getAppQualityHistory(req.loadedApp.id, days));
+ res.json(await getAppQualityHistory(req.loadedApp, days));
+}));
+
+// POST /api/apps/:id/quality-snapshot - Commit this app's numeric snapshot into its
+// repo as `.quality.json`. Deliberately NOT gated on publishQualitySnapshot: the
+// toggle automates the audit hook, a manual call here is explicit intent.
+router.post('/:id/quality-snapshot', loadApp, asyncHandler(async (req, res) => {
+ res.json({ success: true, ...await publishAppQualitySnapshot(req.loadedApp) });
}));
// GET /api/apps/:id - Get single app
diff --git a/server/routes/apps/crud.test.js b/server/routes/apps/crud.test.js
index daa434bac7..6fe81dfd6c 100644
--- a/server/routes/apps/crud.test.js
+++ b/server/routes/apps/crud.test.js
@@ -1,12 +1,14 @@
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 } }))) }));
+vi.mock('../../services/appQualitySnapshotFile.js', () => ({ publishAppQualitySnapshot: vi.fn(async () => ({ published: true, hash: 'abc1234', path: '.quality.json' })) }));
import { describe, it, expect, vi, beforeEach } from 'vitest';
import express from 'express';
import { request } from '../../lib/testHelper.js';
import { errorEvents } from '../../lib/errorHandler.js';
import crudRoutes from './crud.js';
import { enrichAppsWithQuality, getAppQualityHistory } from '../../services/appQuality.js';
+import { publishAppQualitySnapshot } from '../../services/appQualitySnapshotFile.js';
// Mock the services this router (and its port-config service) touch.
vi.mock('../../services/apps.js', () => ({
@@ -96,6 +98,25 @@ describe('Apps CRUD Routes', () => {
}
});
+ // Uniquely pins the on-demand publish route: it commits for the loaded app
+ // regardless of the opt-in toggle, and 404s rather than publishing for a stranger.
+ it('publishes a managed app snapshot on demand and 404s for an unknown app', async () => {
+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Example App', repoPath: '/repo/example-app' });
+ const published = await request(app).post('/api/apps/app-001/quality-snapshot');
+ expect(published.status).toBe(200);
+ expect(published.body).toEqual({ success: true, published: true, hash: 'abc1234', path: '.quality.json' });
+ expect(publishAppQualitySnapshot).toHaveBeenCalledWith({ id: 'app-001', name: 'Example App', repoPath: '/repo/example-app' });
+
+ publishAppQualitySnapshot.mockResolvedValueOnce({ published: false, reason: 'no-evidence', path: '.quality.json' });
+ expect((await request(app).post('/api/apps/app-001/quality-snapshot')).body)
+ .toEqual({ success: true, published: false, reason: 'no-evidence', path: '.quality.json' });
+
+ appsService.getAppById.mockResolvedValue(null);
+ const missing = await request(app).post('/api/apps/nope/quality-snapshot');
+ expect(missing.status).toBe(404);
+ expect(publishAppQualitySnapshot).toHaveBeenCalledTimes(2);
+ });
+
describe('GET /api/apps', () => {
it('should return list of apps with PM2 status', async () => {
const mockApps = [
@@ -166,7 +187,7 @@ describe('Apps CRUD Routes', () => {
expect(detail.body.quality).toEqual({ score: 75 });
const history = await request(app).get('/api/apps/portos-default/quality-history?days=90');
expect(history.status).toBe(200);
- expect(getAppQualityHistory).toHaveBeenCalledWith('portos-default', 90);
+ expect(getAppQualityHistory).toHaveBeenCalledWith({ id: 'portos-default', name: 'PortOS', type: 'ios-native' }, 90);
expect((await request(app).get('/api/apps/portos-default/quality-history?days=9999')).status).toBe(400);
});
diff --git a/server/routes/apps/documents.js b/server/routes/apps/documents.js
index d15c773ff7..ecbd7b5974 100644
--- a/server/routes/apps/documents.js
+++ b/server/routes/apps/documents.js
@@ -202,7 +202,9 @@ router.put('/:id/documents/*docPath', loadApp, asyncHandler(async (req, res) =>
}
const message = commitMessage || `docs: update ${filename} via PortOS`;
- const result = await git.commit(app.repoPath, message);
+ // Scope the commit to this document: the user may have staged unrelated work
+ // in their checkout, and a doc edit must never sweep it into this commit.
+ const result = await git.commit(app.repoPath, message, { paths: [filename] });
console.log(`📝 ${created ? 'Created' : 'Updated'} ${filename} in ${app.name} (${result.hash})`);
res.json({ success: true, hash: result.hash, created });
diff --git a/server/routes/apps/documents.test.js b/server/routes/apps/documents.test.js
index 9b2eaaa078..eae4519d68 100644
--- a/server/routes/apps/documents.test.js
+++ b/server/routes/apps/documents.test.js
@@ -121,6 +121,8 @@ describe('Apps Document Routes', () => {
expect(res.status).toBe(200);
expect(res.body).toMatchObject({ success: true, hash: 'abc1234', created: false });
expect(git.stageFiles).toHaveBeenCalledWith(repoPath, ['docs/decisions/2026-01-01-choice.md']);
+ // Scoped so a doc edit cannot sweep in whatever the user had staged.
+ expect(git.commit).toHaveBeenCalledWith(repoPath, expect.any(String), { paths: ['docs/decisions/2026-01-01-choice.md'] });
expect(await readFile(join(repoPath, 'docs', 'decisions', '2026-01-01-choice.md'), 'utf-8')).toBe('# Revised');
});
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index cd8a90cc76..0977d08ffd 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -1390,6 +1390,25 @@ async function recoverBareSentinelPayload(contents, taskType) {
}
}
+/**
+ * Opt-in only: an app with `publishQualitySnapshot` gets its freshly recorded
+ * measurement committed into the repo's `.quality.json`. This is a completion
+ * boundary outside the Express request lifecycle, so a missing repo, a git
+ * failure, or a locked index must log and let finalization finish.
+ */
+async function publishAppSnapshotFileAfterAudit(appId) {
+ if (!appId) return;
+ try {
+ const { getAppById } = await import('./apps.js');
+ const app = await getAppById(appId);
+ if (app?.publishQualitySnapshot !== true) return;
+ const { publishAppQualitySnapshot } = await import('./appQualitySnapshotFile.js');
+ await publishAppQualitySnapshot(app);
+ } catch (err) {
+ emitLog('error', `❌ Quality snapshot publish failed for app ${appId}: ${err.message}`, { appId });
+ }
+}
+
/**
* Read the finished agent's `.agent-done` payload and run the task type's
* `processTaskOutput` hook, if it registers one. No-op for the vast majority of
@@ -1403,9 +1422,10 @@ async function dispatchTaskOutputHook({ agentId, task, success, workspacePath, a
if (!taskType) return { ran: false };
if (isAuditTaskType(taskType)) {
const { recordAuditQuality } = await import('./appQuality.js');
- await recordAuditQuality({ task, taskType, agentId, success, assessedAt,
+ const recorded = await recordAuditQuality({ task, taskType, agentId, success, assessedAt,
workspacePath: readPayload ? (workspacePath || task?.metadata?.repoPath) : null })
.catch(err => emitLog('warn', `⚠️ Audit quality was not saved for ${agentId}: ${err.message}`, { agentId }));
+ if (recorded === true) await publishAppSnapshotFileAfterAudit(task?.metadata?.app);
// Assessment telemetry never waives commit/PR success criteria for fix mode.
return { ran: false };
}
diff --git a/server/services/agentFinalization.outputHooks.test.js b/server/services/agentFinalization.outputHooks.test.js
index 80c23a2802..13517fd2c2 100644
--- a/server/services/agentFinalization.outputHooks.test.js
+++ b/server/services/agentFinalization.outputHooks.test.js
@@ -1,5 +1,11 @@
vi.mock('./appQuality.js', () => ({ recordAuditQuality: vi.fn(async () => true) }));
import { recordAuditQuality } from './appQuality.js';
+// Hoisted doubles rather than static imports: the audit path reaches both modules
+// lazily, and importing them here would drag their subtrees into this suite's closure.
+const appsRegistry = vi.hoisted(() => ({ getAppById: vi.fn(async () => null) }));
+vi.mock('./apps.js', () => appsRegistry);
+const snapshotFile = vi.hoisted(() => ({ publishAppQualitySnapshot: vi.fn(async () => ({ published: true, hash: 'abc1234' })) }));
+vi.mock('./appQualitySnapshotFile.js', () => snapshotFile);
// The goal-fidelity gate (#5994) reaches a local model at completion. Pinned OFF
// here so these tests exercise the path they are about without depending on the
// developer's own reviewer settings — and so a machine that HAS a local reviewer
@@ -56,6 +62,7 @@ vi.mock('./agentErrorAnalysis.js', async importOriginal => {
vi.mock('./agentRunTracking.js', () => ({ completeAgentRun: vi.fn(async () => null) }));
vi.mock('./agentCompletion.js', () => ({ processAgentCompletion: vi.fn(async () => null) }));
vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn(), cosEvents: { emit: vi.fn(), on: vi.fn() } }));
+import { emitLog } from './cosEvents.js';
vi.mock('./taskSchedule.js', () => ({
recordTaskTypeFailure: vi.fn(async () => null),
recordTaskTypeSuccess: vi.fn(async () => null),
@@ -110,6 +117,43 @@ describe('recovery output-hook dispatch (#3182)', () => {
expect(updateAgent).not.toHaveBeenCalled();
});
+ // Committing the app's `.quality.json` is opt-in and runs outside the request
+ // lifecycle, so it must never fire for an un-opted app nor fail a completion.
+ // Each dispatch needs its own agent id — dispatchTaskOutputHookOnce caches by id.
+ it('commits a repo snapshot only for an opted-in app that just recorded a measurement', async () => {
+ const task = { ...TASK, metadata: { ...TASK.metadata, analysisType: 'better-complexity' } };
+ let run = 0;
+ const dispatch = () => dispatchTaskOutputHookOnce({ agentId: `agent-snapshot-${run += 1}`, task, success: true, workspacePath: '/worktree' });
+ const optedIn = { id: 'app-example', repoPath: '/repo/example-app', publishQualitySnapshot: true };
+
+ appsRegistry.getAppById.mockResolvedValue(optedIn);
+ await expect(dispatch()).resolves.toEqual({ ran: false });
+ expect(snapshotFile.publishAppQualitySnapshot).toHaveBeenCalledWith(optedIn);
+
+ for (const app of [{ ...optedIn, publishQualitySnapshot: false }, { ...optedIn, publishQualitySnapshot: 'true' },
+ { id: 'app-example' }, null]) {
+ snapshotFile.publishAppQualitySnapshot.mockClear();
+ appsRegistry.getAppById.mockResolvedValue(app);
+ await dispatch();
+ expect(snapshotFile.publishAppQualitySnapshot).not.toHaveBeenCalled();
+ }
+
+ // A missing or invalid report records nothing, so there is nothing new to publish.
+ appsRegistry.getAppById.mockResolvedValue(optedIn);
+ recordAuditQuality.mockResolvedValueOnce(false);
+ await dispatch();
+ expect(snapshotFile.publishAppQualitySnapshot).not.toHaveBeenCalled();
+
+ // A locked index or an unreadable registry must not fail the completion.
+ snapshotFile.publishAppQualitySnapshot.mockRejectedValueOnce(new Error('index.lock exists'));
+ await expect(dispatch()).resolves.toEqual({ ran: false });
+ appsRegistry.getAppById.mockRejectedValueOnce(new Error('registry unreadable'));
+ await expect(dispatch()).resolves.toEqual({ ran: false });
+ for (const reason of ['index.lock exists', 'registry unreadable']) {
+ expect(emitLog).toHaveBeenCalledWith('error', `❌ Quality snapshot publish failed for app app-example: ${reason}`, { appId: 'app-example' });
+ }
+ });
+
it.each([
['orphan cleanup', false],
['post-restart completion', true],
diff --git a/server/services/appQuality.db.test.js b/server/services/appQuality.db.test.js
index 38cd6b5c34..df10a450c1 100644
--- a/server/services/appQuality.db.test.js
+++ b/server/services/appQuality.db.test.js
@@ -34,7 +34,7 @@ describe.skipIf(!runDb)('app quality persistence', () => {
const deps = { getPeers: async () => [], getAppById: async id => ({ id }) };
const [app, other] = await enrichAppsWithQuality([{ id: appId }, { id: `${appId}-other` }], deps);
expect(app.quality).toMatchObject({ score: 65, ratedCategories: 1 });
- const history = await getAppQualityHistory(appId, 30, deps);
+ const history = await getAppQualityHistory({ id: appId }, 30, deps);
expect(history.points.at(-1)).toMatchObject({ score: 65, ratedCategories: 1 });
const retained = await query('SELECT report FROM app_quality_measurements WHERE app_id = $1 ORDER BY assessed_at', [appId]);
expect(retained.rows.map(row => row.report.score)).toEqual([30, 65]);
diff --git a/server/services/appQuality.js b/server/services/appQuality.js
index bfea7913bd..a5e80547fe 100644
--- a/server/services/appQuality.js
+++ b/server/services/appQuality.js
@@ -3,7 +3,6 @@ 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 { collectAppQuality, qualityRecord, readQualityRecords, readReleaseQuality } from './appQualityFederation.js';
export async function recordAuditQuality({ task, taskType, agentId, workspacePath, success, assessedAt }, deps = {}) {
@@ -40,28 +39,30 @@ export async function enrichAppsWithQuality(apps, deps = {}) {
console.error(`❌ App quality unavailable: ${err.message}`);
return null;
});
- const release = apps.some(app => app.id === PORTOS_APP_ID) ? await readReleaseQuality(deps) : [];
- return Promise.all(apps.map(async app => {
+ // Shipped evidence: PortOS's own snapshot file, or any managed app's committed `.quality.json`.
+ // 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(() => [])));
+ return Promise.all(apps.map(async (app, index) => {
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 : []),
+ ...shared.records, ...releases[index],
]), deps.now ?? Date.now()), federation: shared.federation }
: { ...summarizeAppQuality(), unavailable: true },
};
}));
}
-export async function getAppQualityHistory(appId, days, deps = {}) {
+/** Takes the full app record: the repo path is what locates a managed app's `.quality.json`. */
+export async function getAppQualityHistory(app, days, deps = {}) {
const now = deps.now ?? Date.now();
- const records = await readQualityRecords(appId, days, now, 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;
- const release = appId === PORTOS_APP_ID ? await readReleaseQuality(deps) : [];
- return { ...buildAppQualityHistory([...records, ...(shared?.records || []), ...release], days, now),
- ...(shared ? { federation: shared.federation } : {}) };
+ const records = await readQualityRecords(app.id, days, now, deps);
+ const shared = await collectAppQuality(app, days, deps)
+ .catch(() => ({ records: [], federation: { failed: true } }));
+ const release = await readReleaseQuality(deps, app).catch(() => []);
+ return { ...buildAppQualityHistory([...records, ...shared.records, ...release], days, now),
+ federation: shared.federation };
}
diff --git a/server/services/appQualityFederation.js b/server/services/appQualityFederation.js
index 888ad5c91d..3a137e0dc4 100644
--- a/server/services/appQualityFederation.js
+++ b/server/services/appQualityFederation.js
@@ -129,12 +129,29 @@ export async function collectAppQuality(app, days, deps = {}) {
unavailable: results.filter(r => r.status === 'rejected').length } };
}
+/**
+ * PortOS reads its own committed `quality-snapshot.json`; every other managed app
+ * reads a `.quality.json` at its repo root. Both files are the same numeric
+ * snapshot shape and get the same guards — repository match, no future dates, 4 MiB cap.
+ */
+async function releasePayload(deps, app) {
+ let raw = null;
+ if (app.id === PORTOS_APP_ID) {
+ const body = await (deps.readSnapshot || (() => readFile(join(PATHS.root, 'quality-snapshot.json'), 'utf8')))().catch(() => null);
+ // jsonIo stays out of this widely-reached module's static closure (import budget).
+ if (body && Buffer.byteLength(body) <= MAX_PAYLOAD_BYTES) raw = await Promise.resolve().then(() => JSON.parse(body)).catch(() => null);
+ } else if (app.repoPath) {
+ const { readAppQualitySnapshotFile } = await import('./appQualitySnapshotFile.js');
+ raw = await readAppQualitySnapshotFile(app.repoPath, deps);
+ }
+ const parsed = payloadSchema.safeParse(raw);
+ return parsed.success ? parsed.data : null;
+}
+
/** 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 [];
+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.' },
diff --git a/server/services/appQualityFederation.test.js b/server/services/appQualityFederation.test.js
index 8a81f6c0b4..ac5acf05bd 100644
--- a/server/services/appQualityFederation.test.js
+++ b/server/services/appQualityFederation.test.js
@@ -40,7 +40,7 @@ it('combines newest categories in app view and UTC history without changing othe
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);
+ const history = await getAppQualityHistory({ id: '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);
@@ -72,7 +72,7 @@ it('lets newer partial evidence supersede older broad scores and breaks ties con
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();
+ expect((await getAppQualityHistory({ id: '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 = [];
@@ -80,7 +80,7 @@ it('lets newer partial evidence supersede older broad scores and breaks ties con
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);
+ scores.push((await getAppQualityHistory({ id: 'portos-default' }, 30, combined)).points.at(-1).score);
}
expect(new Set(scores).size).toBe(1);
});
@@ -94,7 +94,7 @@ it('matches managed repositories with different local ids and excludes other ori
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 getAppQualityHistory({ id: 'local-id', repoPath: '/local/app' }, 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);
@@ -106,8 +106,49 @@ 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 getAppQualityHistory({ id: '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([]);
});
+
+it('reads a managed app\'s committed .quality.json as release evidence and rejects a foreign or broken one', 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 file = body => ({ ...deps([]), getOriginInfo, getPeers: async () => [], readFile: async () => body });
+
+ const local = file(JSON.stringify(published));
+ const records = await readReleaseQuality(local, managed);
+ expect(records).toMatchObject([{ category: 'security', sourcePeerName: 'Release snapshot', report: { score: 76 } }]);
+ expect(JSON.stringify(records)).not.toMatch(/Users|agent-security|app_id|github/);
+ expect((await enrichAppsWithQuality([managed], local))[0].quality.score).toBe(76);
+ expect((await getAppQualityHistory(managed, 30, local)).points.at(-1).score).toBe(76);
+
+ // PortOS's own root snapshot must not be read for a managed app, and vice versa.
+ expect(await readReleaseQuality({ ...local, getOriginInfo: async () => ({ host: 'github.com', fullName: 'owner/other' }) }, managed)).toEqual([]);
+ expect(await readReleaseQuality(file('not json'), managed)).toEqual([]);
+ expect(await readReleaseQuality(file(JSON.stringify({ ...published, schemaVersion: 2 })), managed)).toEqual([]);
+ expect(await readReleaseQuality(file(JSON.stringify({ quality: published })), managed)).toEqual([]);
+ expect(await readReleaseQuality(local, { id: 'local-id' })).toEqual([]);
+ expect(await readReleaseQuality(local)).toEqual([]);
+});
+
+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.
+ const getOriginInfo = async path => {
+ if (path === '/repo/broken') throw new Error('git spawn failed');
+ return { host: 'github.com', fullName: 'owner/app' };
+ };
+ const healthy = { id: 'healthy-id', repoPath: '/repo/example-app' };
+ const broken = { id: 'broken-id', repoPath: '/repo/broken' };
+ const published = await buildQualitySnapshot(healthy, 30, { ...deps([row('security', 64)]), getOriginInfo });
+ const local = { ...deps([]), getOriginInfo, getPeers: async () => [], readFile: async () => JSON.stringify(published) };
+
+ const apps = await enrichAppsWithQuality([healthy, broken], local);
+ expect(apps.map(entry => entry.id)).toEqual(['healthy-id', 'broken-id']);
+ expect(apps[0].quality.score).toBe(64);
+ expect(apps[1].quality.score).toBeNull();
+ expect((await getAppQualityHistory(broken, 30, local)).points.at(-1).score).toBeNull();
+});
diff --git a/server/services/appQualitySnapshotFile.js b/server/services/appQualitySnapshotFile.js
new file mode 100644
index 0000000000..9a272aa0c0
--- /dev/null
+++ b/server/services/appQualitySnapshotFile.js
@@ -0,0 +1,94 @@
+/**
+ * `.quality.json` — the numeric quality snapshot a managed app can carry at its
+ * repo root. The file IS a `buildQualitySnapshot` result verbatim
+ * (`{ schemaVersion, repository, measurements }`), byte-shaped exactly like the
+ * root `quality-snapshot.json` PortOS publishes for itself.
+ *
+ * The filename is deliberately generic and PortOS-agnostic: it is generated
+ * data any tool can read, not PortOS configuration. Publishing is opt-in per app
+ * (`publishQualitySnapshot`), commits only this one path, and never pushes.
+ */
+import { join } from 'node:path';
+import { readFile } from 'node:fs/promises';
+import { atomicWrite } from '../lib/fileCore.js';
+
+export const APP_QUALITY_SNAPSHOT_FILENAME = '.quality.json';
+export const APP_QUALITY_SNAPSHOT_MAX_BYTES = 4 * 1024 * 1024;
+
+const snapshotPath = repoPath => join(repoPath, APP_QUALITY_SNAPSHOT_FILENAME);
+// Byte-identical to scripts/publish-quality-snapshot.js so the two files stay comparable.
+const serialize = snapshot => `${JSON.stringify(snapshot, null, 2)}\n`;
+
+/** 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;
+}
+
+/** Parsed `.quality.json`, or null for every failure mode. Never throws. */
+export async function readAppQualitySnapshotFile(repoPath, deps = {}) {
+ const body = await readSnapshotText(repoPath, deps);
+ if (!body) 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);
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
+}
+
+function skipped(app, reason) {
+ console.log(`📊 Quality snapshot skipped for app ${app?.id}: ${reason}`);
+ return { published: false, reason, path: APP_QUALITY_SNAPSHOT_FILENAME };
+}
+
+// One tail per checkout. Several audit categories for the same app finish
+// together, and read-modify-write against `.quality.json` plus `.git/index` is
+// not re-entrant — the second run must see the first run's bytes (and answer
+// `no-changes`) rather than race it. Keyed by repo path, not app id: two app
+// records can point at one checkout. Same shape as `issueWriteTail`.
+const publishTails = new Map();
+
+/**
+ * Rebuild the app's numeric snapshot and commit it into `.quality.json`.
+ * 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));
+ // The queued value never rejects, so one failed publish cannot poison the tail.
+ const queued = run.then(() => {}, () => {});
+ publishTails.set(repoPath, queued);
+ // Only the newest tail owns the slot; an older one settling must not evict it.
+ queued.then(() => { if (publishTails.get(repoPath) === queued) publishTails.delete(repoPath); });
+ return run;
+}
+
+async function publishNow(app, deps) {
+ const git = deps.git || await import('./git.js');
+ 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 body = await readSnapshotText(app.repoPath, deps);
+ const next = serialize(snapshot);
+ if (next === body) return skipped(app, 'no-changes');
+
+ const count = snapshot.measurements.length;
+ await (deps.writeFile || atomicWrite)(snapshotPath(app.repoPath), next);
+ await git.stageFiles(app.repoPath, [APP_QUALITY_SNAPSHOT_FILENAME]);
+ // A failed commit must not leave the file staged in the user's index, where
+ // their next unrelated commit would carry it. Unstage best-effort, then let
+ // the original failure surface.
+ const { hash } = await git.commit(app.repoPath, `chore: publish PortOS quality snapshot (${count} measurements)`,
+ { paths: [APP_QUALITY_SNAPSHOT_FILENAME] })
+ .catch(err => git.unstageFiles(app.repoPath, [APP_QUALITY_SNAPSHOT_FILENAME])
+ .catch(() => {}).then(() => Promise.reject(err)));
+ console.log(`📊 Published quality snapshot for app ${app.id}: ${count} measurements → ${hash}`);
+ return { published: true, hash, path: APP_QUALITY_SNAPSHOT_FILENAME };
+}
diff --git a/server/services/appQualitySnapshotFile.test.js b/server/services/appQualitySnapshotFile.test.js
new file mode 100644
index 0000000000..7ad336b5b3
--- /dev/null
+++ b/server/services/appQualitySnapshotFile.test.js
@@ -0,0 +1,115 @@
+import { it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { APP_QUALITY_SNAPSHOT_FILENAME, APP_QUALITY_SNAPSHOT_MAX_BYTES,
+ readAppQualitySnapshotFile, publishAppQualitySnapshot } from './appQualitySnapshotFile.js';
+
+const app = { id: 'example-id', repoPath: '/repo/example-app' };
+const snapshot = (count = 1) => ({
+ schemaVersion: 1,
+ repository: 'a'.repeat(64),
+ measurements: Array.from({ length: count }, (_, index) => ({
+ measurementId: String(index).padStart(64, 'b'),
+ assessedAt: '2026-09-10T10:00:00Z',
+ report: { version: 1, category: 'security', score: 82, worstSeverity: 5,
+ coverage: 'broad', confidence: 'high', scannedFiles: 12, totalFiles: 12 },
+ })),
+});
+const gitDouble = () => ({ isRepo: vi.fn(async () => true), stageFiles: vi.fn(async () => true),
+ unstageFiles: vi.fn(async () => true), commit: vi.fn(async () => ({ hash: 'abc1234', message: 'commit' })) });
+const testDeps = (overrides = {}) => ({ git: gitDouble(), writeFile: vi.fn(async () => true),
+ buildQualitySnapshot: vi.fn(async () => snapshot()), readFile: vi.fn(async () => { throw new Error('ENOENT'); }),
+ ...overrides });
+
+let log;
+beforeEach(() => { log = vi.spyOn(console, 'log').mockImplementation(() => {}); });
+afterEach(() => log.mockRestore());
+
+// Uniquely pins the opt-in snapshot file contract: numeric-only content and the
+// four skips that must never touch the app's repo or its git index.
+it('reads a committed snapshot and answers null for every unusable file', async () => {
+ const read = body => readAppQualitySnapshotFile('/repo/example-app', { readFile: async () => body });
+ expect(await read(JSON.stringify(snapshot()))).toEqual(snapshot());
+ expect(await read('not json')).toBeNull();
+ expect(await read('[1,2]')).toBeNull();
+ expect(await read('"a string"')).toBeNull();
+ expect(await read(' '.repeat(APP_QUALITY_SNAPSHOT_MAX_BYTES + 1))).toBeNull();
+ expect(await readAppQualitySnapshotFile('', { readFile: async () => '{}' })).toBeNull();
+ expect(await readAppQualitySnapshotFile('/repo/example-app', { readFile: async () => { throw new Error('ENOENT'); } })).toBeNull();
+ expect(APP_QUALITY_SNAPSHOT_FILENAME).toBe('.quality.json');
+});
+
+it('publishes a changed snapshot as one scoped commit and skips without touching git otherwise', async () => {
+ const deps = testDeps();
+ expect(await publishAppQualitySnapshot(app, deps)).toEqual({ published: true, hash: 'abc1234', path: '.quality.json' });
+ const [path, body] = deps.writeFile.mock.calls[0];
+ expect(path).toBe('/repo/example-app/.quality.json');
+ expect(JSON.parse(body)).toEqual(snapshot());
+ expect(body.endsWith('\n')).toBe(true);
+ // The published file carries numeric evidence only — no prose, paths or run ids.
+ expect(body).not.toMatch(/Users|summary|app_id|agent-|github/);
+ expect(deps.git.stageFiles).toHaveBeenCalledWith('/repo/example-app', ['.quality.json']);
+ expect(deps.git.commit).toHaveBeenCalledWith('/repo/example-app',
+ 'chore: publish PortOS quality snapshot (1 measurements)', { paths: ['.quality.json'] });
+ expect(log).toHaveBeenCalledWith('📊 Published quality snapshot for app example-id: 1 measurements → abc1234');
+
+ // Re-publishing the identical snapshot must not create an empty commit.
+ const unchanged = testDeps({ readFile: async () => body });
+ expect(await publishAppQualitySnapshot(app, unchanged)).toEqual({ published: false, reason: 'no-changes', path: '.quality.json' });
+ expect(unchanged.writeFile).not.toHaveBeenCalled();
+ expect(unchanged.git.stageFiles).not.toHaveBeenCalled();
+ expect(unchanged.git.commit).not.toHaveBeenCalled();
+});
+
+it('never overwrites an existing snapshot with an empty or unreachable one', async () => {
+ const empty = testDeps({ buildQualitySnapshot: async () => snapshot(0), readFile: async () => JSON.stringify(snapshot()) });
+ expect(await publishAppQualitySnapshot(app, empty)).toEqual({ published: false, reason: 'no-evidence', path: '.quality.json' });
+ expect(empty.writeFile).not.toHaveBeenCalled();
+
+ const missing = testDeps({ buildQualitySnapshot: async () => null });
+ expect((await publishAppQualitySnapshot(app, missing)).reason).toBe('no-evidence');
+
+ const notRepo = testDeps({ git: { ...gitDouble(), isRepo: async () => false } });
+ expect(await publishAppQualitySnapshot(app, notRepo)).toEqual({ published: false, reason: 'not-a-repo', path: '.quality.json' });
+ expect(notRepo.buildQualitySnapshot).not.toHaveBeenCalled();
+
+ const noPath = testDeps();
+ expect(await publishAppQualitySnapshot({ id: 'example-id' }, noPath)).toEqual({ published: false, reason: 'no-repo-path', path: '.quality.json' });
+ expect(await publishAppQualitySnapshot(null, noPath)).toMatchObject({ reason: 'no-repo-path' });
+ expect(noPath.git.isRepo).not.toHaveBeenCalled();
+ expect(log).toHaveBeenCalledWith('📊 Quality snapshot skipped for app example-id: not-a-repo');
+});
+
+it('serializes concurrent publishes for one checkout so the second sees the first one\'s bytes', async () => {
+ // Several audit categories for one app finish together; read-modify-write over
+ // `.quality.json` and `.git/index` must not interleave.
+ const calls = [];
+ let releaseCommit;
+ const held = new Promise(resolve => { releaseCommit = resolve; });
+ let stored = null;
+ const deps = {
+ git: {
+ isRepo: async () => { calls.push('isRepo'); return true; },
+ stageFiles: async () => { calls.push('stage'); return true; },
+ unstageFiles: async () => true,
+ commit: async () => { calls.push('commit-start'); await held; calls.push('commit-end'); return { hash: 'abc1234' }; },
+ },
+ buildQualitySnapshot: async () => snapshot(),
+ readFile: async () => { calls.push('read'); if (stored === null) throw new Error('ENOENT'); return stored; },
+ writeFile: async (_path, body) => { calls.push('write'); stored = body; },
+ };
+ const first = publishAppQualitySnapshot(app, deps);
+ const second = publishAppQualitySnapshot(app, deps);
+ releaseCommit();
+ expect(await first).toMatchObject({ published: true, hash: 'abc1234' });
+ expect(await second).toMatchObject({ published: false, reason: 'no-changes' });
+ expect(calls).toEqual(['isRepo', 'read', 'write', 'stage', 'commit-start', 'commit-end', 'isRepo', 'read']);
+});
+
+it('unstages the file and rethrows when the commit fails, so no stray path sits in the index', async () => {
+ const deps = testDeps({ git: { ...gitDouble(), commit: vi.fn(async () => { throw new Error('index.lock exists'); }) } });
+ await expect(publishAppQualitySnapshot(app, deps)).rejects.toThrow('index.lock exists');
+ expect(deps.git.unstageFiles).toHaveBeenCalledWith('/repo/example-app', ['.quality.json']);
+
+ // A failed publish must not poison the checkout's queue for the next one.
+ const next = testDeps();
+ expect(await publishAppQualitySnapshot(app, next)).toMatchObject({ published: true });
+});
diff --git a/server/services/git.commit.test.js b/server/services/git.commit.test.js
new file mode 100644
index 0000000000..3e62d430b1
--- /dev/null
+++ b/server/services/git.commit.test.js
@@ -0,0 +1,34 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('../lib/execGit.js', () => {
+ const execGit = vi.fn();
+ return { execGit, execGitSafe: (...args) => execGit(...args) };
+});
+
+import { execGit } from '../lib/execGit.js';
+import { commit } from './git.js';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ execGit.mockResolvedValue({ stdout: '[main abc1234] chore: example\n', stderr: '', exitCode: 0 });
+});
+
+// Uniquely pins that an automated commit cannot sweep in files the user staged.
+describe('commit', () => {
+ it('scopes the commit to literal pathspecs when paths are given', async () => {
+ await expect(commit('/repo/example-app', 'chore: example', { paths: ['.quality.json', 'app/[id].jsx'] }))
+ .resolves.toEqual({ hash: 'abc1234', message: 'chore: example' });
+ expect(execGit).toHaveBeenCalledWith(
+ ['commit', '-m', 'chore: example', '--', ':(literal).quality.json', ':(literal)app/[id].jsx'],
+ '/repo/example-app'
+ );
+ });
+
+ it('commits the index unchanged when no paths are given and rejects unsafe ones', async () => {
+ await commit('/repo/example-app', 'chore: example');
+ expect(execGit).toHaveBeenCalledWith(['commit', '-m', 'chore: example'], '/repo/example-app');
+ await commit('/repo/example-app', 'chore: example', {});
+ expect(execGit).toHaveBeenLastCalledWith(['commit', '-m', 'chore: example'], '/repo/example-app');
+ await expect(commit('/repo/example-app', 'chore: example', { paths: ['../escape.json'] })).rejects.toThrow('Invalid file path');
+ });
+});
diff --git a/server/services/git.js b/server/services/git.js
index 5eb9bc9258..973b46a9dc 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -139,11 +139,16 @@ export async function unstageFiles(dir, files) {
}
/**
- * Create commit
+ * Create commit.
+ *
+ * `paths` scopes the commit to those repo-relative files (`git commit -m … -- <pathspecs>`),
+ * so an automated commit can never sweep in whatever the user happened to have staged.
+ * Same `:(literal)` pathspec handling as stageFiles. Omitted = commit the index as-is.
*/
-export async function commit(dir, message) {
+export async function commit(dir, message, { paths = [] } = {}) {
+ const pathspecs = paths.length ? ['--', ...validateFilePaths(paths).map(toLiteralPathspec)] : [];
// Using spawn with -m argument passes message safely without shell interpretation
- const result = await execGit(['commit', '-m', message], dir);
+ const result = await execGit(['commit', '-m', message, ...pathspecs], dir);
const hashMatch = result.stdout.match(/\[[\w-]+ ([a-f0-9]+)\]/);
return {
hash: hashMatch ? hashMatch[1] : null,