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: stop the branch-reconcile view listing checkouts that are already gone

Adam Eivyb453102a6e1a
diff --git a/server/services/branchReconcileInventoryPrune.js b/server/services/branchReconcileInventoryPrune.js
new file mode 100644
index 0000000000..e5eea21b22
--- /dev/null
+++ b/server/services/branchReconcileInventoryPrune.js
@@ -0,0 +1,43 @@
+/**
+ * Branch-reconcile persists its last inventory (`remaining`) so the Schedule view
+ * can offer per-row actions. Anything else that retires a checkout or branch
+ * (a claim run's own cleanup, `git worktree prune`, a later sweep) leaves that
+ * stored row behind, and the UI then offers an action on something that no
+ * longer exists. This decides which stored rows are such ghosts.
+ */
+import { execGit } from '../lib/execGit.js';
+import { pathExists } from '../lib/fileCore.js';
+
+// Rows that bind a retirement-receipt obligation are evidence, not display data.
+const isObligationRow = row => ['retirement-review-pending', 'retirement-receipt-unverified'].includes(row?.reason);
+
+async function registeredPaths(repoPath) {
+ const { stdout } = await execGit(['worktree', 'list', '--porcelain'], repoPath);
+ return new Set(stdout.split(/\r?\n/).filter(line => line.startsWith('worktree ')).map(line => line.slice(9)));
+}
+
+/**
+ * Stored inventory rows whose checkout (or, for a branch-only row, local branch)
+ * is gone from the repository. A row whose branch survives but whose checkout is
+ * gone is still a ghost checkout; the next sweep lists the branch afresh.
+ * Fails open: any git read error yields no ghosts, so a flaky read hides nothing.
+ *
+ * @param {string} repoPath
+ * @param {object[]} rows
+ * @returns {Promise<object[]>}
+ */
+export async function findGoneInventoryRows(repoPath, rows) {
+ if (!Array.isArray(rows) || !rows.length) return [];
+ const registered = await registeredPaths(repoPath);
+ const gone = [];
+ for (const row of rows) {
+ if (isObligationRow(row)) continue;
+ if (typeof row?.path === 'string' && row.path) {
+ if (!registered.has(row.path) && !await pathExists(row.path)) gone.push(row);
+ } else if (typeof row?.branch === 'string' && row.branch) {
+ const ref = await execGit(['rev-parse', '--verify', '--quiet', `refs/heads/${row.branch}`], repoPath, { ignoreExitCode: true });
+ if (ref.exitCode === 1) gone.push(row);
+ }
+ }
+ return gone;
+}
diff --git a/server/services/heldCheckoutRecovery.js b/server/services/heldCheckoutRecovery.js
index b0ff0bab2d..baae123244 100644
--- a/server/services/heldCheckoutRecovery.js
+++ b/server/services/heldCheckoutRecovery.js
@@ -18,6 +18,7 @@
* failure leaves the checkout, its lock and its branch exactly as found.
*/
+import { findGoneInventoryRows } from './branchReconcileInventoryPrune.js';
import { createReadStream, realpathSync } from 'node:fs';
import { lstat, stat, readlink, readdir, readFile, chmod } from 'node:fs/promises';
import { createHash, randomUUID } from 'node:crypto';
@@ -641,6 +642,15 @@ export async function retireInventoriedCheckout({ appId, release, review }, opts
if (!outcome?.remaining?.some?.(entry => sameRelease(entry, release))) return { ok: false, reason: 'release-not-in-inventory' };
const inventoryCurrent = async () => (await taskSchedule.getBranchReconcileOutcome(appId))?.remaining?.some(entry => sameRelease(entry, release)) === true;
const result = await retireHeldCheckout({ repoPath: app.repoPath, release, review }, { ...opts, inventoryCurrent, forgeAccount: app.forgeAccount ?? null });
+ // The row was stale: something else already removed the checkout. That is the
+ // outcome the operator asked for, so settle the row instead of refusing it.
+ if (!result.ok && result.reason === 'checkout-not-found') {
+ const gone = await findGoneInventoryRows(app.repoPath, [release]).catch(() => []);
+ if (gone.length) {
+ await taskSchedule.dropInventoryRows(appId, gone);
+ return { ok: true, alreadyRetired: true };
+ }
+ }
if (result.ok) {
await taskSchedule.recordHeldCheckoutRetirement(appId, {
path: release.path, branch: release.branch ?? null, head: release.head, branchDeleted: result.branchDeleted, archiveDir: result.archiveDir,
diff --git a/server/services/heldCheckoutRecovery.test.js b/server/services/heldCheckoutRecovery.test.js
index def46254b0..d166072566 100644
--- a/server/services/heldCheckoutRecovery.test.js
+++ b/server/services/heldCheckoutRecovery.test.js
@@ -317,6 +317,19 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()
expect(outcome.retired[0]).toMatchObject({ path: release.path, branch: 'feature/held', branchDeleted: true, archiveDir: result.archiveDir });
});
+ it('settles a stale inventory row whose checkout was already removed instead of refusing it', async () => {
+ const { path, release } = await heldCheckout('already-gone');
+ await recordBranchReconcileOutcome('app-1', {
+ status: 'incomplete', remaining: [{ ...release, reason: 'worktree-locked' }, { branch: 'other', reason: 'actionable' }],
+ });
+ await execGit(['worktree', 'unlock', path], repo);
+ await execGit(['worktree', 'remove', '--force', path], repo);
+
+ expect(await retireInventoriedCheckout({ appId: 'app-1', release }, { cosDir, readAgents: noOwners }))
+ .toEqual({ ok: true, alreadyRetired: true });
+ expect((await getBranchReconcileOutcome('app-1')).remaining).toEqual([{ branch: 'other', reason: 'actionable' }]);
+ });
+
it('refuses a release that does not name a row of the last inventory', async () => {
const { path, release } = await heldCheckout('not-inventoried');
await recordBranchReconcileOutcome('app-1', { status: 'incomplete', remaining: [{ ...release, lockReason: 'older lock text' }] });
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 5ccf9469b0..22b20e0729 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -21,6 +21,7 @@
import { scheduleExecutionFieldsSchema } from '../lib/scheduleExecutionFieldsValidation.js';
import { unresolvedRetirements, retainRetirementObligations, sameRetirementCheckout } from '../lib/reconcileRetirementEvidence.js';
+import { findGoneInventoryRows } from './branchReconcileInventoryPrune.js';
import { createHash, randomUUID } from 'node:crypto';
import { ServerError } from '../lib/errorHandler.js';
import { taskExecutionKey as executionKey } from '../lib/scheduledTaskTypes.js';
@@ -30,7 +31,7 @@ import { formatSkipCauses } from '../lib/perpetualSkipCauses.js';
import { DAY, safeDate } from '../lib/fileUtils.js';
import { mapWithConcurrency } from '../lib/mapWithConcurrency.js';
import { getAdaptiveCooldownMultiplier } from './taskLearning.js';
-import { isTaskTypeEnabledForApp, getAppTaskTypeInterval, getAppTaskTypeIntervalMs, getActiveApps, getAppTaskTypeOverrides, clearAllPrWatcherState, clearAllIssueWatcherState } from './apps.js';
+import { getAppById, isTaskTypeEnabledForApp, getAppTaskTypeInterval, getAppTaskTypeIntervalMs, getActiveApps, getAppTaskTypeOverrides, clearAllPrWatcherState, clearAllIssueWatcherState } from './apps.js';
import { loadState, isImprovementEnabled } from './cosState.js';
import { getLocalParts } from '../lib/timezone.js';
import { getUserTimezone } from './userTimezone.js';
@@ -785,6 +786,32 @@ export async function getBranchReconcileOutcome(appId) {
return resolveExecutionRecord(schedule, 'branch-reconcile', appId)?.branchReconcileOutcome ?? null;
}
+/** Remove stored inventory rows (display data only; obligations are untouched). */
+export async function dropInventoryRows(appId, rows) {
+ return updateSchedule(async (schedule) => {
+ const outcome = ensureExecutionRecord(schedule, 'branch-reconcile', appId).branchReconcileOutcome;
+ if (!Array.isArray(outcome?.remaining)) return { result: outcome ?? null, changed: false };
+ const kept = outcome.remaining.filter(entry => !rows.some(row => sameRetirementCheckout(row, entry)));
+ if (kept.length === outcome.remaining.length) return { result: outcome, changed: false };
+ outcome.remaining = kept;
+ return { result: outcome, changed: true };
+ });
+}
+
+/**
+ * Drop stored inventory rows whose checkout or branch no longer exists, so the
+ * Schedule view never offers an action on something already cleaned up.
+ * Returns the outcome as it now stands.
+ */
+async function pruneGoneInventory(appId, outcome) {
+ if (!appId || !outcome?.remaining?.length) return outcome;
+ const app = await getAppById(appId).catch(() => null);
+ if (!app?.repoPath) return outcome;
+ const gone = await findGoneInventoryRows(app.repoPath, outcome.remaining).catch(() => []);
+ if (!gone.length) return outcome;
+ return await dropInventoryRows(appId, gone).catch(() => null) ?? outcome;
+}
+
const RETIRED_CHECKOUTS_KEPT = 20;
/**
@@ -1675,11 +1702,14 @@ export async function getScheduleStatus() {
}
if (taskType === 'branch-reconcile') {
- taskStatus.reconcileOutcomes = Object.fromEntries([
+ const outcomes = [
...(execution.branchReconcileOutcome ? [[null, execution.branchReconcileOutcome]] : []),
...Object.entries(execution.perApp || {}).filter(([, record]) => record.branchReconcileOutcome)
.map(([appId, record]) => [appId, record.branchReconcileOutcome]),
- ]);
+ ];
+ taskStatus.reconcileOutcomes = Object.fromEntries(
+ await mapWithConcurrency(outcomes, 8, async ([appId, outcome]) => [appId, await pruneGoneInventory(appId, outcome)])
+ );
}
status.tasks[taskType] = taskStatus;
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index 0351f609c7..ade8bc014e 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -65,6 +65,7 @@ vi.mock('./apps.js', () => ({
getAppTaskTypeInterval: vi.fn().mockResolvedValue(null),
getAppTaskTypeIntervalMs: vi.fn().mockResolvedValue(null),
getActiveApps: vi.fn().mockResolvedValue([]),
+ getAppById: vi.fn().mockResolvedValue(null),
getAppTaskTypeOverrides: vi.fn().mockResolvedValue({}),
clearAllPrWatcherState: vi.fn().mockResolvedValue({ changed: false }),
clearAllIssueWatcherState: vi.fn().mockResolvedValue({ changed: false })