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

address review (codex): make PR verification forge-aware, and stop gating non-GitHub repos on gh (#3358)

[._.]/ Adam Eivyb9a202a86c84
diff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.js
index 272a14cca7..a01f72ea62 100644
--- a/server/services/agentCompletionCleanup.js
+++ b/server/services/agentCompletionCleanup.js
@@ -318,10 +318,14 @@ export async function runAgentCompletionCleanup({ agentId, task, agent, effectiv
// `leanMode` are persisted on the agent record for this; a pre-upgrade record
// carries neither, and a blank command reads as `claude` — which is what the
// old id allowlist effectively assumed for the claude-code ids anyway.
+ // Read off the PERSISTED record first (#3358): the in-memory `runnerAgents`
+ // entry carries only `providerId`, so a lean `--bare` or path-configured
+ // provider would be misjudged here — and finalizeAgent's PR verification
+ // keys on the same question, so the two must resolve it identically.
const agentOwnsPR = taskOpenPR && canTypeSlashCommands({
- providerId: agent.providerId,
- providerCommand: agent.providerCommand,
- leanMode: agent.leanMode === true,
+ providerId: agentState?.metadata?.providerId ?? agent.providerId,
+ providerCommand: agentState?.metadata?.providerCommand ?? agent.providerCommand ?? null,
+ leanMode: (agentState?.metadata?.leanMode ?? agent.leanMode) === true,
});
// Merge per-task reviewer metadata with the user's Code Review Defaults
// (AI Providers → Code Review Defaults panel). Settings I/O is cached
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index adb4fe04f9..6c7c805f63 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -219,6 +219,10 @@ async function resolveWorkspaceBranch(workspacePath) {
* `cleanupAgentWorktree` AFTER finalize, so checking here would report every
* correct run as missing.
*
+ * Forge-aware: a GitLab repo is asked via `glab mr list`, mirroring the `gh`/
+ * `glab` split `createPR` already makes. Asking `gh` about a GitLab remote
+ * would fail and record every correct MR run as `forge-unreachable`.
+ *
* Three outcomes, never collapsed:
* - `ok: true` — a PR exists, or there was nothing to check
* - `ok: false, category: 'pr-missing'` — the forge answered: no PR
@@ -236,22 +240,28 @@ export async function verifyPrClaim({ task, workspacePath, success, prExpected }
// verified — say nothing rather than invent a failure.
return { ok: true, branch: null };
}
- const { findPullRequestForBranch } = await import('./github.js');
- const found = await findPullRequestForBranch(branch, { cwd: workspacePath });
+
+ const { resolveForgeForRepo } = await import('./git.js');
+ const { cli } = await resolveForgeForRepo(workspacePath).catch(() => ({ cli: 'gh' }));
+ const found = cli === 'glab'
+ ? await (await import('./gitlab.js')).findMergeRequestForBranch(branch, workspacePath)
+ : await (await import('./github.js')).findPullRequestForBranch(branch, { cwd: workspacePath });
+
+ const noun = cli === 'glab' ? 'merge request' : 'pull request';
if (found.status === 'found') return { ok: true, branch };
if (found.status === 'none') {
return {
ok: false,
branch,
category: PR_MISSING_CATEGORY,
- message: `Agent reported success but no pull request exists for branch ${branch}`
+ message: `Agent reported success but no ${noun} exists for branch ${branch}`
};
}
return {
ok: false,
branch,
category: FORGE_UNREACHABLE_CATEGORY,
- message: `Could not confirm a pull request for branch ${branch} — the forge is unreachable${found.detail ? ` (${String(found.detail).split('\n')[0].slice(0, 120)})` : ''}`
+ message: `Could not confirm a ${noun} for branch ${branch} — the forge is unreachable${found.detail ? ` (${String(found.detail).split('\n')[0].slice(0, 120)})` : ''}`
};
}
@@ -267,8 +277,8 @@ function prVerificationAnalysis(verdict) {
message: verdict.message,
actionable: false,
suggestedFix: verdict.category === PR_MISSING_CATEGORY
- ? `The branch ${verdict.branch} is pushed but has no pull request. Re-run the task, or open the PR by hand with \`gh pr create --head ${verdict.branch}\`.`
- : 'Check the forge probe on the System Health page — `gh` could not reach the forge, so the run\'s PR could not be confirmed.'
+ ? `The branch ${verdict.branch} is pushed but has no open change request. Re-run the task, or open it by hand (\`gh pr create --head ${verdict.branch}\` / \`glab mr create --source-branch ${verdict.branch}\`).`
+ : 'Check the forge probe on the System Health page — the forge CLI could not reach the forge, so the run\'s change request could not be confirmed.'
};
}
diff --git a/server/services/agentFinalization.prVerification.test.js b/server/services/agentFinalization.prVerification.test.js
index e2f60b7b4d..8274c95c9f 100644
--- a/server/services/agentFinalization.prVerification.test.js
+++ b/server/services/agentFinalization.prVerification.test.js
@@ -22,6 +22,16 @@ vi.mock('./github.js', () => ({
ensureForgeReachable: vi.fn(async () => ({ ok: true, status: 'ok' })),
}));
+const findMergeRequestForBranchMock = vi.fn();
+vi.mock('./gitlab.js', () => ({
+ findMergeRequestForBranch: (...args) => findMergeRequestForBranchMock(...args),
+}));
+
+const resolveForgeForRepoMock = vi.fn(async () => ({ cli: 'gh' }));
+vi.mock('./git.js', () => ({
+ resolveForgeForRepo: (...args) => resolveForgeForRepoMock(...args),
+}));
+
vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));
const completeAgentMock = vi.fn();
@@ -88,6 +98,8 @@ beforeEach(() => {
vi.clearAllMocks();
execGitMock.mockResolvedValue({ stdout: 'claim/issue-1\n', stderr: '', exitCode: 0 });
findPullRequestForBranchMock.mockResolvedValue({ status: 'found', number: 7, url: 'https://example.com/pr/7' });
+ findMergeRequestForBranchMock.mockResolvedValue({ status: 'found', number: 12, url: 'https://example.com/mr/12' });
+ resolveForgeForRepoMock.mockResolvedValue({ cli: 'gh' });
});
describe('verifyPrClaim (#3358)', () => {
@@ -120,6 +132,24 @@ describe('verifyPrClaim (#3358)', () => {
expect(verdict.category).not.toBe(PR_MISSING_CATEGORY);
});
+ it('asks glab on a GitLab repo — asking gh there would fail every correct MR run', async () => {
+ onBranch('claim/issue-1');
+ resolveForgeForRepoMock.mockResolvedValue({ cli: 'glab' });
+ const verdict = await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true });
+ expect(verdict.ok).toBe(true);
+ expect(findMergeRequestForBranchMock).toHaveBeenCalledWith('claim/issue-1', '/w');
+ expect(findPullRequestForBranchMock).not.toHaveBeenCalled();
+ });
+
+ it('names the GitLab noun when an MR is missing', async () => {
+ onBranch('claim/issue-1');
+ resolveForgeForRepoMock.mockResolvedValue({ cli: 'glab' });
+ findMergeRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });
+ const verdict = await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true });
+ expect(verdict.category).toBe(PR_MISSING_CATEGORY);
+ expect(verdict.message).toMatch(/merge request/);
+ });
+
it('does not check when PortOS (not the agent) owns PR creation', async () => {
// The PR is created by cleanupAgentWorktree AFTER finalize, so a check here
// would report every correct slashdo-free TUI / runner-mode run as missing.
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index aa67f5bf73..daec0f8fd3 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -27,7 +27,7 @@ import { readFile, writeFile } from 'fs/promises';
import { existsSync } from 'fs';
import { cosEvents, emitLog } from './cosEvents.js';
import { registerAgent, updateAgent, completeAgent } from './cosAgents.js';
-import { getConfig, updateTask, getTaskById } from './cos.js';
+import { getConfig, updateTask, getTaskById, getAgent as getAgentRecord } from './cos.js';
import { spawnAgentViaRunner, getRunnerHealth } from './cosRunnerClient.js';
import { MAX_TOTAL_SPAWNS, normalizeReviewers } from '../lib/validation.js';
import { isInternalTaskId } from '../lib/taskParser.js';
@@ -898,10 +898,18 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration
// the run that was told to open its own PR is exactly the run we check for
// one. When PortOS owns it the PR is created by that cleanup, i.e. AFTER
// finalize, so verifying here would fail every correct run.
+ //
+ // Read off the PERSISTED record, not the in-memory `runnerAgents` entry: the
+ // entry carries only `providerId` (and a post-restart survivor recovered by
+ // syncRunnerAgents carries even less), so a lean `--bare` runner agent would
+ // read as slashdo-capable — and be downgraded for not opening a PR PortOS
+ // was about to open for it. registerAgent writes both fields into metadata
+ // precisely so this question survives a restart.
+ const persistedAgent = await getAgentRecord(agentId).catch(() => null);
const runnerAgentOwnsPR = isTruthyMeta(task?.metadata?.openPR) && canTypeSlashCommands({
- providerId: agent.providerId,
- providerCommand: agent.providerCommand,
- leanMode: agent.leanMode === true,
+ providerId: persistedAgent?.metadata?.providerId ?? agent.providerId,
+ providerCommand: persistedAgent?.metadata?.providerCommand ?? null,
+ leanMode: persistedAgent?.metadata?.leanMode === true,
});
// Extract pipeline output summary before completion writes metadata to disk
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index 88be8a0e90..d53b3173fd 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -499,16 +499,22 @@ export async function cleanupMerged(repoPath, defaultBranch, merged, { activeAge
* and the caller must retry rather than park on it (#3358).
*/
export async function reconcile(repoPath = PATHS.root, { cleanup = true, activeAgentIds = new Set() } = {}) {
- // Every classification below depends on PR state, so an unreadable forge makes
- // the whole pass a guess. Skip with one line rather than report a quiet repo.
- // Probed against THIS repo's API host (enterprise-correct) — a bare probe
- // would gate an enterprise checkout on github.com's health. A non-GitHub
- // origin has no host to probe and falls through to gh's default, which is the
- // pre-existing behavior for the `new Map()` no-PR-state path below.
+ // On a GitHub repo every classification below depends on PR state, so an
+ // unreadable forge makes the whole pass a guess — skip with one line rather
+ // than report a quiet repo. Probed against THIS repo's API host
+ // (enterprise-correct): a bare probe would gate an enterprise checkout on
+ // github.com's health.
+ //
+ // A NON-GitHub repo (GitLab, no origin) is deliberately not gated: it has no
+ // `gh` PR state to lose — `getOpenPrsByHead` returns an empty Map by design —
+ // and gating it on a `gh` probe that will never pass would permanently block
+ // the git-only merged-branch cleanup those repos still benefit from.
const origin = await getOriginInfo(repoPath).catch(() => null);
- const forge = await ensureForgeReachable('branch-reconcile', { hostname: githubApiHost(origin?.host) });
- if (!forge.ok) {
- return { defaultBranch: null, cleaned: [], inFlight: [], wip: [], skipped: [], forgeUnavailable: true, forgeStatus: forge.status };
+ if (githubRepoSpec(origin)) {
+ const forge = await ensureForgeReachable('branch-reconcile', { hostname: githubApiHost(origin.host) });
+ if (!forge.ok) {
+ return { defaultBranch: null, cleaned: [], inFlight: [], wip: [], skipped: [], forgeUnavailable: true, forgeStatus: forge.status };
+ }
}
const defaultBranch = await getDefaultBranch(repoPath).catch(() => 'main') || 'main';
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index d78c92ee63..7c9ee79a9f 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -64,6 +64,12 @@ import { getOriginInfo } from '../lib/gitRemote.js';
beforeEach(() => {
vi.clearAllMocks();
+ // clearAllMocks keeps implementations, so restore the default GitHub origin —
+ // a case that swaps in a GitLab/origin-less remote would otherwise leak into
+ // every test after it.
+ getOriginInfo.mockResolvedValue({
+ hasOrigin: true, isGithub: true, host: 'github.com', fullName: 'atomantic/PortOS'
+ });
git.getDefaultBranch.mockResolvedValue('main');
git.deleteBranch.mockResolvedValue({ branch: 'x', results: { local: 'deleted' } });
wt.forceRemoveWorktreeDir.mockResolvedValue(undefined);
@@ -493,6 +499,22 @@ describe('unreachable forge (#3358)', () => {
expect(ensureForgeReachableMock).toHaveBeenCalledWith('branch-reconcile', { hostname: 'github.acme-corp.example' });
});
+ it('does not gate a non-GitHub repo on the gh probe — it has no gh PR state to lose', async () => {
+ // A GitLab or origin-less checkout would otherwise be blocked forever from
+ // the git-only merged-branch cleanup by a probe that can never pass.
+ getOriginInfo.mockResolvedValue({ hasOrigin: true, isGithub: false, host: 'gitlab.example', fullName: 'g/p' });
+ git.getBranches.mockResolvedValue([
+ { name: 'feature/x', isDefault: false, current: false, tracking: 'origin/feature/x', merged: true }
+ ]);
+ wt.listWorktrees.mockResolvedValue([]);
+ git.isBranchMergedInto.mockResolvedValue(true);
+
+ const res = await reconcile('/repo');
+ expect(ensureForgeReachableMock).not.toHaveBeenCalled();
+ expect(res.forgeUnavailable).toBeUndefined();
+ expect(res.cleaned).toEqual(['feature/x']);
+ });
+
it('skips the whole cycle (never touches git) when the gh probe is not ok', async () => {
ensureForgeReachableMock.mockResolvedValueOnce({ ok: false, status: 'unreachable', detail: 'dial tcp' });
const res = await reconcile('/repo');
diff --git a/server/services/gitlab.js b/server/services/gitlab.js
index 907a72904d..da4282151b 100644
--- a/server/services/gitlab.js
+++ b/server/services/gitlab.js
@@ -27,3 +27,30 @@ export function execGlab(args, cwd) {
child.on('error', () => resolve(null));
});
}
+
+/**
+ * Does a merge request exist for `branch`? The GitLab mirror of
+ * `github.js#findPullRequestForBranch` (#3358), with the same three answers
+ * rather than two: `found`, `none` (glab answered, none exist), `unavailable`
+ * (we could not ask). Collapsing the last into `none` is what lets a run that
+ * opened no MR be recorded as a success.
+ *
+ * `--all` widens past glab's opened-only default: an MR that was opened and
+ * later closed still proves the agent reached the forge, which is the question.
+ *
+ * @param {string} branch - source branch name
+ * @param {string} cwd - repo root (glab resolves the project from its cwd)
+ * @returns {Promise<{ status: 'found'|'none'|'unavailable', number: number|null, url: string|null, detail: string|null }>}
+ */
+export async function findMergeRequestForBranch(branch, cwd) {
+ if (!branch || !cwd) return { status: 'unavailable', number: null, url: null, detail: 'no branch or repo path' };
+ const raw = await execGlab(['mr', 'list', '--source-branch', branch, '--all', '-P', '1', '-F', 'json'], cwd);
+ if (raw === null) return { status: 'unavailable', number: null, url: null, detail: 'glab call failed' };
+ let parsed;
+ try { parsed = JSON.parse(raw); } catch { parsed = null; }
+ // A zero-exit glab that emitted nothing parseable told us nothing.
+ if (!Array.isArray(parsed)) return { status: 'unavailable', number: null, url: null, detail: 'glab returned unparseable output' };
+ const mr = parsed[0];
+ if (!mr) return { status: 'none', number: null, url: null, detail: null };
+ return { status: 'found', number: mr.iid ?? null, url: mr.web_url || null, detail: mr.state || null };
+}
diff --git a/server/services/gitlab.test.js b/server/services/gitlab.test.js
new file mode 100644
index 0000000000..db388aa1a4
--- /dev/null
+++ b/server/services/gitlab.test.js
@@ -0,0 +1,70 @@
+/**
+ * `findMergeRequestForBranch` — the GitLab mirror of the GitHub PR lookup the
+ * agent PR-claim verification uses (#3358). Same three-state contract: asking
+ * and getting nothing must never be confused with not being able to ask.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { EventEmitter } from 'events';
+
+const spawnMock = vi.fn();
+vi.mock('child_process', () => ({ spawn: (...args) => spawnMock(...args) }));
+
+const { findMergeRequestForBranch } = await import('./gitlab.js');
+
+/** A fake `glab` child that writes `stdout` then exits with `code`. */
+const glabChild = ({ code = 0, stdout = '' } = {}) => {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ setImmediate(() => {
+ if (stdout) child.stdout.emit('data', Buffer.from(stdout));
+ child.emit('close', code);
+ });
+ return child;
+};
+
+beforeEach(() => {
+ spawnMock.mockReset();
+ spawnMock.mockImplementation(() => glabChild({ code: 0, stdout: '[]' }));
+});
+
+describe('findMergeRequestForBranch (#3358)', () => {
+ it('reports `found` with the MR iid', async () => {
+ spawnMock.mockImplementationOnce(() => glabChild({
+ stdout: '[{"iid":12,"web_url":"https://gitlab.example/g/p/-/merge_requests/12","state":"opened"}]'
+ }));
+ await expect(findMergeRequestForBranch('claim/issue-1', '/repo'))
+ .resolves.toMatchObject({ status: 'found', number: 12 });
+ });
+
+ it('queries by source branch across every state', async () => {
+ await findMergeRequestForBranch('claim/issue-1', '/repo');
+ const [, args, opts] = spawnMock.mock.calls[0];
+ expect(args).toEqual(['mr', 'list', '--source-branch', 'claim/issue-1', '--all', '-P', '1', '-F', 'json']);
+ expect(opts.cwd).toBe('/repo');
+ });
+
+ it('reports `none` for an ANSWERED empty list', async () => {
+ await expect(findMergeRequestForBranch('claim/issue-1', '/repo'))
+ .resolves.toMatchObject({ status: 'none', number: null });
+ });
+
+ it('reports `unavailable` — never `none` — when glab fails', async () => {
+ spawnMock.mockImplementationOnce(() => glabChild({ code: 1 }));
+ await expect(findMergeRequestForBranch('claim/issue-1', '/repo'))
+ .resolves.toMatchObject({ status: 'unavailable' });
+ });
+
+ it('reports `unavailable` when a zero-exit glab emits unparseable output', async () => {
+ spawnMock.mockImplementationOnce(() => glabChild({ stdout: 'not json' }));
+ await expect(findMergeRequestForBranch('claim/issue-1', '/repo'))
+ .resolves.toMatchObject({ status: 'unavailable' });
+ });
+
+ it('never spawns without a branch or a repo path', async () => {
+ await expect(findMergeRequestForBranch('', '/repo')).resolves.toMatchObject({ status: 'unavailable' });
+ await expect(findMergeRequestForBranch('b', '')).resolves.toMatchObject({ status: 'unavailable' });
+ expect(spawnMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/prWatcher.js b/server/services/prWatcher.js
index cf925e0545..4bb41ad25e 100644
--- a/server/services/prWatcher.js
+++ b/server/services/prWatcher.js
@@ -135,9 +135,14 @@ async function listOpenPullRequests(repoSpec, baseBranch) {
// otherwise throw a SyntaxError, breaking this module's "never throws"
// contract and aborting the scheduler tick (the generator calls
// checkPullRequests with no try/catch). Degrade to the pr-list-failed path.
+ // Anything that isn't an array is output we could not READ, not an empty
+ // repo — degrading it to [] would clear the watcher's lastError and record a
+ // quiet poll for a page we never parsed (#3358).
const parsed = safeJSONParse(raw, null);
- if (parsed === null) return null;
- if (!Array.isArray(parsed)) return [];
+ if (!Array.isArray(parsed)) {
+ console.error(`❌ pr-watcher: gh pr list returned unreadable output for ${repoSpec} — deferring this cycle`);
+ return null;
+ }
return parsed.map((pr) => ({
number: pr.number,
title: pr.title || '',
diff --git a/server/services/prWatcher.test.js b/server/services/prWatcher.test.js
index 9d53cea4a2..b01382ad14 100644
--- a/server/services/prWatcher.test.js
+++ b/server/services/prWatcher.test.js
@@ -354,6 +354,18 @@ describe('checkPullRequests', () => {
expect(r.reason).toBe('pr-list-failed');
});
+ it('reports pr-list-failed for a zero-exit gh that emits a non-array', async () => {
+ // Degrading unreadable output to [] would clear lastError and record a quiet
+ // poll for a page we never parsed.
+ getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, host: 'github.com', fullName: 'o/r' });
+ execGhMock
+ .mockResolvedValueOnce('main')
+ .mockResolvedValueOnce('{"message":"Not Found"}');
+ const r = await checkPullRequests(app, { authorFilter: 'any' });
+ expect(r.ok).toBe(false);
+ expect(r.reason).toBe('pr-list-failed');
+ });
+
it('bails when the default branch cannot be resolved', async () => {
getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, host: 'github.com', fullName: 'o/r' });
execGhMock.mockResolvedValueOnce(''); // repo view → empty