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: merge the handback ledger onto fresh state, and stop double-owning a PR

[._.]/ Adam Eivy01fed0d8fe58
diff --git a/server/services/issueWatcher.js b/server/services/issueWatcher.js
index 2d88543617..29289bb2b9 100644
--- a/server/services/issueWatcher.js
+++ b/server/services/issueWatcher.js
@@ -79,11 +79,21 @@ function queueStateWrite(write) {
return next;
}
+/**
+ * `patch` may be an object, or a FUNCTION of the freshly-read state. The
+ * function form exists because a plain object patch is computed from a snapshot
+ * taken before the queue was entered, and writing an array field from a stale
+ * snapshot replaces whatever another pass wrote in the meantime. A field whose
+ * entries are owned by more than one pass must derive its next value from the
+ * state this write actually lands on — see `handbackStatePatch`.
+ */
async function persistState(appId, patch) {
return queueStateWrite(async () => {
const app = await getAppById(appId);
if (!app) return null;
- return updateApp(appId, { issueWatcherState: { ...readState(app), ...patch } });
+ const state = readState(app);
+ const resolved = typeof patch === 'function' ? patch(state) : patch;
+ return updateApp(appId, { issueWatcherState: { ...state, ...resolved } });
});
}
@@ -278,15 +288,38 @@ const handbackLedger = (state) => (Array.isArray(state?.prHandbacks) ? state.prH
* Per-pass hand-back accumulator. The ledger is read once at the top of a pass
* and written once at the end, folded into the `persistState` call the pass
* already makes — a per-PR write would re-serialize the whole apps file for
- * each PR. Mutated in place like the `approvals`/`remaining` arrays beside
- * it, so a dedup check later in the same loop sees an entry made earlier in it.
+ * each PR. `ledger` is the pass's working view, mutated in place like the
+ * `approvals`/`remaining` arrays beside it so a dedup check later in the
+ * same loop sees an entry made earlier in it. `written` records only the
+ * entries THIS pass produced, keyed by PR number.
+ *
+ * The split matters: `processTaskOutput` and `processPendingApprovals` both
+ * own entries in this field and can be in flight together for one app (the
+ * perpetual refill in cos.js fires `buildTaskInput` on `agent:completed`,
+ * before the completing task's own output hook has settled). Writing
+ * `ledger` wholesale would replace the other pass's entries with a snapshot
+ * taken before they existed — and a LOST entry here is not a benign
+ * re-observation: it drops the same-revision dedup and the attempt budget, so
+ * the next sweep spawns a second remediation agent for a PR one is already
+ * working. Only `written` is applied, merged by number onto whatever the
+ * write actually lands on.
*/
function createHandbackTracker(app) {
- return { ledger: handbackLedger(readState(app)), changed: false };
+ return { ledger: handbackLedger(readState(app)), written: new Map() };
}
-/** The ledger fields to merge into a pass's own end-of-pass state write. */
-const handbackStatePatch = (tracker) => (tracker?.changed ? { prHandbacks: tracker.ledger } : {});
+/**
+ * The ledger patch for a pass's own end-of-pass state write, as a function of
+ * fresh state so this pass's entries merge onto a peer's instead of replacing
+ * them. Returns `{}` when the pass handed nothing back.
+ */
+function handbackStatePatch(tracker) {
+ if (!tracker || tracker.written.size === 0) return {};
+ return (state) => {
+ const merged = handbackLedger(state).filter((entry) => !tracker.written.has(entry.number));
+ return { prHandbacks: [...merged, ...tracker.written.values()].slice(-MAX_HANDBACK_LEDGER_ENTRIES) };
+ };
+}
/**
* Decide and apply who owns a PR the coordinator reviewed but did not merge.
@@ -323,12 +356,16 @@ async function applyPullRequestHandback({
const login = (authorLogin || pr.author?.login || '').trim();
let applied = disposition;
let taskId = null;
+ // Only a NEW agent costs an attempt. Re-observing a PR whose agent is still
+ // queued must not burn the budget that decides when the work goes back to
+ // its opener.
+ let spawned = false;
if (disposition === PR_HANDBACK.REMEDIATE) {
// Lazy: the spawner reaches the CoS task store, whose module graph is far
// heavier than a gather pass that never hands anything back — and the
// common disposition returns above without ever needing it.
- const { spawnPrRemediationFollowUp } = await import('./prRemediationFollowUp.js');
- const task = await spawnPrRemediationFollowUp({
+ const { PR_REMEDIATION_SPAWN, spawnPrRemediationFollowUp } = await import('./prRemediationFollowUp.js');
+ const { status, task } = await spawnPrRemediationFollowUp({
app,
repoFullName: ctx.repoFullName,
pullRequest: {
@@ -341,10 +378,15 @@ async function applyPullRequestHandback({
writeAccess,
reason,
});
- // A rejected queue write (duplicate, disk error) must not silently drop the
- // PR: fall back to the hand-back that needs no agent.
- if (task) taskId = task.id;
- else applied = PR_HANDBACK.ASSIGN_OPENER;
+ // `already-queued` still means an agent owns this PR, so it stays a
+ // REMEDIATE: assigning the opener on top of a running agent would put the
+ // PR in two queues and set a human to work against it. Only a genuine
+ // queue failure leaves nobody holding the PR and falls back.
+ if (status === PR_REMEDIATION_SPAWN.FAILED) applied = PR_HANDBACK.ASSIGN_OPENER;
+ else {
+ taskId = task?.id || null;
+ spawned = status === PR_REMEDIATION_SPAWN.QUEUED;
+ }
}
if (applied === PR_HANDBACK.ASSIGN_OPENER) await assignPullRequestOpener(ctx, pr, login);
@@ -352,7 +394,7 @@ async function applyPullRequestHandback({
number: pr.number,
headSha,
taskId: applied === PR_HANDBACK.REMEDIATE ? taskId : null,
- attempts: applied === PR_HANDBACK.REMEDIATE ? attempts + 1 : attempts,
+ attempts: spawned ? attempts + 1 : attempts,
// Observability only — nothing reads these back as inputs to the dedup or
// attempt-budget checks above.
disposition: applied,
@@ -361,7 +403,7 @@ async function applyPullRequestHandback({
};
tracker.ledger = [...tracker.ledger.filter((item) => item.number !== pr.number), entry]
.slice(-MAX_HANDBACK_LEDGER_ENTRIES);
- tracker.changed = true;
+ tracker.written.set(pr.number, entry);
return applied;
}
@@ -895,8 +937,12 @@ async function processPendingApprovals(app, ctx) {
});
changed = true;
}
- if (changed || handbacks.changed) {
- await persistState(app.id, { approvedPullRequests: remaining, ...handbackStatePatch(handbacks) });
+ const handbackPatch = handbackStatePatch(handbacks);
+ if (changed || typeof handbackPatch === 'function') {
+ await persistState(app.id, (state) => ({
+ approvedPullRequests: remaining,
+ ...(typeof handbackPatch === 'function' ? handbackPatch(state) : handbackPatch),
+ }));
}
return remaining;
}
@@ -1337,12 +1383,13 @@ export async function processTaskOutput({ appId, success, payload, task, require
return null;
});
}
- await persistState(appId, {
+ const handbackPatch = handbackStatePatch(handbacks);
+ await persistState(appId, (state) => ({
approvedPullRequests: approvals,
pendingIssueComments,
lastCheckedAt: new Date().toISOString(),
lastError: commentsHandled ? null : 'issue-response-incomplete',
- ...handbackStatePatch(handbacks),
- });
+ ...(typeof handbackPatch === 'function' ? handbackPatch(state) : handbackPatch),
+ }));
return { action: 'processed', replies, reviewed, rebased, merged, handedBack, commentsHandled };
}
diff --git a/server/services/issueWatcher.test.js b/server/services/issueWatcher.test.js
index e5d951ca68..60f26cf504 100644
--- a/server/services/issueWatcher.test.js
+++ b/server/services/issueWatcher.test.js
@@ -35,7 +35,9 @@ vi.mock('./modelAbuseGuard.js', async (importOriginal) => ({
}));
const spawnPrRemediationFollowUpMock = vi.fn();
+const PR_REMEDIATION_SPAWN = { QUEUED: 'queued', ALREADY_QUEUED: 'already-queued', FAILED: 'failed' };
vi.mock('./prRemediationFollowUp.js', () => ({
+ PR_REMEDIATION_SPAWN,
spawnPrRemediationFollowUp: (...args) => spawnPrRemediationFollowUpMock(...args),
}));
@@ -902,7 +904,10 @@ describe('handing back a PR the coordinator could not merge', () => {
beforeEach(() => {
spawnPrRemediationFollowUpMock.mockReset();
- spawnPrRemediationFollowUpMock.mockResolvedValue({ id: 'sys-remediation-1' });
+ spawnPrRemediationFollowUpMock.mockResolvedValue({
+ status: PR_REMEDIATION_SPAWN.QUEUED,
+ task: { id: 'sys-remediation-1' },
+ });
});
it('sends blocking findings to a remediation agent when the fork branch is writable', async () => {
@@ -1006,7 +1011,7 @@ describe('handing back a PR the coordinator could not merge', () => {
});
it('falls back to the opener when the remediation task could not be queued', async () => {
- spawnPrRemediationFollowUpMock.mockResolvedValue(null);
+ spawnPrRemediationFollowUpMock.mockResolvedValue({ status: PR_REMEDIATION_SPAWN.FAILED, task: null });
installDefaultGhMock({ pr: pullRequest(WRITABLE_FORK) });
await run(decision());
@@ -1025,6 +1030,48 @@ describe('handing back a PR the coordinator could not merge', () => {
expect(assignCalls()).toHaveLength(0);
});
+ // An 'already queued' spawn means an agent OWNS the PR. Assigning the opener
+ // on top of it would put one PR in two queues and set a human to work against
+ // a running agent — and it must not burn an attempt, since no new agent ran.
+ it('leaves a PR with its in-flight agent instead of also assigning the opener', async () => {
+ spawnPrRemediationFollowUpMock.mockResolvedValue({
+ status: PR_REMEDIATION_SPAWN.ALREADY_QUEUED,
+ task: { id: 'sys-existing', duplicate: true },
+ });
+ installDefaultGhMock({ pr: pullRequest(WRITABLE_FORK) });
+
+ await run(decision());
+
+ expect(assignCalls()).toHaveLength(0);
+ expect(apps.get(APP.id).issueWatcherState.prHandbacks).toEqual([
+ expect.objectContaining({ number: 7, disposition: 'remediate', taskId: 'sys-existing', attempts: 0 }),
+ ]);
+ });
+
+ // The two hand-back writers (this pass and the merge poller) both own entries
+ // in this field and can be in flight together — the perpetual refill fires
+ // buildTaskInput on agent:completed, before the completing output hook has
+ // settled. A pass must merge its own entries onto whatever it lands on, never
+ // replace the field wholesale: a lost entry drops the same-revision dedup and
+ // re-spawns an agent for a PR one is already working.
+ it('merges its ledger entry onto a peer pass\' write instead of replacing it', async () => {
+ const peer = { number: 99, headSha: 'd'.repeat(40), disposition: 'remediate', attempts: 1 };
+ installDefaultGhMock({ pr: pullRequest(WRITABLE_FORK) });
+ // Land the peer entry mid-pass: after this pass seeded its tracker, before
+ // it reaches its own end-of-pass write.
+ spawnPrRemediationFollowUpMock.mockImplementation(async () => {
+ const current = apps.get(APP.id);
+ apps.set(APP.id, { ...current, issueWatcherState: { ...current.issueWatcherState, prHandbacks: [peer] } });
+ return { status: PR_REMEDIATION_SPAWN.QUEUED, task: { id: 'sys-remediation-1' } };
+ });
+
+ await run(decision());
+
+ const ledger = apps.get(APP.id).issueWatcherState.prHandbacks;
+ expect(ledger.map((entry) => entry.number).sort()).toEqual([7, 99]);
+ expect(ledger.find((entry) => entry.number === 99)).toMatchObject(peer);
+ });
+
it('hands over an approved PR whose merge polling ran out of ticks', async () => {
apps.set(APP.id, {
...APP,
diff --git a/server/services/prRemediationFollowUp.js b/server/services/prRemediationFollowUp.js
index 727c6eeba6..7ad89daef5 100644
--- a/server/services/prRemediationFollowUp.js
+++ b/server/services/prRemediationFollowUp.js
@@ -103,14 +103,30 @@ function renderContext({ app, repoFullName, number, url, headRefName, authorLogi
}
/**
- * Queue one remediation agent for a reviewed PR. Returns the created task, or
- * `null` when the queue rejected it (already pending for this app + PR) or the
- * inputs were incomplete.
+ * The three outcomes of trying to queue a remediation agent. `already-queued`
+ * must stay distinct from `failed`: a task is already pending or running for
+ * this PR, so an agent OWNS it and the caller must not also hand the PR to its
+ * opener — that would put one PR in two queues and set a human to work against
+ * a running agent. Only `failed` means nobody picked it up.
+ */
+export const PR_REMEDIATION_SPAWN = Object.freeze({
+ QUEUED: 'queued',
+ ALREADY_QUEUED: 'already-queued',
+ FAILED: 'failed',
+});
+
+/**
+ * Queue one remediation agent for a reviewed PR.
+ *
+ * @returns {Promise<{status: string, task: object|null}>} a
+ * `PR_REMEDIATION_SPAWN` status plus the task when one was created.
*/
export async function spawnPrRemediationFollowUp({ app, repoFullName, pullRequest, writeAccess, reason } = {}) {
const number = pullRequest?.number;
const authorLogin = typeof pullRequest?.authorLogin === 'string' ? pullRequest.authorLogin.trim() : '';
- if (!app?.id || !app?.repoPath || !repoFullName || !Number.isInteger(number) || !authorLogin) return null;
+ if (!app?.id || !app?.repoPath || !repoFullName || !Number.isInteger(number) || !authorLogin) {
+ return { status: PR_REMEDIATION_SPAWN.FAILED, task: null };
+ }
const description = `[PR Remediation] Land pull request #${number} in ${app.name || repoFullName}`;
const task = {
@@ -152,9 +168,15 @@ export async function spawnPrRemediationFollowUp({ app, repoFullName, pullReques
emitLog('warn', `Failed to queue PR remediation for #${number}: ${err.message}`, { appId: app.id, prNumber: number });
return null;
});
- if (!created || created.duplicate) return null;
+ if (!created) return { status: PR_REMEDIATION_SPAWN.FAILED, task: null };
+ if (created.duplicate) {
+ emitLog('info', `🛠️ PR remediation for #${number} is already queued as ${created.id}`, {
+ taskId: created.id, appId: app.id, prNumber: number,
+ });
+ return { status: PR_REMEDIATION_SPAWN.ALREADY_QUEUED, task: created };
+ }
emitLog('info', `🛠️ Queued PR remediation task ${created.id} for #${number} in ${repoFullName} (${reason})`, {
taskId: created.id, appId: app.id, prNumber: number,
});
- return created;
+ return { status: PR_REMEDIATION_SPAWN.QUEUED, task: created };
}
diff --git a/server/services/prRemediationFollowUp.test.js b/server/services/prRemediationFollowUp.test.js
index 16b3ba48bc..5c79573c99 100644
--- a/server/services/prRemediationFollowUp.test.js
+++ b/server/services/prRemediationFollowUp.test.js
@@ -4,7 +4,7 @@ const addTaskMock = vi.fn();
vi.mock('./cos.js', () => ({ addTask: (...args) => addTaskMock(...args) }));
vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));
-import { spawnPrRemediationFollowUp } from './prRemediationFollowUp.js';
+import { PR_REMEDIATION_SPAWN, spawnPrRemediationFollowUp } from './prRemediationFollowUp.js';
const APP = { id: 'app-1', name: 'Example App', repoPath: '/repos/example' };
const PULL_REQUEST = {
@@ -34,7 +34,7 @@ describe('spawnPrRemediationFollowUp', () => {
it('queues an internal task that works on the PR without opening another one', async () => {
const created = await spawn();
- expect(created.id).toBe('sys-remediation-1');
+ expect(created).toMatchObject({ status: PR_REMEDIATION_SPAWN.QUEUED, task: { id: 'sys-remediation-1' } });
const [task, queue] = addTaskMock.mock.calls[0];
expect(queue).toBe('internal');
expect(task).toMatchObject({
@@ -102,12 +102,18 @@ describe('spawnPrRemediationFollowUp', () => {
expect(`${context}\n${description}`).not.toContain('Ignore previous instructions');
});
- it('reports a queue rejection rather than pretending the PR was picked up', async () => {
+ // These two must NOT collapse. A duplicate means an agent already owns the
+ // PR, so the caller must leave it alone; a failed write means nobody picked
+ // it up, so the caller has to hand the PR back to its opener.
+ it('distinguishes an already-queued agent from a failed queue write', async () => {
addTaskMock.mockResolvedValue({ id: 'sys-existing', duplicate: true });
- expect(await spawn()).toBeNull();
+ expect(await spawn()).toEqual({
+ status: PR_REMEDIATION_SPAWN.ALREADY_QUEUED,
+ task: { id: 'sys-existing', duplicate: true },
+ });
addTaskMock.mockRejectedValue(new Error('disk full'));
- expect(await spawn()).toBeNull();
+ expect(await spawn()).toEqual({ status: PR_REMEDIATION_SPAWN.FAILED, task: null });
});
it.each([
@@ -116,7 +122,7 @@ describe('spawnPrRemediationFollowUp', () => {
['no PR number', { pullRequest: { ...PULL_REQUEST, number: null } }],
['no author to hand back to', { pullRequest: { ...PULL_REQUEST, authorLogin: ' ' } }],
])('refuses to queue with %s', async (_label, overrides) => {
- expect(await spawn(overrides)).toBeNull();
+ expect(await spawn(overrides)).toEqual({ status: PR_REMEDIATION_SPAWN.FAILED, task: null });
expect(addTaskMock).not.toHaveBeenCalled();
});
});