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

fix: bind handoff review evidence to the handed-off head (#12247)

[._.]/ Adam Eivya69e9f8177df
diff --git a/docs/features/chief-of-staff.md b/docs/features/chief-of-staff.md
index 2952be1d0c..c609a6492e 100644
--- a/docs/features/chief-of-staff.md
+++ b/docs/features/chief-of-staff.md
@@ -93,9 +93,11 @@ repository from the run's registration, the PR branch it must own (a bound
claim branch, `reviewLoopMergeTarget` or `prDeliveryTarget`), a same-repository
open non-draft PR whose live head equals the SHA, a checkout of this repository
on that branch at that SHA, a merging completion policy (not leave-open, a JIRA
-handoff or read-only), and the worktree's `portos-review-status` (`clean`;
-absence is accepted only for merge-on-green). Fork targets are refused. The
-binding is persisted on the app's `pendingMergePrs` entry and the response
+handoff or read-only), and the worktree's `portos-review-status`:
+`REVIEW_STATUS=clean` with `REVIEW_HEAD=<sha>` naming that same head for a
+review-then-merge run; merge-on-green accepts no file or a clean one. Fork
+targets are refused. The binding is persisted on the app's `pendingMergePrs`
+entry, an unbound duplicate queue write never replaces it, and the response
carries a receipt.
The pr-watcher pending-merge sweep then merges only the recorded head, under
diff --git a/server/services/cosMergeHandoff.js b/server/services/cosMergeHandoff.js
index 5fc8a37aaa..3fd02b70f6 100644
--- a/server/services/cosMergeHandoff.js
+++ b/server/services/cosMergeHandoff.js
@@ -54,17 +54,29 @@ async function checkoutAtHead(workspace, branch, head, repository, repositoryKey
return ref?.stdout?.trim() === branch && sha?.stdout?.trim().toLowerCase() === head;
}
-// The worktree-private status the review phase writes. null = no file (no
-// local reviewers ran); 'unreadable' covers an unreadable or empty file.
-async function readReviewStatus(workspace) {
+// The worktree-private status the review phase writes: `REVIEW_STATUS=<verdict>`
+// plus `REVIEW_HEAD=<sha>`, the commit its final round reviewed. status null =
+// no file (no local reviewers ran); 'unreadable' covers an unreadable or empty file.
+async function readReviewEvidence(workspace) {
const gitPath = await execGit(['rev-parse', '--git-path', 'portos-review-status'], workspace).catch(() => null);
const relative = gitPath?.stdout?.trim();
- if (!relative) return 'unreadable';
+ if (!relative) return { status: 'unreadable', head: null };
const content = await readFile(resolve(workspace, relative), 'utf-8').catch((err) => (err.code === 'ENOENT' ? null : undefined));
- if (content === null) return null;
- const statuses = [...String(content ?? '').matchAll(/^REVIEW_STATUS=(\S+)\s*$/gm)].map((m) => m[1]);
- if (statuses.length === 0) return 'unreadable';
- return statuses.find((status) => status !== 'clean') ?? 'clean';
+ if (content === null) return { status: null, head: null };
+ const values = (pattern) => [...String(content ?? '').matchAll(pattern)].map((m) => m[1]);
+ const statuses = values(/^REVIEW_STATUS=(\S+)\s*$/gm);
+ const heads = values(/^REVIEW_HEAD=(\S+)\s*$/gm);
+ return {
+ status: statuses.length === 0 ? 'unreadable' : statuses.find((status) => status !== 'clean') ?? 'clean',
+ head: heads.length === 1 ? heads[0].toLowerCase() : null,
+ };
+}
+
+// A clean verdict counts only for the head it reviewed; merge-on-green runs no
+// reviewers, so there only a recorded block or unreadable status refuses.
+function reviewEvidenceAccepted({ status, head: reviewedHead }, head, policy) {
+ if (policy === PR_COMPLETIONS.MERGE_ON_GREEN) return status === null || status === 'clean';
+ return status === 'clean' && reviewedHead === head;
}
async function followUpRoster(task, policy) {
@@ -125,10 +137,8 @@ export async function handoffPendingMerge({ agentId, prUrl, headSha, worktreePat
if (!workspace || !await checkoutAtHead(workspace, view.headRefName, head, repository, repositoryKey)) {
return refuse('checkout-head-unverified');
}
- const reviewStatus = await readReviewStatus(workspace);
- if (!(reviewStatus === 'clean' || (reviewStatus === null && policy === PR_COMPLETIONS.MERGE_ON_GREEN))) {
- return refuse('review-evidence-incomplete');
- }
+ const review = await readReviewEvidence(workspace);
+ if (!reviewEvidenceAccepted(review, head, policy)) return refuse('review-evidence-incomplete');
const receipt = {
id: randomUUID(), appId: app.id, prUrl, prNumber: pr.number, headSha: head, repository,
@@ -148,7 +158,7 @@ export async function handoffPendingMerge({ agentId, prUrl, headSha, worktreePat
},
handoff: {
receiptId: receipt.id, agentId, startedAt: agent.startedAt, taskId: agent.taskId, repository,
- headSha: head, prCompletion: policy, reviewStatus: reviewStatus ?? 'not-configured', acceptedAt: receipt.queuedAt,
+ headSha: head, prCompletion: policy, reviewStatus: review.status ?? 'not-configured', acceptedAt: receipt.queuedAt,
},
followUp: await followUpRoster(task, policy),
}).catch((err) => {
diff --git a/server/services/cosMergeHandoff.test.js b/server/services/cosMergeHandoff.test.js
index 533eb7f693..3ec54d6e31 100644
--- a/server/services/cosMergeHandoff.test.js
+++ b/server/services/cosMergeHandoff.test.js
@@ -90,7 +90,7 @@ beforeEach(async () => {
isCrossRepository: false, headRefName: 'claim/issue-1', headRefOid: HEAD,
mergeStateStatus: 'CLEAN', statusCheckRollup: [{ conclusion: 'SUCCESS' }],
};
- await writeFile(join(workspace, 'portos-review-status'), 'REVIEW_STATUS=clean\n');
+ await writeFile(join(workspace, 'portos-review-status'), `REVIEW_STATUS=clean\nREVIEW_HEAD=${HEAD}\n`);
execGhMock.mockReset().mockImplementation(async (args) => {
if (args[0] === 'pr' && args[1] === 'view') return JSON.stringify(f.pr);
if (args[0] === 'pr' && args[1] === 'diff') return 'diff --git a/example.js b/example.js\n+const ok = true;';
@@ -139,6 +139,7 @@ describe('pending-merge handoff', () => {
['a leave-open policy', () => { f.tasks['task-agent-1'].metadata.prCompletion = 'leave-open'; }, 'completion-policy-leaves-open'],
['a JIRA human handoff', () => { f.tasks['task-agent-1'].metadata.jiraTicketId = 'EX-1'; }, 'completion-policy-leaves-open'],
['blocked review evidence', () => writeFile(join(workspace, 'portos-review-status'), 'REVIEW_STATUS=review-blocked\n'), 'review-evidence-incomplete'],
+ ['a clean verdict for an earlier head', () => writeFile(join(workspace, 'portos-review-status'), `REVIEW_STATUS=clean\nREVIEW_HEAD=${'f'.repeat(40)}\n`), 'review-evidence-incomplete'],
['missing required review evidence', () => rm(join(workspace, 'portos-review-status')), 'review-evidence-incomplete'],
])('refuses %s and queues nothing', async (_name, arrange, reason) => {
const overrides = await arrange();
@@ -175,6 +176,14 @@ describe('pending-merge handoff', () => {
expect(pending()).toEqual([expect.objectContaining({ ticks: 1, handoff: expect.objectContaining({ headSha: HEAD }) })]);
});
+ it('keeps the head binding when an unbound duplicate is queued for the same PR', async () => {
+ await handoff();
+ const { queuePendingMerge } = await import('./prWatcher.js');
+ const { handoff: _binding, followUp: _roster, ...unbound } = pending()[0];
+ expect(await queuePendingMerge('app1', unbound)).toBe(true);
+ expect(pending()[0].handoff).toMatchObject({ headSha: HEAD });
+ });
+
it('never merges an unreadable binding and hands it to the operator', async () => {
await handoff();
f.apps.set('app1', { ...f.apps.get('app1'), pendingMergePrs: [{ ...pending()[0], handoff: { headSha: 'not-a-sha' } }] });
diff --git a/server/services/prWatcher.js b/server/services/prWatcher.js
index 8859e16ffd..bf77a67d61 100644
--- a/server/services/prWatcher.js
+++ b/server/services/prWatcher.js
@@ -274,6 +274,9 @@ export async function queuePendingMerge(appId, pending) {
const key = pendingMergeKey(normalized);
const index = existing.findIndex((entry) => pendingMergeKey(entry) === key);
if (index === -1) return [...existing, normalized];
+ // Only a newly verified handoff replaces a head binding: an unbound
+ // duplicate would otherwise reopen the legacy merge-current-head path.
+ if (existing[index].handoff && !normalized.handoff) return existing;
const next = [...existing];
// Preserve the existing tick count so a duplicated completion callback
// cannot reset an already-wedged PR's bounded-watch budget. A handoff of a