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

reap verified-superseded branches instead of recommending a human delete them

[._.]/ Adam Eivy6bfe4ba27e3e
diff --git a/.gitignore b/.gitignore
index 7fc4906e28..4d97b6dc44 100644
--- a/.gitignore
+++ b/.gitignore
@@ -63,6 +63,11 @@ Thumbs.db
/.agent-done
/.agent-done-*
+# Public-review input bundle PortOS materializes into a reviewer's worktree
+# (see server/lib/agentScratchPaths.js) — pipeline state, never work product
+/PORTOS_PUBLIC_REVIEW_INPUT.json
+/.portos-public-review/
+
# BTW messages (ephemeral agent context, cleaned up after ingestion)
BTW.md
diff --git a/server/lib/README.md b/server/lib/README.md
index 53411080ea..f638912ef3 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -49,6 +49,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `agentOutputMarkers.js` | Status lines PortOS itself appends to an agent's output buffer: `SENTINEL_COMPLETION_MARKER` (the line `ingestDoneSentinel` writes just before the agent's `.agent-done` summary) plus `isAgentLifecycleLine(line)`/`stripLifecycleLines(lines)`, which match PortOS's telemetry on its actual message shapes rather than on a leading emoji (an agent's own summary may well start a line with `✅`). Pure — shared by the emitter (`services/agentTuiSpawning.js`) and by readers that must show only the agent's own words (notably the generated PR description). |
| `agentRunEvents.js` | CoS run lifecycle-event envelope (#4540) — pure half of the append-only ledger in `services/agentRunEventLog.js`. `AGENT_RUN_EVENT_KINDS` (closed vocabulary: spawned, handoff, output, reconnected, paused, resumed, interrupted, pr-verified, orphan-recovered, runner-recovered, finalized), `agentRunEventSchema` (Zod, `.strict()`), `buildRunEvent()` which redacts then mints a CONTENT-derived `eventId` (sha256 of the canonicalized envelope) so a redelivered lifecycle transition dedupes instead of double-counting, `redactRunEventData()` (drops prompt/description/output/result-class keys to a `{ redacted, chars }` stub, scrubs the home-dir prefix out of every remaining string via `scrubHomePath`, runs `redactOutput`, and caps string/array/key/depth per `RUN_EVENT_LIMITS`), and `projectRunStates()` — the clock-free fold that derives current run status from the ordered stream, so replay-after-restart and read-current-status are one code path. Unknown kinds fold as no-ops so a newer install's ledger replays on an older one. |
| `agentRunReconcile.js` | CoS run reconciliation (#4540) — pure diff between a ledger projection (`projectRunStates`) and the durable run record. Closed finding vocabulary `RUN_RECONCILE_FINDINGS` (`record-open`, `record-missing`, `verdict-mismatch`, `ledger-open`), `diffRunRecord()`, `reconcileRunRecords()` with a zero-filled per-kind summary, and `planRunRecordRepair()` — the metadata patch that closes a record the ledger proves is finished. Repairs are one-directional (ledger → record) by design: a record closed while the ledger missed the close is reported, never back-filled, so the stream stays an audit of the record rather than a copy of it. I/O half: `services/agentRunReconciler.js`. |
+| `agentScratchPaths.js` | Runtime scratch PortOS itself writes into an agent worktree and never commits — `PUBLIC_REVIEW_INPUT_FILENAME` / `PUBLIC_REVIEW_PATCH_DIRNAME` (the public-review bundle materialized by `services/modelAbuseGuard.js`), the `AGENT_SCRATCH_PATHS` list, prefix-aware `matchesScratchRoot(path, roots)` and `isAgentScratchPath(path)`. `classifyWorktreeDirt` (`services/worktreeManager.js`) subtracts these for EVERY caller and uses the same matcher for its per-call `ignoredPaths`, so a worktree holding only scratch reads as clean end to end — before this, it was preserved by `removeWorktree`, held by `reapMergedWorktrees`, filed as a repo-state recovery task, and dispatched to a branch-reconcile coordinator, forever. Only STATIC names live here; a run-scoped name like `.agent-done-<agentId>` (`agentSentinel.js`) is passed per call instead. |
| `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME`, `doneSentinelName(agentId)` → the per-instance filename `.agent-done-<agentId>` (worktree-less agents share one workspace, so a shared name lets concurrent runs clobber — and finalize on — each other's signal), `doneSentinelPath(workspacePath, agentId)` → the single path every producer and consumer resolves, + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. `extractSentinelPayloadFromTranscript(transcript, isPayload)` (async) is the third tier for programmatic-I/O types ONLY — scans the ANSI-stripped PTY transcript, newest balanced JSON block first, for a payload the model PRINTED instead of writing, and adopts it only if the owning hook's shape predicate accepts it (#3640). `PROGRAMMATIC_OUTPUT_COMPLETION_HEADING` names the briefing section that prints this run's absolute sentinel path — a task-type hook renders its prompt before spawn, so it points the agent at that section by name rather than at a filename it cannot know. |
| `persistentMind.js` | Pure persistent-CoS-mind runtime state: default-off durable shape, normalization, FIFO-message/self-wake selection, interrupted-wake requeue, image-work rollback guard, bounded exponential backoff, watchdog staleness, and next-wake projection. |
| `persistentMindCapabilities.js` | Default-off persistent-mind action grants plus bounded typed CoS-task, private-Eidoverse, and self-cleanup contracts (app/provider/model/effort, PR completion policy, the optional exact provider/model task allowlist, and mind-owned context scopes). |
diff --git a/server/lib/agentScratchPaths.js b/server/lib/agentScratchPaths.js
new file mode 100644
index 0000000000..f8ad40c4e1
--- /dev/null
+++ b/server/lib/agentScratchPaths.js
@@ -0,0 +1,62 @@
+/**
+ * Runtime scratch PortOS itself writes into an agent worktree.
+ *
+ * These files are pipeline state, never work product: the public-review harness
+ * materializes a screened input bundle into the worktree it hands a reviewer
+ * model, and nothing ever commits it. `git status` cannot tell that apart from a
+ * half-finished feature, so a worktree holding ONLY scratch reads as "dirty with
+ * uncommitted work" at every stage of the teardown chain — `removeWorktree`
+ * preserved it, `reapMergedWorktrees` held it, repo-state verification filed a
+ * recovery agent run against it, and branch-reconcile dispatched it to a
+ * coordinator that came back "no real work product, a human should discard it".
+ * Two `pr-reviewer` worktrees survived that chain indefinitely.
+ *
+ * Naming them here makes the classification deterministic, and
+ * `classifyWorktreeDirt` (worktreeManager.js) subtracts them for every caller —
+ * so the whole chain sees a clean tree rather than each consumer learning the
+ * names. Kept in `lib/` (not beside the writer in `services/modelAbuseGuard.js`)
+ * so the classifier can ask without importing that module's provider graph.
+ *
+ * Only the STATIC names live here. The completion sentinel is the same concept
+ * but its name embeds a run id (`agentSentinel.js`'s `doneSentinelName(agentId)`),
+ * and ignoring another run's sentinel would be wrong — so `removeWorktree` passes
+ * that one through `classifyWorktreeDirt`'s per-call `ignoredPaths` instead.
+ */
+
+/** The screened input bundle handed to a public-review model. */
+export const PUBLIC_REVIEW_INPUT_FILENAME = 'PORTOS_PUBLIC_REVIEW_INPUT.json';
+/** Directory of read-only PR patches materialized alongside it. */
+export const PUBLIC_REVIEW_PATCH_DIRNAME = '.portos-public-review';
+
+/**
+ * Worktree-relative paths (files or directory roots) that are PortOS runtime
+ * scratch. A directory entry also covers everything under it.
+ */
+export const AGENT_SCRATCH_PATHS = [PUBLIC_REVIEW_INPUT_FILENAME, PUBLIC_REVIEW_PATCH_DIRNAME];
+
+/**
+ * Does this worktree-relative path sit at, or under, one of `roots`? Pure.
+ *
+ * The prefix half is why `classifyWorktreeDirt`'s `ignoredPaths` needed this
+ * rather than a `Set.has`: git collapses an untracked directory to its root
+ * (`.portos-public-review/`) but expands it to individual files under `-uall`,
+ * and both spellings have to name the same thing.
+ *
+ * @param {string} path - worktree-relative path from `git status --porcelain`
+ * @param {string[]} roots - file or directory-root paths
+ * @returns {boolean}
+ */
+export function matchesScratchRoot(path, roots = []) {
+ if (typeof path !== 'string' || !roots.length) return false;
+ const normalized = path.trim().replace(/\/+$/, '');
+ if (!normalized) return false;
+ return roots.some((root) => normalized === root || normalized.startsWith(`${root}/`));
+}
+
+/**
+ * Is this worktree-relative path PortOS's own runtime scratch rather than work
+ * product? Pure — `matchesScratchRoot` against the static list.
+ * @param {string} path
+ * @returns {boolean}
+ */
+export const isAgentScratchPath = (path) => matchesScratchRoot(path, AGENT_SCRATCH_PATHS);
diff --git a/server/lib/agentScratchPaths.test.js b/server/lib/agentScratchPaths.test.js
new file mode 100644
index 0000000000..59c667ad2a
--- /dev/null
+++ b/server/lib/agentScratchPaths.test.js
@@ -0,0 +1,48 @@
+/**
+ * `matchesScratchRoot` decides whether an abandoned worktree holds work or only
+ * PortOS's own pipeline state — a false negative costs an agent run per teardown
+ * pass, a false positive would let a real change set be reaped. The input is
+ * `git status --porcelain` output as `classifyWorktreeDirt` strips it, so the
+ * cases here are the shapes git actually emits.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { isAgentScratchPath, matchesScratchRoot, AGENT_SCRATCH_PATHS } from './agentScratchPaths.js';
+
+describe('matchesScratchRoot', () => {
+ it('matches a directory root, its trailing-slash form, and anything beneath it', () => {
+ const roots = ['.portos-public-review'];
+ expect(matchesScratchRoot('.portos-public-review', roots)).toBe(true);
+ // git collapses an untracked directory to its root with a trailing slash…
+ expect(matchesScratchRoot('.portos-public-review/', roots)).toBe(true);
+ // …and expands it to individual files under `-uall`.
+ expect(matchesScratchRoot('.portos-public-review/PR-42.patch', roots)).toBe(true);
+ expect(matchesScratchRoot('.portos-public-review/nested/deep.json', roots)).toBe(true);
+ });
+
+ it('does not match a sibling that merely shares the prefix', () => {
+ const roots = ['.portos-public-review', 'PORTOS_PUBLIC_REVIEW_INPUT.json'];
+ expect(matchesScratchRoot('.portos-public-review-notes.md', roots)).toBe(false);
+ expect(matchesScratchRoot('PORTOS_PUBLIC_REVIEW_INPUT.json.bak', roots)).toBe(false);
+ // A same-named file nested under real source is not the harness's bundle.
+ expect(matchesScratchRoot('docs/PORTOS_PUBLIC_REVIEW_INPUT.json', roots)).toBe(false);
+ });
+
+ it('is false for non-strings, empties and an empty root list rather than throwing', () => {
+ expect(matchesScratchRoot(undefined, ['x'])).toBe(false);
+ expect(matchesScratchRoot(null, ['x'])).toBe(false);
+ expect(matchesScratchRoot('', ['x'])).toBe(false);
+ expect(matchesScratchRoot(' ', ['x'])).toBe(false);
+ expect(matchesScratchRoot(42, ['x'])).toBe(false);
+ expect(matchesScratchRoot('anything', [])).toBe(false);
+ });
+});
+
+describe('isAgentScratchPath', () => {
+ it('recognizes the public-review bundle and nothing else', () => {
+ expect(isAgentScratchPath('PORTOS_PUBLIC_REVIEW_INPUT.json')).toBe(true);
+ expect(isAgentScratchPath('.portos-public-review/PR-42.patch')).toBe(true);
+ expect(isAgentScratchPath('server/services/thing.js')).toBe(false);
+ expect(AGENT_SCRATCH_PATHS).toEqual(['PORTOS_PUBLIC_REVIEW_INPUT.json', '.portos-public-review']);
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index 2d1e4fbfe5..9f5df74dce 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -260,6 +260,7 @@ export * from './persistentMindTrajectory.js';
export * from './persistentMindProfile.js';
export * from './persistentMindPrompt.js';
export * from './persistentMindPublic.js';
+export * from './agentScratchPaths.js';
export * from './agentSentinel.js';
export * from './bareUrl.js';
export * from './bashResolver.js';
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index e64c85398d..89a91377a4 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -32,7 +32,8 @@ import { getOriginInfo } from '../lib/gitRemote.js';
import { githubRepoSpec, githubApiHost } from '../lib/workTracker.js';
import { safeJSONParse, PATHS } from '../lib/fileUtils.js';
import { PROTECTED_BRANCHES } from '../lib/gitArgs.js';
-import { readVerdictLedger, partitionSuperseded, recordVerdictInstruction } from './supersededLedger.js';
+import { readVerdictLedger, partitionSuperseded, recordVerdictInstruction, recordVerdict, sameSet } from './supersededLedger.js';
+import { backupSupersededBranch } from './supersededBackup.js';
// Never reconciled — the canonical long-lived-branch set (`main`/`master`/`dev`/
// `develop`/`release`/`gh-pages`) shared with the git branch-cleanup guards in
@@ -401,7 +402,13 @@ export function resolveLiveOwnerReason({ branch, path, locked, activeAgentIds })
}
/**
- * A worktree's real (non-lockfile) uncommitted paths, or [] when clean/unreadable.
+ * A worktree's real uncommitted paths, or [] when clean/unreadable.
+ *
+ * `classifyWorktreeDirt` subtracts what is not work product — auto-generated
+ * lockfiles and PortOS's own runtime scratch — so this list is only authored
+ * changes. That matters here because it is what makes a branch ABANDONED_WIP,
+ * the state that dispatches a coordinator agent.
+ *
* @param {string} worktreePath
* @returns {Promise<string[]>}
*/
@@ -885,42 +892,17 @@ export async function cleanupMerged(repoPath, defaultBranch, merged, { activeAge
skipped.push({ branch: b.branch, reason: 'not-merged-on-recheck' });
continue;
}
- if (b.worktreePath) {
- // Never tear down a worktree that's locked, a RECENT human /claim session, or
- // an active CoS agent workspace — even if its branch is merged and clean. An
- // abandoned claim worktree (merged + clean + older than STALE_CLAIM_IDLE_MS)
- // falls through and IS reaped; that's the "cleaned 0 forever" leak this fixes.
- // A SHIPPED claim (see SHIPPED_CLAIM above) waits out the short window
- // instead of the week-long one — `stillMerged` is proven above, and the
- // dirty gate below is still ahead of it.
- const gate = {
- path: b.worktreePath,
- locked: b.worktreeLocked,
- activeAgentIds,
- ageMs: b.worktreeAgeMs,
- staleClaimIdleMs: b.upstreamGone ? SHIPPED_CLAIM_IDLE_MS : STALE_CLAIM_IDLE_MS,
- };
- const protectedReason = worktreeProtectionReason(gate);
- if (protectedReason) {
- // Carry WHEN the hold lifts when it lifts on a clock (a claim worktree
- // still inside its grace window). Without it the caller can only park on
- // the recheck cadence and the two waits stack — see boundParkedUntil.
- const retryAt = worktreeProtectionExpiresAt(gate);
- skipped.push({ branch: b.branch, reason: protectedReason, ...(retryAt ? { retryAt } : {}) });
- continue;
- }
- const dirty = await isWorktreeDirty(b.worktreePath);
- if (dirty) {
- skipped.push({ branch: b.branch, reason: 'worktree-dirty' });
- continue;
- }
- await forceRemoveWorktreeDir(repoPath, b.worktreePath, {
- label: `🔀 branch-reconcile: remove worktree for ${b.branch}`, log: 'all'
- });
- }
- const result = await deleteBranch(repoPath, b.branch, { local: true }).catch((err) => ({ error: err.message }));
- if (result?.error || result?.results?.local?.startsWith?.('failed')) {
- skipped.push({ branch: b.branch, reason: `delete-failed: ${result.error || result.results.local}` });
+ // A SHIPPED claim (see SHIPPED_CLAIM above) waits out the short window instead
+ // of the week-long one — `stillMerged` is proven above, and retireBranch's
+ // dirty gate is still ahead of the removal.
+ const retired = await retireBranch(repoPath, b, {
+ activeAgentIds,
+ staleClaimIdleMs: b.upstreamGone ? SHIPPED_CLAIM_IDLE_MS : STALE_CLAIM_IDLE_MS,
+ label: `🔀 branch-reconcile: remove worktree for ${b.branch}`,
+ });
+ if (!retired.ok) {
+ const { ok, ...failure } = retired;
+ skipped.push({ branch: b.branch, ...failure });
continue;
}
cleaned.push(b.branch);
@@ -929,25 +911,175 @@ export async function cleanupMerged(repoPath, defaultBranch, merged, { activeAge
}
/**
- * Full Tier-1 reconcile: gather → classify → clean up merged. Returns the
- * in-flight set (branches needing an agent) for the scheduler to dispatch.
+ * Reap the branches whose SUPERSEDED verdict is cached and still verifies:
+ * back the branch up, remove its worktree, delete the local branch.
+ *
+ * Why this is deterministic cleanup and not a recommendation. A SUPERSEDED
+ * branch is the one terminal state nothing else can retire. Its work landed on
+ * the default branch under other file and function names, so `isMerged` is false
+ * forever and `cleanupMerged` never sees it; merging it would REGRESS what
+ * shipped, so no agent may finish it either. Left as a report, it survives every
+ * pass — and every recheck either re-derives the verdict at full coordinator cost
+ * or (once cached) prints the same "a human should run these two commands" block
+ * that nobody runs. Nine verdicts had accumulated in this install that way, each
+ * one a branch and a worktree still on disk.
+ *
+ * What makes deleting safe here is the BACKUP, not the verdict: nothing is
+ * removed until `backupSupersededBranch` has written the branch's commits, its
+ * worktree diff and its untracked files under
+ * `data/cos/abandoned-worktree-backups/`. A backup that throws skips the reap.
+ *
+ * Ordering is deliberate and costs nothing to get right: the verdict/branch
+ * pairing is a pure contract check for a direct caller (through `reconcile` it is
+ * already proven by `isVerdictFresh`, but this function is exported and deletes
+ * things, so it does not take the pairing on faith), then `retireBranch`'s own
+ * pure protection gate, and only then — as its `prepare` hook, past every way
+ * this can still refuse — is a backup written. A branch permanently held by a
+ * lock or a live CoS agent therefore costs no I/O at all on a recurring pass.
+ *
+ * @param {string} repoPath
+ * @param {string} defaultBranch
+ * @param {object[]} superseded - `applySupersededLedger`'s superseded entries, each
+ * carrying the ledger `verdict` it matched
+ * @param {{ activeAgentIds?: Set<string>, cosDir?: string }} [opts]
+ * @returns {Promise<{reaped:string[], held:object[], skipped:{branch:string,reason:string,retryAt?:string}[]}>}
+ * `held` is the live entries the reap could not take, for the caller to report.
+ */
+export async function reapSupersededBranches(repoPath, defaultBranch, superseded, { activeAgentIds = new Set(), cosDir } = {}) {
+ const reaped = [];
+ const held = [];
+ const skipped = [];
+ const hold = (b, failure) => { held.push(b); skipped.push({ branch: b.branch, ...failure }); };
+
+ for (const b of superseded || []) {
+ const verdict = b.verdict || {};
+ if (!b.tip || b.tip !== verdict.tip || !sameSet(b.dirtyPaths || [], verdict.dirtyPaths || [])) {
+ hold(b, { reason: 'verdict-does-not-match-branch' });
+ continue;
+ }
+ const retired = await retireBranch(repoPath, b, {
+ activeAgentIds,
+ label: `🔀 branch-reconcile: remove superseded worktree for ${b.branch}`,
+ // The dirty tree IS this branch's deliverable — an abandoned agent worktree
+ // has no commits of its own — so refusing on it would make the reap a no-op
+ // for the exact shape it exists to retire. What replaces the gate: the
+ // verdict was recorded against these same paths (checked above) and
+ // `prepare` copies them into the backup before anything is removed.
+ requireCleanWorktree: false,
+ prepare: async () => {
+ const backup = await backupSupersededBranch(repoPath, b, { defaultBranch, ...(cosDir ? { cosDir } : {}) })
+ .catch((err) => ({ error: err.message }));
+ if (!backup?.error) return backup;
+ console.error(`❌ branch-reconcile: backup failed for ${b.branch}, not reaping: ${backup.error}`);
+ return { error: `backup-failed: ${backup.error}` };
+ },
+ });
+ if (!retired.ok) {
+ const { ok, ...failure } = retired;
+ hold(b, failure);
+ continue;
+ }
+ const backup = retired.prepared;
+ // Keep the verdict, stamped with what happened to it. The entry is now a
+ // record rather than a cache — it names the backup a human needs to undo this.
+ await recordVerdict(
+ { ...verdict, branch: b.branch, repoPath, reapedAt: new Date().toISOString(), backupPatch: backup.dir },
+ cosDir
+ ).catch((err) => console.error(`⚠️ branch-reconcile: reaped ${b.branch} but could not update the verdict ledger: ${err.message}`));
+ console.log(`🔀 branch-reconcile: reaped superseded branch ${b.branch} (backup: ${backup.dir})`);
+ reaped.push(b.branch);
+ }
+ return { reaped, held, skipped };
+}
+
+/**
+ * Remove a branch's worktree (when it has one) and delete the local branch.
+ *
+ * The destructive tail shared by `cleanupMerged` and `reapSupersededBranches`.
+ * Both prove their own safety FIRST — one that the work is merged, the other
+ * that it is superseded and backed up — and then run exactly this: the same
+ * protection gate, the same dirty-tree refusal, the same removal order (the
+ * branch delete fails while a worktree still has it checked out). Extracted so
+ * the two cannot drift, since a guard added to one and missed on the other is a
+ * data-loss bug rather than an inconsistency.
+ *
+ * @param {string} repoPath
+ * @param {object} b - a gathered branch entry
+ * @param {{ activeAgentIds?: Set<string>, staleClaimIdleMs?: number, label: string, requireCleanWorktree?: boolean, prepare?: () => Promise<any> }} opts
+ * `prepare` runs after every gate has passed and before the first irreversible
+ * step, and aborts the retirement by resolving to `{ error }`. That is the only
+ * place work like "write a recoverable backup" belongs: earlier it is paid for
+ * branches that are then refused, later it is too late to matter.
+ *
+ * `requireCleanWorktree` (default true) is the caller's answer to "could this
+ * tree hold work that is not accounted for?". For `cleanupMerged` it can, so a
+ * dirty tree refuses: merged proves the COMMITS landed and says nothing about
+ * the working tree. `reapSupersededBranches` sets it false because the dirty
+ * tree is the branch's whole deliverable and it accounts for that tree twice
+ * over — the verdict was recorded against exactly these paths, and `prepare`
+ * copies them out before anything is removed. Never set it false without both.
+ * @returns {Promise<{ ok: true, prepared?: any } | { ok: false, reason: string, retryAt?: string }>}
+ */
+async function retireBranch(repoPath, b, { activeAgentIds = new Set(), staleClaimIdleMs = STALE_CLAIM_IDLE_MS, label, requireCleanWorktree = true, prepare }) {
+ if (b.worktreePath) {
+ // Never tear down a worktree that's locked, a RECENT human /claim session, or
+ // an active CoS agent workspace. An abandoned claim worktree (clean and older
+ // than the window) falls through and IS retired; that's the "cleaned 0
+ // forever" leak this exists to close.
+ const gate = {
+ path: b.worktreePath,
+ locked: b.worktreeLocked,
+ activeAgentIds,
+ ageMs: b.worktreeAgeMs,
+ staleClaimIdleMs,
+ };
+ const protectedReason = worktreeProtectionReason(gate);
+ if (protectedReason) {
+ // Carry WHEN the hold lifts when it lifts on a clock (a claim worktree
+ // still inside its grace window). Without it the caller can only park on
+ // the recheck cadence and the two waits stack — see boundParkedUntil.
+ const retryAt = worktreeProtectionExpiresAt(gate);
+ return { ok: false, reason: protectedReason, ...(retryAt ? { retryAt } : {}) };
+ }
+ if (requireCleanWorktree && await isWorktreeDirty(b.worktreePath)) return { ok: false, reason: 'worktree-dirty' };
+ }
+ const prepared = prepare ? await prepare() : null;
+ if (prepared?.error) return { ok: false, reason: prepared.error };
+ if (b.worktreePath) await forceRemoveWorktreeDir(repoPath, b.worktreePath, { label, log: 'all' });
+ const result = await deleteBranch(repoPath, b.branch, { local: true }).catch((err) => ({ error: err.message }));
+ if (result?.error || result?.results?.local?.startsWith?.('failed')) {
+ return { ok: false, reason: `delete-failed: ${result.error || result.results.local}` };
+ }
+ return { ok: true, prepared };
+}
+
+/**
+ * Full Tier-1 reconcile: gather → classify → clean up merged + verified-superseded.
+ * Returns the in-flight set (branches needing an agent) for the scheduler to dispatch.
*
* @param {string} [repoPath=PATHS.root]
- * @param {{ cleanup?: boolean, reapRemotes?: boolean, activeAgentIds?: Set<string> }} [opts] - when
- * cleanup is false, merged branches are reported (in `skipped`, reason `cleanup-disabled`)
- * but not deleted. `reapRemotes` (default false) additionally deletes merged
+ * @param {{ cleanup?: boolean, reapSuperseded?: boolean, reapRemotes?: boolean, activeAgentIds?: Set<string> }} [opts] - when
+ * cleanup is false, merged branches are reported (in `skipped`, reason
+ * `cleanup-disabled`) but not deleted. `reapSuperseded` (defaults to `cleanup`)
+ * governs the separate destructive step for verified-superseded branches, whose
+ * work is NOT on the default branch and survives only as a backup — a caller
+ * whose "clean up merged branches" toggle never meant that turns it off
+ * explicitly. `reapRemotes` (default false) additionally deletes merged
* branches left on `origin` that nothing local points at; off, they are only
* reported — see `reapOrphanedRemotes`. `activeAgentIds` protects in-use CoS
* agent worktrees.
* @returns {Promise<{ defaultBranch:string, cleaned:string[], inFlight:object[], wip:object[], skipped:{branch:string,reason:string}[], orphanRemotes:{reaped:string[],reported:object[]}, forgeUnavailable?:boolean, prStateUnavailable?:boolean }>}
* A `wip` entry with a `liveOwnerReason` is held because a live agent/claim/lock
- * owns it — the "leave it alone, this reconcile IS done" case.
+ * owns it — the "leave it alone, this reconcile IS done" case. `superseded` holds
+ * only the verified-superseded branches the reap could NOT take this cycle; the
+ * ones it took are named in `reapedSuperseded`, kept OUT of `cleaned` because
+ * that key means "merged" to its readers.
* `forgeUnavailable: true` means the cycle was SKIPPED before it started because
* the `gh` probe failed; `prStateUnavailable: true` means it ran but a gh read
* failed mid-cycle. Either way an empty `inFlight` says nothing about the repo
* and the caller must retry rather than park on it (#3358).
*/
-export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapRemotes = false, activeAgentIds = new Set() } = {}) {
+export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapSuperseded = cleanup, reapRemotes = false, activeAgentIds = new Set() } = {}) {
// Worktree cleanup is the first reconcile step, before any forge probe. It
// only removes a tree after proving both that it is completely clean and
// that every branch commit is already in the default branch (including
@@ -1011,6 +1143,13 @@ export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapRem
// stays in-flight forever — re-analyzed at full cost on every recheck. Drop it
// out of the actionable set on a cached verdict that still verifies (#3842).
const { actionable: inFlight, superseded } = await applySupersededLedger(repoPath, allInFlight, defaultBranch);
+ // A verified-superseded branch is TERMINAL, so it is reaped here rather than
+ // reported: nothing else can ever retire it, and a report that survives every
+ // pass is how nine of them accumulated in this install. Backed up first, and
+ // held by the same protection gate as cleanupMerged — see reapSupersededBranches.
+ const supersededReap = reapSuperseded
+ ? await reapSupersededBranches(repoPath, defaultBranch, superseded, { activeAgentIds })
+ : { reaped: [], held: superseded, skipped: superseded.map((b) => ({ branch: b.branch, reason: 'reap-superseded-disabled' })) };
// Every WIP entry carries its `liveOwnerReason`, so a caller that needs the
// "held by a live owner" subset (to report "the only branches left belong to
// running sessions" rather than a bare "nothing actionable") filters `wip` on it.
@@ -1033,7 +1172,21 @@ export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapRem
? await reapOrphanedRemotes(repoPath, defaultBranch, { reap: reapRemotes })
: { reaped: [], reported: [] };
- return { defaultBranch, cleaned, inFlight, superseded, wip, skipped, orphanRemotes, prStateUnavailable };
+ return {
+ defaultBranch,
+ cleaned,
+ // Kept OUT of `cleaned`: readers of that key render it as "deleted merged
+ // branch" (repoSync.js) and a superseded branch is precisely not merged.
+ reapedSuperseded: supersededReap.reaped,
+ inFlight,
+ // Only the branches still standing — listing a deleted one would put it in
+ // the coordinator prompt.
+ superseded: supersededReap.held,
+ wip,
+ skipped: [...skipped, ...supersededReap.skipped],
+ orphanRemotes,
+ prStateUnavailable
+ };
}
/**
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index 8be9d8ea3c..bcf105d31e 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -19,22 +19,28 @@ vi.mock('./git.js', () => ({
vi.mock('../lib/execGit.js', () => ({
execGit: vi.fn(async () => ({ stdout: '', exitCode: 0 }))
}));
-vi.mock('./worktreeManager.js', () => ({
- listWorktrees: vi.fn(async () => []),
- forceRemoveWorktreeDir: vi.fn(async () => {}),
- reapMergedWorktrees: vi.fn(async () => ({ reaped: [], skipped: [] })),
- // Real pure classifier semantics: empty porcelain = clean, and every non-empty
- // line is a real change path (the suite never feeds it lockfile churn). The
- // paths matter — gatherDivergence intersects them with the default branch's
- // changes to find work that may have been superseded.
- classifyWorktreeDirt: vi.fn((p) => {
- const lines = (p || '').split('\n').map((l) => l.trim()).filter(Boolean);
- return {
- hasRealChanges: lines.length > 0,
- realChangePaths: lines.map((l) => l.replace(/^\s*\S+\s+/, ''))
- };
- }),
-}));
+vi.mock('./worktreeManager.js', async () => {
+ const { AGENT_SCRATCH_PATHS, matchesScratchRoot } = await import('../lib/agentScratchPaths.js');
+ return {
+ listWorktrees: vi.fn(async () => []),
+ forceRemoveWorktreeDir: vi.fn(async () => {}),
+ reapMergedWorktrees: vi.fn(async () => ({ reaped: [], skipped: [] })),
+ // Real pure classifier semantics: empty porcelain = clean, and every non-empty
+ // line is a real change path (the suite never feeds it lockfile churn) EXCEPT
+ // PortOS's own runtime scratch, which the real classifier subtracts for every
+ // caller. Mocking that away would hide the case this suite exists to cover.
+ // The paths matter — gatherDivergence intersects them with the default
+ // branch's changes to find work that may have been superseded.
+ classifyWorktreeDirt: vi.fn((p) => {
+ const paths = (p || '').split('\n')
+ .map((l) => l.trim())
+ .filter(Boolean)
+ .map((l) => l.replace(/^\s*\S+\s+/, ''))
+ .filter((path) => !matchesScratchRoot(path, AGENT_SCRATCH_PATHS));
+ return { hasRealChanges: paths.length > 0, realChangePaths: paths };
+ }),
+ };
+});
// Worktree age drives the claim windows (STALE_CLAIM_IDLE_MS / SHIPPED_CLAIM_IDLE_MS),
// and gatherBranchState reads it via stat(). Default to "ancient" so tests that
// don't care about age behave as before; set worktreeMtimeMs to pin a specific age.
@@ -65,6 +71,15 @@ vi.mock('../lib/fileUtils.js', () => ({
atomicWrite: vi.fn(async () => {})
}));
+const backupSupersededBranchMock = vi.fn(async (_repoPath, branch) => ({
+ dir: `/repo/data/cos/abandoned-worktree-backups/${branch.branch.replace(/\//g, '-')}`,
+ manifest: 'manifest.json',
+ untracked: []
+}));
+vi.mock('./supersededBackup.js', () => ({
+ backupSupersededBranch: (...args) => backupSupersededBranchMock(...args)
+}));
+
import {
classifyBranch, classifyBranches, cleanupMerged, reconcile, gatherBranchState, worktreeProtectionReason,
isAbandonedAgentWorktree, resolveLiveOwnerReason, gatherDivergence,
@@ -97,6 +112,11 @@ beforeEach(() => {
wt.reapMergedWorktrees.mockResolvedValue({ reaped: [], skipped: [] });
execGit.mockResolvedValue({ stdout: '', exitCode: 0 });
tryReadFileMock.mockResolvedValue(null);
+ backupSupersededBranchMock.mockImplementation(async (_repoPath, branch) => ({
+ dir: `/repo/data/cos/abandoned-worktree-backups/${branch.branch.replace(/\//g, '-')}`,
+ manifest: 'manifest.json',
+ untracked: []
+ }));
});
describe('classifyBranch', () => {
@@ -1077,16 +1097,112 @@ describe('reconcile — cached SUPERSEDED verdicts (#3842)', () => {
}]
});
- it('drops a branch with a fresh cached verdict out of the actionable set', async () => {
+ it('reaps a branch with a fresh cached verdict, after backing it up', async () => {
setupAbandoned();
tryReadFileMock.mockResolvedValue(ledger());
const res = await reconcile('/repo', { activeAgentIds: new Set() });
expect(res.inFlight).toEqual([]);
- expect(res.superseded.map((s) => s.branch)).toEqual([BRANCH]);
- // Left completely alone — the whole point is that merging it would regress main.
+ // Reported under its own key, NOT `cleaned` — a superseded branch's work is
+ // not on the default branch — and gone from the prompt's superseded block.
+ expect(res.reapedSuperseded).toEqual([BRANCH]);
+ expect(res.cleaned).not.toContain(BRANCH);
+ expect(res.superseded).toEqual([]);
+ expect(backupSupersededBranchMock).toHaveBeenCalledTimes(1);
+ expect(wt.forceRemoveWorktreeDir).toHaveBeenCalledWith('/repo', WORKTREE, expect.anything());
+ expect(git.deleteBranch).toHaveBeenCalledWith('/repo', BRANCH, { local: true });
+ });
+
+ it('backs up before it deletes anything', async () => {
+ setupAbandoned();
+ tryReadFileMock.mockResolvedValue(ledger());
+ const order = [];
+ backupSupersededBranchMock.mockImplementation(async () => {
+ order.push('backup');
+ return { dir: '/backups/x', manifest: 'manifest.json', untracked: [] };
+ });
+ wt.forceRemoveWorktreeDir.mockImplementation(async () => { order.push('remove'); });
+ git.deleteBranch.mockImplementation(async () => { order.push('delete'); return { results: { local: 'deleted' } }; });
+
+ await reconcile('/repo', { activeAgentIds: new Set() });
+ expect(order[0]).toBe('backup');
+ });
+
+ // No recoverable copy, no delete. The verdict is not what makes this safe.
+ it('does not reap when the backup fails', async () => {
+ setupAbandoned();
+ tryReadFileMock.mockResolvedValue(ledger());
+ backupSupersededBranchMock.mockRejectedValue(new Error('disk full'));
+
+ const res = await reconcile('/repo', { activeAgentIds: new Set() });
expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();
expect(git.deleteBranch).not.toHaveBeenCalled();
+ expect(res.superseded.map((b) => b.branch)).toEqual([BRANCH]);
+ expect(res.skipped).toContainEqual({ branch: BRANCH, reason: 'backup-failed: disk full' });
+ });
+
+ // "Superseded" must never become a way around the worktree protection gate —
+ // it is the same gate cleanupMerged applies. A recent /claim tree is the case
+ // that reaches it: the branch is clean and un-pushed (NEEDS_PR), so nothing
+ // upstream of the reaper holds it back.
+ it('holds the reap while a claim worktree is still inside its idle window', async () => {
+ const CLAIM = 'claim/issue-5769';
+ const CLAIM_TREE = '/repo/data/cos/worktrees/claim-issue-5769';
+ git.getBranches.mockResolvedValue([
+ { name: CLAIM, isDefault: false, current: false, tracking: null, merged: false }
+ ]);
+ wt.listWorktrees.mockResolvedValue([{ path: CLAIM_TREE, branch: `refs/heads/${CLAIM}` }]);
+ git.isBranchMergedInto.mockResolvedValue(false);
+ execGit.mockImplementation(async (args) => {
+ const [cmd] = args;
+ if (cmd === 'rev-parse') return { stdout: 'aaaaaaa\n', exitCode: 0 };
+ if (cmd === 'merge-base' && args[1] === '--is-ancestor') return { stdout: '', exitCode: 0 };
+ if (cmd === 'merge-base') return { stdout: 'base000\n', exitCode: 0 };
+ if (cmd === 'diff') return { stdout: 'server/services/thing.js\n', exitCode: 0 };
+ if (cmd === 'rev-list') return { stdout: '600\t3\n', exitCode: 0 };
+ return { stdout: '', exitCode: 0 }; // clean worktree
+ });
+ worktreeMtimeMs = Date.now(); // claimed minutes ago, not abandoned
+ tryReadFileMock.mockResolvedValue(JSON.stringify({
+ version: 1,
+ entries: [{
+ branch: CLAIM, repoPath: '/repo', verdict: 'SUPERSEDED', tip: 'aaaaaaa',
+ dirtyPaths: [], collisionPaths: ['server/services/thing.js'], replacedBy: ['ffffff1']
+ }]
+ }));
+
+ const res = await reconcile('/repo', { activeAgentIds: new Set() });
+ expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();
+ expect(git.deleteBranch).not.toHaveBeenCalled();
+ expect(backupSupersededBranchMock).not.toHaveBeenCalled();
+ // Still reported, so a held-back reap is visible rather than silent.
+ expect(res.superseded.map((b) => b.branch)).toEqual([CLAIM]);
+ expect(res.skipped.find((sk) => sk.branch === CLAIM)?.reason).toBeTruthy();
+ });
+
+ // `cleanupMerged` means "delete branches whose work is already on main". This
+ // deletes branches whose work is NOT, so it gets its own switch for a caller
+ // (repoSync) whose toggle never meant that.
+ it('is refusable on its own, without turning off merged cleanup', async () => {
+ setupAbandoned();
+ tryReadFileMock.mockResolvedValue(ledger());
+
+ const res = await reconcile('/repo', { reapSuperseded: false, activeAgentIds: new Set() });
+ expect(backupSupersededBranchMock).not.toHaveBeenCalled();
+ expect(git.deleteBranch).not.toHaveBeenCalled();
+ expect(res.reapedSuperseded).toEqual([]);
+ expect(res.skipped).toContainEqual({ branch: BRANCH, reason: 'reap-superseded-disabled' });
+ });
+
+ it('reports but never reaps with cleanup disabled', async () => {
+ setupAbandoned();
+ tryReadFileMock.mockResolvedValue(ledger());
+
+ const res = await reconcile('/repo', { cleanup: false, activeAgentIds: new Set() });
+ expect(backupSupersededBranchMock).not.toHaveBeenCalled();
+ expect(git.deleteBranch).not.toHaveBeenCalled();
+ expect(res.skipped).toContainEqual({ branch: BRANCH, reason: 'reap-superseded-disabled' });
+ expect(res.superseded.map((b) => b.branch)).toEqual([BRANCH]);
});
it('re-analyzes when the branch tip moved', async () => {
@@ -1145,6 +1261,51 @@ describe('reconcile — cached SUPERSEDED verdicts (#3842)', () => {
});
});
+// PortOS materializes the public-review bundle INTO the worktree it hands a
+// reviewer model, and nothing ever commits it. Counted as uncommitted work, a
+// worktree holding only that read as ABANDONED_WIP forever: cleanupMerged
+// refused to delete a dirty tree, and every pass instead spent a coordinator run
+// that came back "no real work product, a human should discard it".
+describe('reconcile — a worktree holding only PortOS runtime scratch', () => {
+ const BRANCH = 'cos/app-improve-pr-reviewer-x/agent-985a8c77';
+ const WORKTREE = '/repo/data/cos/worktrees/agent-985a8c77';
+
+ const setup = (porcelain) => {
+ git.getBranches.mockResolvedValue([
+ { name: BRANCH, isDefault: false, current: false, tracking: null, merged: true }
+ ]);
+ wt.listWorktrees.mockResolvedValue([{ path: WORKTREE, branch: `refs/heads/${BRANCH}` }]);
+ git.isBranchMergedInto.mockResolvedValue(true);
+ execGit.mockImplementation(async (args) => {
+ if (args[0] === 'rev-list') return { stdout: '114\t0\n', exitCode: 0 };
+ if (args[0] === 'status') return { stdout: porcelain, exitCode: 0 };
+ return { stdout: '', exitCode: 0 };
+ });
+ };
+
+ it('reaps it instead of dispatching an agent to look at it', async () => {
+ setup('?? PORTOS_PUBLIC_REVIEW_INPUT.json\n?? .portos-public-review/\n');
+
+ const res = await reconcile('/repo', { activeAgentIds: new Set() });
+ expect(res.inFlight).toEqual([]);
+ expect(res.cleaned).toContain(BRANCH);
+ expect(wt.forceRemoveWorktreeDir).toHaveBeenCalledWith('/repo', WORKTREE, expect.anything());
+ expect(git.deleteBranch).toHaveBeenCalledWith('/repo', BRANCH, { local: true });
+ });
+
+ it('still holds a worktree carrying one real change alongside the scratch', async () => {
+ setup('?? PORTOS_PUBLIC_REVIEW_INPUT.json\n M server/services/thing.js\n');
+
+ const res = await reconcile('/repo', { activeAgentIds: new Set() });
+ expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();
+ expect(git.deleteBranch).not.toHaveBeenCalled();
+ // The real change makes it ABANDONED_WIP — dispatched to an agent, not reaped —
+ // and the scratch is subtracted from the change set the agent is pointed at.
+ expect(res.inFlight.map((b) => b.branch)).toEqual([BRANCH]);
+ expect(res.inFlight[0].dirtyPaths).toEqual(['server/services/thing.js']);
+ });
+});
+
describe('actionOn', () => {
it('is ON for absent/true, OFF only for explicit false', () => {
expect(actionOn(undefined, 'openPr')).toBe(true);
diff --git a/server/services/cosTaskPreStepBlocks.js b/server/services/cosTaskPreStepBlocks.js
index e98fddc1c4..ac35a9a3ec 100644
--- a/server/services/cosTaskPreStepBlocks.js
+++ b/server/services/cosTaskPreStepBlocks.js
@@ -378,12 +378,18 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskS
if (result.cleaned.length) {
emitLog('info', `🔀 branch-reconcile ${app.name}: cleaned ${result.cleaned.length} merged branch(es)`, { appId: app.id, analysisType: taskType });
}
- // Branches whose SUPERSEDED verdict is already cached and still verifies were
- // dropped from `inFlight` by the reconciler (#3842). They are real branches a
- // human still has to reap, so name them rather than letting them vanish into a
- // quiet park — the invisibility is the same failure mode as a lingering worktree
- // reported as "cleaned 0".
- const supersededSuffix = countSuffix(result.superseded, 'branch(es) already verified superseded and awaiting human reap');
+ // Reported separately from `cleaned`: a superseded branch's work is NOT on the
+ // default branch — it landed there under other names — so it survives only as
+ // the backup the reap wrote before deleting it.
+ if (result.reapedSuperseded?.length) {
+ emitLog('info', `🔀 branch-reconcile ${app.name}: reaped ${result.reapedSuperseded.length} verified-superseded branch(es) (backed up under data/cos/abandoned-worktree-backups)`, { appId: app.id, analysisType: taskType });
+ }
+ // Verified-superseded branches are reaped by the reconciler itself and counted
+ // in `cleaned`. What is left in `superseded` is the reap's leftovers — held by a
+ // lock, a live agent, or a claim window — so name them rather than letting them
+ // vanish into a quiet park; the invisibility is the same failure mode as a
+ // lingering worktree reported as "cleaned 0".
+ const supersededSuffix = countSuffix(result.superseded, 'branch(es) verified superseded, reap held back');
// Branches somebody is actively working in (a running CoS agent, a live human
// /claim, a locked worktree) are classified WIP and never reach `inFlight` — the
// reconcile is DONE when they are all that's left, not stuck. Named in the park
diff --git a/server/services/modelAbuseGuard.js b/server/services/modelAbuseGuard.js
index c030a215f6..76ac16f4bd 100644
--- a/server/services/modelAbuseGuard.js
+++ b/server/services/modelAbuseGuard.js
@@ -47,6 +47,9 @@ import { publicReviewProviderBlock, PUBLIC_REVIEW_NO_TOOL_POSTURE } from '../lib
import { withSpawnCwdEnv } from '../lib/spawnCwd.js';
import { detectVenvBasePythonSync, createVenv, installPackages } from '../lib/pythonSetup.js';
import { safeChildProcessOptions } from '../lib/processEnv.js';
+// Declared in lib/ so `classifyWorktreeDirt` can subtract this scratch without
+// importing this module's provider/runtime graph — see agentScratchPaths.js.
+import { PUBLIC_REVIEW_INPUT_FILENAME, PUBLIC_REVIEW_PATCH_DIRNAME } from '../lib/agentScratchPaths.js';
import { downloadHfRepo } from './hfDownload.js';
import { getHfToken } from './hfToken.js';
import { listModels } from './localLlm.js';
@@ -68,8 +71,6 @@ const MAX_SCAN_TIMEOUT_MS = 10 * 60 * 1000;
const MAX_INSTALL_EVENT_CHARS = 300;
const MAX_PUBLIC_REVIEW_SNAPSHOT_CHARS = MODEL_ABUSE_GUARD_MAX_INPUT_CHARS * 3;
const PUBLIC_REVIEW_INPUT_DIR = join(PATHS.cos, 'public-review-inputs');
-export const PUBLIC_REVIEW_INPUT_FILENAME = 'PORTOS_PUBLIC_REVIEW_INPUT.json';
-export const PUBLIC_REVIEW_PATCH_DIRNAME = '.portos-public-review';
export const PUBLIC_REVIEW_PATCH_MANIFEST_FILENAME = 'PORTOS_PUBLIC_REVIEW_PATCHES.json';
let cachedRuntime = null;
diff --git a/server/services/modelAbuseGuard.materialize.test.js b/server/services/modelAbuseGuard.materialize.test.js
index faac742be4..558223d865 100644
--- a/server/services/modelAbuseGuard.materialize.test.js
+++ b/server/services/modelAbuseGuard.materialize.test.js
@@ -3,12 +3,11 @@ import { mkdtemp, readFile, rm, stat } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { PATHS } from '../lib/fileUtils.js';
+import { PUBLIC_REVIEW_INPUT_FILENAME, PUBLIC_REVIEW_PATCH_DIRNAME } from '../lib/agentScratchPaths.js';
import {
materializePublicReviewInput,
materializePublicReviewPatches,
writePublicReviewInputSnapshot,
- PUBLIC_REVIEW_INPUT_FILENAME,
- PUBLIC_REVIEW_PATCH_DIRNAME,
PUBLIC_REVIEW_PATCH_MANIFEST_FILENAME,
} from './modelAbuseGuard.js';
diff --git a/server/services/repoSync.js b/server/services/repoSync.js
index 1d600d345e..dc3f0b49ba 100644
--- a/server/services/repoSync.js
+++ b/server/services/repoSync.js
@@ -811,6 +811,7 @@ export async function syncRepo(repo, { activeAgentIds = new Set() } = {}) {
});
if (result) {
for (const branch of result.cleaned || []) performed.push(`deleted merged branch/worktree ${branch}`);
+ for (const branch of result.reapedSuperseded || []) performed.push(`reaped superseded branch/worktree ${branch} (backed up)`);
for (const entry of result.inFlight || []) {
escalations.push({
kind: ESCALATION_KINDS.IN_FLIGHT_BRANCH,
diff --git a/server/services/supersededBackup.js b/server/services/supersededBackup.js
new file mode 100644
index 0000000000..7df33dad2a
--- /dev/null
+++ b/server/services/supersededBackup.js
@@ -0,0 +1,151 @@
+/**
+ * Pre-reap backup for a SUPERSEDED branch.
+ *
+ * `branch-reconcile` records a SUPERSEDED verdict and then deletes the branch and
+ * its worktree (see `reapSupersededBranches` in `branchReconcile.js`). That is the
+ * only way the reconciler converges — a branch whose work landed on the default
+ * branch under other names is never `isMerged`, so nothing else ever reaps it and
+ * every recheck re-derives the same verdict at full coordinator cost.
+ *
+ * Deleting a worktree is irreversible, and a superseded branch's uncommitted work
+ * is redundant rather than worthless — so nothing is removed until a recoverable
+ * copy exists on disk. This module writes that copy, and the reap is gated on it
+ * succeeding: no backup, no delete.
+ *
+ * Layout, one directory per branch under `data/cos/abandoned-worktree-backups/`:
+ * <slug>/manifest.json what it was, why it was reaped, how to restore it
+ * <slug>/commits.patch `git format-patch <default>..<branch>` (branch commits)
+ * <slug>/worktree.diff `git diff HEAD` in its worktree (tracked edits)
+ * <slug>/untracked/… verbatim copies of its untracked, non-ignored files
+ *
+ * Untracked files are COPIED rather than rendered as a `--no-index` patch: they
+ * are usually the whole deliverable of an abandoned agent worktree, and a copy
+ * survives binary content and needs no patch tooling to read back.
+ */
+
+import { cp, stat, writeFile } from 'node:fs/promises';
+import { dirname, join } from 'node:path';
+import { atomicWrite, ensureDir, PATHS } from '../lib/fileUtils.js';
+import { kebabCase } from '../lib/textUtils.js';
+import { execGitSafe } from './git.js';
+
+/** Where an install keeps its pre-reap backups. */
+export const backupRoot = (cosDir = PATHS.cos) => join(cosDir, 'abandoned-worktree-backups');
+
+/** Branch name → a filesystem-safe directory name. Pure. */
+export const backupSlug = (branch) => kebabCase(String(branch || '')) || 'branch';
+
+// A single untracked file above this is almost certainly build output or a model
+// artifact rather than authored work; it is named in the manifest instead of
+// copied, so one stray blob can't turn a backup into a disk-filling operation.
+// The tracked diff is deliberately uncapped by contrast — every byte of it is
+// authored, and truncating it would break the "no backup, no delete" gate.
+const MAX_UNTRACKED_FILE_BYTES = 5 * 1024 * 1024;
+const MAX_UNTRACKED_TOTAL_BYTES = 50 * 1024 * 1024;
+
+const gitText = async (args, cwd) => (await execGitSafe(args, cwd, { ignoreExitCode: true })).stdout || '';
+
+/** Newline-separated git stdout → trimmed non-empty lines. */
+const gitLines = (stdout) => (stdout || '').split('\n').map((l) => l.trim()).filter(Boolean);
+
+/**
+ * Copy a worktree's untracked, non-ignored files into the backup, preserving
+ * their relative layout.
+ * @returns {Promise<{copied:string[], skipped:{path:string,reason:string}[]}>}
+ */
+async function copyUntracked(worktreePath, destDir) {
+ const paths = gitLines(await gitText(['ls-files', '--others', '--exclude-standard'], worktreePath));
+ const copied = [];
+ const skipped = [];
+ const created = new Set();
+ let total = 0;
+ for (const rel of paths) {
+ const source = join(worktreePath, rel);
+ const size = await stat(source).then((s) => s.size, () => null);
+ if (size === null) {
+ skipped.push({ path: rel, reason: 'unreadable' });
+ continue;
+ }
+ // The running total makes the budget order-dependent on purpose — a copy is
+ // either fully made or not made at all, never truncated.
+ if (size > MAX_UNTRACKED_FILE_BYTES || total + size > MAX_UNTRACKED_TOTAL_BYTES) {
+ skipped.push({ path: rel, reason: `too-large (${size} bytes)` });
+ continue;
+ }
+ const destination = join(destDir, rel);
+ const parent = dirname(destination);
+ if (!created.has(parent)) {
+ await ensureDir(parent);
+ created.add(parent);
+ }
+ const ok = await cp(source, destination).then(() => true, () => false);
+ if (ok) {
+ copied.push(rel);
+ total += size;
+ } else {
+ skipped.push({ path: rel, reason: 'copy-failed' });
+ }
+ }
+ return { copied, skipped };
+}
+
+/**
+ * Write the recoverable copy of a branch before it is reaped.
+ *
+ * Throws on any failure that would leave the backup incomplete — the caller
+ * treats that as "do not reap", which is the whole point of the gate.
+ *
+ * @param {string} repoPath
+ * @param {object} branch - a reconcile entry: { branch, tip, worktreePath, verdict }
+ * @param {{ defaultBranch?: string, cosDir?: string }} [opts]
+ * @returns {Promise<{ dir:string, manifest:string, untracked:string[] }>}
+ */
+export async function backupSupersededBranch(repoPath, branch, { defaultBranch = 'main', cosDir = PATHS.cos } = {}) {
+ const dir = join(backupRoot(cosDir), backupSlug(branch.branch));
+ await ensureDir(dir);
+
+ const commitsPath = join(dir, 'commits.patch');
+ const commits = await gitText(['format-patch', `${defaultBranch}..${branch.branch}`, '--stdout'], repoPath);
+ const hasCommits = Boolean(commits.trim());
+ if (hasCommits) await writeFile(commitsPath, commits);
+
+ const diffPath = join(dir, 'worktree.diff');
+ let hasDiff = false;
+ let untracked = { copied: [], skipped: [] };
+ if (branch.worktreePath) {
+ const worktreeDiff = await gitText(['diff', 'HEAD', '--binary'], branch.worktreePath);
+ hasDiff = Boolean(worktreeDiff.trim());
+ if (hasDiff) await writeFile(diffPath, worktreeDiff);
+ // No upfront mkdir: copyUntracked creates each parent lazily, so a worktree
+ // with nothing untracked leaves no empty directory behind.
+ untracked = await copyUntracked(branch.worktreePath, join(dir, 'untracked'));
+ }
+
+ const manifest = {
+ branch: branch.branch,
+ repoPath,
+ defaultBranch,
+ tip: branch.tip || null,
+ worktreePath: branch.worktreePath || null,
+ reapedAt: new Date().toISOString(),
+ verdict: branch.verdict || null,
+ captured: {
+ commitsPatch: hasCommits,
+ worktreeDiff: hasDiff,
+ untrackedFiles: untracked.copied,
+ untrackedSkipped: untracked.skipped,
+ },
+ // The branch ref is gone after the reap, but its objects are not — git keeps
+ // them until they are gc'd (90 days by default), so the tip SHA is a real
+ // restore path for as long as that lasts, and the patches outlive even that.
+ restore: [
+ branch.tip ? `git -C ${repoPath} branch ${branch.branch} ${branch.tip}` : null,
+ hasCommits ? `git -C ${repoPath} am ${commitsPath}` : null,
+ hasDiff ? `git -C ${repoPath} apply ${diffPath}` : null,
+ untracked.copied.length ? `cp -R ${join(dir, 'untracked')}/. <worktree>/` : null,
+ ].filter(Boolean),
+ };
+ const manifestPath = join(dir, 'manifest.json');
+ await atomicWrite(manifestPath, manifest);
+ return { dir, manifest: manifestPath, untracked: untracked.copied };
+}
diff --git a/server/services/supersededBackup.test.js b/server/services/supersededBackup.test.js
new file mode 100644
index 0000000000..139c297f6c
--- /dev/null
+++ b/server/services/supersededBackup.test.js
@@ -0,0 +1,104 @@
+/**
+ * The reap of a verified-SUPERSEDED branch is gated on this backup, so what
+ * matters is not that it wrote files but that what it wrote can bring the branch
+ * back. Run against real git: the commits patch, the worktree diff and the
+ * untracked copies are all git output, and a mocked `execGit` would only prove
+ * the calls were made.
+ */
+
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { mkdtemp, mkdir, readFile, rm, writeFile, stat } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { execGit } from '../lib/execGit.js';
+import { makeGitSandbox, destroyGitSandbox, SKIP_HEAVY_INTEGRATION } from '../lib/gitTestRepo.js';
+import { backupSupersededBranch, backupSlug, backupRoot } from './supersededBackup.js';
+
+const BRANCH = 'cos/task-x/agent-dead';
+
+describe.skipIf(SKIP_HEAVY_INTEGRATION)('backupSupersededBranch', () => {
+ let sandbox;
+ let repo;
+ let worktree;
+ let cosDir;
+ let tip;
+
+ beforeAll(async () => {
+ sandbox = await makeGitSandbox({ prefix: 'portos-superseded-backup-' });
+ repo = sandbox.repo;
+ worktree = join(sandbox.scratch, 'worktrees', 'agent-dead');
+ cosDir = await mkdtemp(join(tmpdir(), 'portos-superseded-cos-'));
+
+ // One commit of its own on the branch, then uncommitted work on top: the
+ // shape of a CoS agent that committed once and died mid-edit.
+ await execGit(['worktree', 'add', '-b', BRANCH, worktree, 'main'], repo);
+ await writeFile(join(worktree, 'shipped.txt'), 'committed on the branch\n');
+ await execGit(['add', '-A'], worktree);
+ await execGit(['commit', '-m', 'branch commit'], worktree);
+ await writeFile(join(worktree, 'initial.txt'), 'edited but never committed\n');
+ await mkdir(join(worktree, 'notes'), { recursive: true });
+ await writeFile(join(worktree, 'notes', 'draft.md'), '# untracked draft\n');
+ tip = (await execGit(['rev-parse', BRANCH], repo)).stdout.trim();
+ });
+
+ afterAll(async () => {
+ await destroyGitSandbox(sandbox.scratch);
+ await rm(cosDir, { recursive: true, force: true });
+ });
+
+ it('captures the commits, the uncommitted edits and the untracked files', async () => {
+ const result = await backupSupersededBranch(
+ repo,
+ { branch: BRANCH, tip, worktreePath: worktree, verdict: { replacedBy: ['abc123'] } },
+ { defaultBranch: 'main', cosDir }
+ );
+
+ expect(result.dir).toBe(join(backupRoot(cosDir), backupSlug(BRANCH)));
+
+ // The patches' CONTENT is proven by the replay test below, which applies
+ // them; here it is enough that both were written.
+ expect(await stat(join(result.dir, 'commits.patch'))).toBeTruthy();
+ expect(await stat(join(result.dir, 'worktree.diff'))).toBeTruthy();
+
+ // Untracked work is COPIED, not patched — it is usually the whole deliverable
+ // of an abandoned worktree, and a copy needs no tooling to read back.
+ expect(await readFile(join(result.dir, 'untracked', 'notes', 'draft.md'), 'utf8'))
+ .toBe('# untracked draft\n');
+ expect(result.untracked).toContain(join('notes', 'draft.md'));
+
+ const manifest = JSON.parse(await readFile(result.manifest, 'utf8'));
+ expect(manifest).toMatchObject({ branch: BRANCH, repoPath: repo, tip, worktreePath: worktree });
+ expect(manifest.verdict).toEqual({ replacedBy: ['abc123'] });
+ // The ref is deleted right after this, so the tip SHA is the restore path.
+ expect(manifest.restore.join('\n')).toContain(`git -C ${repo} branch ${BRANCH} ${tip}`);
+ });
+
+ it('applies its own patches back onto the default branch', async () => {
+ const result = await backupSupersededBranch(
+ repo,
+ { branch: BRANCH, tip, worktreePath: worktree, verdict: {} },
+ { defaultBranch: 'main', cosDir }
+ );
+ const replay = join(sandbox.scratch, 'worktrees', 'replay');
+ await execGit(['worktree', 'add', '--detach', replay, 'main'], repo);
+ await execGit(['am', join(result.dir, 'commits.patch')], replay);
+ await execGit(['apply', join(result.dir, 'worktree.diff')], replay);
+
+ expect(await readFile(join(replay, 'shipped.txt'), 'utf8')).toBe('committed on the branch\n');
+ expect(await readFile(join(replay, 'initial.txt'), 'utf8')).toBe('edited but never committed\n');
+ });
+
+ it('writes a manifest even for a branch with nothing to capture', async () => {
+ await execGit(['branch', 'empty/branch', 'main'], repo);
+ const result = await backupSupersededBranch(
+ repo,
+ { branch: 'empty/branch', tip: null, worktreePath: null, verdict: {} },
+ { defaultBranch: 'main', cosDir }
+ );
+ const manifest = JSON.parse(await readFile(result.manifest, 'utf8'));
+ expect(manifest.captured).toMatchObject({ commitsPatch: false, worktreeDiff: false, untrackedFiles: [] });
+ expect(manifest.restore).toEqual([]);
+ // No empty artifacts left beside it.
+ await expect(stat(join(result.dir, 'commits.patch'))).rejects.toThrow();
+ });
+});
diff --git a/server/services/supersededLedger.js b/server/services/supersededLedger.js
index d7243e3273..be4b20c3f1 100644
--- a/server/services/supersededLedger.js
+++ b/server/services/supersededLedger.js
@@ -20,14 +20,17 @@
* unreadable, or malformed ledger yields no entries, which restores the old
* re-analyze-everything behavior rather than silently hiding a branch.
*
- * DELIBERATELY NOT auto-reap. A superseded branch's uncommitted work is
- * redundant, not worthless, and deleting a worktree is irreversible. The
- * expensive part of the loop is the *analysis*, so caching the verdict removes
- * the cost while the destructive step stays a human action.
+ * Caching the verdict removes the cost of re-analysis; it does not retire the
+ * branch. `reapSupersededBranches` (branchReconcile.js) does that, gated on a
+ * recoverable backup written by `supersededBackup.js` — a superseded branch's
+ * uncommitted work is redundant, not worthless, so it is preserved before the
+ * worktree is removed. What reaches `formatSupersededForPrompt` is therefore not
+ * the whole superseded set but the leftovers the reap could not take this cycle.
*/
import { PATHS, tryReadFile, safeJSONParse, atomicWrite } from '../lib/fileUtils.js';
import { join } from 'node:path';
+import { isAgentScratchPath } from '../lib/agentScratchPaths.js';
export const LEDGER_VERSION = 1;
@@ -35,7 +38,7 @@ export const LEDGER_VERSION = 1;
export const ledgerPath = (cosDir = PATHS.cos) => join(cosDir, 'branch-reconcile-verdicts.json');
/** Order-independent set equality over two path lists. Pure. */
-const sameSet = (a = [], b = []) => {
+export const sameSet = (a = [], b = []) => {
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
const left = new Set(a);
return b.every((x) => left.has(x)) && left.size === new Set(b).size;
@@ -121,7 +124,15 @@ export function isVerdictFresh(entry, branch, { replacedByPresent = true, repoPa
if (!replacedByPresent) return false;
if (!entry.tip || entry.tip !== branch.tip) return false;
if (!sameSet(entry.collisionPaths, branch.collisionPaths)) return false;
- return sameSet(entry.dirtyPaths || [], branch.dirtyPaths || []);
+ // A verdict recorded before `classifyWorktreeDirt` learned to subtract PortOS's
+ // own runtime scratch lists that scratch among its dirty paths, while the live
+ // side no longer does. Comparing raw would expire every such entry and re-pay
+ // the coordinator analysis that the ledger exists to avoid — so subtract on
+ // both sides. Nothing else changes: a live list never contains scratch.
+ return sameSet(
+ (entry.dirtyPaths || []).filter((path) => !isAgentScratchPath(path)),
+ (branch.dirtyPaths || []).filter((path) => !isAgentScratchPath(path))
+ );
}
/**
@@ -153,18 +164,18 @@ export function partitionSuperseded(inFlight, entries, replacedByPresent = () =>
}
/**
- * Render the cached-superseded set for the coordinator prompt. These branches are
- * NOT work — they are named so the coordinator doesn't re-discover them, and so
- * the reap commands are one copy away for the human who authorizes them.
+ * Render the still-standing superseded set for the coordinator prompt. These
+ * branches are NOT work — they are named so the coordinator doesn't re-discover
+ * them, and so a held-back reap is visible rather than silent.
* @param {object[]} superseded - partitionSuperseded()'s `superseded`
* @returns {string}
*/
export function formatSupersededForPrompt(superseded) {
if (!superseded?.length) return '';
const lines = [
- `## Already verified SUPERSEDED — awaiting reap (${superseded.length}) — DO NOT ANALYZE`,
+ `## Already verified SUPERSEDED — reap held back (${superseded.length}) — DO NOT ANALYZE`,
'',
- 'Each branch below was analyzed by an earlier run and confirmed superseded: the default branch already solves its problem, so merging it would REGRESS shipped work. The verdict is cached and still valid (branch tip, uncommitted change set, and collision paths all unchanged; the replacing commits are still on the default branch). Do not read these worktrees, do not re-derive the verdict, do not commit, rebase, resolve, or merge anything on them. They are listed only so you can report them — reaping is a human action.',
+ 'Each branch below was analyzed by an earlier run and confirmed superseded: the default branch already solves its problem, so merging it would REGRESS shipped work. The verdict is cached and still valid (branch tip, uncommitted change set, and collision paths all unchanged; the replacing commits are still on the default branch). PortOS reaps a verified-superseded branch itself, after backing it up — these are the ones this cycle could NOT take, because something still holds them: a locked worktree, a live CoS agent, a claim tree inside its idle window, or a tip that moved after the verdict was recorded. Do not read these worktrees, do not re-derive the verdict, do not commit, rebase, resolve, or merge anything on them. Report them; the next cycle reaps whatever has since been released.',
''
];
for (const b of superseded) {
@@ -174,8 +185,7 @@ export function formatSupersededForPrompt(superseded) {
if (v.replacedBy?.length) lines.push(`- Replaced on the default branch by: ${v.replacedBy.map((s) => `\`${s}\``).join(', ')}${v.replacedByNote ? ` — ${v.replacedByNote}` : ''}`);
if (v.backupPatch) lines.push(`- Uncommitted work backed up at: \`${v.backupPatch}\``);
if (b.worktreePath) {
- lines.push('- Reap (destructive — report these commands, do NOT run them):');
- lines.push(` \`git worktree remove --force ${b.worktreePath} && git branch -D ${b.branch}\``);
+ lines.push(`- Worktree still on disk: \`${b.worktreePath}\` — PortOS reaps it once its hold lifts. Do NOT run the removal yourself.`);
}
lines.push('');
}
diff --git a/server/services/supersededLedger.test.js b/server/services/supersededLedger.test.js
index 1fdd930abb..d04a1dfe16 100644
--- a/server/services/supersededLedger.test.js
+++ b/server/services/supersededLedger.test.js
@@ -225,7 +225,7 @@ describe('formatSupersededForPrompt', () => {
expect(formatSupersededForPrompt(undefined)).toBe('');
});
- it('names the branch, the replacing commits, the backup and the reap commands', () => {
+ it('names the branch, the replacing commits, the backup and the worktree still on disk', () => {
const out = formatSupersededForPrompt([{
...branch(),
verdict: entry({
@@ -240,13 +240,18 @@ describe('formatSupersededForPrompt', () => {
expect(out).toContain('honor the video backend pin');
expect(out).toContain('fff999');
expect(out).toContain('agent-dead.patch');
- expect(out).toContain('git worktree remove --force /repo/data/cos/worktrees/agent-dead');
- expect(out).toContain('git branch -D cos/task-x/agent-dead');
+ expect(out).toContain('/repo/data/cos/worktrees/agent-dead');
});
- it('tells the agent the reap is a human action, not something to run', () => {
+ // The reap is PortOS's own deterministic step now (reapSupersededBranches), so
+ // a branch reaching this block is one the reap could not take. Handing the
+ // coordinator a copy-pasteable `worktree remove` would race that step and skip
+ // the backup it is gated on.
+ it('never hands the agent removal commands to run', () => {
const out = formatSupersededForPrompt([{ ...branch(), verdict: entry() }]);
- expect(out).toMatch(/do NOT run them/i);
+ expect(out).not.toMatch(/git worktree remove/);
+ expect(out).not.toMatch(/git branch -D/);
+ expect(out).toMatch(/PortOS reaps/i);
});
});
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index 958d8bbdd8..b2a374367f 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -14,6 +14,7 @@ import { readdir, rm, stat } from 'fs/promises';
import { join } from 'path';
import { ensureDir, isPathInsideDir, PATHS, sleep, tryReadFile } from '../lib/fileUtils.js';
import { DONE_SENTINEL_NAME, doneSentinelName } from '../lib/agentSentinel.js';
+import { AGENT_SCRATCH_PATHS, matchesScratchRoot } from '../lib/agentScratchPaths.js';
import { execGit } from '../lib/execGit.js';
import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';
import { enforceSafeBranchUpstream } from '../lib/branchUpstreamGuard.js';
@@ -270,11 +271,20 @@ async function enforceUpstreamOrUndoAdd(sourceWorkspace, branchName, worktreePat
* Classify a `git status --porcelain` blob into real changes vs auto-generated
* lockfile churn. Pure (testable) — callers decide what to do with the result.
*
+ * PortOS's own runtime scratch (`AGENT_SCRATCH_PATHS` — the public-review input
+ * bundle and its patch directory) is subtracted for EVERY caller, not passed in
+ * per call. It is written by PortOS into the worktree and never committed, so a
+ * tree holding only that is finished work by every consumer's definition; making
+ * each one learn the names is how two `pr-reviewer` worktrees survived
+ * `removeWorktree`, `reapMergedWorktrees` and branch-reconcile in turn.
+ *
* @param {string} porcelain - raw `git status --porcelain` stdout
* @param {object} [options]
- * @param {string[]} [options.ignoredPaths] - runtime-only paths that must not
- * preserve a completed worktree. They are still removed only when the rest of
- * the tree is safe to remove.
+ * @param {string[]} [options.ignoredPaths] - ADDITIONAL runtime-only paths that
+ * must not preserve a completed worktree — for names this module cannot know
+ * statically, notably one run's own `.agent-done-<agentId>` sentinel. Matched
+ * as roots: a directory entry also covers everything under it. They are still
+ * removed only when the rest of the tree is safe to remove.
* @returns {{ clean: boolean, lockfileOnly: boolean, lockfilePaths: string[], realChangePaths: string[], hasRealChanges: boolean }}
* - clean: no changes at all
* - lockfileOnly: every change is an auto-generated lockfile (safe to discard)
@@ -286,12 +296,12 @@ async function enforceUpstreamOrUndoAdd(sourceWorkspace, branchName, worktreePat
* - hasRealChanges: at least one non-lockfile change (worktree must be preserved)
*/
export function classifyWorktreeDirt(porcelain, { ignoredPaths = [] } = {}) {
- const ignored = new Set(ignoredPaths);
+ const ignored = [...AGENT_SCRATCH_PATHS, ...ignoredPaths];
const toPath = (line) => line.replace(/^\s*\S+\s+/, '').split(' -> ').pop();
const lines = (porcelain || '').split('\n')
.map(l => l.trim())
.filter(Boolean)
- .filter(line => !ignored.has(toPath(line)));
+ .filter(line => !matchesScratchRoot(toPath(line), ignored));
if (lines.length === 0) {
return { clean: true, lockfileOnly: false, lockfilePaths: [], realChangePaths: [], hasRealChanges: false };
}
diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.js
index 2dd02a9444..377ee378ea 100644
--- a/server/services/worktreeManager.test.js
+++ b/server/services/worktreeManager.test.js
@@ -356,6 +356,28 @@ describe('classifyWorktreeDirt (real exported helper)', () => {
// shared checkout is still dirt this caller must not silently discard.
expect(classifyWorktreeDirt('?? .agent-done-agent-2', { ignoredPaths }).clean).toBe(false);
});
+
+ // PortOS materializes the public-review bundle INTO the worktree it hands a
+ // reviewer model and never commits it. Subtracted for EVERY caller rather than
+ // passed in per call: counted as work, it made `removeWorktree` preserve the
+ // tree, `reapMergedWorktrees` hold it, and branch-reconcile spend a coordinator
+ // run per pass concluding "no real work product, a human should discard it".
+ it('subtracts PortOS runtime scratch with no ignoredPaths from the caller', () => {
+ expect(classifyWorktreeDirt('?? PORTOS_PUBLIC_REVIEW_INPUT.json').clean).toBe(true);
+ // Untracked directories arrive collapsed to their root…
+ expect(classifyWorktreeDirt('?? .portos-public-review/').clean).toBe(true);
+ // …and expanded to files under -uall.
+ expect(classifyWorktreeDirt('?? .portos-public-review/PR-42.patch').clean).toBe(true);
+ expect(classifyWorktreeDirt('?? PORTOS_PUBLIC_REVIEW_INPUT.json\n?? .portos-public-review/').clean).toBe(true);
+ });
+
+ it('still reports real work sitting beside the scratch', () => {
+ const r = classifyWorktreeDirt('?? PORTOS_PUBLIC_REVIEW_INPUT.json\n M src/index.js');
+ expect(r.hasRealChanges).toBe(true);
+ expect(r.realChangePaths).toEqual(['src/index.js']);
+ // A sibling that merely shares the prefix is real work, not scratch.
+ expect(classifyWorktreeDirt('?? .portos-public-review-notes.md').hasRealChanges).toBe(true);
+ });
});
describe('Broken Worktree Detection', () => {