Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: land quality snapshots through a merge-on-green pull request
[._.]/ Adam Eivy778209505b9c
diff --git a/AGENTS.md b/AGENTS.mdindex 999cad69a0..72d82b7e01 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -207,7 +207,7 @@ This complements the Security Model (the deployed product) — this section gove- **main**: active development. **release**: push `main` to `release` to trigger the GitHub Release workflow.- **Before pushing**: inspect branch/upstream and working-tree state, preserve unrelated changes, and commit the intended work. Fetch and integrate the workflow's intended base explicitly; a feature branch's tracking branch is not necessarily the default branch. Run `npm run pregate` on the resulting commits, then push. Re-run it after any subsequent rebase; do not blindly pull with autostash.- **No per-branch changelog entries.** PRs do not write a changelog file or fragment — commit messages are the record, and `/do:release` synthesizes the release notes from the commit log since the last tag into `.changelog/v{version}.md`. **Write commit subjects/bodies for a human release-note reader** (see "Git commits and PRs" in the global instructions). Rationale: `.changelog/README.md`.-- **Release quality snapshot**: before a release, run `npm run quality:snapshot` on the install holding PortOS audit evidence. It publishes numeric local assessments only (no provider calls, no private run prose) into the repo-root `.quality.json`; with no local evidence it commits nothing and says so.+- **Release quality snapshot**: before a release, run `npm run quality:snapshot` on the install holding PortOS audit evidence. It publishes numeric local assessments only (no provider calls, no private run prose) into the repo-root `.quality.json` through a merge-on-green pull request; with no local evidence it commits nothing and says so.- **Versioning**: `package.json` reflects the last release. Do not bump during development — `/do:release` handles it.- After each feature or bug fix, review the diff for unnecessary complexity and duplication; use `/simplify` when available, otherwise perform the review directly. Follow the active task's delivery workflow for commit/push; a review-only request does not authorize shipping changes.- **Deferred work follows “Don't leave trash on the floor” above.** Make routine design decisions rather than parking an issue for input. PortOS issue labels come only from `MANDATORY_DISPATCH_HINT_GUIDANCE` in `server/lib/dispatchLabels.js`; do not duplicate the vocabulary in instructions.diff --git a/client/src/components/apps/AppQuality.jsx b/client/src/components/apps/AppQuality.jsxindex 50a23bc30a..30b25ff2fd 100644--- a/client/src/components/apps/AppQuality.jsx+++ b/client/src/components/apps/AppQuality.jsx@@ -14,6 +14,9 @@ const PUBLISH_SKIPPED = {'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',+ 'no-remote': 'App repo has no origin remote to open a pull request against',+ 'no-default-branch': 'Could not resolve the repository default branch',+ 'pr-failed': 'Could not open a quality snapshot pull request',};export default function AppQuality({ app, detail = false }) {@@ -26,8 +29,9 @@ export default function AppQuality({ app, detail = false }) {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}`);+ return toast.success(result.prUrl+ ? 'Quality snapshot pull request opened; it will merge when CI is green'+ : 'Quality snapshot published to .quality.json');}toast(PUBLISH_SKIPPED[result?.reason] || 'Nothing to publish to .quality.json');};diff --git a/client/src/components/apps/AppQuality.test.jsx b/client/src/components/apps/AppQuality.test.jsxindex 5703a1e96d..3ddfe287df 100644--- a/client/src/components/apps/AppQuality.test.jsx+++ b/client/src/components/apps/AppQuality.test.jsx@@ -118,15 +118,19 @@ describe('AppQuality snapshot publishing', () => {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' });+ it('reports the pull request that carries the snapshot into the repo', async () => {+ publishAppQualitySnapshot.mockResolvedValue({+ success: true, published: true, hash: 'abc1234def', path: '.quality.json',+ prUrl: 'https://github.com/example/app/pull/42',+ });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)'));+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith(+ 'Quality snapshot pull request opened; it will merge when CI is green'));});it('explains a refusal instead of claiming a commit that never happened', async () => {diff --git a/client/src/components/apps/EditAppDrawer.jsx b/client/src/components/apps/EditAppDrawer.jsxindex 6230da2a58..bc0aeac3ae 100644--- a/client/src/components/apps/EditAppDrawer.jsx+++ b/client/src/components/apps/EditAppDrawer.jsx@@ -742,7 +742,7 @@ export default function EditAppDrawer({ app, onClose, onSave }) {<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.+ After each audit, PortOS writes the app’s numeric quality scores to .quality.json, opens a pull request, and merges it when CI is green so the live checkout never diverges from origin. Off by default.</p></div>)}diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.jsindex ede62da544..ad61b0ad7b 100644--- a/client/src/services/apiApps.js+++ b/client/src/services/apiApps.js@@ -12,11 +12,12 @@ 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 }.+// Land the app's numeric quality scores as `.quality.json` through a+// merge-on-green pull request, 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, prUrl?, prNumber? }.export const publishAppQualitySnapshot = (id, options = {}) =>request(`/apps/${id}/quality-snapshot`, { method: 'POST', silent: true, ...options });// The Quality tab's weekly-schedule form. `get` returns the applicable checks,diff --git a/docs/API.md b/docs/API.mdindex 1a47750836..6eca9fc5d1 100644--- a/docs/API.md+++ b/docs/API.md@@ -100,7 +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 app's committed `.quality.json` is read back as a "Release snapshot" quality source, PortOS's own checkout included (`npm run quality:snapshot` is the same publish, run from the release step). |+| POST | `/apps/:id/quality-snapshot` | Rebuild the app's numeric quality snapshot and land `.quality.json` through a merge-on-green pull request on `portos/quality-snapshot` (scoped to that one path; the live checkout is not committed). Answers `{ success, published, path }` plus the commit `hash`, `prUrl`, and `prNumber`, or a `reason` of `no-repo-path` / `not-a-repo` / `no-evidence` / `no-changes` / `no-remote` / `no-default-branch` / `pr-failed` when nothing was written. Not gated on the app's `publishQualitySnapshot` toggle — that toggle only automates the same publish after each audit. Any app's committed `.quality.json` is read back as a "Release snapshot" quality source, PortOS's own checkout included (`npm run quality:snapshot` is the same publish, run from the release step). || GET | `/apps/:id/quality-schedule` | The Quality tab's weekly-schedule form: every audit check with its applicability verdict and reason, the repository shapes that verdict came from, the cron expressions already occupied on this app, and the plan the shipped defaults produce. Read-only — no LLM call, no write. || POST | `/apps/:id/quality-schedule/preview` | Re-plan for an edited form (selection, per-check delivery mode, checks per day, hour window, claim-drain task and offset). Still read-only; a POST only because the option bag carries a per-check map. || POST | `/apps/:id/quality-schedule/apply` | Persist the plan as ordinary per-app task-type overrides: the selected checks enabled with their weekly cron and `fileIssues` mode, the audit types left out disabled with their interval cleared, and — when at least one selected check files issues — one daily cron for the issue-claim drain (one an earlier plan planted is retired when it is switched off or replaced). Other task types are untouched. |diff --git a/docs/decisions/2026-09-10-portos-quality-federation.md b/docs/decisions/2026-09-10-portos-quality-federation.mdindex cf74f8480d..8180e234eb 100644--- a/docs/decisions/2026-09-10-portos-quality-federation.md+++ b/docs/decisions/2026-09-10-portos-quality-federation.md@@ -127,3 +127,13 @@ The rename is a git rename of tracked, derived content — no migration, since`scripts/migrations/` governs `data/` paths and there is no install state tocarry. A fork that published under the old name resolves one rename conflict;worst case it regenerates the file from its own database on the next publish.++## September 21: land snapshots through a merge-on-green PR++Committing `.quality.json` on the live checkout left the default branch ahead of+origin, and many managed apps refuse direct pushes to `main`. Publishing now+writes the file in a temporary worktree on `portos/quality-snapshot`, opens a+pull request, and queues the existing merge-on-green sweep (`queuePendingMerge`+on GitHub; GitLab auto-merge when the pipeline succeeds). No review is requested.+The live checkout is not committed, staged, or switched. An unchanged snapshot+still skips git entirely.diff --git a/scripts/publish-quality-snapshot.js b/scripts/publish-quality-snapshot.jsindex cf41dfd7b6..322ac2cca9 100644--- a/scripts/publish-quality-snapshot.js+++ b/scripts/publish-quality-snapshot.js@@ -1,9 +1,10 @@/**- * Explicit, local-only release step: no provider calls and no peer evidence.+ * Explicit release step: no provider calls and no peer evidence.** PortOS publishes its own `.quality.json` through the same publisher every other* managed app uses — this command is the manual trigger, equivalent to the audit- * hook the app's `publishQualitySnapshot` toggle automates.+ * hook the app's `publishQualitySnapshot` toggle automates. The publisher opens+ * a merge-on-green pull request rather than committing on the live checkout.*/import { getAppById, PORTOS_APP_ID } from '../server/services/apps.js';import { publishAppQualitySnapshot, APP_QUALITY_SNAPSHOT_FILENAME } from '../server/services/appQualitySnapshotFile.js';diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 4fb4fa1e11..0e083959f0 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -296,7 +296,7 @@ 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.+ // Unset/false = off (default); true = land a `.quality.json` quality snapshot through a merge-on-green PR after each audit.publishQualitySnapshot: z.boolean().optional(),featureOverrides: appFeatureOverridesSchema.optional(),jira: jiraConfigSchema.optional().nullable(),diff --git a/server/routes/apps/crud.js b/server/routes/apps/crud.jsindex db606f576c..6fc835e4a6 100644--- a/server/routes/apps/crud.js+++ b/server/routes/apps/crud.js@@ -74,9 +74,10 @@ router.get('/:id/quality-history', loadApp, asyncHandler(async (req, res) => {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.+// POST /api/apps/:id/quality-snapshot - Land this app's numeric snapshot as+// `.quality.json` through a merge-on-green PR. 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) });}));diff --git a/server/routes/apps/crud.test.js b/server/routes/apps/crud.test.jsindex 6fe81dfd6c..0a5cff4e93 100644--- a/server/routes/apps/crud.test.js+++ b/server/routes/apps/crud.test.js@@ -98,8 +98,9 @@ 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.+ // Uniquely pins the on-demand publish route: it lands a snapshot PR 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');diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsindex bef0403544..a77b1a8ec8 100644--- a/server/services/agentFinalization.js+++ b/server/services/agentFinalization.js@@ -1675,9 +1675,10 @@ 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.+ * measurement landed as the repo's `.quality.json` through a merge-on-green+ * pull request. 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;diff --git a/server/services/agentFinalization.outputHooks.test.js b/server/services/agentFinalization.outputHooks.test.jsindex 13517fd2c2..caf6a8def6 100644--- a/server/services/agentFinalization.outputHooks.test.js+++ b/server/services/agentFinalization.outputHooks.test.js@@ -117,7 +117,7 @@ describe('recovery output-hook dispatch (#3182)', () => {expect(updateAgent).not.toHaveBeenCalled();});- // Committing the app's `.quality.json` is opt-in and runs outside the request+ // Landing the app's `.quality.json` PR 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 () => {diff --git a/server/services/appQualitySnapshotFile.js b/server/services/appQualitySnapshotFile.jsindex fe09f52a4b..eab58b1878 100644--- a/server/services/appQualitySnapshotFile.js+++ b/server/services/appQualitySnapshotFile.js@@ -9,19 +9,33 @@** 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.+ * (`publishQualitySnapshot`), commits only this one path on a dedicated branch,+ * and lands it through a merge-on-green pull request so the live checkout never+ * diverges from origin and repos that block pushes to the default branch still+ * receive the file.*/import { join } from 'node:path';-import { readFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { mkdtemp, readFile, rm } 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;+export const QUALITY_SNAPSHOT_BRANCH = 'portos/quality-snapshot';const snapshotPath = repoPath => join(repoPath, APP_QUALITY_SNAPSHOT_FILENAME);// Byte-identical across every publisher so two files of the same snapshot compare equal.const serialize = snapshot => `${JSON.stringify(snapshot, null, 2)}\n`;+const QUALITY_PR_TITLE = 'chore: publish quality snapshot';+const QUALITY_PR_BODY = `## Summary+Update the repository \`.quality.json\` numeric quality snapshot generated by PortOS.++## Test plan+- Generated numeric measurements only; no application code changes+- Merge when required CI is green; no code review required+`;+/** Raw bytes, or null when absent/unreadable/oversize. The publish path needs the* exact text so an unchanged snapshot can skip git entirely. */async function readSnapshotText(repoPath, deps = {}) {@@ -52,11 +66,22 @@ function skipped(app, reason) {// `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();+// Bytes the in-process publisher last landed (or confirmed on origin) for a+// checkout. Origin/default still holds the previous file until the PR merges,+// so the next audit in this process must not open a duplicate PR of the same+// snapshot.+const lastPublishedBody = new Map();++export function __resetQualitySnapshotPublishState() {+ publishTails.clear();+ lastPublishedBody.clear();+}/**- * 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.+ * Rebuild the app's numeric snapshot and land it as `.quality.json` through a+ * merge-on-green pull request. An empty snapshot never overwrites a populated+ * file, and an unchanged snapshot never reaches git — an audit that moved+ * nothing leaves no commit.*/export async function publishAppQualitySnapshot(app, deps = {}) {if (!app?.repoPath) return skipped(app, 'no-repo-path');@@ -71,6 +96,18 @@ export async function publishAppQualitySnapshot(app, deps = {}) {return run;}+async function showRefFile(git, repoPath, spec) {+ const result = await git.execGit(['show', spec], repoPath, { ignoreExitCode: true }).catch(() => null);+ if (!result || result.exitCode !== 0) return null;+ const body = result.stdout;+ if (typeof body !== 'string' || Buffer.byteLength(body) > APP_QUALITY_SNAPSHOT_MAX_BYTES) return null;+ return body;+}++function hasOrigin(remote) {+ return Boolean(remote?.origin && (remote.origin.fetch || remote.origin.push || remote.origin['']));+}+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');@@ -78,20 +115,188 @@ async function publishNow(app, deps) {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');+ if (lastPublishedBody.get(app.repoPath) === next) return skipped(app, 'no-changes');++ if (!hasOrigin(await git.getRemote(app.repoPath))) return skipped(app, 'no-remote');++ await git.fetchOrigin(app.repoPath).catch(() => {});+ const defaultBranch = await git.getDefaultBranch(app.repoPath);+ if (!defaultBranch) return skipped(app, 'no-default-branch');++ const fromDefault = await showRefFile(git, app.repoPath, `origin/${defaultBranch}:${APP_QUALITY_SNAPSHOT_FILENAME}`);+ if (fromDefault === next) {+ lastPublishedBody.set(app.repoPath, next);+ return skipped(app, 'no-changes');+ }++ const fromBranch = await showRefFile(git, app.repoPath, `origin/${QUALITY_SNAPSHOT_BRANCH}:${APP_QUALITY_SNAPSHOT_FILENAME}`);+ if (fromBranch === next) {+ const reused = await reuseOpenSnapshotPr(app, git, defaultBranch, deps);+ if (reused.published) lastPublishedBody.set(app.repoPath, next);+ return reused;+ }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])+ const result = await landSnapshotPr(app, { body: next, count, defaultBranch, git, deps });+ lastPublishedBody.set(app.repoPath, next);+ return result;+}++async function reuseOpenSnapshotPr(app, git, defaultBranch, deps) {+ const probe = deps.probePrForBranch+ || (await import('./prProbe.js')).probePrForBranch;+ const found = await probe(app.repoPath, QUALITY_SNAPSHOT_BRANCH);+ const prState = typeof found?.prState === 'string' ? found.prState.toUpperCase() : '';+ if (found?.prUrl && found?.prNumber && prState === 'OPEN') {+ const queued = await queueMergeWhenGreen(app, {+ url: found.prUrl, number: found.prNumber, cli: found.cli,+ }, deps);+ console.log(`📊 Quality snapshot PR already open for app ${app.id}: ${found.prUrl}`);+ return {+ published: true, hash: null, path: APP_QUALITY_SNAPSHOT_FILENAME,+ prUrl: found.prUrl, prNumber: found.prNumber, queuedMerge: queued === true,+ };+ }+ return landExistingBranchPr(app, git, defaultBranch, deps);+}++async function landExistingBranchPr(app, git, defaultBranch, deps) {+ const created = await openOrAdoptPr(git, app.repoPath, defaultBranch, deps);+ if (!created?.url) {+ return skipped(app, 'pr-failed');+ }+ const queued = await queueMergeWhenGreen(app, created, deps);+ console.log(`📊 Quality snapshot PR opened for app ${app.id}: ${created.url}`);+ return {+ published: true, hash: null, path: APP_QUALITY_SNAPSHOT_FILENAME,+ prUrl: created.url, prNumber: created.number, queuedMerge: queued === true,+ };+}++async function landSnapshotPr(app, { body, count, defaultBranch, git, deps }) {+ const makeTemp = deps.mkdtemp || mkdtemp;+ const worktreePath = await makeTemp(join(tmpdir(), 'portos-quality-'));+ const addWorktree = deps.addWorktree || (async (args, repo) => {+ const { addWorktreeWithRetry } = await import('./worktreeManager.js');+ return addWorktreeWithRetry(args, repo);+ });+ const removeTemp = deps.rm || rm;++ const run = async () => {+ const baseRef = `origin/${defaultBranch}`;+ await addWorktree(+ ['worktree', 'add', '--no-track', '-B', QUALITY_SNAPSHOT_BRANCH, worktreePath, baseRef],+ app.repoPath,+ );+ await (deps.writeFile || atomicWrite)(join(worktreePath, APP_QUALITY_SNAPSHOT_FILENAME), body);+ await git.stageFiles(worktreePath, [APP_QUALITY_SNAPSHOT_FILENAME]);+ const { hash } = await git.commit(+ worktreePath,+ `chore: publish PortOS quality snapshot (${count} measurements)`,+ { paths: [APP_QUALITY_SNAPSHOT_FILENAME] },+ ).catch(err => git.unstageFiles(worktreePath, [APP_QUALITY_SNAPSHOT_FILENAME]).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 };++ await pushSnapshotBranch(git, app.repoPath, worktreePath);+ const pr = await openOrAdoptPr(git, worktreePath, defaultBranch, deps);+ if (!pr?.url) {+ throw new Error(pr?.error || 'quality snapshot pull request was not created');+ }+ const queued = await queueMergeWhenGreen(app, pr, deps);+ console.log(`📊 Published quality snapshot for app ${app.id}: ${count} measurements → ${hash} (${pr.url})`);+ return {+ published: true, hash, path: APP_QUALITY_SNAPSHOT_FILENAME,+ prUrl: pr.url, prNumber: pr.number, queuedMerge: queued === true,+ };+ };++ return run().finally(() => Promise.all([+ git.execGit(['worktree', 'remove', '--force', worktreePath], app.repoPath, { ignoreExitCode: true })+ .catch(() => {}),+ removeTemp(worktreePath, { recursive: true, force: true }).catch(() => {}),+ ]));+}++async function pushSnapshotBranch(git, repoPath, worktreePath) {+ const remote = await git.execGit(+ ['rev-parse', `origin/${QUALITY_SNAPSHOT_BRANCH}`],+ repoPath,+ { ignoreExitCode: true },+ ).catch(() => null);+ const remoteSha = remote?.exitCode === 0 ? String(remote.stdout || '').trim() : '';+ if (remoteSha && /^[0-9a-f]{7,40}$/i.test(remoteSha)) {+ await git.execGit([+ 'push',+ `--force-with-lease=refs/heads/${QUALITY_SNAPSHOT_BRANCH}:${remoteSha}`,+ 'origin',+ `HEAD:refs/heads/${QUALITY_SNAPSHOT_BRANCH}`,+ ], worktreePath);+ return;+ }+ await git.execGit(+ ['push', '-u', 'origin', `HEAD:refs/heads/${QUALITY_SNAPSHOT_BRANCH}`],+ worktreePath,+ );+}++async function openOrAdoptPr(git, cwd, base, deps) {+ const created = await git.createPR(cwd, {+ title: QUALITY_PR_TITLE,+ body: QUALITY_PR_BODY,+ base,+ head: QUALITY_SNAPSHOT_BRANCH,+ }).catch(err => ({ success: false, error: err.message }));++ if (created?.success && created.url) return decoratePr(git, created);++ const probe = deps.probePrForBranch+ || (await import('./prProbe.js')).probePrForBranch;+ const found = await probe(cwd, QUALITY_SNAPSHOT_BRANCH);+ const prState = typeof found?.prState === 'string' ? found.prState.toUpperCase() : '';+ if (found?.prUrl && found?.prNumber && prState === 'OPEN') {+ return { url: found.prUrl, number: found.prNumber, cli: found.cli || created?.cli };+ }+ return { error: created?.error || 'pull request was not created' };+}++function decoratePr(git, created) {+ const parsed = git.parsePullRequestUrl(created.url);+ return {+ url: created.url,+ number: parsed?.number ?? null,+ cli: created.cli,+ };+}++async function queueMergeWhenGreen(app, pr, deps) {+ if (!pr?.url || !pr?.number) return false;+ if (pr.cli === 'glab') {+ const execGlab = deps.execGlab || (await import('./gitlab.js')).execGlab;+ const run = args => execGlab(args, app.repoPath, undefined, { rejectOnError: true })+ .then(() => true, err => err);+ let result = await run(['mr', 'merge', String(pr.number), '--yes', '--auto-merge']);+ if (result !== true && /unknown flag|unknown shorthand/i.test(result?.message || '')) {+ result = await run(['mr', 'merge', String(pr.number), '--yes', '--when-pipeline-succeeds']);+ }+ if (result !== true) {+ console.log(`📊 Quality snapshot MR #${pr.number} left open for app ${app.id}: ${result?.message || 'auto-merge unavailable'}`);+ return false;+ }+ return true;+ }+ const queuePendingMerge = deps.queuePendingMerge+ || (await import('./prWatcher.js')).queuePendingMerge;+ return queuePendingMerge(app.id, {+ prUrl: pr.url,+ prNumber: pr.number,+ prBranch: QUALITY_SNAPSHOT_BRANCH,+ sourceAgentId: null,+ sourceTask: {+ id: `quality-snapshot-${app.id}`,+ priority: 'LOW',+ description: 'Publish PortOS quality snapshot',+ metadata: { app: app.id },+ },+ });}diff --git a/server/services/appQualitySnapshotFile.test.js b/server/services/appQualitySnapshotFile.test.jsindex 43d0543f88..a23e3f78c6 100644--- a/server/services/appQualitySnapshotFile.test.js+++ b/server/services/appQualitySnapshotFile.test.js@@ -1,9 +1,13 @@import { it, expect, vi, beforeEach, afterEach } from 'vitest';import { join } from 'node:path';-import { APP_QUALITY_SNAPSHOT_FILENAME, APP_QUALITY_SNAPSHOT_MAX_BYTES,- readAppQualitySnapshotFile, publishAppQualitySnapshot } from './appQualitySnapshotFile.js';+import {+ APP_QUALITY_SNAPSHOT_FILENAME, APP_QUALITY_SNAPSHOT_MAX_BYTES, QUALITY_SNAPSHOT_BRANCH,+ readAppQualitySnapshotFile, publishAppQualitySnapshot, __resetQualitySnapshotPublishState,+} from './appQualitySnapshotFile.js';const app = { id: 'example-id', repoPath: '/repo/example-app' };+const worktreePath = '/tmp/portos-quality-test';+const prUrl = 'https://github.com/example/app/pull/42';const snapshot = (count = 1) => ({schemaVersion: 1,repository: 'a'.repeat(64),@@ -14,18 +18,47 @@ const snapshot = (count = 1) => ({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 });+const serialized = body => `${JSON.stringify(body, null, 2)}\n`;+const missingShow = { exitCode: 1, stdout: '', stderr: 'exists' };+const gitDouble = (overrides = {}) => ({+ isRepo: vi.fn(async () => true),+ getRemote: vi.fn(async () => ({ origin: { fetch: '[email protected]:example/app.git' } })),+ fetchOrigin: vi.fn(async () => true),+ getDefaultBranch: vi.fn(async () => 'main'),+ execGit: vi.fn(async (args) => {+ if (args[0] === 'show' || (args[0] === 'rev-parse' && String(args[1] || '').includes(QUALITY_SNAPSHOT_BRANCH))) {+ return missingShow;+ }+ return { exitCode: 0, stdout: '', stderr: '' };+ }),+ stageFiles: vi.fn(async () => true),+ unstageFiles: vi.fn(async () => true),+ commit: vi.fn(async () => ({ hash: 'abc1234', message: 'commit' })),+ createPR: vi.fn(async () => ({ success: true, url: prUrl, cli: 'gh' })),+ parsePullRequestUrl: vi.fn(() => ({ number: 42, host: 'github.com', owner: 'example', repo: 'app' })),+ ...overrides,+});+const testDeps = (overrides = {}) => ({+ git: gitDouble(),+ writeFile: vi.fn(async () => true),+ buildQualitySnapshot: vi.fn(async () => snapshot()),+ mkdtemp: vi.fn(async () => worktreePath),+ rm: vi.fn(async () => {}),+ addWorktree: vi.fn(async () => true),+ queuePendingMerge: vi.fn(async () => true),+ probePrForBranch: vi.fn(async () => ({ prState: null, prUrl: null, prNumber: null, readable: true })),+ ...overrides,+});let log;-beforeEach(() => { log = vi.spyOn(console, 'log').mockImplementation(() => {}); });+beforeEach(() => {+ __resetQualitySnapshotPublishState();+ 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.+// skips that must never touch the app's live checkout 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());@@ -36,32 +69,91 @@ it('reads a committed snapshot and answers null for every unusable file', asyncexpect(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');+ expect(QUALITY_SNAPSHOT_BRANCH).toBe('portos/quality-snapshot');});-it('publishes a changed snapshot as one scoped commit and skips without touching git otherwise', async () => {+it('lands a changed snapshot on a dedicated branch PR and queues merge-on-green', async () => {const deps = testDeps();- expect(await publishAppQualitySnapshot(app, deps)).toEqual({ published: true, hash: 'abc1234', path: '.quality.json' });+ expect(await publishAppQualitySnapshot(app, deps)).toEqual({+ published: true, hash: 'abc1234', path: '.quality.json',+ prUrl, prNumber: 42, queuedMerge: true,+ });const [path, body] = deps.writeFile.mock.calls[0];- expect(path).toBe(join('/repo/example-app', '.quality.json')); // join(): Windows CI joins with backslashes+ expect(path).toBe(join(worktreePath, '.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',+ expect(deps.addWorktree).toHaveBeenCalledWith(+ ['worktree', 'add', '--no-track', '-B', 'portos/quality-snapshot', worktreePath, 'origin/main'],+ '/repo/example-app',+ );+ expect(deps.git.stageFiles).toHaveBeenCalledWith(worktreePath, ['.quality.json']);+ expect(deps.git.commit).toHaveBeenCalledWith(worktreePath,'chore: publish PortOS quality snapshot (1 measurements)', { paths: ['.quality.json'] });- expect(log).toHaveBeenCalledWith('📊 Published quality snapshot for app example-id: 1 measurements → abc1234');+ expect(deps.git.execGit).toHaveBeenCalledWith(+ ['push', '-u', 'origin', 'HEAD:refs/heads/portos/quality-snapshot'], worktreePath);+ expect(deps.git.createPR).toHaveBeenCalledWith(worktreePath, expect.objectContaining({+ title: 'chore: publish quality snapshot',+ base: 'main',+ head: 'portos/quality-snapshot',+ }));+ expect(deps.git.createPR.mock.calls[0][1].body).toContain('no code review required');+ expect(deps.queuePendingMerge).toHaveBeenCalledWith('example-id', expect.objectContaining({+ prUrl, prNumber: 42, prBranch: 'portos/quality-snapshot',+ sourceTask: expect.objectContaining({ metadata: { app: 'example-id' } }),+ }));+ expect(log).toHaveBeenCalledWith(`📊 Published quality snapshot for app example-id: 1 measurements → abc1234 (${prUrl})`);+ expect(deps.git.execGit).toHaveBeenCalledWith(+ ['worktree', 'remove', '--force', worktreePath], '/repo/example-app', { ignoreExitCode: true });- // 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' });+ const unchanged = testDeps();+ 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();+ expect(unchanged.addWorktree).not.toHaveBeenCalled();+ expect(unchanged.git.createPR).not.toHaveBeenCalled();+});++it('skips when origin already has the snapshot and does not write the live checkout', async () => {+ const body = serialized(snapshot());+ const deps = testDeps({+ git: gitDouble({+ execGit: vi.fn(async (args) => args[0] === 'show' && String(args[1]).startsWith('origin/main:')+ ? { exitCode: 0, stdout: body, stderr: '' }+ : missingShow),+ }),+ });+ expect(await publishAppQualitySnapshot(app, deps)).toEqual({+ published: false, reason: 'no-changes', path: '.quality.json',+ });+ expect(deps.writeFile).not.toHaveBeenCalled();+ expect(deps.addWorktree).not.toHaveBeenCalled();+ expect(deps.git.stageFiles).not.toHaveBeenCalled();+});++it('re-queues an already-open snapshot PR whose branch already has the same bytes', async () => {+ const body = serialized(snapshot());+ const deps = testDeps({+ git: gitDouble({+ execGit: vi.fn(async (args) => args[0] === 'show' && String(args[1]).includes(QUALITY_SNAPSHOT_BRANCH)+ ? { exitCode: 0, stdout: body, stderr: '' }+ : missingShow),+ }),+ probePrForBranch: vi.fn(async () => ({+ prState: 'OPEN', prUrl, prNumber: 42, cli: 'gh', readable: true,+ })),+ });+ expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({+ published: true, prUrl, prNumber: 42, queuedMerge: true,+ });+ expect(deps.writeFile).not.toHaveBeenCalled();+ expect(deps.addWorktree).not.toHaveBeenCalled();+ expect(deps.queuePendingMerge).toHaveBeenCalledWith('example-id', expect.objectContaining({ prNumber: 42 }));});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()) });+ const empty = testDeps({ buildQualitySnapshot: async () => snapshot(0) });expect(await publishAppQualitySnapshot(app, empty)).toEqual({ published: false, reason: 'no-evidence', path: '.quality.json' });expect(empty.writeFile).not.toHaveBeenCalled();@@ -77,40 +169,93 @@ it('never overwrites an existing snapshot with an empty or unreachable one', asyexpect(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');++ const noRemote = testDeps({ git: { ...gitDouble(), getRemote: async () => ({}) } });+ expect(await publishAppQualitySnapshot(app, noRemote)).toEqual({ published: false, reason: 'no-remote', path: '.quality.json' });+ expect(noRemote.git.fetchOrigin).not.toHaveBeenCalled();});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,+ const deps = testDeps({+ git: gitDouble({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; },- };+ }),+ addWorktree: async () => { calls.push('worktree'); return true; },+ writeFile: async () => { calls.push('write'); },+ });const first = publishAppQualitySnapshot(app, deps);const second = publishAppQualitySnapshot(app, deps);releaseCommit();- expect(await first).toMatchObject({ published: true, hash: 'abc1234' });+ expect(await first).toMatchObject({ published: true, hash: 'abc1234', prUrl });expect(await second).toMatchObject({ published: false, reason: 'no-changes' });- expect(calls).toEqual(['isRepo', 'read', 'write', 'stage', 'commit-start', 'commit-end', 'isRepo', 'read']);+ expect(calls).toEqual(['worktree', 'write', 'commit-start', 'commit-end']);});-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'); }) } });+it('unstages the file and rethrows when the commit fails, so no stray path sits in the worktree 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']);+ expect(deps.git.unstageFiles).toHaveBeenCalledWith(worktreePath, ['.quality.json']);+ expect(deps.git.createPR).not.toHaveBeenCalled();- // 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 });+ expect(await publishAppQualitySnapshot(app, next)).toMatchObject({ published: true, prUrl });+});++it('force-with-lease updates an existing snapshot branch rather than committing on the live checkout', async () => {+ const deps = testDeps({+ git: gitDouble({+ execGit: vi.fn(async (args) => {+ if (args[0] === 'show') return missingShow;+ if (args[0] === 'rev-parse' && args[1] === `origin/${QUALITY_SNAPSHOT_BRANCH}`) {+ return { exitCode: 0, stdout: 'aa'.repeat(20), stderr: '' };+ }+ return { exitCode: 0, stdout: '', stderr: '' };+ }),+ }),+ });+ expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ published: true, prUrl });+ expect(deps.git.execGit).toHaveBeenCalledWith([+ 'push',+ `--force-with-lease=refs/heads/${QUALITY_SNAPSHOT_BRANCH}:${'aa'.repeat(20)}`,+ 'origin',+ `HEAD:refs/heads/${QUALITY_SNAPSHOT_BRANCH}`,+ ], worktreePath);+ expect(deps.writeFile.mock.calls[0][0]).toBe(join(worktreePath, '.quality.json'));+});++it('adopts an already-open PR when createPR reports a conflict and still queues the merge', async () => {+ const deps = testDeps({+ git: gitDouble({+ createPR: vi.fn(async () => ({ success: false, error: 'a pull request already exists' })),+ }),+ probePrForBranch: vi.fn(async () => ({+ prState: 'OPEN', prUrl, prNumber: 42, cli: 'gh', readable: true,+ })),+ });+ expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({+ published: true, prUrl, prNumber: 42, queuedMerge: true,+ });+ expect(deps.queuePendingMerge).toHaveBeenCalled();+});++it('enables GitLab auto-merge instead of the GitHub pending-merge queue', async () => {+ const execGlab = vi.fn(async () => '');+ const deps = testDeps({+ git: gitDouble({+ createPR: vi.fn(async () => ({ success: true, url: 'https://gitlab.com/example/app/-/merge_requests/7', cli: 'glab' })),+ parsePullRequestUrl: vi.fn(() => ({ number: 7, host: 'gitlab.com', owner: 'example', repo: 'app' })),+ }),+ execGlab,+ });+ expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({+ published: true, prNumber: 7, queuedMerge: true,+ });+ expect(deps.queuePendingMerge).not.toHaveBeenCalled();+ expect(execGlab).toHaveBeenCalledWith(+ ['mr', 'merge', '7', '--yes', '--auto-merge'],+ '/repo/example-app', undefined, { rejectOnError: true },+ );});