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: merge quality snapshot PRs immediately without waiting for CI

[._.]/ Adam Eivyc3a33cb33053
diff --git a/AGENTS.md b/AGENTS.md
index 4f559d9b99..657dcd4f57 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -208,7 +208,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` through a merge-on-green pull request; 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 an immediately-merged 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.jsx
index 294b10a4f8..157366b2cc 100644
--- a/client/src/components/apps/AppQuality.jsx
+++ b/client/src/components/apps/AppQuality.jsx
@@ -32,7 +32,7 @@ export default function AppQuality({ app, detail = false }) {
if (result?.failure) return toast.error(result.failure.message || 'Could not publish the quality snapshot');
if (result?.published) {
return toast.success(result.prUrl
- ? 'Quality snapshot pull request opened; it will merge when CI is green'
+ ? 'Quality snapshot pull request opened; it merges immediately'
: '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.jsx
index 746ad93e34..855aaa37f3 100644
--- a/client/src/components/apps/AppQuality.test.jsx
+++ b/client/src/components/apps/AppQuality.test.jsx
@@ -130,7 +130,7 @@ describe('AppQuality snapshot publishing', () => {
await waitFor(() => expect(publishAppQualitySnapshot).toHaveBeenCalledWith('example'));
await waitFor(() => expect(toast.success).toHaveBeenCalledWith(
- 'Quality snapshot pull request opened; it will merge when CI is green'));
+ 'Quality snapshot pull request opened; it merges immediately'));
});
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.jsx
index bc0aeac3ae..2e83d14db5 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, opens a pull request, and merges it when CI is green so the live checkout never diverges from origin. Off by default.
+ After each audit, PortOS writes the app’s numeric quality scores to .quality.json, opens a pull request, and merges it immediately 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.js
index ad61b0ad7b..8b91bf1893 100644
--- a/client/src/services/apiApps.js
+++ b/client/src/services/apiApps.js
@@ -12,8 +12,8 @@ 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 });
-// 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
+// Land the app's numeric quality scores as `.quality.json` through an
+// immediately-merged 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.
diff --git a/docs/API.md b/docs/API.md
index c17b5fb57c..e06252ee78 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -101,7 +101,7 @@ legacy list for local Apps/Dashboard views.
| GET | `/apps/:id/status` | Get PM2 status |
| GET | `/apps/:id/logs` | Get recent logs |
| POST | `/apps/:id/refresh-config` | Re-parse ecosystem config |
-| POST | `/apps/:id/quality-snapshot` | Rebuild the app's numeric quality snapshot and land canonical schema v2 `.quality.json` through a merge-on-green pull request on `portos/quality-snapshot` (scoped to that one path; the live checkout is not committed). The file is not the peer wire payload (`PORTOS_SCHEMA_VERSIONS.appQuality` stays 1). A v1 file is rewritten when current evidence exists. Answers `{ success, published, path }` plus the commit `hash`, `prUrl`, and `prNumber`, or a `reason` of `no-repo-path` / `not-a-repo` / `no-evidence` / `no-changes` / `no-remote` / `no-default-branch` / `pr-failed` / `unsupported-format` / `invalid-evidence` when nothing was written. `unsupported-format` means a future, unrecognized, malformed, or oversize file was left in place. Not gated on the app's `publishQualitySnapshot` toggle — that toggle only automates the same publish after each audit. Any app's committed `.quality.json` (or a historical `quality-snapshot.json` when `.quality.json` is absent) is read back as a "Release snapshot" quality source, PortOS's own checkout included (`npm run quality:snapshot` is the same publish, run from the release step; `npm run quality:snapshot -- --migrate` converts an old file without reading the database). |
+| POST | `/apps/:id/quality-snapshot` | Rebuild the app's numeric quality snapshot and land canonical schema v2 `.quality.json` through an immediately-merged pull request on `portos/quality-snapshot` (scoped to that one path; the live checkout is not committed). The file is not the peer wire payload (`PORTOS_SCHEMA_VERSIONS.appQuality` stays 1). A v1 file is rewritten when current evidence exists. Answers `{ success, published, path }` plus the commit `hash`, `prUrl`, and `prNumber`, or a `reason` of `no-repo-path` / `not-a-repo` / `no-evidence` / `no-changes` / `no-remote` / `no-default-branch` / `pr-failed` / `unsupported-format` / `invalid-evidence` when nothing was written. `unsupported-format` means a future, unrecognized, malformed, or oversize file was left in place. Not gated on the app's `publishQualitySnapshot` toggle — that toggle only automates the same publish after each audit. Any app's committed `.quality.json` (or a historical `quality-snapshot.json` when `.quality.json` is absent) is read back as a "Release snapshot" quality source, PortOS's own checkout included (`npm run quality:snapshot` is the same publish, run from the release step; `npm run quality:snapshot -- --migrate` converts an old file without reading the database). |
| GET | `/apps/:id/quality-schedule` | The Quality tab's weekly-schedule form: every audit check with its applicability verdict and reason, the repository shapes that verdict came from, the cron expressions already occupied on this app, and the plan the shipped defaults produce. Read-only — no LLM call, no write. |
| POST | `/apps/:id/quality-schedule/preview` | Re-plan for an edited form (selection, per-check delivery mode, checks per day, hour window, claim-drain task and offset). Still read-only; a POST only because the option bag carries a per-check map. |
| POST | `/apps/:id/quality-schedule/apply` | Persist the plan as ordinary per-app task-type overrides: the selected checks enabled with their weekly cron and `fileIssues` mode, the audit types left out disabled with their interval cleared, and — when at least one selected check files issues — one daily cron for the issue-claim drain (one an earlier plan planted is retired when it is switched off or replaced). Other task types are untouched. |
diff --git a/docs/features/app-quality.md b/docs/features/app-quality.md
index a366cafdf5..68d17d9588 100644
--- a/docs/features/app-quality.md
+++ b/docs/features/app-quality.md
@@ -98,7 +98,7 @@ A managed app can publish its recent numeric scores into `.quality.json` at the
repository root. The file is a bounded projection, not the audit history:
PostgreSQL keeps every measurement, and the file keeps one row per UTC day and
category for the same 30-day window the quality panel uses, capped at 4 MiB.
-Publish opens a merge-on-green pull request on `portos/quality-snapshot` and
+Publish opens an immediately-merged pull request on `portos/quality-snapshot` and
does not commit the live checkout. With no local evidence, a non-empty file is
left as it is.
diff --git a/scripts/publish-quality-snapshot.js b/scripts/publish-quality-snapshot.js
index c1989f22f5..8f8574f7ab 100644
--- a/scripts/publish-quality-snapshot.js
+++ b/scripts/publish-quality-snapshot.js
@@ -4,7 +4,7 @@
* 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. The publisher opens
- * a merge-on-green pull request rather than committing on the live checkout.
+ * a pull request and merges it immediately rather than committing on the live checkout.
*
* `--migrate` rewrites a v1 file, or a historical `quality-snapshot.json`, to
* canonical schema v2 using only the rows already in the file. It does not read
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 6fe62a82b2..de9fb5a0bf 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 = land a `.quality.json` quality snapshot through a merge-on-green PR after each audit.
+ // Unset/false = off (default); true = land a `.quality.json` quality snapshot through an immediately-merged 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.js
index 6fc835e4a6..a7df43f962 100644
--- a/server/routes/apps/crud.js
+++ b/server/routes/apps/crud.js
@@ -75,7 +75,7 @@ router.get('/:id/quality-history', loadApp, asyncHandler(async (req, res) => {
}));
// 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
+// `.quality.json` through an immediately-merged 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) => {
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index 55bcc933d4..400b16ecbd 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -1692,8 +1692,8 @@ async function recoverBareSentinelPayload(contents, taskType) {
/**
* Opt-in only: an app with `publishQualitySnapshot` gets its freshly recorded
- * measurement landed as the repo's `.quality.json` through a merge-on-green
- * pull request. This is a completion boundary outside the Express request
+ * measurement landed as the repo's `.quality.json` through an
+ * immediately-merged 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.
*/
diff --git a/server/services/appQualitySnapshotFile.js b/server/services/appQualitySnapshotFile.js
index bfcabea08d..d784d33966 100644
--- a/server/services/appQualitySnapshotFile.js
+++ b/server/services/appQualitySnapshotFile.js
@@ -11,9 +11,12 @@
* 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 on a dedicated branch,
- * and lands it through a merge-on-green pull request so the live checkout never
+ * and merges its pull request immediately so the live checkout never
* diverges from origin and repos that block pushes to the default branch still
- * receive the file. Reads never write. A v1 file or historical
+ * receive the file. The snapshot is numeric data only and cannot affect tests,
+ * so there is no reason to wait for CI; when branch protection still refuses
+ * the immediate merge the publisher falls back to the merge-on-green queue.
+ * Reads never write. A v1 file or historical
* `quality-snapshot.json` is explicit legacy input.
*/
import { join } from 'node:path';
@@ -39,7 +42,7 @@ Update the repository \`.quality.json\` numeric quality snapshot generated by Po
## Test plan
- Generated numeric measurements only; no application code changes
-- Merge when required CI is green; no code review required
+- Data-only change, safe to merge immediately without waiting for CI; no code review required
`;
async function readSnapshotEntry(repoPath, filename, deps = {}) {
@@ -123,7 +126,7 @@ function enqueue(repoPath, task) {
/**
* Rebuild the app's numeric snapshot and land it as canonical v2 `.quality.json`
- * through a merge-on-green pull request. An empty snapshot never overwrites a
+ * through an immediately-merged pull request. An empty snapshot never overwrites a
* populated file. A v1 file is rewritten when current evidence exists. An
* already-canonical v2 snapshot with the same records never reaches git.
*/
@@ -274,13 +277,14 @@ async function reuseOpenSnapshotPr(app, git, defaultBranch, deps) {
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, {
+ const outcome = await mergeSnapshotPr(app, {
url: found.prUrl, number: found.prNumber, cli: found.cli,
- }, deps);
+ }, deps, git);
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,
+ prUrl: found.prUrl, prNumber: found.prNumber,
+ merged: outcome.merged === true, queuedMerge: outcome.queued === true,
};
}
return landExistingBranchPr(app, git, defaultBranch, deps);
@@ -291,11 +295,12 @@ async function landExistingBranchPr(app, git, defaultBranch, deps) {
if (!created?.url) {
return skipped(app, 'pr-failed');
}
- const queued = await queueMergeWhenGreen(app, created, deps);
+ const outcome = await mergeSnapshotPr(app, created, deps, git);
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,
+ prUrl: created.url, prNumber: created.number,
+ merged: outcome.merged === true, queuedMerge: outcome.queued === true,
};
}
@@ -338,11 +343,12 @@ async function landSnapshotPr(app, { body, count, defaultBranch, git, deps, mess
if (!pr?.url) {
throw new Error(pr?.error || 'quality snapshot pull request was not created');
}
- const queued = await queueMergeWhenGreen(app, pr, deps);
+ const queued = await mergeSnapshotPr(app, pr, deps, git);
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,
+ prUrl: pr.url, prNumber: pr.number,
+ merged: queued.merged === true, queuedMerge: queued.queued === true,
};
};
@@ -404,7 +410,52 @@ function decoratePr(git, created) {
};
}
-async function queueMergeWhenGreen(app, pr, deps) {
+/**
+ * Merge a quality snapshot PR immediately: the change is numeric data only and
+ * cannot affect tests, so there is no reason to wait for CI. When branch
+ * protection still refuses the immediate merge, fall back to the merge-on-green
+ * queue (GitHub) or pipeline auto-merge (GitLab) so the PR still lands.
+ *
+ * @returns {{merged: boolean, queued: boolean}} — exactly one is true on success.
+ */
+async function mergeSnapshotPr(app, pr, deps, git) {
+ if (!pr?.url || !pr?.number) return { merged: false, queued: false };
+ if (await tryImmediateMerge(app, pr, deps, git)) return { merged: true, queued: false };
+ const queued = await queueMergeWhenGreenFallback(app, pr, deps);
+ return { merged: false, queued: queued === true };
+}
+
+async function tryImmediateMerge(app, pr, deps, git) {
+ 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);
+ // Immediate merge: explicitly NOT waiting for the pipeline.
+ let result = await run(['mr', 'merge', String(pr.number), '--yes', '--when-pipeline-succeeds=false']);
+ if (result !== true && /unknown flag|unknown shorthand/i.test(result?.message || '')) {
+ result = await run(['mr', 'merge', String(pr.number), '--yes']);
+ }
+ if (result !== true) {
+ console.log(`📊 Quality snapshot MR #${pr.number} immediate merge unavailable for app ${app.id}: ${result?.message || 'merge refused'}`);
+ return false;
+ }
+ console.log(`📊 Quality snapshot MR #${pr.number} merged immediately for app ${app.id}`);
+ return true;
+ }
+ const mergePR = deps.mergePR || git?.mergePR;
+ if (typeof mergePR !== 'function') return false;
+ const result = await mergePR.call(git || null,
+ app.repoPath, pr.number, { forgeAccount: app?.forgeAccount || null },
+ ).catch(err => ({ success: false, error: err?.message }));
+ if (result?.success !== true) {
+ console.log(`📊 Quality snapshot PR #${pr.number} immediate merge unavailable for app ${app.id}: ${result?.error || 'merge refused'}`);
+ return false;
+ }
+ console.log(`📊 Quality snapshot PR #${pr.number} merged immediately for app ${app.id}`);
+ return true;
+}
+
+async function queueMergeWhenGreenFallback(app, pr, deps) {
if (!pr?.url || !pr?.number) return false;
if (pr.cli === 'glab') {
const execGlab = deps.execGlab || (await import('./gitlab.js')).execGlab;
diff --git a/server/services/appQualitySnapshotFile.test.js b/server/services/appQualitySnapshotFile.test.js
index 61416ce235..c4eef358d4 100644
--- a/server/services/appQualitySnapshotFile.test.js
+++ b/server/services/appQualitySnapshotFile.test.js
@@ -40,6 +40,7 @@ const gitDouble = (overrides = {}) => ({
unstageFiles: vi.fn(async () => true),
commit: vi.fn(async () => ({ hash: 'abc1234', message: 'commit' })),
createPR: vi.fn(async () => ({ success: true, url: prUrl, cli: 'gh' })),
+ mergePR: vi.fn(async () => ({ success: true })),
parsePullRequestUrl: vi.fn(() => ({ number: 42, host: 'github.com', owner: 'example', repo: 'app' })),
...overrides,
});
@@ -81,7 +82,7 @@ it('lands a changed snapshot from a detached worktree so the PR branch stays att
const deps = testDeps();
expect(await publishAppQualitySnapshot(app, deps)).toEqual({
published: true, hash: 'abc1234', path: '.quality.json',
- prUrl, prNumber: 42, queuedMerge: true,
+ prUrl, prNumber: 42, merged: true, queuedMerge: false,
});
const [path, body] = deps.writeFile.mock.calls[0];
expect(path).toBe(join(worktreePath, '.quality.json'));
@@ -110,10 +111,11 @@ it('lands a changed snapshot from a detached worktree so the PR branch stays att
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(deps.git.createPR.mock.calls[0][1].body).toContain('without waiting for CI');
+ expect(deps.git.mergePR).toHaveBeenCalledWith('/repo/example-app', 42, expect.objectContaining({
+ forgeAccount: null,
}));
+ expect(deps.queuePendingMerge).not.toHaveBeenCalled();
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 });
@@ -144,7 +146,7 @@ it('skips when origin already has the snapshot and does not write the live check
expect(deps.git.stageFiles).not.toHaveBeenCalled();
});
-it('re-queues an already-open snapshot PR whose branch already has the same bytes', async () => {
+it('merges an already-open snapshot PR whose branch already has the same bytes without waiting for CI', async () => {
const body = canonical();
const deps = testDeps({
git: gitDouble({
@@ -157,10 +159,32 @@ it('re-queues an already-open snapshot PR whose branch already has the same byte
})),
});
expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({
- published: true, prUrl, prNumber: 42, queuedMerge: true,
+ published: true, prUrl, prNumber: 42, merged: true, queuedMerge: false,
});
expect(deps.writeFile).not.toHaveBeenCalled();
expect(deps.addWorktree).not.toHaveBeenCalled();
+ expect(deps.git.mergePR).toHaveBeenCalledWith('/repo/example-app', 42, expect.objectContaining({
+ forgeAccount: null,
+ }));
+ expect(deps.queuePendingMerge).not.toHaveBeenCalled();
+});
+
+it('falls back to the merge-on-green queue when branch protection refuses the immediate merge', async () => {
+ const body = canonical();
+ 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),
+ mergePR: vi.fn(async () => ({ success: false, error: 'required status checks' })),
+ }),
+ probePrForBranch: vi.fn(async () => ({
+ prState: 'OPEN', prUrl, prNumber: 42, cli: 'gh', readable: true,
+ })),
+ });
+ expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({
+ published: true, prUrl, prNumber: 42, merged: false, queuedMerge: true,
+ });
expect(deps.queuePendingMerge).toHaveBeenCalledWith('example-id', expect.objectContaining({ prNumber: 42 }));
});
@@ -238,7 +262,7 @@ it('force-with-lease updates an existing snapshot branch rather than committing
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 () => {
+it('adopts an already-open PR when createPR reports a conflict and merges it immediately', async () => {
const deps = testDeps({
git: gitDouble({
createPR: vi.fn(async () => ({ success: false, error: 'a pull request already exists' })),
@@ -248,12 +272,13 @@ it('adopts an already-open PR when createPR reports a conflict and still queues
})),
});
expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({
- published: true, prUrl, prNumber: 42, queuedMerge: true,
+ published: true, prUrl, prNumber: 42, merged: true, queuedMerge: false,
});
- expect(deps.queuePendingMerge).toHaveBeenCalled();
+ expect(deps.git.mergePR).toHaveBeenCalled();
+ expect(deps.queuePendingMerge).not.toHaveBeenCalled();
});
-it('enables GitLab auto-merge instead of the GitHub pending-merge queue', async () => {
+it('merges a GitLab MR immediately instead of arming pipeline auto-merge', async () => {
const execGlab = vi.fn(async () => '');
const deps = testDeps({
git: gitDouble({
@@ -263,9 +288,33 @@ it('enables GitLab auto-merge instead of the GitHub pending-merge queue', async
execGlab,
});
expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({
- published: true, prNumber: 7, queuedMerge: true,
+ published: true, prNumber: 7, merged: true, queuedMerge: false,
});
expect(deps.queuePendingMerge).not.toHaveBeenCalled();
+ expect(execGlab).toHaveBeenCalledWith(
+ ['mr', 'merge', '7', '--yes', '--when-pipeline-succeeds=false'],
+ '/repo/example-app', undefined, { rejectOnError: true },
+ );
+});
+
+it('falls back to GitLab auto-merge when the immediate merge is refused', async () => {
+ const execGlab = vi.fn()
+ .mockRejectedValueOnce(new Error('pipeline must succeed'))
+ .mockResolvedValueOnce('');
+ 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, merged: false, queuedMerge: true,
+ });
+ expect(execGlab).toHaveBeenCalledWith(
+ ['mr', 'merge', '7', '--yes', '--when-pipeline-succeeds=false'],
+ '/repo/example-app', undefined, { rejectOnError: true },
+ );
expect(execGlab).toHaveBeenCalledWith(
['mr', 'merge', '7', '--yes', '--auto-merge'],
'/repo/example-app', undefined, { rejectOnError: true },