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: refresh branch reconciliation inventory and separate archive history

[._.]/ Adam Eivy3a5d422746fd
diff --git a/client/src/components/cos/tabs/schedule/BranchReconcileOutcome.jsx b/client/src/components/cos/tabs/schedule/BranchReconcileOutcome.jsx
index befd634689..7212fe58be 100644
--- a/client/src/components/cos/tabs/schedule/BranchReconcileOutcome.jsx
+++ b/client/src/components/cos/tabs/schedule/BranchReconcileOutcome.jsx
@@ -1,6 +1,6 @@
-import { useId, useState } from 'react';
+import { useId, useRef, useState } from 'react';
import { formatCount, formatDateTime } from '../../../../utils/formatters';
-import { retireBranchReconcileCheckout, reviewBranchReconcileCheckout } from '../../../../services/api';
+import { retireBranchReconcileCheckout, reviewBranchReconcileCheckout, refreshBranchReconcileInventory } from '../../../../services/api';
const STATUS_LABELS = { drained: 'No remaining work in last scan', incomplete: 'Incomplete', running: 'Sweep running' };
@@ -10,6 +10,20 @@ const isInventoriedCheckout = entry => Boolean(!entry.checkoutMissing && entry.p
const checkoutKey = (appId, entry) => `${appId}\0${entry.path}\0${entry.head}`;
const NONE = new Set();
+function InventoryEntry({ appId, entry, onRetired }) {
+ return (
+ <li 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.checkoutMissing || entry.branchMissing) && <p>Original checkout or branch no longer exists. Its historical archive evidence is unresolved and retained separately from current local work.</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>}
+ {appId !== 'null' && isInventoriedCheckout(entry) && <RetireCheckout key={JSON.stringify([appId, entry.path, entry.head, entry.branch, entry.locked, entry.lockReason, entry.reason])} appId={appId} entry={entry} onRetired={onRetired} />}
+ </li>
+ );
+}
+
// The confirmation IS the scoped release: it names this row's path, HEAD,
// branch and lock text, and the server refuses if any of them changed since.
function RetireCheckout({ appId, entry, onRetired }) {
@@ -89,37 +103,69 @@ export default function BranchReconcileOutcome({ outcomes, apps }) {
// Hides a retired row at once. Scoped to the outcomes it was retired from:
// the schedule event's fresh inventory is authoritative once it arrives.
const [retired, setRetired] = useState({ source: outcomes, keys: NONE });
+ const [refreshed, setRefreshed] = useState({ source: outcomes, values: {} });
+ const [refreshStates, setRefreshStates] = useState({});
+ const pending = useRef(new Set());
const retiredKeys = retired.source === outcomes ? retired.keys : NONE;
if (!outcomes || !Object.keys(outcomes).length) return null;
const markRetired = key => setRetired(current => ({
source: outcomes, keys: new Set(current.source === outcomes ? current.keys : NONE).add(key),
}));
+ const refresh = async appId => {
+ if (pending.current.has(appId)) return;
+ pending.current.add(appId);
+ setRefreshStates(current => ({ ...current, [appId]: { pending: true } }));
+ const result = await refreshBranchReconcileInventory(appId, { silent: true }).catch(err => {
+ setRefreshStates(current => ({ ...current, [appId]: { error: err?.message || 'Inventory refresh failed' } }));
+ return null;
+ });
+ pending.current.delete(appId);
+ if (!result) return;
+ if (!result.outcome || result.appId !== appId) {
+ setRefreshStates(current => ({ ...current, [appId]: { error: 'Refresh returned no matching inventory; previous inventory retained.' } }));
+ return;
+ }
+ setRefreshed(current => ({ source: outcomes, values: { ...(current.source === outcomes ? current.values : {}), [appId]: result.outcome } }));
+ setRetired(current => ({ source: outcomes, keys: new Set([...(current.source === outcomes ? current.keys : NONE)].filter(key => !key.startsWith(`${appId}\0`))) }));
+ setRefreshStates(current => ({ ...current, [appId]: {} }));
+ };
return (
<div className="mx-4 mb-3 space-y-2 text-xs">
- {Object.entries(outcomes).map(([appId, outcome]) => {
- const remaining = Array.isArray(outcome.remaining) ? outcome.remaining.filter(entry => !retiredKeys.has(checkoutKey(appId, entry))) : null;
+ {Object.entries(outcomes).map(([appId, storedOutcome]) => {
+ const outcome = (refreshed.source === outcomes && refreshed.values[appId]) || storedOutcome;
+ const recorded = Array.isArray(outcome.remaining) ? outcome.remaining.filter(entry => !retiredKeys.has(checkoutKey(appId, entry))) : null;
+ const historical = recorded?.filter(entry => entry.checkoutMissing || entry.branchMissing) || [];
+ const remaining = recorded?.filter(entry => !entry.checkoutMissing && !entry.branchMissing && entry.reason !== 'remote-branch-held') ?? null;
+ const remote = [...(outcome.remoteInventory?.reported || []), ...(recorded?.filter(entry => entry.reason === 'remote-branch-held') || [])];
// Sweep interruptions and retirement can leave an incomplete outcome
// with no recorded work. This does not establish a newly drained scan.
- const incompleteEmptyInventory = outcome.status === 'incomplete' && outcome.observedAt && remaining?.length === 0;
+ const incompleteEmptyInventory = outcome.status === 'incomplete' && outcome.observedAt && remaining?.length === 0 && historical.length === 0;
return (
<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)}
{' · '}{incompleteEmptyInventory ? 'No remaining recorded work' : STATUS_LABELS[outcome.status] || 'Outcome unavailable'}
{remaining && ` · ${formatCount(remaining.length)} remaining`}
- {remaining?.some(entry => entry.checkoutMissing) && ' · missing checkout evidence'}
+ {historical.length > 0 && ` · ${formatCount(historical.length)} unresolved archive records`}
</summary>
<div className="mt-2 space-y-2 text-gray-400">
<p>{outcome.observedAt ? `Last inventory: ${formatDateTime(outcome.observedAt)}` : 'No readable inventory yet.'}</p>
+ {appId !== 'null' && <div className="space-y-1">
+ <button type="button" className="rounded border border-port-border px-2 py-1 disabled:opacity-50" disabled={refreshStates[appId]?.pending} onClick={() => refresh(appId)}>
+ {refreshStates[appId]?.pending ? 'Refreshing inventory…' : 'Refresh inventory'}
+ </button>
+ <p>Rescan this repository without deleting checkouts or starting an AI agent. Missing archive evidence is retained.</p>
+ {refreshStates[appId]?.error && <p role="alert" className="break-words text-port-error">{refreshStates[appId].error}</p>}
+ </div>}
{incompleteEmptyInventory && <p>Last sweep: Incomplete</p>}
{outcome.reason && <p className="break-words">Reason: {outcome.reason}</p>}
{outcome.nextAction && <p>{outcome.nextAction}</p>}
- {outcome.remoteInventory?.reported?.length > 0 && (
+ {remote.length > 0 && (
<details>
- <summary className="cursor-pointer">Remote-only inventory · {formatCount(outcome.remoteInventory.reported.length)} informational</summary>
+ <summary className="cursor-pointer">Remote-only inventory · {formatCount(remote.length)} informational</summary>
<p>Local cleanup status covers this machine’s branches and checkouts. Remote-only refs may belong to another instance.</p>
<ul className="max-h-48 overflow-y-auto">
- {outcome.remoteInventory.reported.map((entry, index) => <li key={index} className="break-all">
+ {remote.map((entry, index) => <li key={index} className="break-all">
{typeof entry === 'string' ? entry : `${entry.branch}: ${entry.reason}`}
</li>)}
</ul>
@@ -127,18 +173,15 @@ export default function BranchReconcileOutcome({ outcomes, apps }) {
)}
{!remaining && <p>Remaining work is unknown.</p>}
<ul className="space-y-2 max-h-64 overflow-y-auto">
- {(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.checkoutMissing && <p>Checkout no longer exists. This is a historical preservation obligation, not an extra worktree. Its archive receipt must be recovered or investigated before it can be cleared.</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>}
- {appId !== 'null' && isInventoriedCheckout(entry) && <RetireCheckout key={JSON.stringify([appId, entry.path, entry.head, entry.branch, entry.locked, entry.lockReason, entry.reason])} appId={appId} entry={entry} onRetired={markRetired} />}
- </li>
- ))}
+ {(remaining || []).map((entry, index) => <InventoryEntry key={`${entry.path || entry.branch || entry.issue || entry.reason}:${index}`} appId={appId} entry={entry} onRetired={markRetired} />)}
</ul>
+ {historical.length > 0 && <details>
+ <summary className="cursor-pointer">Archive history · {formatCount(historical.length)} unresolved</summary>
+ <p>These records describe missing originals, not current branches or checkouts. Refreshing does not verify their preservation or clear their evidence.</p>
+ <ul className="mt-2 max-h-64 space-y-2 overflow-y-auto">
+ {historical.map((entry, index) => <InventoryEntry key={`${entry.path || entry.branch}:${index}`} appId={appId} entry={entry} onRetired={markRetired} />)}
+ </ul>
+ </details>}
{(remaining || []).some(isInventoriedCheckout) && (
<p>Retiring a checkout is a scoped release of the exact row shown. It needs merged work, no live owner or manual handoff, and a verified archive of unique tracked, untracked and ignored content. Lock age, an absent process, and lock text never release a checkout on their own.</p>
)}
diff --git a/client/src/components/cos/tabs/schedule/BranchReconcileOutcome.test.jsx b/client/src/components/cos/tabs/schedule/BranchReconcileOutcome.test.jsx
index 2c6012727e..bb7256bc90 100644
--- a/client/src/components/cos/tabs/schedule/BranchReconcileOutcome.test.jsx
+++ b/client/src/components/cos/tabs/schedule/BranchReconcileOutcome.test.jsx
@@ -3,7 +3,8 @@ import { render, screen, fireEvent, waitFor } from '@testing-library/react';
const retire = vi.hoisted(() => vi.fn());
const prepare = vi.hoisted(() => vi.fn());
-vi.mock('../../../../services/api', () => ({ retireBranchReconcileCheckout: retire, reviewBranchReconcileCheckout: prepare }));
+const refresh = vi.hoisted(() => vi.fn());
+vi.mock('../../../../services/api', () => ({ retireBranchReconcileCheckout: retire, reviewBranchReconcileCheckout: prepare, refreshBranchReconcileInventory: refresh }));
import BranchReconcileOutcome from './BranchReconcileOutcome';
@@ -21,7 +22,7 @@ function open() {
}
describe('BranchReconcileOutcome checkout retirement', () => {
- beforeEach(() => { retire.mockReset(); prepare.mockReset(); });
+ beforeEach(() => { retire.mockReset(); prepare.mockReset(); refresh.mockReset(); });
it('shows peer remote inventory separately from drained local work without offering retirement', () => {
render(<BranchReconcileOutcome outcomes={{ 'app-1': { status: 'drained', remaining: [], remoteInventory: {
@@ -105,9 +106,37 @@ describe('BranchReconcileOutcome checkout retirement', () => {
});
});
- it('explains missing historical checkouts without offering retirement or claiming completion', () => {
+it('separates missing historical checkouts from current work without offering retirement or claiming completion', () => {
render(<BranchReconcileOutcome outcomes={{ 'app-1': { status: 'incomplete', remaining: [{ ...held, checkoutMissing: true, reason: 'retirement-receipt-unverified' }] } }} apps={[{ id: 'app-1', name: 'Example App' }]} />);
- expect(screen.getByText(/Example App · Incomplete · 1 remaining · missing checkout evidence/)).toBeTruthy();
- expect(screen.getByText(/historical preservation obligation, not an extra worktree/)).toBeTruthy();
+ expect(screen.getByText(/Example App · Incomplete · 0 remaining · 1 unresolved archive records/)).toBeTruthy();
+ expect(screen.getByText('Archive history · 1 unresolved')).toBeTruthy();
+ expect(screen.getByText(/historical archive evidence is unresolved/)).toBeTruthy();
expect(screen.queryByRole('button', { name: 'Archive and retire checkout…' })).toBeNull();
});
+
+it('refreshes one app immediately, excludes legacy remote holds, and restores authoritative props on the next event', async () => {
+ let finish;
+ refresh.mockImplementation(() => new Promise(resolve => { finish = resolve; }));
+ const stale = { 'app-1': { status: 'incomplete', remaining: [held, { branch: 'peer-only', reason: 'remote-branch-held' }] } };
+ const { rerender } = render(<BranchReconcileOutcome outcomes={stale} apps={[]} />);
+ fireEvent.click(screen.getByText(/app-1 · Incomplete · 1 remaining/));
+ expect(screen.getByText('Remote-only inventory · 1 informational')).toBeVisible();
+ fireEvent.click(screen.getByRole('button', { name: 'Refresh inventory' }));
+ expect(screen.getByRole('button', { name: 'Refreshing inventory…' })).toBeDisabled();
+ finish({ appId: 'app-1', outcome: { status: 'drained', remaining: [], observedAt: '2026-10-02T00:00:00Z' } });
+ expect(await screen.findByText(/app-1 · No remaining work in last scan · 0 remaining/)).toBeVisible();
+ expect(screen.queryByText('/example/held')).toBeNull();
+ expect(refresh).toHaveBeenCalledWith('app-1', { silent: true });
+ rerender(<BranchReconcileOutcome outcomes={{ ...stale }} apps={[]} />);
+ expect(screen.getByText('/example/held')).toBeVisible();
+});
+
+it('keeps the previous inventory and permits retry when a refresh fails', async () => {
+ refresh.mockRejectedValue(new Error('Repository scan unavailable'));
+ render(<BranchReconcileOutcome outcomes={outcomes} apps={[]} />);
+ fireEvent.click(screen.getByText(/app-1 · Incomplete/));
+ fireEvent.click(screen.getByRole('button', { name: 'Refresh inventory' }));
+ expect(await screen.findByRole('alert')).toHaveTextContent('Repository scan unavailable');
+ expect(screen.getByText('/example/held')).toBeVisible();
+ expect(screen.getByRole('button', { name: 'Refresh inventory' })).toBeEnabled();
+});
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index 630a3dca2b..a2c21280dd 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -391,6 +391,10 @@ export const triggerCosOnDemandTask = (taskType, appId = null, options = {}) =>
body: JSON.stringify({ taskType, appId }),
...options
});
+export const refreshBranchReconcileInventory = (appId, options = {}) => request('/cos/schedule/branch-reconcile/refresh', {
+ method: 'POST', body: JSON.stringify({ appId }), ...options
+});
+
// Archive and retire one held checkout named exactly as the last branch-reconcile inventory reported it.
export const retireBranchReconcileCheckout = ({ appId, path, head, branch = null, locked, lockReason = null, review }, options = {}) => request('/cos/schedule/branch-reconcile/checkouts/retire', {
method: 'POST',
diff --git a/server/routes/cosScheduleRoutes.js b/server/routes/cosScheduleRoutes.js
index b823400a15..69ed6708a6 100644
--- a/server/routes/cosScheduleRoutes.js
+++ b/server/routes/cosScheduleRoutes.js
@@ -289,6 +289,13 @@ router.post('/schedule/trigger', asyncHandler(async (req, res) => {
res.json({ success: true, request });
}));
+// Scan without changing Git state or scheduling provider work.
+router.post('/schedule/branch-reconcile/refresh', asyncHandler(async (req, res) => {
+ const { appId } = validateRequest(heldCheckoutReviewBodySchema.pick({ appId: true }).strict(), req.body);
+ const { refreshBranchReconcileInventory } = await import('../services/branchReconcileRefresh.js');
+ res.json(await refreshBranchReconcileInventory(appId));
+}));
+
// Prepare evidence only; the separate confirmation binds its digest to fresh facts.
router.post('/schedule/branch-reconcile/checkouts/review', asyncHandler(async (req, res) => {
const { appId, prUrl, ...release } = validateRequest(heldCheckoutReviewBodySchema, req.body);
diff --git a/server/routes/cosScheduleRoutes.test.js b/server/routes/cosScheduleRoutes.test.js
index deaed7c795..435532779f 100644
--- a/server/routes/cosScheduleRoutes.test.js
+++ b/server/routes/cosScheduleRoutes.test.js
@@ -9,6 +9,8 @@ const maintenance = vi.hoisted(() => ({ updateMaintenanceStep: vi.fn(), listMain
vi.mock('../services/maintenanceRun.js', () => maintenance);
const recovery = vi.hoisted(() => ({ prepareInventoriedCheckoutRetirement: vi.fn(), retireInventoriedCheckout: vi.fn() }));
vi.mock('../services/heldCheckoutRecovery.js', () => recovery);
+const refreshInventory = vi.hoisted(() => vi.fn());
+vi.mock('../services/branchReconcileRefresh.js', () => ({ refreshBranchReconcileInventory: refreshInventory }));
const initialized = vi.hoisted(() => ({ reviewInitializedCheckout: vi.fn(), retireInitializedCheckout: vi.fn(), initializedCheckoutStatus: vi.fn(), restoreInitializedCheckout: vi.fn(), verifyInitializedCheckoutArchive: vi.fn(), reviewInitializedCheckoutBranch: vi.fn(), retireInitializedCheckoutBranch: vi.fn(), reviewInitializedCheckoutMetadataRestore: vi.fn(), restoreInitializedCheckoutMetadata: vi.fn(), reviewInitializedCheckoutRestoredFinalization: vi.fn(), finalizeInitializedCheckoutRestored: vi.fn(), reviewInitializedCheckoutQuarantineResumption: vi.fn(), resumeInitializedCheckoutQuarantine: vi.fn() }));
vi.mock('../services/initializedCheckoutRecovery.js', () => initialized);
@@ -47,6 +49,20 @@ describe('CoS Schedule Routes', () => {
vi.clearAllMocks();
});
+ it('refreshes only a validated managed app target', async () => {
+ const result = { appId: 'app-1', outcome: { status: 'drained', remaining: [] } };
+ refreshInventory.mockResolvedValue(result);
+ const response = await request(app).post('/api/cos/schedule/branch-reconcile/refresh').send({ appId: 'app-1' });
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual(result);
+ expect(refreshInventory).toHaveBeenCalledWith('app-1');
+ refreshInventory.mockClear();
+ for (const body of [{}, { appId: null }, { appId: 4 }, { appId: 'app-1', cleanup: true }]) {
+ expect((await request(app).post('/api/cos/schedule/branch-reconcile/refresh').send(body)).status).toBe(400);
+ }
+ expect(refreshInventory).not.toHaveBeenCalled();
+ });
+
it.each([false, true])('validates retirement review evidence with optional observation identity: %s', async withObservation => {
const tuple = { path: '/synthetic/checkout', head: 'a'.repeat(40), branch: 'claim/42', locked: false, lockReason: null };
if (withObservation) Object.assign(tuple, { checkoutIdentity: 'c'.repeat(64), observedAt: '2026-10-23T00:00:00Z' });
diff --git a/server/services/branchReconcileRefresh.js b/server/services/branchReconcileRefresh.js
new file mode 100644
index 0000000000..3bf5d0b693
--- /dev/null
+++ b/server/services/branchReconcileRefresh.js
@@ -0,0 +1,42 @@
+import { ServerError } from '../lib/errorHandler.js';
+import { getAppById } from './apps.js';
+import { getActiveAgentIds } from './agentState.js';
+import { readClaimOwnershipAgents } from './cosClaimOwnership.js';
+import { reconcile, buildActiveOwnerIds, describeIdleReconcilePark } from './branchReconcile.js';
+import { recordBranchReconcileOutcome, getBranchReconcileInventory } from './taskSchedule.js';
+import { cosEvents } from './cosEvents.js';
+
+/** Refresh evidence only: no cleanup, provider dispatch, or delivery recovery. */
+export async function refreshBranchReconcileInventory(appId) {
+ const app = await getAppById(appId);
+ if (!app?.repoPath) throw new ServerError('Managed repository not found', { status: 404, code: 'NOT_FOUND' });
+ const agents = await readClaimOwnershipAgents();
+ if (!Array.isArray(agents)) throw new ServerError('Repository ownership state unavailable', { status: 503 });
+ const result = await reconcile(app.repoPath, {
+ appId, cleanup: false, reapSuperseded: false, reapRemotes: false,
+ activeAgentIds: buildActiveOwnerIds(new Set(getActiveAgentIds()), agents),
+ claimOwners: { agents, readAgents: readClaimOwnershipAgents },
+ forgeAccount: app.forgeAccount || null,
+ });
+ // An unreadable scan must not replace the last inventory with a false zero.
+ if (result.forgeUnavailable || result.prStateUnavailable || result.worktreeInventory == null || result.orphanRemotes?.remoteUnavailable) {
+ throw new ServerError('Repository scan unavailable; previous inventory retained. Try refreshing again.', { status: 503, code: 'RECONCILE_SCAN_UNAVAILABLE' });
+ }
+ const inventory = describeIdleReconcilePark([
+ ...(result.skipped || []),
+ ...(result.inFlight || []).map(row => ({ ...row, reason: 'actionable' })),
+ ], [], {
+ wip: result.wip, detachedWorktrees: result.detachedWorktrees,
+ superseded: result.superseded, claimMarkersHeld: result.claimMarkersHeld,
+ worktreeInventory: result.worktreeInventory,
+ });
+ await recordBranchReconcileOutcome(appId, {
+ status: inventory.remaining.length ? 'incomplete' : 'drained',
+ reason: inventory.reason, remaining: inventory.remaining,
+ remoteInventory: result.orphanRemotes ?? { reaped: [], reported: [] },
+ nextAction: inventory.remaining.length ? 'Resolve the listed local holds, then refresh inventory.' : null,
+ });
+ const outcome = await getBranchReconcileInventory(appId);
+ cosEvents.emit('schedule:changed', { taskType: 'branch-reconcile', appId });
+ return { appId, outcome };
+}
diff --git a/server/services/branchReconcileRefresh.test.js b/server/services/branchReconcileRefresh.test.js
new file mode 100644
index 0000000000..a1d17be171
--- /dev/null
+++ b/server/services/branchReconcileRefresh.test.js
@@ -0,0 +1,73 @@
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'fs/promises';
+import { realpathSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { execGit } from '../lib/execGit.js';
+import { materializeGitRepo, SKIP_HEAVY_INTEGRATION } from '../lib/gitTestRepo.js';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+const getApp = vi.hoisted(() => vi.fn());
+const owners = vi.hoisted(() => vi.fn(async () => []));
+vi.mock('../lib/paths.js', async importOriginal => makePathsProxy(await importOriginal(), {
+ dataRoot: () => lazyTempDataRoot('portos-refresh-inventory-'),
+}));
+vi.mock('./apps.js', () => ({ getAppById: getApp }));
+vi.mock('./cosClaimOwnership.js', () => ({ readClaimOwnershipAgents: owners }));
+vi.mock('./agentState.js', () => ({ getActiveAgentIds: () => new Set() }));
+vi.mock('./userTimezone.js', () => ({ getUserTimezone: async () => 'UTC' }));
+vi.mock('./supersededLedger.js', async importOriginal => ({ ...await importOriginal(), readVerdictLedger: async () => [] }));
+vi.mock('./heldCheckoutRecovery.js', () => ({ recoverMissingCheckoutPreservations: async ({ outcome }) => outcome }));
+
+import { PATHS } from '../lib/paths.js';
+import { getBranchReconcileOutcome, recordBranchReconcileOutcome } from './taskSchedule.js';
+import { refreshBranchReconcileInventory } from './branchReconcileRefresh.js';
+
+describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch reconciliation inventory refresh (real Git)', () => {
+ let scratch;
+ let repoPath;
+ beforeAll(async () => {
+ scratch = realpathSync(await mkdtemp(join(tmpdir(), 'portos-refresh-git-')));
+ repoPath = join(scratch, 'repo');
+ await mkdir(repoPath);
+ await materializeGitRepo(repoPath);
+ await execGit(['branch', 'release'], repoPath);
+ getApp.mockResolvedValue({ id: 'example', repoPath });
+ });
+ afterAll(async () => {
+ await rm(scratch, { recursive: true, force: true });
+ await cleanupTempDataRoots();
+ });
+
+ it('replaces stale local and remote inventory while retaining missing-source evidence without changing Git or dispatching work', async () => {
+ const missing = { branch: 'fix/old', path: join(scratch, 'missing'), head: 'a'.repeat(40), locked: false, lockReason: null, reason: 'checkout-retained' };
+ await recordBranchReconcileOutcome('example', { status: 'incomplete', remaining: [missing, { branch: 'peer-old', reason: 'remote-branch-held' }] });
+ const refs = (await execGit(['show-ref'], repoPath)).stdout;
+ await writeFile(join(repoPath, 'private-untracked.txt'), 'preserve this content');
+ const result = await refreshBranchReconcileInventory('example');
+ expect(result.outcome).toMatchObject({ status: 'incomplete',
+ remaining: [{ ...missing, reason: 'retirement-provenance-unverified', checkoutMissing: true }],
+ retirementObligations: [{ ...missing, reason: 'retirement-provenance-unverified' }],
+ remoteInventory: { reaped: [], reported: [] }, observedAt: expect.any(String),
+ });
+ expect((await execGit(['show-ref'], repoPath)).stdout).toBe(refs);
+ expect(await readFile(join(repoPath, 'private-untracked.txt'), 'utf8')).toBe('preserve this content');
+ const schedule = JSON.parse(await readFile(join(PATHS.cos, 'task-schedule.json'), 'utf8'));
+ expect(schedule.onDemandRequests || []).toEqual([]);
+ expect(schedule.executions['task:branch-reconcile'].perApp.example.lastRun).toBeFalsy();
+
+ await execGit(['branch', 'fix/current'], repoPath);
+ const current = await refreshBranchReconcileInventory('example');
+ expect(current.outcome.remaining).toEqual(expect.arrayContaining([expect.objectContaining({ branch: 'fix/current', reason: 'cleanup-disabled' })]));
+ expect((await execGit(['branch', '--list', 'fix/current'], repoPath)).stdout).toContain('fix/current');
+ });
+
+ it('preserves the last scan on unreadable ownership and rejects unknown targets', async () => {
+ const before = await getBranchReconcileOutcome('example');
+ owners.mockResolvedValueOnce(null);
+ await expect(refreshBranchReconcileInventory('example')).rejects.toMatchObject({ status: 503 });
+ expect(await getBranchReconcileOutcome('example')).toEqual(before);
+ getApp.mockResolvedValueOnce(null);
+ await expect(refreshBranchReconcileInventory('missing')).rejects.toMatchObject({ status: 404 });
+ });
+});
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index a9aed0ea14..e2fb76e3fa 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -893,6 +893,10 @@ export async function getBranchReconcileOutcome(appId) {
return resolveExecutionRecord(schedule, 'branch-reconcile', appId)?.branchReconcileOutcome ?? null;
}
+export async function getBranchReconcileInventory(appId) {
+ return reconcileMissingInventory(appId, await getBranchReconcileOutcome(appId));
+}
+
const missingPreservationObligation = row => ({ ...row, reason: 'retirement-provenance-unverified' });
const missingPreservationStatus = {
status: 'incomplete', reason: 'retirement-provenance-unverified',
@@ -933,6 +937,7 @@ async function reconcileMissingInventory(appId, outcome) {
return { ...current, remaining: current.remaining.map(row => ({
...row,
...(row.path && gone.some(missing => sameRetirementCheckout(missing, row)) && { checkoutMissing: true }),
+ ...(!row.path && row.branch && gone.some(missing => sameRetirementCheckout(missing, row)) && { branchMissing: true }),
})) };
}