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(cos): expose held checkout recovery inventory (#12002)

Adam Eivy9ddd9adc079e
diff --git a/client/src/components/cos/tabs/ScheduleTab.jsx b/client/src/components/cos/tabs/ScheduleTab.jsx
index 78c88303ee..4a22fe8177 100644
--- a/client/src/components/cos/tabs/ScheduleTab.jsx
+++ b/client/src/components/cos/tabs/ScheduleTab.jsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, useCallback } from 'react';
+import { useCallback } from 'react';
import { useSearchParams } from 'react-router';
import { AlertCircle, RefreshCw } from 'lucide-react';
import toast from '../../ui/Toast';
@@ -7,10 +7,13 @@ import { formatDateTime, formatTimeOfDaySeconds, timeAgo } from '../../../utils/
import Banner from '../../ui/Banner';
import { CodeReviewDefaultsProvider } from '../../../hooks/useCodeReviewDefaults';
import { useAppOverrideActions } from '../../../hooks/useAppOverrideActions';
+import { useSocketResource } from '../../../hooks/useSocketResource';
import AppTaskTypeSection from './schedule/AppTaskTypeSection';
import TaskConfigDrawer from './schedule/TaskConfigDrawer';
import { TASK_FILTERS, DEFAULT_FILTER_ID, TASK_SORTS, DEFAULT_SORT_ID, suggestedOrderSteps } from './schedule/scheduleConstants';
+const SCHEDULE_EVENTS = ['cos:schedule:changed'];
+
export function mergeUpdatedTaskInterval(schedule, taskType, interval, status) {
if (!schedule) return schedule;
return {
@@ -43,9 +46,10 @@ function mergeOnDemandRequest(schedule, request) {
// same data.
export default function ScheduleTab({ apps, providers, providersLoaded, activeProviderId, daemonRunning }) {
const [searchParams, setSearchParams] = useSearchParams();
- const [schedule, setSchedule] = useState(null);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState(null);
+ const { data: schedule, updateData: setSchedule, loading, error, refetch: fetchSchedule } = useSocketResource(
+ () => api.getCosSchedule({ silent: true }),
+ { namespace: 'cos', events: SCHEDULE_EVENTS }
+ );
const label = searchParams.get('label') || '';
const setLabel = next => {
@@ -84,23 +88,6 @@ export default function ScheduleTab({ apps, providers, providersLoaded, activePr
setSearchParams(params, { replace: true });
}, [searchParams, setSearchParams]);
- const fetchSchedule = useCallback(async () => {
- const data = await api.getCosSchedule({ silent: true }).catch(err => {
- setError(err?.message || 'Failed to load task schedule');
- return null;
- });
- if (data) {
- setSchedule(data);
- setError(null);
- }
- setLoading(false);
- return data;
- }, []);
-
- useEffect(() => {
- fetchSchedule();
- }, [fetchSchedule]);
-
// Resolves a boolean so optimistic callers (the card's quick model pins) can
// roll their local selection back — this handler owns the error toast, so it
// never rejects. Stable identity: every card holds it through useTaskModelPins,
@@ -119,7 +106,7 @@ export default function ScheduleTab({ apps, providers, providersLoaded, activePr
// stale render while a background refetch is still in flight.
setSchedule(current => mergeUpdatedTaskInterval(current, taskType, result.interval, result.status));
return true;
- }, []);
+ }, [setSchedule]);
const handleTriggerTask = useCallback(async (taskType, appId = null) => {
const result = await api.triggerCosOnDemandTask(taskType, appId, { silent: true }).catch(err => {
@@ -145,7 +132,7 @@ export default function ScheduleTab({ apps, providers, providersLoaded, activePr
}
fetchSchedule();
return result.request || true;
- }, [apps, fetchSchedule, daemonRunning]);
+ }, [apps, fetchSchedule, daemonRunning, setSchedule]);
const handleTriggerAppImprovement = handleTriggerTask;
@@ -197,7 +184,7 @@ export default function ScheduleTab({ apps, providers, providersLoaded, activePr
{error && (
<Banner tone="error" icon={AlertCircle} title="Schedule unavailable — showing the last loaded schedule">
- {error}
+ {error.message || String(error)}
</Banner>
)}
diff --git a/client/src/components/cos/tabs/ScheduleTab.test.jsx b/client/src/components/cos/tabs/ScheduleTab.test.jsx
index 2fc5e02247..dfdfba7a4c 100644
--- a/client/src/components/cos/tabs/ScheduleTab.test.jsx
+++ b/client/src/components/cos/tabs/ScheduleTab.test.jsx
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { render, screen, waitFor } from '@testing-library/react';
+import { act, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router';
import { __resetToolUseModelIdsCache } from '../../../hooks/useToolUseModelIds.js';
@@ -264,3 +264,21 @@ it('keeps the last saved schedule after a refresh failure', async () => {
expect(screen.getByText('Security')).toBeVisible();
expect(screen.queryByText('Failed to load task schedule')).not.toBeInTheDocument();
});
+
+it('refreshes the reconciliation inventory on a schedule event without polling', async () => {
+ const config = { type: 'on-demand', enabled: true, displayName: 'Branch Reconciler' };
+ api.getCodeReviewDefaults.mockResolvedValue({});
+ api.getCosSchedule.mockReset().mockResolvedValueOnce({ tasks: { 'branch-reconcile': config } })
+ .mockResolvedValueOnce({ tasks: { 'branch-reconcile': { ...config, reconcileOutcomes: {
+ example: { status: 'incomplete', reason: 'worktree-locked', observedAt: '2026-10-01T00:00:00Z', remaining: [
+ { path: '/example/held', reason: 'worktree-locked', locked: true, lockReason: 'owner handoff' },
+ ] },
+ } } } });
+ render(<MemoryRouter><ScheduleTab apps={[{ id: 'example', name: 'Example App' }]} providers={[]} providersLoaded /></MemoryRouter>);
+ await screen.findByText('Branch Reconciler');
+ const handler = socket.on.mock.calls.findLast(([event]) => event === 'cos:schedule:changed')[1];
+ await act(async () => handler());
+ expect(await screen.findByText(/Example App · Incomplete/)).toBeTruthy();
+ expect(screen.getByText('Lock: owner handoff')).toBeTruthy();
+ expect(api.getCosSchedule).toHaveBeenCalledTimes(2);
+});
diff --git a/client/src/components/cos/tabs/schedule/AppTaskCard.jsx b/client/src/components/cos/tabs/schedule/AppTaskCard.jsx
index d28876d412..3c084a3027 100644
--- a/client/src/components/cos/tabs/schedule/AppTaskCard.jsx
+++ b/client/src/components/cos/tabs/schedule/AppTaskCard.jsx
@@ -8,6 +8,7 @@ import TaskModelQuickControls from './TaskModelQuickControls';
import ToggleSwitch from '../../../ToggleSwitch';
import { isCronExpression } from '../../../../utils/cronHelpers';
import Banner from '../../../ui/Banner';
+import BranchReconcileOutcome from './BranchReconcileOutcome';
// One scheduled task rendered as a status-rich card. Browsing plus the common
// "retarget the model and run it" loop happen here; the rest of the
@@ -96,6 +97,10 @@ export default function AppTaskCard({ taskType, config, apps, onTrigger, onConfi
</div>}
</button>
+ {taskType === 'branch-reconcile' && !appContext && (
+ <BranchReconcileOutcome outcomes={config.reconcileOutcomes} apps={apps} />
+ )}
+
{config.enabled === false && (
<Banner
tone="warning"
diff --git a/client/src/components/cos/tabs/schedule/AppTaskCard.test.jsx b/client/src/components/cos/tabs/schedule/AppTaskCard.test.jsx
index 2278677f9a..4c7565fe63 100644
--- a/client/src/components/cos/tabs/schedule/AppTaskCard.test.jsx
+++ b/client/src/components/cos/tabs/schedule/AppTaskCard.test.jsx
@@ -51,6 +51,34 @@ function renderCardWithPins(overrides = {}, props = {}) {
}
describe('AppTaskCard', () => {
+ it('exposes held checkout evidence and recovery prerequisites independently of coordinator success', () => {
+ renderCard({ perpetual: false, reconcileOutcomes: {
+ example: { status: 'incomplete', reason: 'merged-branches-held-back', observedAt: '2026-10-01T00:00:00Z', nextAction: 'Resolve the listed holds and run again.', remaining: [
+ { path: '/example/held', branch: 'fix/example', head: 'abc123', locked: true, lockReason: '<script>owner handoff</script>', managed: false, reason: 'worktree-locked' },
+ ] },
+ } }, { apps: [{ id: 'example', name: 'Example App' }] }, 'branch-reconcile');
+ fireEvent.click(screen.getByText(/Example App · Incomplete/));
+ expect(screen.getByText('/example/held')).toBeVisible();
+ expect(screen.getByText('HEAD: abc123')).toBeVisible();
+ expect(screen.getByText('Lock: <script>owner handoff</script>')).toBeVisible();
+ expect(document.querySelector('script')).toBeNull();
+ expect(screen.getByText('Outside managed worktree roots')).toBeVisible();
+ expect(screen.getByText(/Checkout recovery requires verified owner authority/)).toBeVisible();
+ expect(screen.getByText('Resolve the listed holds and run again.')).toBeVisible();
+ expect(screen.queryByRole('button', { name: /Remove|Unlock|Retire/i })).toBeNull();
+ });
+
+ it('distinguishes an unreadable inventory from a completed empty scan', () => {
+ renderCard({ reconcileOutcomes: {
+ example: { status: 'incomplete', remaining: null, observedAt: null },
+ empty: { status: 'drained', remaining: [], observedAt: '2026-10-01T00:00:00Z' },
+ } }, {}, 'branch-reconcile');
+ expect(screen.getByText(/example · Incomplete/)).toBeTruthy();
+ expect(screen.getByText('Remaining work is unknown.')).toBeTruthy();
+ expect(screen.getByText('No readable inventory yet.')).toBeTruthy();
+ expect(screen.getByText(/empty · No remaining work in last scan · 0 remaining/)).toBeTruthy();
+ });
+
it('shows app coverage prominently', () => {
renderCard();
expect(screen.getByText('3/5 apps')).toBeTruthy();
diff --git a/client/src/components/cos/tabs/schedule/BranchReconcileOutcome.jsx b/client/src/components/cos/tabs/schedule/BranchReconcileOutcome.jsx
new file mode 100644
index 0000000000..37265ca7aa
--- /dev/null
+++ b/client/src/components/cos/tabs/schedule/BranchReconcileOutcome.jsx
@@ -0,0 +1,42 @@
+import { formatCount, formatDateTime } from '../../../../utils/formatters';
+
+const STATUS_LABELS = { drained: 'No remaining work in last scan', incomplete: 'Incomplete', running: 'Sweep running' };
+
+// A persisted scan describes convergence independently of coordinator success.
+// Paths and lock text are display data, never executable recovery instructions.
+export default function BranchReconcileOutcome({ outcomes, apps }) {
+ if (!outcomes || !Object.keys(outcomes).length) return null;
+ return (
+ <div className="mx-4 mb-3 space-y-2 text-xs">
+ {Object.entries(outcomes).map(([appId, outcome]) => (
+ <details key={appId} className="rounded border border-port-border p-2">
+ <summary className="cursor-pointer text-gray-300">
+ {apps?.find(app => app.id === appId)?.name || (appId === 'null' ? 'Repository' : appId)}
+ {' · '}{STATUS_LABELS[outcome.status] || 'Outcome unavailable'}
+ {Array.isArray(outcome.remaining) && ` · ${formatCount(outcome.remaining.length)} remaining`}
+ </summary>
+ <div className="mt-2 space-y-2 text-gray-400">
+ <p>{outcome.observedAt ? `Last inventory: ${formatDateTime(outcome.observedAt)}` : 'No readable inventory yet.'}</p>
+ {outcome.reason && <p className="break-words">Reason: {outcome.reason}</p>}
+ {outcome.nextAction && <p>{outcome.nextAction}</p>}
+ {!Array.isArray(outcome.remaining) && <p>Remaining work is unknown.</p>}
+ <ul className="space-y-2 max-h-64 overflow-y-auto">
+ {(outcome.remaining || []).map((entry, index) => (
+ <li key={`${entry.path || entry.branch || entry.issue || entry.reason}:${index}`} className="break-words border-t border-port-border pt-2">
+ <p className="text-gray-300">{entry.branch || (entry.detached ? 'Detached checkout' : entry.issue ? `Issue #${entry.issue}` : 'Repository scan')}: {entry.reason}</p>
+ {entry.path && <p className="break-all">{entry.path}</p>}
+ {entry.head && <p className="break-all">HEAD: {entry.head}</p>}
+ {entry.locked && <p>Lock: {entry.lockReason || 'No reason recorded'}</p>}
+ {entry.managed === false && <p>Outside managed worktree roots</p>}
+ </li>
+ ))}
+ </ul>
+ {(outcome.remaining || []).some(entry => entry.path) && (
+ <p>Checkout recovery requires verified owner authority or a scoped release, fresh ownership and merge checks, and a verified archive of unique tracked, untracked and ignored content. Lock age, an absent process, and lock text do not prove release. Keep active owners and manual handoffs protected.</p>
+ )}
+ </div>
+ </details>
+ ))}
+ </div>
+ );
+}
diff --git a/docs/README.md b/docs/README.md
index 3672e6013f..38da8f7d58 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -69,7 +69,7 @@ Start with the [product surface map](./features/product-surfaces.md) for a compl
App management: [app-wizard](./features/app-wizard.md) · [app-quality](./features/app-quality.md) · [autofixer](./features/autofixer.md) · [browser](./features/browser.md) · [error-handling](./features/error-handling.md) · [jira-sprint-manager](./features/jira-sprint-manager.md)
-Chief of Staff: [chief-of-staff](./features/chief-of-staff.md) · [cos-agent-runner](./features/cos-agent-runner.md) · [cos-enhancement](./features/cos-enhancement.md) · [self-improvement-audits](./features/self-improvement-audits.md) · [agent-context](./features/agent-context.md) · [agent-skills](./features/agent-skills.md) · [memory-system](./features/memory-system.md) · [claude-ollama](./features/claude-ollama.md) · [grok-box-local-mind](./features/grok-box-local-mind.md) · [fleet-llm-host](./features/fleet-llm-host.md) · [mtplx](./features/mtplx.md) · [slotstream](./features/slotstream.md) · [dflash2](./features/dflash2.md) ([DSpark vs DFlash 2](./research/2026-08-19-dspark-vs-dflash2.md), [Ternary Bonsai 2 27B](./research/2026-09-18-ternary-bonsai-2-27b.md)) · [qwen38-rtx3090](./features/qwen38-rtx3090.md) ([3090 bring-up](./research/2026-08-21-qwen38-rtx3090-vllm.md)) · [sglang-qwen38](./features/sglang-qwen38.md) ([SGLang Hopper/Blackwell evaluation](./research/2026-08-21-sglang-qwen38-27b.md)) · [prompt-manager](./features/prompt-manager.md) · [development-watchdog](./features/development-watchdog.md) · [review-queue](./features/review-queue.md) · [scheduled-audit-organization](./features/scheduled-audit-organization.md)
+Chief of Staff: [chief-of-staff](./features/chief-of-staff.md) · [branch-reconciliation](./features/branch-reconciliation.md) · [cos-agent-runner](./features/cos-agent-runner.md) · [cos-enhancement](./features/cos-enhancement.md) · [self-improvement-audits](./features/self-improvement-audits.md) · [agent-context](./features/agent-context.md) · [agent-skills](./features/agent-skills.md) · [memory-system](./features/memory-system.md) · [claude-ollama](./features/claude-ollama.md) · [grok-box-local-mind](./features/grok-box-local-mind.md) · [fleet-llm-host](./features/fleet-llm-host.md) · [mtplx](./features/mtplx.md) · [slotstream](./features/slotstream.md) · [dflash2](./features/dflash2.md) ([DSpark vs DFlash 2](./research/2026-08-19-dspark-vs-dflash2.md), [Ternary Bonsai 2 27B](./research/2026-09-18-ternary-bonsai-2-27b.md)) · [qwen38-rtx3090](./features/qwen38-rtx3090.md) ([3090 bring-up](./research/2026-08-21-qwen38-rtx3090-vllm.md)) · [sglang-qwen38](./features/sglang-qwen38.md) ([SGLang Hopper/Blackwell evaluation](./research/2026-08-21-sglang-qwen38-27b.md)) · [prompt-manager](./features/prompt-manager.md) · [development-watchdog](./features/development-watchdog.md) · [review-queue](./features/review-queue.md) · [scheduled-audit-organization](./features/scheduled-audit-organization.md)
Federation: [peer-administration](./features/peer-administration.md) · [tailcat-peers](./features/tailcat-peers.md) · Models: [decision-classifiers](./features/decision-classifiers.md)
- [Persistent Mind continuous play + local context](./features/persistent-mind-continuous-play.md) — explore/invent playbook and mind-adjustable `numCtx` clamps
diff --git a/docs/features/branch-reconciliation.md b/docs/features/branch-reconciliation.md
new file mode 100644
index 0000000000..aa85ffc449
--- /dev/null
+++ b/docs/features/branch-reconciliation.md
@@ -0,0 +1,34 @@
+# Branch reconciliation outcomes
+
+In **Chief of Staff > Schedule**, expand the outcome beneath the
+`branch-reconcile` task. Each app has its own persisted outcome, separate from
+whether its coordinator agent completed successfully. The card updates on
+schedule changes and reconnects.
+
+A manual run continues through eligible batches even when perpetual scheduling
+is disabled. No-progress and dispatch limits bound that sweep. A failed provider,
+unreadable scan, ownership uncertainty, or remaining hold produces an incomplete
+outcome rather than implying repository convergence. The inventory timestamp is
+the last observation; an interruption can preserve an older inventory.
+
+The remaining-work list includes branch holds and a post-cleanup inventory of
+secondary checkouts. It shows checkout paths, HEADs, detached state, lock text,
+and whether a checkout lies outside managed roots. Detached checkouts with
+unmerged work are included, even though merged-checkout cleanup cannot retire
+them. A failed or empty Git checkout listing is unknown evidence and prevents a
+completed empty-scan outcome. Lock text is descriptive data, never authority.
+
+This is a recovery inventory, not an unlock or retirement control. Retained
+checkouts remain protected. Before a future recovery action can retire one, it
+must prove existing owner authority or an explicit scoped release, recheck the
+exact checkout/HEAD, merge evidence and ownership immediately before mutation,
+and verify a recoverable archive of all unique tracked, untracked and ignored
+content. An archive failure must leave the checkout and branch intact. Lock age,
+an absent process, and natural-language lock text do not prove release; live
+owners and manual handoffs remain protected.
+
+The remaining scope of #12002 is an enforceable scoped release and archived
+retirement workflow with ownership-change and archive-failure integration tests.
+The inventory does not grant that authority. Long-lived protected branches and
+the primary checkout remain governed by the existing reconciliation policy;
+an empty reported work list is not permission to remove them.
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index 12fe5a34b2..d6e31c7b4c 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -1017,7 +1017,7 @@ export async function gatherBranchState(repoPath, { defaultBranch, activeAgentId
* Persist counts and typed causes, with the earliest known hold expiry as the
* next possible wake-up; raw cleanup diagnostics stay out of scheduler state.
*/
-export function describeIdleReconcilePark(skipped = [], heldLive = [], { wip = [], detachedWorktrees = [], superseded = [], gated = [], claimMarkersHeld = [] } = {}) {
+export function describeIdleReconcilePark(skipped = [], heldLive = [], { wip = [], detachedWorktrees = [], superseded = [], gated = [], claimMarkersHeld = [], worktreeInventory = [] } = {}) {
// One entry per surviving branch/checkout, even when it appears in both the
// skipped and detached/superseded projections. Never persist raw error text.
const holds = new Map();
@@ -1041,6 +1041,16 @@ export function describeIdleReconcilePark(skipped = [], heldLive = [], { wip = [
for (const entry of gated) add(entry, entry.openPr?.isDraft ? 'draft-review-required' : 'action-disabled');
// Marker cleanup is distinct from successful local branch retirement.
for (const entry of claimMarkersHeld) add({ ...entry, claimMarker: true }, entry.reason || 'claim-marker-held', `claim-marker:${entry.issue ?? entry.branch}`);
+ // Include checkouts the branch classifier cannot see (protected branches,
+ // detached unmerged HEADs, stale registrations), and enrich existing holds.
+ // Inventory is evidence only: a lock's prose never grants release authority.
+ const holdKeysByPath = new Map([...holds].map(([key, entry]) => [entry.path || entry.worktreePath, key]));
+ for (const tree of worktreeInventory || []) {
+ const key = holdKeysByPath.get(tree.path) ?? tree.branch ?? tree.path;
+ const existing = holds.get(key);
+ add({ ...tree, ...existing }, existing?.cause || tree.reason, key);
+ }
+ if (worktreeInventory === null) add({}, 'worktree-inventory-unavailable', 'worktree-inventory-unavailable');
const entries = [...holds.values()];
const heldBackMerged = skipped.filter(s => !s.detached && s.reason?.startsWith('worktree-'));
const skipCauses = {};
@@ -1061,6 +1071,10 @@ export function describeIdleReconcilePark(skipped = [], heldLive = [], { wip = [
...(entry.branch && { branch: entry.branch }),
...((entry.path || entry.worktreePath) && { path: entry.path || entry.worktreePath }),
...(entry.issue && { issue: entry.issue }),
+ ...(entry.head && { head: entry.head }),
+ ...(entry.locked !== undefined && { locked: entry.locked, lockReason: entry.lockReason ?? null }),
+ ...(entry.detached && { detached: true }),
+ ...(entry.managed !== undefined && { managed: entry.managed }),
reason: entry.cause,
})),
notLaterThan: lifts.length ? new Date(Math.min(...lifts)).toISOString() : null
@@ -1414,6 +1428,27 @@ const isCommitOnBranch = (repoPath, sha, branch) =>
.then((r) => r?.exitCode === 0)
.catch(() => false);
+// Read after cleanup so removed holders cannot survive in the recovery report.
+// No content or ownership inference: retirement still uses its existing gates.
+async function gatherRecoveryWorktrees(repoPath) {
+ const trees = await listWorktrees(repoPath).catch(() => null);
+ if (!trees?.length) return null;
+ return trees.slice(1).filter(tree => !tree.bare).map(tree => {
+ const managed = worktreeOwnershipReason({ path: tree.path, roots: reconcileWorktreeRoots(repoPath), allowLiveClaim: true }) !== 'worktree-unmanaged-location';
+ return {
+ path: tree.path,
+ ...(tree.branch && { branch: tree.branch.replace(/^refs\/heads\//, '') }),
+ head: tree.head ?? null,
+ detached: !tree.branch,
+ locked: Boolean(tree.locked),
+ lockReason: tree.lockReason ?? null,
+ managed,
+ reason: tree.prunable ? 'worktree-prunable' : tree.locked ? 'worktree-locked'
+ : !managed ? 'worktree-unmanaged-location' : 'checkout-retained',
+ };
+ });
+}
+
const isStillDetachedOnMerged = async (repoPath, treePath, defaultBranch) => {
const onBranch = await execGit(['symbolic-ref', '-q', 'HEAD'], treePath, { ignoreExitCode: true })
.then((r) => r?.exitCode === 0)
@@ -1669,6 +1704,7 @@ export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapSup
skipped: [...skipped, ...supersededReap.skipped, ...detachedReap.skipped],
// Detached trees at merged commits that were NOT removed, managed or not.
detachedWorktrees: detachedReap.held,
+ worktreeInventory: await gatherRecoveryWorktrees(repoPath),
orphanRemotes,
prStateUnavailable
};
diff --git a/server/services/branchReconcile.ownership.test.js b/server/services/branchReconcile.ownership.test.js
index e72ab9a9fe..ac5c57c93c 100644
--- a/server/services/branchReconcile.ownership.test.js
+++ b/server/services/branchReconcile.ownership.test.js
@@ -54,7 +54,7 @@ vi.mock('./supersededLedger.js', async (importOriginal) => ({
readVerdictLedger: async () => [],
}));
-const { reconcile, cleanupMerged, reapSupersededBranches } = await import('./branchReconcile.js');
+const { reconcile, cleanupMerged, reapSupersededBranches, describeIdleReconcilePark } = await import('./branchReconcile.js');
const { clearAgentDispatching, getActiveAgentIds, markAgentDispatching } = await import('./agentState.js');
const { deleteMergedBranches } = await import('./git.js');
@@ -90,6 +90,33 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch-reconcile worktree ownership (re
}
const branches = async () => (await execGit(['branch', '--format=%(refname:short)'], repo)).stdout.trim().split('\n');
+ // Git expands Windows' short TEMP spelling and emits forward slashes; the
+ // inventory promises Git's checkout path, not Node's fixture-input spelling.
+ const gitCheckoutPath = async (path) => (await execGit(['rev-parse', '--show-toplevel'], path)).stdout.trim();
+
+ it('reports an unmerged detached checkout without discarding its tracked, untracked or ignored content', async () => {
+ const path = await addTree(join(external, 'detached-work'), 'temporary-work');
+ await writeFile(join(path, 'tracked.txt'), 'unique committed work\n');
+ await writeFile(join(path, '.gitignore'), 'ignored.txt\n');
+ await execGit(['add', 'tracked.txt', '.gitignore'], path);
+ await execGit(['commit', '-m', 'feat: synthetic detached work'], path);
+ const head = (await execGit(['rev-parse', 'HEAD'], path)).stdout.trim();
+ await execGit(['checkout', '--detach'], path);
+ await execGit(['branch', '-D', 'temporary-work'], repo);
+ await writeFile(join(path, 'untracked.txt'), 'unique untracked work\n');
+ await writeFile(join(path, 'ignored.txt'), 'unique ignored work\n');
+ await execGit(['worktree', 'lock', '--reason', 'explicit owner handoff required', path], repo);
+
+ const result = await reconcile(repo, { activeAgentIds: new Set() });
+ expect(result.detachedWorktrees).toEqual([]); // old merged-only projection cannot see it
+ const report = describeIdleReconcilePark(result.skipped, [], { worktreeInventory: result.worktreeInventory });
+ expect(report.remaining).toEqual([{
+ path: await gitCheckoutPath(path), head, detached: true, locked: true, lockReason: 'explicit owner handoff required',
+ managed: false, reason: 'worktree-locked',
+ }]);
+ for (const name of ['tracked.txt', 'untracked.txt', 'ignored.txt']) expect(existsSync(join(path, name))).toBe(true);
+ expect((await execGit(['rev-parse', 'HEAD'], path)).stdout.trim()).toBe(head);
+ });
it('retires inactive managed trees but never a fresh or old unmanaged one', async () => {
const claudeRoot = join(repo, '.claude', 'worktrees');
@@ -98,10 +125,11 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch-reconcile worktree ownership (re
const old = await addTree(join(external, 'old-workspace'), 'old-workspace', { ageMs: 30 * DAY });
const staleClaim = await addTree(join(claudeRoot, 'claim-issue-5'), 'claim/issue-5', { ageMs: 30 * DAY });
const lockedClaim = await addTree(join(claudeRoot, 'claim-issue-6'), 'claim/issue-6', { ageMs: 30 * DAY });
- await execGit(['worktree', 'lock', lockedClaim], repo);
+ await execGit(['worktree', 'lock', '--reason', 'await scoped owner release', lockedClaim], repo);
const dirtyClaim = await addTree(join(claudeRoot, 'claim-issue-7'), 'claim/issue-7');
await writeFile(join(dirtyClaim, 'wip.txt'), 'unsaved\n');
await utimes(dirtyClaim, new Date(Date.now() - 30 * DAY), new Date(Date.now() - 30 * DAY));
+ const staleClaimPath = await gitCheckoutPath(staleClaim);
const result = await reconcile(repo, { activeAgentIds: new Set() });
const reasonFor = (branch) => result.skipped.find((s) => s.branch === branch)?.reason;
@@ -118,6 +146,17 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch-reconcile worktree ownership (re
expect(existsSync(staleClaim)).toBe(false);
expect(reasonFor('claim/issue-6'), context).toBe('worktree-locked');
expect(existsSync(lockedClaim)).toBe(true);
+ const report = describeIdleReconcilePark(result.skipped, [], {
+ wip: result.wip, worktreeInventory: result.worktreeInventory,
+ });
+ expect(report.remaining).toContainEqual(expect.objectContaining({
+ branch: 'claim/issue-6', path: await gitCheckoutPath(lockedClaim), reason: 'worktree-locked',
+ head: expect.any(String), locked: true, lockReason: 'await scoped owner release', managed: true,
+ }));
+ expect(report.remaining).toContainEqual(expect.objectContaining({
+ branch: 'old-workspace', path: await gitCheckoutPath(old), reason: 'worktree-unmanaged-location', managed: false,
+ }));
+ expect(report.remaining.some(entry => entry.path === staleClaimPath)).toBe(false);
expect(result.cleaned, context).not.toContain('claim/issue-7');
expect(existsSync(dirtyClaim)).toBe(true);
diff --git a/server/services/branchReconcileSweep.test.js b/server/services/branchReconcileSweep.test.js
index 23556a988a..0d1dc6c8fb 100644
--- a/server/services/branchReconcileSweep.test.js
+++ b/server/services/branchReconcileSweep.test.js
@@ -87,6 +87,9 @@ describe('manual branch reconciliation sweep', () => {
it.each([
[{ skipped: [{ branch: 'moved', reason: 'not-merged-on-recheck' }] }, { branch: 'moved', reason: 'not-merged-on-recheck' }],
[{ orphanRemotes: { remoteUnavailable: true, reported: [] } }, { reason: 'remote-state-unavailable' }],
+ [{ worktreeInventory: null }, { reason: 'worktree-inventory-unavailable' }],
+ [{ worktreeInventory: [{ path: '/example/unmerged-detached', detached: true, head: 'abc123', locked: true, lockReason: 'owner handoff', managed: false, reason: 'worktree-locked' }] },
+ { path: '/example/unmerged-detached', detached: true, head: 'abc123', locked: true, lockReason: 'owner handoff', managed: false, reason: 'worktree-locked' }],
])('does not report drained when the final scan has incomplete evidence (%j)', async (extra, remaining) => {
reconcile.mockResolvedValue(scan([], extra));
expect(await run()).toEqual({ skip: true });
diff --git a/server/services/cosTaskPreStepBlocks.js b/server/services/cosTaskPreStepBlocks.js
index aa47897963..26d187eb4a 100644
--- a/server/services/cosTaskPreStepBlocks.js
+++ b/server/services/cosTaskPreStepBlocks.js
@@ -506,9 +506,11 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskS
// A detached worktree has no branch to list anywhere else, so name it here too.
const detachedSuffix = countSuffix(result.detachedWorktrees, 'detached worktree(s) held back', (d) => d.reason);
const allActionable = filterActionable(result.inFlight, actions);
+ const actionableNames = new Set(allActionable.map(branch => branch.branch));
const idlePark = describeIdleReconcilePark(result.skipped || [], heldLive, {
wip: result.wip, detachedWorktrees: result.detachedWorktrees, superseded: result.superseded,
claimMarkersHeld: result.claimMarkersHeld,
+ worktreeInventory: result.worktreeInventory?.filter(tree => !actionableNames.has(tree.branch)) ?? result.worktreeInventory,
gated: result.inFlight.filter(branch => !allActionable.includes(branch))
});
// This is a scan outcome, not the coordinator's success flag or a claim that
diff --git a/server/services/creative/creativeRunLedger.test.js b/server/services/creative/creativeRunLedger.test.js
index f825755464..ceb380a86a 100644
--- a/server/services/creative/creativeRunLedger.test.js
+++ b/server/services/creative/creativeRunLedger.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
-import { mkdtemp, rm } from 'fs/promises';
+import { mkdtemp, rm, writeFile } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
import { argsDigest, appendCreativeLedgerEntry, readCreativeLedger, MAX_LEDGER_ENTRIES } from './creativeRunLedger.js';
@@ -46,12 +46,17 @@ describe('creative run ledger store', () => {
});
it('caps at MAX_LEDGER_ENTRIES, keeping the most recent', async () => {
- for (let i = 0; i < MAX_LEDGER_ENTRIES + 5; i += 1) {
- await appendCreativeLedgerEntry('proj-1', { tool: `t.${i}`, outcome: 'executed' }, { dir });
- }
+ // Exercise retention through the public append boundary with a persisted
+ // full ledger, without 505 durable setup writes timing out on Windows.
+ const existing = Array.from({ length: MAX_LEDGER_ENTRIES }, (_, i) => ({
+ at: '2026-01-01T00:00:00.000Z', tool: `t.${i}`, outcome: 'executed',
+ }));
+ await writeFile(join(dir, 'proj-1.json'), JSON.stringify(existing));
+ await appendCreativeLedgerEntry('proj-1', { tool: `t.${MAX_LEDGER_ENTRIES}`, outcome: 'executed' }, { dir });
const list = await readCreativeLedger('proj-1', { dir });
expect(list.length).toBe(MAX_LEDGER_ENTRIES);
- expect(list[list.length - 1].tool).toBe(`t.${MAX_LEDGER_ENTRIES + 4}`);
+ expect(list[0]).toEqual(existing[1]);
+ expect(list[list.length - 1].tool).toBe(`t.${MAX_LEDGER_ENTRIES}`);
});
it('returns [] for an absent ledger', async () => {
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index e250a9bcd5..6ffae858e0 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -1527,6 +1527,7 @@ export async function listWorktrees(sourceWorkspace) {
} else if (line === 'locked' || line.startsWith('locked ')) {
// `git worktree list --porcelain` emits a bare `locked` line, or `locked <reason>`.
current.locked = true;
+ current.lockReason = line.startsWith('locked ') ? line.slice(7) : null;
} else if (line === 'prunable' || line.startsWith('prunable ')) {
// Same two spellings. Set when git considers the registration disposable —
// its directory is gone, or its .git pointer no longer resolves.
diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.js
index c45ce5ed1d..093008d7d0 100644
--- a/server/services/worktreeManager.test.js
+++ b/server/services/worktreeManager.test.js
@@ -367,7 +367,7 @@ describe('listWorktrees line endings', () => {
'worktree /repo/.claude/worktrees/wt',
'HEAD def456',
'branch refs/heads/feature',
- 'locked',
+ 'locked waiting for explicit owner handoff',
'prunable',
'',
'worktree /repo/detached',
@@ -392,6 +392,7 @@ describe('listWorktrees line endings', () => {
head: 'def456',
branch: 'refs/heads/feature',
locked: true,
+ lockReason: 'waiting for explicit owner handoff',
prunable: true,
});
expect(worktrees[2]).toEqual({ path: '/repo/detached', head: 'fed789', detached: true });