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: deduplicate PR hand-back comments across failed retries (#12523)

[._.]/ Adam Eivy52a7b33e9978
diff --git a/server/services/orphanedPrNotifier.test.js b/server/services/orphanedPrNotifier.test.js
index 74c66479d1..b8e7246cf6 100644
--- a/server/services/orphanedPrNotifier.test.js
+++ b/server/services/orphanedPrNotifier.test.js
@@ -17,7 +17,7 @@ vi.mock('./notifications.js', () => ({
vi.mock('./brainTaskThreads.js', () => ({ ensureTaskThread: vi.fn().mockResolvedValue({}) }));
vi.mock('./cos.js', () => ({ addTask: vi.fn(), getTaskById: vi.fn(), updateTask: vi.fn() }));
-vi.mock('./github.js', () => ({ execGh: vi.fn().mockResolvedValue('') }));
+vi.mock('./github.js', () => ({ execGh: vi.fn().mockImplementation(async (args) => args[0] === 'api' ? 'maintainer' : 'false') }));
vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));
vi.mock('./forgeAuth.js', () => ({ resolveForgeForRepo: vi.fn().mockResolvedValue({ cli: 'gh', env: {} }) }));
vi.mock('./apps.js', () => ({ getAppById: vi.fn().mockResolvedValue({ repoPath: '/repos/example' }) }));
@@ -150,16 +150,17 @@ describe('blocked PR remediation hand-back', () => {
});
const change = { task: structuredClone(task), previousStatus: 'pending' };
expect(await Promise.all([notifyIfPrLeftOrphaned(change), notifyIfPrLeftOrphaned(change)])).toEqual([true, false]);
- expect(execGh.mock.calls.map(([args]) => args.slice(0, 3))).toEqual([
+ const writes = execGh.mock.calls.filter(([args]) => ['comment', 'edit'].includes(args[1]));
+ expect(writes.map(([args]) => args.slice(0, 3))).toEqual([
['pr', 'comment', PR_URL], ['pr', 'edit', PR_URL],
]);
- expect(execGh.mock.calls[0][0].at(-1)).toContain('remediation task is now blocked');
- expect(execGh.mock.calls[0][0].at(-1)).not.toContain('it did not run');
- expect(execGh.mock.calls[1][0]).toContain('contributor');
+ expect(writes[0][0].at(-1)).toContain('remediation task is now blocked');
+ expect(writes[0][0].at(-1)).not.toContain('it did not run');
+ expect(writes[1][0]).toContain('contributor');
expect(task.metadata.prRemediationHandedBackAt).toEqual(expect.any(String));
expect(updateTask).toHaveBeenCalledWith(task.id, { metadata: { prRemediationHandedBackAt: expect.any(String) } }, 'internal');
expect(await notifyIfPrLeftOrphaned(change)).toBe(false);
- expect(execGh).toHaveBeenCalledTimes(2);
+ expect(execGh).toHaveBeenCalledTimes(4);
expect(addNotification).not.toHaveBeenCalled();
});
diff --git a/server/services/prRemediationFollowUp.js b/server/services/prRemediationFollowUp.js
index 3802a0119f..5a6f382de7 100644
--- a/server/services/prRemediationFollowUp.js
+++ b/server/services/prRemediationFollowUp.js
@@ -239,6 +239,12 @@ export async function handBackPrRemediation({ task, workspacePath } = {}) {
: 'an earlier revision';
const login = typeof meta.prRemediationAuthorLogin === 'string' ? meta.prRemediationAuthorLogin.trim() : '';
const terminalBlock = meta.blockedCategory && meta.blockedCategory !== 'pr-head-moved';
+ const marker = `<!-- portos-pr-remediation-handback:${task.id} -->`;
+ const viewer = (await execGh(['api', 'user', '--jq', '.login'], undefined, options)).trim();
+ if (!viewer) throw new Error('Could not resolve the authenticated hand-back account');
+ const existing = await execGh(['pr', 'view', ...prRef, '--json', 'comments', '--jq',
+ `any(.comments[]; .author.login == ${JSON.stringify(viewer)} and (.body | contains(${JSON.stringify(marker)})))`], undefined, options);
+ if (!['true', 'false'].includes(existing.trim())) throw new Error('Could not check prior remediation hand-back');
const body = [
...(terminalBlock ? [
`PortOS reviewed this pull request at ${reviewed} and queued an agent to finish it, but the remediation task is now blocked.`,
@@ -249,7 +255,9 @@ export async function handBackPrRemediation({ task, workspacePath } = {}) {
]),
`${login ? `@${login}, this` : 'This'} pull request is back with its author; the next push gets a fresh review.`,
].join(' ');
- await execGh(['pr', 'comment', ...prRef, '--body', body], undefined, options);
+ // Forge-side dedupe survives a failed assignment or local stamp write. Only
+ // this authenticated account's marker counts; contributor prose cannot claim it.
+ if (existing.trim() !== 'true') await execGh(['pr', 'comment', ...prRef, '--body', `${body}\n\n${marker}`], undefined, options);
if (login) await execGh(['pr', 'edit', ...prRef, '--add-assignee', login], undefined, options);
emitLog('info', `↩️ Handed PR #${number} in ${repoFullName} back after its remediation was blocked`, { taskId: task.id, prNumber: number });
return true;
diff --git a/server/services/prRemediationFollowUp.test.js b/server/services/prRemediationFollowUp.test.js
index 41de82e55b..9f4a496374 100644
--- a/server/services/prRemediationFollowUp.test.js
+++ b/server/services/prRemediationFollowUp.test.js
@@ -176,7 +176,7 @@ describe('spawnPrRemediationFollowUp', () => {
});
describe('handBackPrRemediation', () => {
- beforeEach(() => { execGhMock.mockReset(); execGhMock.mockResolvedValue(''); });
+ beforeEach(() => { execGhMock.mockReset(); execGhMock.mockImplementation(async (args) => args[0] === 'api' ? 'maintainer' : 'false'); });
it('comments on the PR by URL and assigns it back to its opener', async () => {
const task = {
@@ -193,9 +193,34 @@ describe('handBackPrRemediation', () => {
expect(await handBackPrRemediation({ task, workspacePath: '/repos/example' })).toBe(true);
- const [[comment], [assign]] = execGhMock.mock.calls;
+ const [[comment], [assign]] = execGhMock.mock.calls.filter(([args]) => ['comment', 'edit'].includes(args[1]));
expect(comment.slice(0, 3)).toEqual(['pr', 'comment', 'https://github.com/o/r/pull/7']);
expect(comment.at(-1)).toContain('aaaaaaaaaaaa');
expect(assign).toEqual(['pr', 'edit', 'https://github.com/o/r/pull/7', '--add-assignee', 'contributor']);
});
});
+
+
+it('retries assignment without duplicating a posted hand-back after an assignment failure', async () => {
+ const task = { id: 'sys-remediation-retry', app: 'app-1', metadata: {
+ prRemediationNumber: 7, prRemediationRepoFullName: 'o/r',
+ prRemediationUrl: 'https://github.com/o/r/pull/7', prRemediationAuthorLogin: 'contributor',
+ } };
+ let posted = false;
+ let assignmentAttempts = 0;
+ execGhMock.mockImplementation(async (args) => {
+ if (args[0] === 'api') return 'maintainer';
+ if (args[1] === 'view') {
+ expect(args.at(-1)).toContain('.author.login == "maintainer"');
+ expect(args.at(-1)).toContain('portos-pr-remediation-handback:sys-remediation-retry');
+ return String(posted);
+ }
+ if (args[1] === 'comment') posted = true;
+ if (args[1] === 'edit' && ++assignmentAttempts === 1) throw new Error('Assignment unavailable');
+ return '';
+ });
+ await expect(handBackPrRemediation({ task, workspacePath: '/repos/example' })).rejects.toThrow('Assignment unavailable');
+ expect(await handBackPrRemediation({ task, workspacePath: '/repos/example' })).toBe(true);
+ expect(execGhMock.mock.calls.filter(([args]) => args[1] === 'comment')).toHaveLength(1);
+ expect(assignmentAttempts).toBe(2);
+});