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
don't fail a CoS run for a missing PR when its branch holds no commits
[._.]/ Adam Eivy9af72531992b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 87f1995dfe..b69f2f89b4 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -216,3 +216,5 @@- **[issue-3716] Dropped the unreachable legacy `.icloud` placeholder probe from the MortalLoom store.** macOS has two possible representations for an iCloud file evicted by "Optimize Mac Storage": the modern APFS *dataless* vnode (path stays put, `stat` reports a real size with zero blocks) and the pre-APFS `.<name>.icloud` sibling stub that *replaces* the file. `mortalLoomStore` guarded both — the stub probe added speculatively alongside a real dataless incident, never observed firing — and the Obsidian vault adapter guarded only the first, so `createNote` would have written a fresh note beside a stub-shadowed one. Before copying the probe into a second adapter, the representation was measured: across 223 iCloud ubiquity containers holding 373 evicted files (macOS 26, APFS), every evicted file was dataless and zero `.icloud` placeholders existed anywhere under the iCloud root or the home directory. The probe is dead code, so it was deleted rather than duplicated — an absent path is now unambiguously absent on both read and write, and `updateStore`'s overwrite guard makes one `existsSync` call instead of three. The finding, and where the probe would have to go if a placeholder is ever actually observed, is recorded in `server/lib/icloudFile.js`. No user-visible behavior change: refusing to overwrite an evicted (dataless) store, and the on-demand `brctl download` pre-warm, are untouched.- **[issue-3725] A worktree agent is no longer failed for a commit it merely rebased onto.** The primary-checkout branch-jack guard attributes stranded commits to the agent's own branch before blaming a run, but one of its two attribution paths asked only "is this commit reachable from the agent's branch tip?" — which is equally true of a commit the agent *authored and applied to `main`* and one another actor put on `main` mid-run that the agent then *rebased onto*. Since `/do:pr` rebases on `main` before pushing, every worktree run that outlived a concurrent commit to `main` inherited that commit into its branch's base and was failed with `primary-checkout-mutated`, escalating to a human and denting the task type's success rate — in the observed case the run had actually finished its work and pushed its branch. Attribution now recognizes that a branch built strictly *on top of* the drift descends from it rather than causing it, and skips the blame. A real branch-jack leaves the primary *at* a commit the agent authored, never strictly behind its own branch, so the original incident shape is still caught.++- **A CoS agent that correctly concludes "nothing to fix here" is no longer failed for not opening a pull request.** The PR-claim check asks the forge whether a run that promised a change request produced one, and recorded a bare "no" as `pr-missing`. But "no PR" only means the agent slipped if there was something to open one *for*: an agent that investigates its task, finds the reported defect already fixed on `main`, and stops without touching a file leaves a branch with zero commits — and `gh pr create` refuses that branch because there is no diff, not because anyone made a mistake. Since `pr-missing` is deliberately non-actionable so a genuine miss can retry, a correct no-op conclusion was instead re-run to the full retry budget, spending three agents to reach the same answer three times and then escalating it to a human as a failure. A missing PR on a branch that holds **no commits** is now recorded as the completion it is, logged so the run stays visible rather than passing silently, while a missing PR on a branch that holds real commits still fails exactly as before. The commit count is taken against `origin/<default>` rather than the worktree's local copy, which routinely sits behind the commit the worktree branched from and would otherwise report inherited merge commits as the agent's own work; an unreadable count is treated as unknown and leaves the failure standing, since not being able to look is not evidence of an empty branch. The advice attached to a real miss also no longer asserts the branch "is pushed" — that was never checked — and now names how many commits are waiting.diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsindex 8b593d3a2a..02c5b8e1e7 100644--- a/server/services/agentFinalization.js+++ b/server/services/agentFinalization.js@@ -225,6 +225,41 @@ async function resolveWorkspaceBranch(workspacePath) {return branch && branch !== 'HEAD' ? branch : null;}+/**+ * How many commits the finished branch holds that its base does not — or `null`+ * when we could not work it out.+ *+ * The `null` sentinel matters: it is the difference between "we looked and the+ * agent committed nothing" and "we could not look". Only a confirmed `0` is+ * allowed to excuse a missing PR (see `verifyPrClaim`); an unreadable count+ * leaves the miss standing rather than inventing an excuse for it.+ *+ * Compares against `origin/<default>` in preference to the local branch. A+ * worktree's local `main` is routinely STALE — it is whatever the primary+ * checkout last pulled, which can sit well behind the commit the worktree was+ * actually branched from. Counting against it reports the merge commits the+ * agent inherited as commits the agent authored, which is precisely backwards+ * for a check that exists to recognize "this agent wrote nothing".+ */+async function countCommitsAhead(workspacePath) {+ const { getDefaultBranch } = await import('./git.js');+ // `allowRemote: false` — finalize must not block on a network round-trip to+ // answer a bookkeeping question; the local fallbacks resolve main/master fine.+ const defaultBranch = await getDefaultBranch(workspacePath, { allowRemote: false }).catch(() => null);+ if (!defaultBranch) return null;++ const remoteRef = `refs/remotes/origin/${defaultBranch}`;+ const hasRemote = await execGit(['rev-parse', '--verify', '--quiet', remoteRef], workspacePath, { ignoreExitCode: true })+ .then(r => !!(r?.stdout || '').trim())+ .catch(() => false);++ const base = hasRemote ? `origin/${defaultBranch}` : defaultBranch;+ const result = await execGit(['rev-list', '--count', `${base}..HEAD`], workspacePath, { ignoreExitCode: true })+ .catch(() => null);+ const count = Number.parseInt((result?.stdout || '').trim(), 10);+ return Number.isInteger(count) ? count : null;+}+/*** Verify that a run whose task shape PROMISED a pull request actually produced* one (#3358).@@ -245,12 +280,16 @@ async function resolveWorkspaceBranch(workspacePath) {* `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:+ * Four outcomes, never collapsed:* - `ok: true` — a PR exists, or there was nothing to check- * - `ok: false, category: 'pr-missing'` — the forge answered: no PR+ * - `ok: true, noChangesToShip: true` — the forge answered "no PR" and the+ * branch holds no commits, so there was nothing a PR could have been opened+ * for; the run concluded that no change was warranted+ * - `ok: false, category: 'pr-missing'` — the forge answered "no PR" for a+ * branch that DOES hold commits* - `ok: false, category: 'forge-unreachable'` — we could not ask*- * @returns {Promise<{ ok: boolean, category?: string, message?: string, branch?: string|null }>}+ * @returns {Promise<{ ok: boolean, category?: string, message?: string, branch?: string|null, noChangesToShip?: boolean, commitsAhead?: number|null }>}*/export async function verifyPrClaim({ task, workspacePath, success, prExpected }) {// Only a run that CLAIMED success has a claim to verify; a failed run is@@ -276,9 +315,24 @@ export async function verifyPrClaim({ task, workspacePath, success, prExpected }const noun = cli === 'glab' ? 'merge request' : 'pull request';if (found.status === 'found') return { ok: true, branch };if (found.status === 'none') {+ // "No PR" is only a MISS if there was something to open one for. An agent+ // that investigated its task, found the defect already fixed on main, and+ // stopped without touching a file leaves a branch with zero commits — and+ // `gh pr create` on a zero-commit branch does not fail because the agent+ // slipped, it fails because there is no diff. Recording that as `pr-missing`+ // failed a correct run and, being non-actionable, re-ran the whole+ // investigation twice more to reach the same conclusion (agent-446c4f47).+ //+ // Deliberately gated on an EXPLICIT 0: an unreadable count is not evidence+ // of an empty branch, so it leaves the miss standing.+ const ahead = await countCommitsAhead(workspacePath).catch(() => null);+ if (ahead === 0) {+ return { ok: true, branch, noChangesToShip: true };+ }return {ok: false,branch,+ commitsAhead: ahead,category: PR_MISSING_CATEGORY,message: `Agent reported success but no ${noun} exists for branch ${branch}`};@@ -344,7 +398,7 @@ function prVerificationAnalysis(verdict) {message: verdict.message,actionable: false,suggestedFix: verdict.category === PR_MISSING_CATEGORY- ? `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}\`).`+ ? `The branch ${verdict.branch} holds ${verdict.commitsAhead ?? 'unreviewed'} commit(s) 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.'};}@@ -626,6 +680,12 @@ export async function finalizeAgent({emitLog('warn', `⚠️ ${prVerdict.message} — recording ${agentId} as needs-attention (${prVerdict.category}) rather than complete`, {agentId, taskId: task?.id, branch: prVerdict.branch, category: prVerdict.category});+ } else if (prVerdict.noChangesToShip) {+ // A no-op run is a legitimate completion, not a silent one — the human still+ // wants to know a task burned an agent and concluded there was nothing to do.+ emitLog('info', `🫧 ${agentId} opened no change request and committed nothing to ${prVerdict.branch} — recording the run as complete with no change warranted`, {+ agentId, taskId: task?.id, branch: prVerdict.branch+ });}if (success && isTruthyMetaFn) {diff --git a/server/services/agentFinalization.prVerification.test.js b/server/services/agentFinalization.prVerification.test.jsindex 28d09fd86b..9005e7cfb4 100644--- a/server/services/agentFinalization.prVerification.test.js+++ b/server/services/agentFinalization.prVerification.test.js@@ -28,8 +28,10 @@ vi.mock('./gitlab.js', () => ({}));const resolveForgeForRepoMock = vi.fn(async () => ({ cli: 'gh' }));+const getDefaultBranchMock = vi.fn(async () => 'main');vi.mock('./git.js', () => ({resolveForgeForRepo: (...args) => resolveForgeForRepoMock(...args),+ getDefaultBranch: (...args) => getDefaultBranchMock(...args),}));vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));@@ -90,7 +92,24 @@ import {FORGE_UNREACHABLE_CATEGORY,} from './agentFinalization.js';-const onBranch = (name) => execGitMock.mockResolvedValue({ stdout: `${name}\n`, stderr: '', exitCode: 0 });+/**+ * Routes the git calls verifyPrClaim makes by their argv, so a test can set the+ * branch and the commit count independently. A blanket `mockResolvedValue`+ * cannot: `rev-list --count` and `rev-parse --abbrev-ref HEAD` want different+ * answers, and feeding a branch name to the counter reads as "unknown".+ */+const git = { branch: 'claim/issue-1', ahead: 3, hasOriginRef: true };+const ok = (stdout) => ({ stdout, stderr: '', exitCode: 0 });+const routeGit = (args) => {+ if (args[0] === 'rev-parse' && args.includes('--abbrev-ref')) return ok(`${git.branch}\n`);+ if (args[0] === 'rev-parse' && args.includes('--verify')) return ok(git.hasOriginRef ? 'abc1234\n' : '');+ if (args[0] === 'rev-list' && args.includes('--count')) return ok(git.ahead === null ? '\n' : `${git.ahead}\n`);+ return ok('');+};+const onBranch = (name) => {+ git.branch = name;+ execGitMock.mockImplementation(async (args) => routeGit(args));+};const prTask = () => ({id: 'task-1',@@ -101,7 +120,9 @@ const prTask = () => ({beforeEach(() => {vi.clearAllMocks();- execGitMock.mockResolvedValue({ stdout: 'claim/issue-1\n', stderr: '', exitCode: 0 });+ Object.assign(git, { branch: 'claim/issue-1', ahead: 3, hasOriginRef: true });+ execGitMock.mockImplementation(async (args) => routeGit(args));+ getDefaultBranchMock.mockResolvedValue('main');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' });@@ -134,6 +155,85 @@ describe('verifyPrClaim (#3358)', () => {expect(verdict.branch).toBe('claim/issue-1');});+ it('passes when the branch holds no commits — there was nothing to open a PR for', async () => {+ // agent-446c4f47: the agent investigated, found the reported defect already+ // fixed on main, and stopped without touching a file. `gh pr create` on a+ // zero-commit branch fails because there is no diff, not because the agent+ // slipped — recording that as pr-missing failed a correct run.+ onBranch('cos/sys-1/agent-1');+ git.ahead = 0;+ findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });+ const verdict = await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true });+ expect(verdict.ok).toBe(true);+ expect(verdict.noChangesToShip).toBe(true);+ expect(verdict.category).toBeUndefined();+ });++ it('counts against origin/<default>, not the worktree\'s stale local copy', async () => {+ // A worktree's local `main` is whatever the primary last pulled and routinely+ // sits behind the commit the worktree branched from. Counting against it+ // reports inherited merge commits as the agent's own — backwards for a check+ // that exists to recognize "this agent wrote nothing".+ onBranch('cos/sys-1/agent-1');+ git.ahead = 0;+ findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });+ await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true });+ expect(execGitMock).toHaveBeenCalledWith(['rev-list', '--count', 'origin/main..HEAD'], '/w', expect.anything());+ });++ it('falls back to the local default branch when origin/<default> is absent', async () => {+ onBranch('cos/sys-1/agent-1');+ git.ahead = 0;+ git.hasOriginRef = false;+ findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });+ await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true });+ expect(execGitMock).toHaveBeenCalledWith(['rev-list', '--count', 'main..HEAD'], '/w', expect.anything());+ });++ it('keeps pr-missing when the commit count is unreadable — that is not evidence of an empty branch', async () => {+ onBranch('claim/issue-1');+ git.ahead = null;+ findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });+ const verdict = await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true });+ expect(verdict.ok).toBe(false);+ expect(verdict.category).toBe(PR_MISSING_CATEGORY);+ });++ it('keeps pr-missing when the default branch cannot be resolved', async () => {+ onBranch('claim/issue-1');+ git.ahead = 0;+ getDefaultBranchMock.mockResolvedValue(null);+ findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });+ const verdict = await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true });+ expect(verdict.ok).toBe(false);+ expect(verdict.category).toBe(PR_MISSING_CATEGORY);+ });++ it('never blocks finalize on a network round-trip to name the default branch', async () => {+ onBranch('claim/issue-1');+ git.ahead = 0;+ findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });+ await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true });+ expect(getDefaultBranchMock).toHaveBeenCalledWith('/w', { allowRemote: false });+ });++ it('still reports pr-missing when the branch DOES hold commits', async () => {+ // The #3358 case must survive the no-op exemption: real work, pushed, no PR.+ onBranch('claim/issue-1');+ git.ahead = 4;+ findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });+ const verdict = await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true });+ expect(verdict.ok).toBe(false);+ expect(verdict.category).toBe(PR_MISSING_CATEGORY);+ expect(verdict.commitsAhead).toBe(4);+ });++ it('does not count commits when a PR was found — the check is only for the miss path', async () => {+ onBranch('claim/issue-1');+ await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true });+ expect(getDefaultBranchMock).not.toHaveBeenCalled();+ });+it('fails with forge-unreachable — NOT pr-missing — when we could not ask', async () => {onBranch('claim/issue-1');findPullRequestForBranchMock.mockResolvedValue({@@ -225,6 +325,20 @@ describe('finalizeAgent — a PR-shaped run with no PR is not a success (#3358)'expect(updateTaskMock).not.toHaveBeenCalledWith('task-1', expect.objectContaining({ status: 'completed' }), 'internal');});+ it('records "completed" for a run that committed nothing and opened no PR', async () => {+ // The retry loop this closes: pr-missing is non-actionable, so a correct+ // "nothing to fix here" conclusion was re-run to the retry budget, burning+ // three Opus agents to reach the same answer three times (agent-446c4f47).+ onBranch('cos/sys-1/agent-1');+ git.ahead = 0;+ findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });+ await finalize();++ expect(completeAgentMock).toHaveBeenCalledWith('agent-1', expect.objectContaining({ success: true }));+ expect(updateTaskMock).toHaveBeenCalledWith('task-1', expect.objectContaining({ status: 'completed' }), 'internal');+ expect(resolveFailedTaskUpdateMock).not.toHaveBeenCalled();+ });+it('marks the RUN record failed too, even though the process exited 0', async () => {onBranch('claim/issue-1');findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });