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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
simplify the repo-state audit: fix the dead pending-owner gate, drop a redundant check, detach it from the completion path
[._.]/ Adam Eivy54955c718295
diff --git a/client/src/components/apps/EditAppDrawer.jsx b/client/src/components/apps/EditAppDrawer.jsxindex eb13e2318e..efd56f9fb5 100644--- a/client/src/components/apps/EditAppDrawer.jsx+++ b/client/src/components/apps/EditAppDrawer.jsx@@ -650,18 +650,19 @@ export default function EditAppDrawer({ app, onClose, onSave }) {{prCompletionOption(formData.defaultPrCompletion)?.description}</p></div>- <label className="flex items-center gap-2 cursor-pointer">+ <label htmlFor="edit-app-verify-repo-state" className="flex items-center gap-2 cursor-pointer"><input+ id="edit-app-verify-repo-state"type="checkbox"checked={formData.verifyRepoStateOnCompletion}onChange={e => setFormData(prev => ({ ...prev, verifyRepoStateOnCompletion: e.target.checked }))}className="rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"/><ShieldCheck size={14} className="text-amber-400" />- <span className="text-sm text-white" title="After each agent finishes, check that its worktree was removed, its branch deleted, and its PR merged. When the repo diverges, PortOS files a recovery task for an agent to finish the cleanup.">Verify repo state after each agent</span>+ <span className="text-sm text-white">Verify repo state after each agent</span></label><p className="ml-6 text-xs text-gray-500">- Audits git and the forge once the agent completes. A leftover worktree, an undeleted branch, or an unmerged PR files a recovery task instead of being silently left behind.+ Audits git and the forge once an agent completes. A leftover worktree, an undeleted branch, or an unmerged PR files a recovery task instead of being silently left behind.</p></div>)}diff --git a/server/lib/README.md b/server/lib/README.mdindex 8a32eb6b7e..2ceda02c38 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -413,7 +413,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers), `canonicalStringify` (recursive sorted-key JSON serialization for cross-machine content hashing), `isEmptyScalar` (true for null/undefined/whitespace-string/empty-array — merge gap-fill gate). || `openapiSpec.js` | `buildOpenApiSpec(settings, { baseUrl, version })` — builds an OpenAPI 3.1 document for the currently-exposed public APIs from `apiRegistry`, reusing route Zod schemas via `z.toJSONSchema`. Exposed+`requireAuth` operations get a `security` requirement; passwordless ones don't. Served by `routes/apiDocs.js`. || `prDisposition.js` | `resolvePrCompletion(metadata)` resolves the explicit `review-then-merge` / `merge-on-green` / `leave-open` policy, with legacy `reviewLoop` fallback; `leavesPrForHuman(task)` + `PR_STAYS_OPEN_TASK_TYPES` keep JIRA hand-offs open. Shared by the agent prompt builder and `agentWorktreeCleanup` so both halves agree. `resolvePrCreation({taskOpenPR, agentOwnsPr, prClaimVerified})` → a `PR_CREATION` tri-state (`never` / `if-missing` / `always`) naming who opens the change request for a completing worktree agent, so the runner, TUI, and direct-CLI completion paths cannot drift into double-firing `gh pr create`. |-| `repoStateExpectations.js` | Post-completion repo-state audit, pure half. `resolveRepoStateExpectation({...})` answers what the repo SHOULD look like now that one worktree agent finished (worktree gone, branch gone locally + remotely, branch merged, PR merged) and names every not-audited path via `REPO_STATE_SKIPS` (a failed run is preserved for its retry; a pending review-loop follow-up still owns the branch). `classifyRepoStateIssues(expectation, observed)` turns probed facts into `REPO_STATE_ISSUES` codes — observations are tri-state, and `null` ("could not ask") never produces an issue. `repoStateVerificationEnabled(app)` reads the per-app `verifyRepoStateOnCompletion` switch (unset = on). Probing + remediation live in `services/agentRepoStateVerification.js`. |+| `repoStateExpectations.js` | Post-completion repo-state audit, pure half. `resolveRepoStateExpectation({...})` answers whether one finished worktree agent should be audited — naming every not-audited path via `REPO_STATE_SKIPS` (a failed run is preserved for its retry; a review-loop follow-up or pr-watcher pending merge still owns the branch) — and returns just `staysOpen` + `prExpected`, from which `classifyRepoStateIssues(expectation, observed)` derives every check into `REPO_STATE_ISSUES` codes. Observations are tri-state: `null` ("could not ask") never produces an issue. `repoStateVerificationEnabled(app)` reads the per-app `verifyRepoStateOnCompletion` switch (unset = on). Probing + remediation live in `services/agentRepoStateVerification.js`. || `shellCd.js` | `buildCdCommand(path, shell)` + `formatShellCommandLine(command, args, shell)` + `detectShellFlavor(shell, platform?)` + `quoteForShell(value, flavor, position?)` — build `cd` and arbitrary command-token lines for the shell a PTY session is ACTUALLY running (`cmd.exe` → Windows-escaped double quotes, PowerShell → doubled single quotes with `&` for a quoted command token, everything else → POSIX `shellQuote`). The Shell page's "cd to app" picker used to hard-code the POSIX form, which on Windows both mis-quoted the path and silently refused to cross drives (a bare `cd` does not switch drive). Flavor comes from the shell binary name, not the platform, so git-bash on Windows still gets POSIX quoting. `formatShellCommandLine` joins a command + argv into one quoted line and is shared by `agentTuiSpawning.js#buildTuiSpawnConfig` and the AI Providers page's "Launch in Shell" deep link, so a hand-launched TUI provider is quoted exactly the way the CoS runner would quote it. Renders the LINE only; the Enter byte that submits it is `SUBMIT_KEY` in `tuiHandshake.js`. || `shellExit.js` | `buildRunThenExitCommand(commandLine, shell)` — "run this CLI, then close the shell with its status", in the dialect the session speaks. An agent TUI shell exists only to host one CLI and must die with it. The POSIX `cmd; exit $?` was applied everywhere and is actively wrong off-POSIX: in PowerShell `$?` is a BOOLEAN, so `exit $?` reports success as 1 and failure as 0 (inverted) — use `$LASTEXITCODE`, pre-seeded to 1 so a command that never ran still exits non-zero; in cmd.exe `;` is an argument separator, so the CLI is handed `;`/`exit`/`$?` as arguments — use `& exit`. Verified against node-pty on Windows 11 for pwsh 7, PowerShell 5.1 and cmd.exe. || `shellLivenessProbe.js` | `buildLivenessProbeCommand(shellPid, platform?)` + `parseLivenessProbeOutput(stdout, shellPid)` + `shellHasLiveChild(shellPid, opts?)` — platform-aware process-liveness probe for a launched TUI command in a persistent PTY shell. POSIX (`ps -Ao ppid=`) / Windows (`Get-CimInstance Win32_Process \| Select-Object -ExpandProperty ParentProcessId` via PowerShell). Resolves true (assume alive) when the probe fails or cannot run. |diff --git a/server/lib/repoStateExpectations.js b/server/lib/repoStateExpectations.jsindex fa967a764c..8e0ca49811 100644--- a/server/lib/repoStateExpectations.js+++ b/server/lib/repoStateExpectations.js@@ -1,28 +1,30 @@/**- * Post-completion repo-state expectations for CoS worktree agents.+ * Post-completion repo-state expectations for CoS worktree agents — the pure half.*- * Cleanup (`agentWorktreeCleanup.js`) reports a warning only when a step it- * *attempted* failed. It says nothing when a step was never attempted — an agent- * that owned its own PR workflow and exited before `gh pr merge`, a `removeWorktree`- * that reported success while the directory survived, a branch whose PR merged on- * the forge while the local ref stayed behind. Those runs finish "clean" and leave- * a branch and a worktree on disk forever.+ * Cleanup (`services/agentWorktreeCleanup.js`) reports only the steps it TRIED+ * and failed. A run whose steps were never attempted finishes with zero warnings+ * and still leaves debris: an agent that owns its own PR workflow merges the PR+ * itself, so cleanup stands down (`skipMerge`, `PR_CREATION.NEVER`) and nothing+ * checks whether the branch and worktree actually went away.*- * This module is the pure half of the audit that closes that gap: given what the- * task ASKED for, what should the repository look like now, and which of the- * observed facts contradict it. No git, no forge, no I/O — the probing lives in- * `services/agentRepoStateVerification.js`, which is what makes both halves- * testable without a repository.+ * This module answers "what should the repo look like now" and "which observed+ * facts contradict that". No I/O — the probing and remediation live in+ * `services/agentRepoStateVerification.js`.*- * Deliberately narrow: it judges ONE agent's branch and worktree, right after that- * agent completed. The periodic whole-repo sweep is `services/branchReconcile.js`.+ * Deliberately narrow: ONE agent's branch, right after that agent completed. The+ * periodic whole-repo sweep is `services/branchReconcile.js`.*/import { PR_COMPLETIONS } from './prDisposition.js';/**- * Issue codes, in the order they are reported. Each names a concrete divergence- * from the expected end state, and each is actionable by the investigation agent.+ * Divergences worth reporting, in the order they are reported.+ *+ * There is deliberately no "the agent never opened a PR" code: `verifyPrClaim`+ * (services/agentFinalization.js) already owns that question on every completion+ * path, is forge-agnostic, and carries the `noChangesToShip` carve-out (#3358) —+ * a run that found the work already done ships nothing and must not be told to+ * open a PR for an empty branch.*/export const REPO_STATE_ISSUES = Object.freeze({WORKTREE_PRESENT: 'worktree-present',@@ -30,12 +32,11 @@ export const REPO_STATE_ISSUES = Object.freeze({REMOTE_BRANCH_PRESENT: 'remote-branch-present',BRANCH_UNMERGED: 'branch-unmerged',PR_UNMERGED: 'pr-unmerged',- PR_MISSING: 'pr-missing',});/**- * Why a run was not audited. Returned rather than logged so the caller can emit- * one line and tests can assert the decision instead of the side effect.+ * Why a run was not audited. Returned rather than logged, so "nothing happened"+ * is never ambiguous between "checked and clean" and "never checked".*/export const REPO_STATE_SKIPS = Object.freeze({DISABLED: 'verification-disabled',@@ -46,42 +47,43 @@ export const REPO_STATE_SKIPS = Object.freeze({CLEANUP_WARNED: 'cleanup-already-warned',FOLLOW_UP_PENDING: 'follow-up-pending',MISSING_CONTEXT: 'missing-branch-or-workspace',- // Set by the service half when every probe came back unreadable.+ // Set by the service half when not one probe could be read.PROBE_FAILED: 'probe-failed',});/**- * What the repository should look like now that this agent is done.+ * Should this run be audited, and under which of the two end-state shapes?*- * `verify: false` carries a `skipReason` from `REPO_STATE_SKIPS` — every- * not-audited path is named, so "nothing happened" is never ambiguous between- * "checked and clean" and "never checked".+ * Returns two facts rather than one flag per check: `staysOpen` (the PR is a+ * human's to land, so its branch must survive) and `prExpected`. Every check is+ * derived from those in `classifyRepoStateIssues` — an earlier version carried+ * six `expect*` booleans, three of which were the same expression.*- * The two states worth spelling out:+ * The two skips worth spelling out:** - **A failed run is never audited.** Its branch and worktree are PRESERVED on* purpose (`preserveBranchWithCommits`, `resolveResumePointer`) so the task's* retry resumes rather than restarts. Auditing it would report the resume- * pointer as a leak and spawn an agent to delete the work.- * - **A pending review-loop / merge follow-up defers the audit.** The follow-up- * is the terminal actor for this branch — it merges the PR and deletes the- * branch — so the branch is *supposed* to still exist right now. The follow-up- * is itself a worktree agent, so its own completion gets audited instead.+ * pointer as a leak.+ * - **A pending owner defers the audit.** A review-loop follow-up or a pr-watcher+ * pending merge lands this branch next, so it is *supposed* to still exist.+ * `FOLLOW_UP_PENDING` is tested last because answering it costs two file reads;+ * every free gate above it runs first.** @param {object} params* @param {boolean} params.enabled - the app's `verifyRepoStateOnCompletion` setting* @param {boolean} params.success - the run's effective success- * @param {boolean} params.isWorktree - agent ran in a worktree- * @param {boolean} [params.isPersistentWorktree] - long-lived feature worktree (never torn down)- * @param {boolean} [params.discardWorktree] - reasoning agent whose tree is thrown away unmerged- * @param {boolean} [params.followUpPending] - a review-loop/merge follow-up owns this branch next- * @param {number} [params.cleanupWarningCount] - warnings cleanup already raised (it spawns its own recovery)+ * @param {boolean} params.isWorktree+ * @param {boolean} [params.isPersistentWorktree] - long-lived feature worktree+ * @param {boolean} [params.discardWorktree] - reasoning agent whose tree is thrown away+ * @param {boolean} [params.followUpPending] - something is already queued to land this branch+ * @param {number} [params.cleanupWarningCount] - cleanup spawns its own recovery when it warned* @param {string} [params.prCompletion] - resolved `PR_COMPLETIONS` policy* @param {boolean} [params.leaveOpen] - the PR is a human's to land (JIRA hand-off)- * @param {boolean} [params.prExpected] - a PR was requested for this branch+ * @param {boolean} [params.prExpected] - the task asked for a PR* @param {string|null} [params.branchName]* @param {string|null} [params.sourceWorkspace]- * @returns {{verify: boolean, skipReason: string|null, expectWorktreeGone: boolean, expectLocalBranchGone: boolean, expectRemoteBranchGone: boolean, expectBranchMerged: boolean, expectPrMerged: boolean, expectPrExists: boolean}}+ * @returns {{verify: boolean, skipReason: string|null, staysOpen: boolean, prExpected: boolean}}*/export function resolveRepoStateExpectation({enabled,@@ -97,16 +99,7 @@ export function resolveRepoStateExpectation({branchName = null,sourceWorkspace = null,} = {}) {- const skip = (skipReason) => ({- verify: false,- skipReason,- expectWorktreeGone: false,- expectLocalBranchGone: false,- expectRemoteBranchGone: false,- expectBranchMerged: false,- expectPrMerged: false,- expectPrExists: false,- });+ const skip = (skipReason) => ({ verify: false, skipReason, staysOpen: false, prExpected: false });if (enabled === false) return skip(REPO_STATE_SKIPS.DISABLED);if (!isWorktree) return skip(REPO_STATE_SKIPS.NOT_WORKTREE);@@ -114,35 +107,27 @@ export function resolveRepoStateExpectation({if (discardWorktree) return skip(REPO_STATE_SKIPS.DISCARDED_WORKTREE);if (!success) return skip(REPO_STATE_SKIPS.FAILED_RUN);if (cleanupWarningCount > 0) return skip(REPO_STATE_SKIPS.CLEANUP_WARNED);- if (followUpPending) return skip(REPO_STATE_SKIPS.FOLLOW_UP_PENDING);if (!branchName || !sourceWorkspace) return skip(REPO_STATE_SKIPS.MISSING_CONTEXT);-- // `leave-open` is a deliberate hand-off: the PR stays open and its branch must- // stay with it, on both the local and the remote side. The worktree is still- // expected to be gone — nothing about handing a PR to a human needs a checkout.- const staysOpen = leaveOpen || prCompletion === PR_COMPLETIONS.LEAVE_OPEN;+ if (followUpPending) return skip(REPO_STATE_SKIPS.FOLLOW_UP_PENDING);return {verify: true,skipReason: null,- expectWorktreeGone: true,- expectLocalBranchGone: !staysOpen,- expectRemoteBranchGone: !staysOpen,- expectBranchMerged: !staysOpen,- expectPrMerged: !staysOpen && prExpected,- // A requested PR that the forge has never heard of is a leak in its own right,- // whatever the completion policy — the work has nowhere to land.- expectPrExists: prExpected,+ // `leave-open` is a deliberate hand-off: the PR stays open and its branch must+ // stay with it, local and remote. The worktree is still expected to be gone —+ // nothing about handing a PR to a human needs a checkout.+ staysOpen: leaveOpen || prCompletion === PR_COMPLETIONS.LEAVE_OPEN,+ prExpected,};}/*** Which observed facts contradict the expectation.*- * Every observation is tri-state on purpose (`true` / `false` / `null`): `null`- * means "could not determine" — git unreachable, `gh` firewalled, a non-GitHub- * forge. A `null` NEVER produces an issue. Reading "we could not ask" as "it's- * still there" would spawn an investigation agent every time the network hiccups.+ * Every observation is tri-state (`true` / `false` / `null`): `null` means "could+ * not determine" — git unreachable, `gh` firewalled, a non-GitHub forge. A `null`+ * NEVER produces an issue, because reading "we could not ask" as "it's still+ * there" would file a recovery task on every network hiccup.** @param {ReturnType<typeof resolveRepoStateExpectation>} expectation* @param {object} observed@@ -150,47 +135,41 @@ export function resolveRepoStateExpectation({* @param {boolean|null} [observed.localBranchPresent]* @param {boolean|null} [observed.remoteBranchPresent]* @param {boolean|null} [observed.branchMerged]- * @param {string|null} [observed.prState] - upper-cased `MERGED` / `OPEN` / `CLOSED`, or null- * @param {boolean|null} [observed.prExists]+ * @param {string|null} [observed.prState] - upper-cased `MERGED` / `OPEN` / `CLOSED`* @param {string|null} [observed.branchName]* @returns {Array<{code: string, message: string}>}*/export function classifyRepoStateIssues(expectation, observed = {}) {if (!expectation?.verify) return [];- const branch = observed.branchName || expectation.branchName || 'the agent branch';+ const branch = observed.branchName || 'the agent branch';+ const branchShouldBeGone = !expectation.staysOpen;const issues = [];- if (expectation.expectWorktreeGone && observed.worktreePresent === true) {+ if (observed.worktreePresent === true) {issues.push({code: REPO_STATE_ISSUES.WORKTREE_PRESENT,message: `Worktree for ${branch} still exists after cleanup reported success`,});}- if (expectation.expectLocalBranchGone && observed.localBranchPresent === true) {+ if (branchShouldBeGone && observed.localBranchPresent === true) {issues.push({code: REPO_STATE_ISSUES.LOCAL_BRANCH_PRESENT,message: `Local branch ${branch} still exists after the run completed`,});}- if (expectation.expectRemoteBranchGone && observed.remoteBranchPresent === true) {+ if (branchShouldBeGone && observed.remoteBranchPresent === true) {issues.push({code: REPO_STATE_ISSUES.REMOTE_BRANCH_PRESENT,message: `Remote branch origin/${branch} was never deleted`,});}- if (expectation.expectBranchMerged && observed.branchMerged === false) {+ if (branchShouldBeGone && observed.branchMerged === false) {issues.push({code: REPO_STATE_ISSUES.BRANCH_UNMERGED,message: `Branch ${branch} carries commits that are not on the default branch`,});}- if (expectation.expectPrExists && observed.prExists === false) {- issues.push({- code: REPO_STATE_ISSUES.PR_MISSING,- message: `No pull request was ever opened for ${branch}, but the task asked for one`,- });- }- if (expectation.expectPrMerged && observed.prState && observed.prState !== 'MERGED') {+ if (branchShouldBeGone && expectation.prExpected && observed.prState && observed.prState !== 'MERGED') {issues.push({code: REPO_STATE_ISSUES.PR_UNMERGED,message: `Pull request for ${branch} is ${observed.prState}, not MERGED`,@@ -202,11 +181,10 @@ export function classifyRepoStateIssues(expectation, observed = {}) {/*** True when the app's per-app setting leaves the audit on. Unset means ON: the- * audit only ever *reports* on a run the completion path already believed was- * finished, and an install that never hears about a leaked branch accumulates- * them silently — the failure this exists to catch.+ * audit only reports on a run the completion path already believed was finished,+ * and an install that never hears about a leaked branch accumulates them silently.*- * @param {object|null} app - managed app record (null for a PortOS-local task)+ * @param {object|null} app - managed app record (null for a task with no app)* @returns {boolean}*/export function repoStateVerificationEnabled(app) {diff --git a/server/lib/repoStateExpectations.test.js b/server/lib/repoStateExpectations.test.jsindex 97cbaa2e61..bccf5bb868 100644--- a/server/lib/repoStateExpectations.test.js+++ b/server/lib/repoStateExpectations.test.js@@ -21,37 +21,16 @@ const auditable = {describe('resolveRepoStateExpectation', () => {it('audits a successful worktree run and expects a fully cleaned repo', () => {const e = resolveRepoStateExpectation({ ...auditable, prExpected: true });- expect(e.verify).toBe(true);- expect(e.skipReason).toBeNull();- expect(e.expectWorktreeGone).toBe(true);- expect(e.expectLocalBranchGone).toBe(true);- expect(e.expectRemoteBranchGone).toBe(true);- expect(e.expectBranchMerged).toBe(true);- expect(e.expectPrMerged).toBe(true);- expect(e.expectPrExists).toBe(true);- });-- it('expects no PR when the task never asked for one', () => {- const e = resolveRepoStateExpectation({ ...auditable, prExpected: false });- expect(e.expectPrExists).toBe(false);- expect(e.expectPrMerged).toBe(false);- // The branch itself is still expected to be gone — it was merged locally.- expect(e.expectLocalBranchGone).toBe(true);+ expect(e).toEqual({ verify: true, skipReason: null, staysOpen: false, prExpected: true });});it.each([['leave-open policy', { prCompletion: PR_COMPLETIONS.LEAVE_OPEN }],['human hand-off', { leaveOpen: true }],- ])('keeps the branch but still expects the worktree gone (%s)', (_label, override) => {+ ])('marks the branch as staying with its PR (%s)', (_label, override) => {const e = resolveRepoStateExpectation({ ...auditable, prExpected: true, ...override });expect(e.verify).toBe(true);- expect(e.expectWorktreeGone).toBe(true);- expect(e.expectLocalBranchGone).toBe(false);- expect(e.expectRemoteBranchGone).toBe(false);- expect(e.expectBranchMerged).toBe(false);- expect(e.expectPrMerged).toBe(false);- // A PR was requested and must exist even when it stays open for a human.- expect(e.expectPrExists).toBe(true);+ expect(e.staysOpen).toBe(true);});it.each([@@ -68,9 +47,6 @@ describe('resolveRepoStateExpectation', () => {const e = resolveRepoStateExpectation({ ...auditable, ...override });expect(e.verify).toBe(false);expect(e.skipReason).toBe(reason);- // Every expect* flag is false on a skip, so a caller that ignores `verify`- // still cannot be told to expect anything.- expect(Object.entries(e).filter(([k]) => k.startsWith('expect')).every(([, v]) => v === false)).toBe(true);});it('reports the app switch ahead of the other gates', () => {@@ -80,6 +56,19 @@ describe('resolveRepoStateExpectation', () => {const e = resolveRepoStateExpectation({ ...auditable, enabled: false, success: false, isWorktree: false });expect(e.skipReason).toBe(REPO_STATE_SKIPS.DISABLED);});++ it('answers every free gate before the one the caller pays for', () => {+ // `followUpPending` costs two task-file reads plus the app record, so the+ // service resolves once WITHOUT it to short-circuit. That only works while+ // every other skip outranks it.+ for (const override of [+ { isWorktree: false }, { isPersistentWorktree: true }, { discardWorktree: true },+ { success: false }, { cleanupWarningCount: 1 }, { branchName: null }, { sourceWorkspace: null },+ ]) {+ const e = resolveRepoStateExpectation({ ...auditable, ...override, followUpPending: true });+ expect(e.skipReason).not.toBe(REPO_STATE_SKIPS.FOLLOW_UP_PENDING);+ }+ });});describe('classifyRepoStateIssues', () => {@@ -91,7 +80,6 @@ describe('classifyRepoStateIssues', () => {localBranchPresent: false,remoteBranchPresent: false,branchMerged: null,- prExists: true,prState: 'MERGED',});expect(issues).toEqual([]);@@ -103,7 +91,6 @@ describe('classifyRepoStateIssues', () => {localBranchPresent: true,remoteBranchPresent: true,branchMerged: false,- prExists: true,prState: 'OPEN',branchName: 'cos/task-abc/agent-1',});@@ -117,26 +104,14 @@ describe('classifyRepoStateIssues', () => {expect(issues[0].message).toContain('cos/task-abc/agent-1');});- it('reports a requested PR the forge never saw', () => {- const issues = classifyRepoStateIssues(expectation, {- worktreePresent: false,- localBranchPresent: false,- remoteBranchPresent: false,- prExists: false,- prState: null,- });- expect(issues.map(i => i.code)).toEqual([REPO_STATE_ISSUES.PR_MISSING]);- });-it('treats every unknown observation as no issue', () => {// This is the whole point of the tri-state: a firewalled `gh` or an- // unreachable git must not spawn an investigation agent.+ // unreachable git must not file a recovery task.const issues = classifyRepoStateIssues(expectation, {worktreePresent: null,localBranchPresent: null,remoteBranchPresent: null,branchMerged: null,- prExists: null,prState: null,});expect(issues).toEqual([]);@@ -149,26 +124,28 @@ describe('classifyRepoStateIssues', () => {localBranchPresent: true,remoteBranchPresent: true,branchMerged: false,- prExists: false,});expect(issues).toEqual([]);});- it('does not report a still-open PR that was meant to stay open', () => {+ it('leaves a deliberately-open PR and its branch alone, but not its worktree', () => {const staysOpen = resolveRepoStateExpectation({ ...auditable, prExpected: true, leaveOpen: true });- const issues = classifyRepoStateIssues(staysOpen, {- worktreePresent: false,- localBranchPresent: true,- remoteBranchPresent: true,- prExists: true,- prState: 'OPEN',- });- expect(issues).toEqual([]);+ const observed = { localBranchPresent: true, remoteBranchPresent: true, branchMerged: false, prState: 'OPEN' };+ expect(classifyRepoStateIssues(staysOpen, { ...observed, worktreePresent: false })).toEqual([]);+ expect(classifyRepoStateIssues(staysOpen, { ...observed, worktreePresent: true }).map(i => i.code))+ .toEqual([REPO_STATE_ISSUES.WORKTREE_PRESENT]);+ });++ it('does not report an unmerged PR for a task that never asked for one', () => {+ // `openPR: false` runs merge into the source workspace directly. A PR the+ // forge happens to know about is not this run's to land.+ const noPr = resolveRepoStateExpectation({ ...auditable, prExpected: false });+ expect(classifyRepoStateIssues(noPr, { prState: 'OPEN' })).toEqual([]);});});describe('repoStateVerificationEnabled', () => {- it('defaults to on for an unset app and for a PortOS-local task', () => {+ it('defaults to on for an unset app and for a task with no app', () => {expect(repoStateVerificationEnabled(null)).toBe(true);expect(repoStateVerificationEnabled({})).toBe(true);expect(repoStateVerificationEnabled({ verifyRepoStateOnCompletion: true })).toBe(true);diff --git a/server/services/agentRepoStateVerification.js b/server/services/agentRepoStateVerification.jsindex 95b9a03ed0..cd789789fa 100644--- a/server/services/agentRepoStateVerification.js+++ b/server/services/agentRepoStateVerification.js@@ -1,30 +1,32 @@/*** Agent Repo-State Verification*- * The programmatic audit that runs AFTER `cleanupAgentWorktree` and asks a+ * The programmatic audit that runs after `cleanupAgentWorktree` and asks the* question cleanup cannot: is the repository actually in the state this task* asked for?*- * Cleanup only reports what it *tried and failed* to do. A run whose steps were- * never attempted finishes with zero warnings and still leaves debris — the case- * this exists for is an agent that owns its own PR workflow (`ownsPrWorkflow`),- * merges the PR itself, and exits before deleting the branch, or exits with the- * PR still open. Cleanup stands down for exactly those runs (`skipMerge`,- * `PR_CREATION.NEVER`), so nothing checked, and the branch plus its worktree- * persist through every later sweep that treats "an agent owns it" as a reason- * to skip.+ * Cleanup reports only what it TRIED and failed to do. The case this exists for+ * is an agent that owns its own PR workflow (`ownsPrWorkflow`), merges the PR+ * itself, and exits before deleting the branch — or exits with the PR still open.+ * Cleanup stands down for exactly those runs, so nothing checked, and the branch+ * plus its worktree persist through every later sweep that treats "an agent owns+ * it" as a reason to skip. (`removeWorktree` also only `console.log`s a failed+ * `git branch -D`, so even the attempted delete can fail silently.)** What it does NOT do: touch anything. It probes, classifies (via the pure- * `lib/repoStateExpectations.js`), and — when the state diverges — files ONE- * investigation task so an agent can finish the work. Deleting a branch from- * here would be a destructive action taken on the basis of a heuristic, which is- * precisely what `branchReconcile.js` is careful not to do either.+ * `lib/repoStateExpectations.js`), and files ONE recovery task. Deleting a branch+ * from here would be a destructive action on the basis of a heuristic, which is+ * what `branchReconcile.js` is careful not to do either.+ *+ * Detection is what this adds over `branchReconcile.js`: that reconciler is an+ * opt-in scheduled task on a recheck cadence, and it parks on no-progress. This+ * is immediate, per-agent, and attributed to the run that caused it.** Gated per managed app by `verifyRepoStateOnCompletion` (default ON).*- * Concurrency: other agents legitimately hold their own worktrees and branches- * at the same time. Every probe here is scoped to ONE branch — the one this- * agent owned — so a live sibling agent is structurally invisible to it.+ * Concurrency: other agents legitimately hold their own worktrees and branches at+ * the same time. Every probe is scoped to ONE branch — the one this agent owned —+ * so a live sibling agent is structurally invisible to it.*/import { existsSync } from 'fs';@@ -33,10 +35,13 @@ import { emitLog } from './cosEvents.js';import { addTask } from './cos.js';import * as git from './git.js';import { listWorktrees } from './worktreeManager.js';+import { listRemoteHeads, driveToMerge } from './branchReconcile.js';+import { readAllTasksFlat } from './investigationTaskProducer.js';import { execGit } from '../lib/execGit.js';import { PATHS } from '../lib/fileUtils.js';import { isTruthyMeta } from './agentState.js';import { RECOVERY_TASK_PREFIX } from './recoveryTasks.js';+import { resolveTaskTargetBranch } from '../lib/taskTargetBranch.js';import { leavesPrForHuman, resolvePrCompletion } from '../lib/prDisposition.js';import {REPO_STATE_ISSUES,@@ -46,42 +51,47 @@ import {resolveRepoStateExpectation,} from '../lib/repoStateExpectations.js';-// `git ls-remote` is a network round trip on a path that must never delay-// completion handling. Short and its own knob so a slow remote degrades to-// "unknown" (no issue reported) instead of stalling the cleanup chain.-const REMOTE_PROBE_TIMEOUT_MS = 10000;+// `resolveForgeForRepo` spawns `git remote get-url` + `gh auth status` + `gh auth+// token` with no internal timeout; git.js races the same call on the agent-SPAWN+// path for exactly this reason. The completion path has the same property — a+// stalled gh (network / keychain hang) must not hold an agent lane open.+const FORGE_RESOLVE_TIMEOUT_MS = 10000;++const withTimeout = (promise, ms, fallback) => Promise.race([+ promise,+ new Promise(resolve => setTimeout(() => resolve(fallback), ms)),+]);/*** Is something ALREADY queued to land this branch?** Two owners can hold a branch after cleanup returns, and neither is a leak:*- * 1. a review-loop / merge follow-up TASK (`reviewLoopPRBranch`), which checks- * the branch out, drives the reviewers, and merges; and- * 2. a pr-watcher PENDING MERGE (`pendingMergePrs` on the app record), the- * model-free path a merge-on-green GitHub PR takes — the next watcher tick- * merges it when CI is green.+ * 1. a review-loop / merge follow-up TASK, which checks the branch out, drives+ * the reviewers, and merges; and+ * 2. a pr-watcher PENDING MERGE (`pendingMergePrs` on the app record) — the+ * model-free path a merge-on-green GitHub PR takes, merged by the next+ * watcher tick once CI is green.*- * In both cases the branch is *supposed* to still exist right now. Auditing it- * would report the thing that is about to land it as debris. The follow-up is- * itself a worktree agent, so its own completion is what gets audited; a- * pr-watcher merge is audited by nothing here, deliberately — pr-watcher owns- * that PR's outcome end to end.+ * In both cases the branch is *supposed* to still exist right now, so auditing it+ * would report the thing about to land it as debris. The follow-up is itself a+ * worktree agent, so its own completion gets audited; a pr-watcher merge is+ * audited by nothing here, deliberately — pr-watcher owns that PR end to end.** @param {string} branchName* @param {object|null} app - the managed app record (carries `pendingMergePrs`)* @returns {Promise<boolean>}*/-export async function branchHasPendingOwner(branchName, app = null) {- if (!branchName) return false;-- const { getAllTasks } = await import('./cos.js');- const tasks = await getAllTasks().catch(() => []);- const claimedByFollowUp = tasks.some(t =>+async function branchHasPendingOwner(branchName, app) {+ // `resolveTaskTargetBranch` is the canonical "which branch does this task own"+ // reader — matching `reviewLoopPRBranch` by hand here would miss a retry holding+ // the same branch through `existingBranch`.+ const tasks = await readAllTasksFlat().catch(() => []);+ const claimedByTask = tasks.some(t =>(t.status === 'pending' || t.status === 'in_progress' || t.status === 'blocked') &&- t.metadata?.reviewLoopPRBranch === branchName+ resolveTaskTargetBranch(t.metadata) === branchName);- if (claimedByFollowUp) return true;+ if (claimedByTask) return true;if (!app) return false;const { readPendingMergePrs } = await import('./prWatcher.js');@@ -94,97 +104,104 @@ export async function branchHasPendingOwner(branchName, app = null) {** Every field is tri-state: `true` / `false` / `null` for "could not determine".* A probe that throws yields `null`, never `false` — see `classifyRepoStateIssues`- * for why collapsing the two would spawn an investigation agent on every network- * hiccup.+ * for why collapsing the two would file a recovery task on every network hiccup.+ *+ * The four probe groups are independent and run concurrently, so latency is the+ * slowest one rather than their sum; only `branchMerged` (needs the local branch+ * and the default branch) is sequenced after its inputs.** @param {object} params* @param {string} params.sourceWorkspace - the parent repository* @param {string} params.branchName- * @param {string|null} [params.worktreePath]- * @param {boolean} [params.probeRemote] - run the `ls-remote` round trip- * @param {boolean} [params.probePr] - ask the forge about this branch's PR- * @returns {Promise<{worktreePresent: boolean|null, localBranchPresent: boolean|null, remoteBranchPresent: boolean|null, branchMerged: boolean|null, prExists: boolean|null, prState: string|null, prUrl: string|null, defaultBranch: string|null}>}+ * @param {string} params.worktreePath+ * @param {boolean} params.branchShouldBeGone - gates the remote + merged probes+ * @param {boolean} params.prExpected - gates the forge lookup+ * @returns {Promise<{worktreePresent: boolean|null, localBranchPresent: boolean|null, remoteBranchPresent: boolean|null, branchMerged: boolean|null, prState: string|null, prUrl: string|null, defaultBranch: string|null}>}*/-export async function probeRepoState({ sourceWorkspace, branchName, worktreePath = null, probeRemote = true, probePr = true }) {- const observed = {- worktreePresent: null,- localBranchPresent: null,- remoteBranchPresent: null,- branchMerged: null,- prExists: null,- prState: null,- prUrl: null,- defaultBranch: null,- };-- // A worktree counts as present if git still tracks it OR the directory survived- // on disk. Either alone is a leak: a registered-but-deleted tree wedges the next- // `git worktree add` for that path, and an unregistered directory is the full- // checkout `removeWorktree` believed it deleted.- const worktrees = await listWorktrees(sourceWorkspace).catch(() => null);- if (worktrees) {- observed.worktreePresent = worktrees.some(wt =>- wt.branch?.replace(/^refs\/heads\//, '') === branchName ||- (worktreePath && wt.path === worktreePath)+async function probeRepoState({ sourceWorkspace, branchName, worktreePath, branchShouldBeGone, prExpected }) {+ // A worktree counts as present if the directory survived on disk OR git still+ // tracks it. Either alone is a leak: an unregistered directory is the full+ // checkout `removeWorktree` believed it deleted, and a registered-but-deleted+ // tree wedges the next `git worktree add` for that path. The cheap disk check+ // first, so the common leaked-directory case skips the `git worktree list` spawn.+ const probeWorktree = async () => {+ if (existsSync(worktreePath)) return true;+ const worktrees = await listWorktrees(sourceWorkspace).catch(() => null);+ if (!worktrees) return null;+ return worktrees.some(wt =>+ wt.branch?.replace(/^refs\/heads\//, '') === branchName || wt.path === worktreePath);- }- if (worktreePath && existsSync(worktreePath)) observed.worktreePresent = true;+ };- observed.localBranchPresent = await execGit(+ const probeLocalBranch = () => execGit(['show-ref', '--verify', '--quiet', `refs/heads/${branchName}`],sourceWorkspace,{ ignoreExitCode: true }).then(r => r.exitCode === 0).catch(() => null);- observed.defaultBranch = await git.getDefaultBranch(sourceWorkspace).catch(() => null);+ // `listRemoteHeads` is branch-reconcile's single answer to "what is on origin+ // right now", already carrying the null-means-could-not-ask contract. It reads+ // `ls-remote` rather than the `refs/remotes/*` mirror, which nothing here fetches.+ const probeRemoteBranch = async () => {+ if (!branchShouldBeGone) return null;+ const heads = await listRemoteHeads(sourceWorkspace).catch(() => null);+ return heads ? heads.has(branchName) : null;+ };- // Only meaningful while the branch still exists locally — a deleted branch has- // no ref to compare, and `isBranchMergedInto` answers `false` for a missing ref,- // which would read as "unmerged work" for the successful case.- if (observed.localBranchPresent === true && observed.defaultBranch) {- observed.branchMerged = await git- .isBranchMergedInto(sourceWorkspace, branchName, observed.defaultBranch)- .catch(() => null);- }+ // GitHub only. `gh pr view` against a GitLab MR answers nothing useful, and a+ // wrong answer is worse than none — leave `prState` null so the PR check simply+ // does not fire on a GitLab remote. `findPullRequestForBranch` already returns+ // the state in `detail`, so no second round trip is needed to read it.+ const probePr = async () => {+ if (!prExpected || !branchShouldBeGone) return { prState: null, prUrl: null };+ const { cli, env } = await withTimeout(+ git.resolveForgeForRepo(sourceWorkspace).catch(() => null),+ FORGE_RESOLVE_TIMEOUT_MS,+ null+ ) || {};+ if (cli !== 'gh') return { prState: null, prUrl: null };+ const { findPullRequestForBranch } = await import('./github.js');+ const found = await findPullRequestForBranch(branchName, { cwd: sourceWorkspace, env: env || null })+ .catch(() => ({ status: 'unavailable' }));+ if (found.status !== 'found') return { prState: null, prUrl: null };+ return { prState: found.detail ? String(found.detail).toUpperCase() : null, prUrl: found.url || null };+ };- if (probeRemote) {- observed.remoteBranchPresent = await execGit(- ['ls-remote', '--heads', 'origin', `refs/heads/${branchName}`],- sourceWorkspace,- { ignoreExitCode: true, timeout: REMOTE_PROBE_TIMEOUT_MS }- ).then(r => (r.exitCode === 0 ? r.stdout.trim() !== '' : null)).catch(() => null);- }+ // `allowRemote: false` — a bookkeeping question must not block on `git remote+ // set-head origin --auto`, the network call the default path can trigger.+ const probeDefaultBranch = () => (branchShouldBeGone+ ? git.getDefaultBranch(sourceWorkspace, { allowRemote: false }).catch(() => null)+ : Promise.resolve(null));- if (probePr) {- const { findPullRequestForBranch, getPullRequestState } = await import('./github.js');- const { cli, env } = await git.resolveForgeForRepo(sourceWorkspace).catch(() => ({ cli: 'gh', env: null }));- // GitHub only. `gh pr view` against a GitLab MR answers nothing useful, and a- // wrong answer here is worse than no answer — leave both fields `null` so the- // PR expectations simply do not fire on a GitLab remote.- if (cli === 'gh') {- const found = await findPullRequestForBranch(branchName, { cwd: sourceWorkspace, env: env || null })- .catch(() => ({ status: 'unavailable' }));- if (found.status === 'found') {- observed.prExists = true;- observed.prUrl = found.url || null;- const state = await getPullRequestState(found.url || found.number, { cwd: sourceWorkspace, env: env || null })- .catch(() => ({ status: 'unavailable' }));- if (state.status === 'known') observed.prState = state.state;- } else if (found.status === 'none') {- observed.prExists = false;- }- }- }+ const [worktreePresent, localBranchPresent, remoteBranchPresent, defaultBranch, pr] = await Promise.all([+ probeWorktree().catch(() => null),+ probeLocalBranch(),+ probeRemoteBranch(),+ probeDefaultBranch(),+ probePr().catch(() => ({ prState: null, prUrl: null })),+ ]);++ // Only meaningful while the branch still exists locally — `isBranchMergedInto`+ // answers `false` for a missing ref, which would read as "unmerged work" for+ // the successful case.+ const branchMerged = localBranchPresent === true && defaultBranch+ ? await git.isBranchMergedInto(sourceWorkspace, branchName, defaultBranch).catch(() => null)+ : null;- return observed;+ return {+ worktreePresent,+ localBranchPresent,+ remoteBranchPresent,+ branchMerged,+ prState: pr.prState,+ prUrl: pr.prUrl,+ defaultBranch,+ };}/*** Verify one completed worktree agent left the repository as its task asked, and- * file an investigation task when it did not.- *- * Never throws: this runs at the tail of completion handling, where a throw would- * strand the very cleanup it is auditing. Failures are logged and swallowed.+ * file a recovery task when it did not.** @param {object} params* @param {string} params.agentId@@ -200,54 +217,52 @@ export async function verifyAgentRepoState({ agentId, task, agentState, success,const branchName = metadata.worktreeBranch || null;const sourceWorkspace = metadata.sourceWorkspace || null;const appId = task?.metadata?.app || null;+ const skipped = (skipReason) => ({ verified: false, skipReason, issues: [], observed: null, recoveryTaskId: null });- // Read the app record BEFORE the cheap structural gates so a disabled app is- // reported as `verification-disabled` rather than as whatever gate happens to- // fire first — the setting is the answer the operator is looking for. The record- // is also what carries pr-watcher's pending-merge queue.- const app = appId ? await (await import('./apps.js')).getAppById(appId).catch(() => null) : null;- const enabled = repoStateVerificationEnabled(app);-- // Only worth asking for a run that could actually be audited — this reads the- // whole task list plus the app's pending-merge queue.- const followUpPending = enabled && success && branchName && metadata.isWorktree === true- ? await branchHasPendingOwner(branchName, app).catch(() => false)- : false;-- const expectation = resolveRepoStateExpectation({- enabled,+ // Resolved twice on purpose. The first pass applies every FREE gate; only a run+ // that survives all of them pays for the pending-owner answer (two task-file+ // reads plus the app record) that the second pass needs. One gate ladder, in+ // one place, still decides.+ const structural = {+ enabled: true,success,isWorktree: metadata.isWorktree === true,isPersistentWorktree: metadata.isPersistentWorktree === true,discardWorktree: isTruthyMeta(task?.metadata?.discardWorktree),- followUpPending,cleanupWarningCount: cleanupWarnings?.length || 0,prCompletion: resolvePrCompletion(task?.metadata),leaveOpen: leavesPrForHuman(task),prExpected,branchName,sourceWorkspace,- });+ };+ const preflight = resolveRepoStateExpectation(structural);+ if (!preflight.verify) return skipped(preflight.skipReason);- if (!expectation.verify) {- return { verified: false, skipReason: expectation.skipReason, issues: [], observed: null, recoveryTaskId: null };- }+ const app = appId ? await (await import('./apps.js')).getAppById(appId).catch(() => null) : null;+ const enabled = repoStateVerificationEnabled(app);+ const followUpPending = enabled ? await branchHasPendingOwner(branchName, app).catch(() => false) : false;++ const expectation = resolveRepoStateExpectation({ ...structural, enabled, followUpPending });+ if (!expectation.verify) return skipped(expectation.skipReason);const worktreePath = metadata.workspacePath || join(PATHS.worktrees, agentId);const observed = await probeRepoState({sourceWorkspace,branchName,worktreePath,- probeRemote: expectation.expectRemoteBranchGone,- probePr: expectation.expectPrExists || expectation.expectPrMerged,+ branchShouldBeGone: !expectation.staysOpen,+ prExpected: expectation.prExpected,}).catch(err => {emitLog('warn', `🔎 Repo-state probe failed for ${agentId}: ${err.message}`, { agentId, branchName });return null;});- if (!observed) {- return { verified: false, skipReason: REPO_STATE_SKIPS.PROBE_FAILED, issues: [], observed: null, recoveryTaskId: null };- }+ // Not one probe answered — a firewalled host or an unreadable repo. Reporting+ // this as "verified clean" would conflate could-not-ask with nothing-wrong.+ const readNothing = !observed+ || [observed.worktreePresent, observed.localBranchPresent, observed.remoteBranchPresent].every(v => v === null);+ if (readNothing) return skipped(REPO_STATE_SKIPS.PROBE_FAILED);const issues = classifyRepoStateIssues(expectation, { ...observed, branchName });if (issues.length === 0) {@@ -257,10 +272,10 @@ export async function verifyAgentRepoState({ agentId, task, agentState, success,emitLog('warn', `🔎 Repo state diverged after ${agentId}: ${issues.map(i => i.code).join(', ')}`, { agentId, branchName, taskId: task?.id });- const recoveryTaskId = await fileRepoStateInvestigation({+ const recoveryTaskId = await fileRepoStateRecoveryTask({agentId, task, branchName, sourceWorkspace, worktreePath, issues, observed, appId,}).catch(err => {- emitLog('warn', `Failed to file repo-state investigation for ${agentId}: ${err.message}`, { agentId, branchName });+ emitLog('warn', `Failed to file repo-state recovery task for ${agentId}: ${err.message}`, { agentId, branchName });return null;});@@ -270,60 +285,59 @@ export async function verifyAgentRepoState({ agentId, task, agentState, success,}/**- * The remediation step for each issue code, as an instruction the investigation- * agent can follow without re-deriving the diagnosis. Kept beside the codes so a- * new check cannot ship without saying what to do about it.+ * The remediation step for each issue code, as an instruction the recovery agent+ * can follow without re-deriving the diagnosis.+ *+ * A map rather than a switch with a `default`, so a new code cannot ship without+ * one — `repoStateExpectations.test.js` asserts the two key sets match.+ * `PR_UNMERGED` delegates to branch-reconcile's `driveToMerge`, which carries the+ * caveats a hand-written line loses: merge from the repo ROOT (gh cannot delete a+ * branch checked out elsewhere), retry `--squash`/`--rebase` on "not allowed",+ * never `--auto`, and remove the worktree before deleting the branch.*/-function remediationFor(code, { branchName, defaultBranch, prUrl, worktreePath }) {- const base = defaultBranch || 'the default branch';- switch (code) {- case REPO_STATE_ISSUES.WORKTREE_PRESENT:- return `Remove the leftover worktree: confirm it is clean ("git -C ${worktreePath} status --porcelain"), commit or discard anything found, then "git worktree remove ${worktreePath}" and "git worktree prune".`;- case REPO_STATE_ISSUES.LOCAL_BRANCH_PRESENT:- return `Delete the local branch once its work is on ${base}: "git branch -d ${branchName}" (use -D only after confirming the commits landed).`;- case REPO_STATE_ISSUES.REMOTE_BRANCH_PRESENT:- return `Delete the remote branch after confirming its work merged: "git push origin --delete ${branchName}".`;- case REPO_STATE_ISSUES.BRANCH_UNMERGED:- return `The branch has commits that are NOT on ${base}. Decide whether they are wanted: land them (open/merge a PR, or merge locally and resolve conflicts) before deleting anything. Do NOT delete this branch until its work is on ${base}.`;- case REPO_STATE_ISSUES.PR_MISSING:- return `The task asked for a pull request but the forge has none for ${branchName}. Open one against ${base}, then drive it to merge.`;- case REPO_STATE_ISSUES.PR_UNMERGED:- return `Finish the pull request${prUrl ? ` ${prUrl}` : ''}: fix failing checks, resolve review threads, then merge it ("gh pr merge --merge --delete-branch").`;- default:- return `Investigate and resolve: ${code}.`;- }-}+export const REPO_STATE_REMEDIATIONS = Object.freeze({+ [REPO_STATE_ISSUES.WORKTREE_PRESENT]: ({ worktreePath }) =>+ `Remove the leftover worktree: confirm it is clean ("git -C ${worktreePath} status --porcelain"), commit or discard anything found, then "git worktree remove ${worktreePath}" and "git worktree prune".`,+ [REPO_STATE_ISSUES.LOCAL_BRANCH_PRESENT]: ({ branchName, base }) =>+ `Delete the local branch once its work is on ${base}: "git branch -d ${branchName}" (use -D only after confirming the commits landed). Remove its worktree first — the delete fails while a worktree still has it checked out.`,+ [REPO_STATE_ISSUES.REMOTE_BRANCH_PRESENT]: ({ branchName }) =>+ `Delete the remote branch after confirming its work merged: "git push origin --delete ${branchName}".`,+ [REPO_STATE_ISSUES.BRANCH_UNMERGED]: ({ base }) =>+ `The branch has commits that are NOT on ${base}. Decide whether they are still wanted: land them (open or merge a PR, or merge locally and resolve conflicts) before deleting anything. Do NOT delete this branch until its work is on ${base}.`,+ [REPO_STATE_ISSUES.PR_UNMERGED]: ({ prUrl }) => `Finish the pull request${prUrl ? ` ${prUrl}` : ''}. ${driveToMerge(prUrl || '<num>')}`,+});/**- * File ONE investigation task covering every issue found for this branch.+ * File ONE recovery task covering every issue found for this branch.** Dedup rides on `addTask`'s first-line + app matching: the description names the* branch, so a re-run of the same audit joins the existing task rather than* stacking a second one.*- * @returns {Promise<string|null>} the task id, or null when the task was a duplicate+ * @returns {Promise<string|null>} the task id, or null when it was a duplicate*/-async function fileRepoStateInvestigation({ agentId, task, branchName, sourceWorkspace, worktreePath, issues, observed, appId }) {+async function fileRepoStateRecoveryTask({ agentId, task, branchName, sourceWorkspace, worktreePath, issues, observed, appId }) {const appName = task?.metadata?.appName || appId || 'PortOS';- const base = observed.defaultBranch || 'main';+ const base = observed.defaultBranch || 'the default branch';+ const ctx = { branchName, base, prUrl: observed.prUrl, worktreePath };const context = [- `An agent finished successfully but the repository did not end up in the expected state.`,- ``,+ 'An agent finished successfully but the repository did not end up in the expected state.',+ '',`Repository: ${sourceWorkspace}`,`Branch: ${branchName}`,`Worktree: ${worktreePath}`,`Default branch: ${base}`,- observed.prUrl ? `Pull request: ${observed.prUrl} (${observed.prState || 'state unknown'})` : `Pull request: none found`,+ observed.prUrl ? `Pull request: ${observed.prUrl} (${observed.prState || 'state unknown'})` : 'Pull request: none found',`Original agent: ${agentId}`,`Original task: ${task?.description || 'unknown'}`,- ``,- `What diverged:`,+ '',+ 'What diverged:',...issues.map((i, n) => `${n + 1}. ${i.message}`),- ``,- `Finish the work, in this order:`,- ...issues.map((i, n) => `${n + 1}. ${remediationFor(i.code, { branchName, defaultBranch: base, prUrl: observed.prUrl, worktreePath })}`),- ``,+ '',+ 'Finish the work, in this order:',+ ...issues.map((i, n) => `${n + 1}. ${REPO_STATE_REMEDIATIONS[i.code](ctx)}`),+ '',`Rules: never delete a branch whose commits are not already on ${base} — land the work first. `+ `Other agents are running concurrently with their own worktrees and branches; touch ONLY ${branchName} and its worktree. `+ `Do not switch branches in ${sourceWorkspace} itself.`,@@ -339,20 +353,24 @@ async function fileRepoStateInvestigation({ agentId, task, branchName, sourceWor}, 'user');if (created?.duplicate) {- emitLog('info', `🔎 Repo-state investigation for ${branchName} already queued as ${created.id}`, { agentId, branchName });+ emitLog('info', `🔎 Repo-state recovery for ${branchName} already queued as ${created.id}`, { agentId, branchName });return null;}- emitLog('info', `🔧 Filed repo-state investigation task for ${branchName} (${issues.length} issue(s))`, { agentId, branchName, appName });+ emitLog('info', `🔧 Filed repo-state recovery task for ${branchName} (${issues.length} issue(s))`, { agentId, branchName, appName });return created?.id || null;}/**- * Surface the divergence to the user alongside the auto-filed task, so a- * repeatedly-diverging app is visible rather than only inferable from a growing- * recovery queue.+ * Surface the divergence alongside the auto-filed task, so a repeatedly-diverging+ * app is visible rather than only inferable from a growing recovery queue.+ *+ * Deduped on the branch (the way `orphanedPrNotifier` dedupes on the PR url) —+ * `addTask` collapses repeats on its side, and a notification card per audit+ * would otherwise stack for a branch nothing manages to fix.*/async function notifyRepoStateDivergence({ agentId, task, branchName, issues, appId }) {- const { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } = await import('./notifications.js');+ const { addNotification, exists, NOTIFICATION_TYPES, PRIORITY_LEVELS } = await import('./notifications.js');+ if (await exists(NOTIFICATION_TYPES.AGENT_WARNING, 'branchName', branchName)) return;const appName = task?.metadata?.appName || appId || 'PortOS';await addNotification({type: NOTIFICATION_TYPES.AGENT_WARNING,diff --git a/server/services/agentRepoStateVerification.test.js b/server/services/agentRepoStateVerification.test.jsindex 8a0fbe50dd..989f5eb6e1 100644--- a/server/services/agentRepoStateVerification.test.js+++ b/server/services/agentRepoStateVerification.test.js@@ -3,9 +3,15 @@** The failure this guards is the one the pure layer cannot see: cleanup returned* ZERO warnings, the completion path called the run a success, and the worktree- * plus its branch are still on disk. Every case here drives the real+ * plus its branch are still on disk. Every case drives the real* `verifyAgentRepoState` against mocked git/forge answers and asserts what it- * files — an investigation task, or deliberately nothing.+ * files — a recovery task, or deliberately nothing.+ *+ * The task-queue mocks return `getAllTasks`'s REAL `{user, cos}` shape via the+ * real `readAllTasksFlat`. An earlier revision mocked it as a bare array, which+ * hid a `tasks.some is not a function` throw that made the pending-owner escape+ * permanently false — the audit then filed a recovery task against every branch a+ * review-loop follow-up was queued to land.*/import { describe, it, expect, beforeEach, vi } from 'vitest';@@ -13,48 +19,54 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));vi.mock('./cos.js', () => ({addTask: vi.fn().mockResolvedValue({ id: 'task-recovery-1' }),- getAllTasks: vi.fn().mockResolvedValue([]),+ getAllTasks: vi.fn().mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [] } }),}));vi.mock('./prWatcher.js', () => ({ readPendingMergePrs: vi.fn().mockReturnValue([]) }));vi.mock('./worktreeManager.js', () => ({ listWorktrees: vi.fn().mockResolvedValue([]) }));+vi.mock('./branchReconcile.js', () => ({+ listRemoteHeads: vi.fn().mockResolvedValue(new Map()),+ driveToMerge: (pr) => `merge ${pr} from the repo root once CI is green`,+}));vi.mock('./git.js', () => ({getDefaultBranch: vi.fn().mockResolvedValue('main'),isBranchMergedInto: vi.fn().mockResolvedValue(true),resolveForgeForRepo: vi.fn().mockResolvedValue({ cli: 'gh', env: null }),}));vi.mock('./github.js', () => ({- findPullRequestForBranch: vi.fn().mockResolvedValue({ status: 'none', url: null, number: null }),- getPullRequestState: vi.fn().mockResolvedValue({ status: 'unavailable', state: null }),+ findPullRequestForBranch: vi.fn().mockResolvedValue({ status: 'none', url: null, detail: null }),}));vi.mock('./apps.js', () => ({ getAppById: vi.fn().mockResolvedValue({ id: 'demo-app', name: 'Demo App' }) }));vi.mock('./notifications.js', () => ({addNotification: vi.fn().mockResolvedValue({}),+ exists: vi.fn().mockResolvedValue(false),NOTIFICATION_TYPES: { AGENT_WARNING: 'agent_warning' },PRIORITY_LEVELS: { HIGH: 'high' },}));vi.mock('../lib/execGit.js', () => ({ execGit: vi.fn() }));vi.mock('fs', () => ({ existsSync: vi.fn().mockReturnValue(false) }));-import { verifyAgentRepoState } from './agentRepoStateVerification.js';+import { verifyAgentRepoState, REPO_STATE_REMEDIATIONS } from './agentRepoStateVerification.js';import { addTask, getAllTasks } from './cos.js';import { listWorktrees } from './worktreeManager.js';-import { isBranchMergedInto } from './git.js';-import { findPullRequestForBranch, getPullRequestState } from './github.js';+import { listRemoteHeads } from './branchReconcile.js';+import { isBranchMergedInto, resolveForgeForRepo } from './git.js';+import { findPullRequestForBranch } from './github.js';import { getAppById } from './apps.js';-import { addNotification } from './notifications.js';+import { addNotification, exists as notificationExists } from './notifications.js';import { readPendingMergePrs } from './prWatcher.js';import { execGit } from '../lib/execGit.js';import { existsSync } from 'fs';import { REPO_STATE_ISSUES, REPO_STATE_SKIPS } from '../lib/repoStateExpectations.js';const BRANCH = 'cos/task-x/agent-1';+const WORKTREE = '/repo/data/cos/worktrees/agent-1';const agentState = (overrides = {}) => ({metadata: {isWorktree: true,sourceWorkspace: '/repo',worktreeBranch: BRANCH,- workspacePath: '/repo/data/cos/worktrees/agent-1',+ workspacePath: WORKTREE,...overrides,},});@@ -65,56 +77,66 @@ const task = (metadata = {}) => ({metadata: { app: 'demo-app', appName: 'Demo App', openPR: true, prCompletion: 'merge-on-green', ...metadata },});-// `git show-ref --verify refs/heads/<branch>` is the ONLY execGit call the audit-// makes when the remote probe is off; exit 0 = branch present.-const localBranch = (present) => execGit.mockImplementation((args) => {- if (args[0] === 'show-ref') return Promise.resolve({ exitCode: present ? 0 : 1, stdout: '', stderr: '' });- if (args[0] === 'ls-remote') return Promise.resolve({ exitCode: 0, stdout: '', stderr: '' });- return Promise.resolve({ exitCode: 0, stdout: '', stderr: '' });+/** `git show-ref --verify refs/heads/<branch>` — exit 0 means the branch is present. */+const localBranch = (present) => execGit.mockResolvedValue({ exitCode: present ? 0 : 1, stdout: '', stderr: '' });++/** The `{user, cos}` shape `getAllTasks` really returns. Follow-ups land in `cos`. */+const queuedTasks = (tasks) => getAllTasks.mockResolvedValue({ user: { tasks: [] }, cos: { tasks } });++const run = (overrides = {}) => verifyAgentRepoState({+ agentId: 'agent-1',+ task: task(),+ agentState: agentState(),+ success: true,+ prExpected: true,+ ...overrides,});beforeEach(() => {vi.clearAllMocks();listWorktrees.mockResolvedValue([]);+ listRemoteHeads.mockResolvedValue(new Map());existsSync.mockReturnValue(false);isBranchMergedInto.mockResolvedValue(true);- getAllTasks.mockResolvedValue([]);+ queuedTasks([]);getAppById.mockResolvedValue({ id: 'demo-app', name: 'Demo App' });readPendingMergePrs.mockReturnValue([]);- findPullRequestForBranch.mockResolvedValue({ status: 'none', url: null, number: null });- getPullRequestState.mockResolvedValue({ status: 'unavailable', state: null });+ resolveForgeForRepo.mockResolvedValue({ cli: 'gh', env: null });+ findPullRequestForBranch.mockResolvedValue({ status: 'none', url: null, detail: null });+ notificationExists.mockResolvedValue(false);addTask.mockResolvedValue({ id: 'task-recovery-1' });localBranch(false);});describe('verifyAgentRepoState — clean runs', () => {it('files nothing when the worktree, branch and PR all landed', async () => {- findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/1', number: 1 });- getPullRequestState.mockResolvedValue({ status: 'known', state: 'MERGED' });+ findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/1', detail: 'MERGED' });- const result = await verifyAgentRepoState({- agentId: 'agent-1', task: task(), agentState: agentState(), success: true, prExpected: true,- });+ const result = await run();expect(result.verified).toBe(true);expect(result.issues).toEqual([]);expect(addTask).not.toHaveBeenCalled();expect(addNotification).not.toHaveBeenCalled();});++ it('reads the PR state from the list call rather than a second forge round trip', async () => {+ findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/1', detail: 'merged' });+ const result = await run();+ expect(result.observed.prState).toBe('MERGED');+ expect(findPullRequestForBranch).toHaveBeenCalledTimes(1);+ });});describe('verifyAgentRepoState — divergent runs', () => {- it('files ONE investigation task for a leftover worktree and branch after a merged PR', async () => {+ it('files ONE recovery task for a leftover worktree and branch after a merged PR', async () => {// The reported failure shape: the agent merged its own PR (branch gone on the// forge) but its local branch and worktree survived cleanup silently.- listWorktrees.mockResolvedValue([{ path: '/repo/data/cos/worktrees/agent-1', branch: `refs/heads/${BRANCH}` }]);+ existsSync.mockReturnValue(true);localBranch(true);- findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/1', number: 1 });- getPullRequestState.mockResolvedValue({ status: 'known', state: 'MERGED' });+ findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/1', detail: 'MERGED' });- const result = await verifyAgentRepoState({- agentId: 'agent-1', task: task(), agentState: agentState(), success: true, prExpected: true,- });+ const result = await run();expect(result.verified).toBe(false);expect(result.issues.map(i => i.code)).toEqual([@@ -132,144 +154,160 @@ describe('verifyAgentRepoState — divergent runs', () => {expect(payload.useWorktree).toBe(false);// Remediation must be actionable without re-diagnosing, and must forbid// deleting unmerged work or touching a sibling agent's branch.- expect(payload.context).toContain('git worktree remove');+ expect(payload.context).toContain(`git worktree remove ${WORKTREE}`);expect(payload.context).toContain(`git branch -d ${BRANCH}`);expect(payload.context).toContain(`touch ONLY ${BRANCH}`);expect(addNotification).toHaveBeenCalledTimes(1);});+ it('finds a worktree git still tracks even when the directory is gone', async () => {+ listWorktrees.mockResolvedValue([{ path: WORKTREE, branch: `refs/heads/${BRANCH}` }]);+ const result = await run({ prExpected: false });+ expect(result.issues.map(i => i.code)).toEqual([REPO_STATE_ISSUES.WORKTREE_PRESENT]);+ });+it('reports an unmerged PR the agent left open', async () => {localBranch(true);isBranchMergedInto.mockResolvedValue(false);- findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/9', number: 9 });- getPullRequestState.mockResolvedValue({ status: 'known', state: 'OPEN' });+ listRemoteHeads.mockResolvedValue(new Map([[BRANCH, 'abc123']]));+ findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/9', detail: 'OPEN' });- const result = await verifyAgentRepoState({- agentId: 'agent-1', task: task(), agentState: agentState(), success: true, prExpected: true,- });+ const result = await run();expect(result.issues.map(i => i.code)).toEqual([REPO_STATE_ISSUES.LOCAL_BRANCH_PRESENT,+ REPO_STATE_ISSUES.REMOTE_BRANCH_PRESENT,REPO_STATE_ISSUES.BRANCH_UNMERGED,REPO_STATE_ISSUES.PR_UNMERGED,]);expect(addTask.mock.calls[0][0].context).toContain('https://example.com/pr/9');});- it('reports a requested PR the forge never saw', async () => {- findPullRequestForBranch.mockResolvedValue({ status: 'none', url: null, number: null });- const result = await verifyAgentRepoState({- agentId: 'agent-1', task: task(), agentState: agentState(), success: true, prExpected: true,- });- expect(result.issues.map(i => i.code)).toEqual([REPO_STATE_ISSUES.PR_MISSING]);- });-- it('does not re-file when an investigation task for the branch already exists', async () => {- listWorktrees.mockResolvedValue([{ path: '/repo/data/cos/worktrees/agent-1', branch: `refs/heads/${BRANCH}` }]);+ it('does not re-file when a recovery task for the branch already exists', async () => {+ existsSync.mockReturnValue(true);addTask.mockResolvedValue({ id: 'task-recovery-1', duplicate: true });- const result = await verifyAgentRepoState({- agentId: 'agent-1', task: task(), agentState: agentState(), success: true, prExpected: false,- });+ const result = await run({ prExpected: false });expect(result.issues.length).toBeGreaterThan(0);expect(result.recoveryTaskId).toBeNull();});++ it('does not stack a second notification for a branch already flagged', async () => {+ existsSync.mockReturnValue(true);+ notificationExists.mockResolvedValue(true);++ await run({ prExpected: false });++ expect(notificationExists).toHaveBeenCalledWith('agent_warning', 'branchName', BRANCH);+ expect(addNotification).not.toHaveBeenCalled();+ });});describe('verifyAgentRepoState — never fires', () => {it('is off for an app with verifyRepoStateOnCompletion: false', async () => {getAppById.mockResolvedValue({ id: 'demo-app', verifyRepoStateOnCompletion: false });- listWorktrees.mockResolvedValue([{ path: '/repo/data/cos/worktrees/agent-1', branch: `refs/heads/${BRANCH}` }]);+ existsSync.mockReturnValue(true);- const result = await verifyAgentRepoState({- agentId: 'agent-1', task: task(), agentState: agentState(), success: true, prExpected: true,- });+ const result = await run();expect(result.skipReason).toBe(REPO_STATE_SKIPS.DISABLED);expect(addTask).not.toHaveBeenCalled();// The switch must short-circuit the probes too, not just the reporting.expect(listWorktrees).not.toHaveBeenCalled();+ expect(findPullRequestForBranch).not.toHaveBeenCalled();});it('leaves a FAILED run alone so its retry can resume from the preserved branch', async () => {- listWorktrees.mockResolvedValue([{ path: '/repo/data/cos/worktrees/agent-1', branch: `refs/heads/${BRANCH}` }]);- const result = await verifyAgentRepoState({- agentId: 'agent-1', task: task(), agentState: agentState(), success: false, prExpected: true,- });+ existsSync.mockReturnValue(true);+ const result = await run({ success: false });expect(result.skipReason).toBe(REPO_STATE_SKIPS.FAILED_RUN);expect(addTask).not.toHaveBeenCalled();});it('defers while a review-loop follow-up still owns the branch', async () => {- getAllTasks.mockResolvedValue([- { status: 'pending', metadata: { reviewLoopPRBranch: BRANCH } },- ]);- listWorktrees.mockResolvedValue([{ path: '/repo/data/cos/worktrees/agent-1', branch: `refs/heads/${BRANCH}` }]);+ queuedTasks([{ status: 'pending', metadata: { reviewLoopFollowUp: true, reviewLoopPRBranch: BRANCH } }]);+ existsSync.mockReturnValue(true);- const result = await verifyAgentRepoState({- agentId: 'agent-1', task: task({ prCompletion: 'review-then-merge' }), agentState: agentState(), success: true, prExpected: true,- });+ const result = await run({ task: task({ prCompletion: 'review-then-merge' }) });expect(result.skipReason).toBe(REPO_STATE_SKIPS.FOLLOW_UP_PENDING);expect(addTask).not.toHaveBeenCalled();});+ it('defers while a retry holds the branch as its resume pointer', async () => {+ queuedTasks([{ status: 'pending', metadata: { existingBranch: BRANCH } }]);+ existsSync.mockReturnValue(true);+ const result = await run();+ expect(result.skipReason).toBe(REPO_STATE_SKIPS.FOLLOW_UP_PENDING);+ });+it('defers while pr-watcher still holds the PR for a deterministic merge', async () => {- // The merge-on-green GitHub path never spawns a follow-up TASK — it queues- // the PR on the app record for the next watcher tick. Reading only the task- // queue would call every one of those branches leaked.+ // The merge-on-green GitHub path never spawns a follow-up TASK — it queues the+ // PR on the app record for the next watcher tick. Reading only the task queue+ // would call every one of those branches leaked.readPendingMergePrs.mockReturnValue([{ prBranch: BRANCH, prUrl: 'https://example.com/pr/2' }]);- listWorktrees.mockResolvedValue([{ path: '/repo/data/cos/worktrees/agent-1', branch: `refs/heads/${BRANCH}` }]);+ existsSync.mockReturnValue(true);- const result = await verifyAgentRepoState({- agentId: 'agent-1', task: task(), agentState: agentState(), success: true, prExpected: true,- });+ const result = await run();expect(result.skipReason).toBe(REPO_STATE_SKIPS.FOLLOW_UP_PENDING);expect(addTask).not.toHaveBeenCalled();});it('stands down when cleanup already raised a warning (it files its own recovery)', async () => {- const result = await verifyAgentRepoState({- agentId: 'agent-1', task: task(), agentState: agentState(), success: true, prExpected: true,+ const result = await run({cleanupWarnings: ['Auto-merge failed for branch cos/task-x/agent-1 — branch preserved for manual recovery'],});expect(result.skipReason).toBe(REPO_STATE_SKIPS.CLEANUP_WARNED);expect(addTask).not.toHaveBeenCalled();});- it('ignores a non-worktree run', async () => {- const result = await verifyAgentRepoState({- agentId: 'agent-1', task: task(), agentState: agentState({ isWorktree: false }), success: true,- });+ it('ignores a non-worktree run without reading the app record', async () => {+ const result = await run({ agentState: agentState({ isWorktree: false }) });expect(result.skipReason).toBe(REPO_STATE_SKIPS.NOT_WORKTREE);+ expect(getAppById).not.toHaveBeenCalled();+ expect(getAllTasks).not.toHaveBeenCalled();});- it('files nothing when git and the forge could not be asked', async () => {- // Everything unknown: listWorktrees rejects, show-ref throws, gh unavailable.- // A firewalled host must not manufacture an investigation agent per run.+ it('reports probe-failed, not "clean", when git could not be asked at all', async () => {+ // A firewalled host must not manufacture a recovery agent per run — and must+ // not be logged as a verified-clean repo either.listWorktrees.mockRejectedValue(new Error('not a git repository'));execGit.mockRejectedValue(new Error('git unavailable'));- findPullRequestForBranch.mockResolvedValue({ status: 'unavailable', url: null, number: null });+ listRemoteHeads.mockResolvedValue(null);+ findPullRequestForBranch.mockResolvedValue({ status: 'unavailable', url: null, detail: null });- const result = await verifyAgentRepoState({- agentId: 'agent-1', task: task(), agentState: agentState(), success: true, prExpected: true,- });+ const result = await run();- expect(result.issues).toEqual([]);+ expect(result.skipReason).toBe(REPO_STATE_SKIPS.PROBE_FAILED);+ expect(result.verified).toBe(false);expect(addTask).not.toHaveBeenCalled();});- it('does not treat a GitLab remote as a missing PR', async () => {- const { resolveForgeForRepo } = await import('./git.js');+ it('does not treat a GitLab remote as an unmerged PR', async () => {resolveForgeForRepo.mockResolvedValue({ cli: 'glab', env: null });- const result = await verifyAgentRepoState({- agentId: 'agent-1', task: task(), agentState: agentState(), success: true, prExpected: true,- });+ const result = await run();expect(findPullRequestForBranch).not.toHaveBeenCalled();expect(result.issues).toEqual([]);});});++describe('remediation coverage', () => {+ it('has a remediation for every issue code', () => {+ // The map is what makes "a new check must say what to do about it" real — the+ // switch-with-default it replaced silently accepted a new code.+ expect(Object.keys(REPO_STATE_REMEDIATIONS).sort()).toEqual(Object.values(REPO_STATE_ISSUES).sort());+ });++ it('renders each remediation from the branch, worktree and PR in hand', () => {+ const ctx = { branchName: BRANCH, base: 'main', prUrl: 'https://example.com/pr/1', worktreePath: WORKTREE };+ for (const [code, render] of Object.entries(REPO_STATE_REMEDIATIONS)) {+ const text = render(ctx);+ expect(text, code).toBeTypeOf('string');+ expect(text.length, code).toBeGreaterThan(20);+ }+ });+});diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex ca602a34cb..a25014b60a 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -78,35 +78,46 @@ export async function cleanupAgentWorktree(agentId, success, options = {}) {// Join the pass already underway. Its warnings are the run's warnings — the// duplicate caller must not re-derive them from a half-removed worktree.if (existing) return existing;- const run = runCleanupAgentWorktree(agentId, success, options)- // The audit hangs off THIS wrapper, not off `runCleanupAgentWorktree`, for two- // reasons: the inner function returns from a dozen branches (no-commits, PR- // failure, push failure, …) and would need the call repeated at each, and every- // completion path — runner, TUI `finish()`, direct-CLI, the manual stop in- // agentManagement — funnels through here. One hook, behind the same- // per-agent coalescing guard, so a duplicate completion callback audits once.- .then(warnings => auditRepoState(agentId, success, options, warnings)- .catch(err => emitLog('warn', `🔎 Repo-state audit failed for ${agentId}: ${err.message}`, { agentId }))- .then(() => warnings))- .finally(() => { inFlightCleanups.delete(agentId); });- inFlightCleanups.set(agentId, run);- return run;++ const run = runCleanupAgentWorktree(agentId, success, options);+ const settled = run.finally(() => { inFlightCleanups.delete(agentId); });+ inFlightCleanups.set(agentId, settled);++ // The audit hangs off THIS wrapper rather than off `runCleanupAgentWorktree`,+ // whose dozen return points would each need the call, and because every+ // completion path — runner, TUI `finish()`, direct-CLI, the manual stop in+ // agentManagement — funnels through here. One `.then` on `run` means a+ // duplicate completion callback that JOINS the in-flight pass audits once.+ //+ // Detached, NOT awaited: it makes two network calls and nothing downstream+ // consumes its result, while the callers awaiting cleanup still owe the run a+ // retry-hold release, a lane release and a shell-session kill. Only+ // `originalTask` is captured — closing over `options` would pin the whole TUI+ // output buffer for the duration of the probes.+ const originalTask = options?.originalTask || null;+ run.then(+ (warnings) => auditRepoState(agentId, success, originalTask, warnings)+ .catch(err => emitLog('warn', `🔎 Repo-state audit failed for ${agentId}: ${err.message}`, { agentId })),+ // A cleanup that threw has no end state to audit; `settled` still rejects.+ () => {}+ );++ return settled;}/*** Post-cleanup repo-state audit — did this run actually leave the repository the- * way its task asked? Never throws and never blocks the warnings it follows;- * `verifyAgentRepoState` itself decides whether the run is even auditable.+ * way its task asked? `verifyAgentRepoState` itself decides whether the run is+ * even auditable, and files a recovery task when it is not clean.*- * Imported lazily so the cleanup graph doesn't pull the verification module (and- * its apps/prWatcher/github reach) into every consumer's module-init.+ * Imported lazily so the cleanup graph doesn't pull the verification module's+ * branch-reconcile / apps / github reach into every consumer's module-init.*/-async function auditRepoState(agentId, success, options, warnings) {+async function auditRepoState(agentId, success, originalTask, warnings) {const { verifyAgentRepoState } = await import('./agentRepoStateVerification.js');// `getAgentRecord`, not `getAgent` — the audit reads three worktree metadata// fields and has no use for the run's whole output.txt.const { getAgentRecord } = await import('./cos.js');- const originalTask = options?.originalTask || null;const agentState = await getAgentRecord(agentId).catch(() => null);await verifyAgentRepoState({agentId,diff --git a/server/services/agentWorktreeCleanup.repoStateAudit.test.js b/server/services/agentWorktreeCleanup.repoStateAudit.test.jsindex 864f44061b..aa6079dc1e 100644--- a/server/services/agentWorktreeCleanup.repoStateAudit.test.js+++ b/server/services/agentWorktreeCleanup.repoStateAudit.test.js@@ -1,6 +1,6 @@/*** Wiring guard: every completion path that cleans a worktree must also audit the- * repo state afterwards.+ * repo state afterwards, and must not WAIT on that audit.** The audit hangs off `cleanupAgentWorktree` — the coalescing wrapper — rather* than off any single completion path, because the runner, the TUI `finish()`,@@ -42,6 +42,7 @@ vi.mock('./agentRepoStateVerification.js', () => ({import { cleanupAgentWorktree } from './agentWorktreeCleanup.js';import { verifyAgentRepoState } from './agentRepoStateVerification.js';import { getAgent, getAgentRecord } from './cos.js';+import { removeWorktree } from './worktreeManager.js';const worktreeAgent = {metadata: {@@ -52,12 +53,16 @@ const worktreeAgent = {},};+/** The audit is fired detached, so it lands a microtask after cleanup resolves. */+const auditRan = () => vi.waitFor(() => expect(verifyAgentRepoState).toHaveBeenCalled());+beforeEach(() => {vi.clearAllMocks();- // A non-worktree agent makes the cleanup itself a no-op, so this exercises the+ // A non-worktree agent makes the cleanup itself a no-op, so these exercise the// wrapper's hook rather than the teardown.getAgent.mockResolvedValue({ metadata: { isWorktree: false } });getAgentRecord.mockResolvedValue(worktreeAgent);+ removeWorktree.mockResolvedValue({ removed: true, warnings: [] });verifyAgentRepoState.mockResolvedValue({ verified: true, issues: [] });});@@ -66,6 +71,7 @@ describe('cleanupAgentWorktree → repo-state audit', () => {const originalTask = { id: 'task-1', metadata: { app: 'demo-app', openPR: true } };await cleanupAgentWorktree('agent-1', true, { originalTask });+ await auditRan();expect(verifyAgentRepoState).toHaveBeenCalledTimes(1);expect(verifyAgentRepoState).toHaveBeenCalledWith({@@ -88,26 +94,41 @@ describe('cleanupAgentWorktree → repo-state audit', () => {cleanupAgentWorktree('agent-1', true, { originalTask }),cleanupAgentWorktree('agent-1', true, { originalTask }),]);+ await auditRan();expect(a).toEqual(b);expect(verifyAgentRepoState).toHaveBeenCalledTimes(1);expect(verifyAgentRepoState.mock.calls[0][0].prExpected).toBe(false);});- it('still returns cleanup warnings when the audit itself throws', async () => {+ it('does not make callers wait on the audit', async () => {+ // The audit makes two network calls; the callers awaiting cleanup still owe+ // the run a retry-hold release, a lane release and a shell-session kill.+ let releaseAudit;+ verifyAgentRepoState.mockReturnValue(new Promise(resolve => { releaseAudit = resolve; }));++ await cleanupAgentWorktree('agent-1', true, { originalTask: { id: 'task-1', metadata: {} } });++ // Reaching here at all is the assertion — an awaited audit would deadlock the+ // test until the timeout.+ await auditRan();+ releaseAudit({ verified: true, issues: [] });+ });++ it('returns the cleanup warnings unchanged, and survives an audit that throws', async () => {// The audit is an observer. A failure in it must never swallow the warnings// the caller uses to notify the user and spawn a merge recovery task.- getAgent.mockResolvedValue({- ...worktreeAgent,- metadata: { ...worktreeAgent.metadata, isPersistentWorktree: false },- });+ getAgent.mockResolvedValue(worktreeAgent);+ removeWorktree.mockResolvedValue({ removed: false, warnings: ['Worktree preserved — uncommitted changes detected'] });verifyAgentRepoState.mockRejectedValue(new Error('probe exploded'));const warnings = await cleanupAgentWorktree('agent-1', true, {originalTask: { id: 'task-1', metadata: {} },});+ await auditRan();- expect(Array.isArray(warnings)).toBe(true);- expect(verifyAgentRepoState).toHaveBeenCalled();+ expect(warnings).toEqual(['Worktree preserved — uncommitted changes detected']);+ expect(verifyAgentRepoState.mock.calls[0][0].cleanupWarnings)+ .toEqual(['Worktree preserved — uncommitted changes detected']);});});diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.jsindex 6808c05727..c14890bdd3 100644--- a/server/services/branchReconcile.js+++ b/server/services/branchReconcile.js@@ -1098,7 +1098,10 @@ const verifyGate = 'Rebase onto the default branch before opening or updating a//// `pr` is the PR's number when the branch already has one, else the `<num>`// placeholder the agent fills in after opening it.-const driveToMerge = (pr) => [+// Exported so the per-agent repo-state audit (services/agentRepoStateVerification.js)+// hands a recovery agent the SAME merge procedure, rather than re-authoring a+// `gh pr merge` line that loses these caveats.+export const driveToMerge = (pr) => ['Opening (or approving) the PR is NOT the end state — a green PR left open is still an unfinished branch that this task will simply re-drive on its next run.',`Wait for CI in-session by re-polling \`gh pr checks ${pr} --required\` every 30s so the run stays observable while CI is pending. Budget 15 minutes for the run; past that, leave the PR open and report that CI was still pending.`,'If a required check FAILS, fix it on the branch, push, and re-poll (max 3 rounds); if it is still red after that, leave the PR open and report exactly which check failed.',