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

audit repo state after each CoS agent so silently leaked branches and worktrees get fixed

[._.]/ Adam Eivyb2517282c1b9
diff --git a/client/src/components/apps/EditAppDrawer.jsx b/client/src/components/apps/EditAppDrawer.jsx
index 2027ba7c0e..eb13e2318e 100644
--- a/client/src/components/apps/EditAppDrawer.jsx
+++ b/client/src/components/apps/EditAppDrawer.jsx
@@ -1,6 +1,6 @@
import { useState, useEffect, useCallback } from 'react';
import { Link } from 'react-router';
-import { GitBranch, GitPullRequest, Lock, Copy } from 'lucide-react';
+import { GitBranch, GitPullRequest, Lock, Copy, ShieldCheck } from 'lucide-react';
import IconPicker from '../IconPicker';
import * as api from '../../services/api';
import { PORTOS_APP_ID } from '../../services/apiCore';
@@ -63,6 +63,8 @@ export default function EditAppDrawer({ app, onClose, onSave }) {
defaultOpenPR: app.defaultOpenPR || false,
defaultPrCompletion: app.defaultPrCompletion || DEFAULT_PR_COMPLETION,
defaultUseWorktree: app.defaultUseWorktree || app.defaultOpenPR || false,
+ // Unset means ON server-side, so an app that has never been saved shows checked.
+ verifyRepoStateOnCompletion: app.verifyRepoStateOnCompletion !== false,
datadogEnabled: app.datadog?.enabled || false,
datadogInstanceId: app.datadog?.instanceId || '',
datadogServiceName: app.datadog?.serviceName || '',
@@ -254,6 +256,7 @@ export default function EditAppDrawer({ app, onClose, onSave }) {
defaultUseWorktree: formData.defaultUseWorktree || formData.defaultOpenPR,
defaultOpenPR: formData.defaultOpenPR,
defaultPrCompletion: formData.defaultPrCompletion,
+ verifyRepoStateOnCompletion: formData.verifyRepoStateOnCompletion,
datadog: formData.datadogEnabled ? {
enabled: true,
instanceId: formData.datadogInstanceId || undefined,
@@ -647,6 +650,19 @@ export default function EditAppDrawer({ app, onClose, onSave }) {
{prCompletionOption(formData.defaultPrCompletion)?.description}
</p>
</div>
+ <label className="flex items-center gap-2 cursor-pointer">
+ <input
+ 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>
+ </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.
+ </p>
</div>
)}
diff --git a/client/src/components/apps/EditAppDrawer.test.jsx b/client/src/components/apps/EditAppDrawer.test.jsx
index 3a3ae80f34..284a497d7d 100644
--- a/client/src/components/apps/EditAppDrawer.test.jsx
+++ b/client/src/components/apps/EditAppDrawer.test.jsx
@@ -165,6 +165,21 @@ describe('EditAppDrawer work tracker selector', () => {
await waitFor(() => expect(api.updateApp).toHaveBeenCalled());
expect(api.updateApp.mock.calls[0][1].defaultPrCompletion).toBe('leave-open');
});
+ it('defaults the repo-state audit ON for an app that has never set it, and saves an opt-out', async () => {
+ // Unset means ON server-side (repoStateVerificationEnabled), so an app record
+ // with no such key must render checked — otherwise the first save of an
+ // unrelated field would silently turn the audit off.
+ renderDrawer({ app: { ...APP, defaultUseWorktree: true } });
+ await openTab('Workflow');
+
+ const toggle = await screen.findByLabelText(/Verify repo state after each agent/);
+ expect(toggle).toBeChecked();
+ fireEvent.click(toggle);
+ fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }));
+
+ await waitFor(() => expect(api.updateApp).toHaveBeenCalled());
+ expect(api.updateApp.mock.calls[0][1].verifyRepoStateOnCompletion).toBe(false);
+ });
});
describe('EditAppDrawer native launch target', () => {
diff --git a/server/lib/README.md b/server/lib/README.md
index 6e0e6fb587..8a32eb6b7e 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -413,6 +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`. |
| `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/index.js b/server/lib/index.js
index d33c95b0a4..06be5ecdaa 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -390,6 +390,7 @@ export * from './mirrorParity.js';
export * from './objects.js';
export * from './openapiSpec.js';
export * from './prDisposition.js';
+export * from './repoStateExpectations.js';
export * from './shellCd.js';
export * from './shellExit.js';
export * from './shellLivenessProbe.js';
diff --git a/server/lib/repoStateExpectations.js b/server/lib/repoStateExpectations.js
new file mode 100644
index 0000000000..fa967a764c
--- /dev/null
+++ b/server/lib/repoStateExpectations.js
@@ -0,0 +1,214 @@
+/**
+ * Post-completion repo-state expectations for CoS worktree agents.
+ *
+ * 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.
+ *
+ * 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.
+ *
+ * Deliberately narrow: it judges ONE agent's branch and worktree, 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.
+ */
+export const REPO_STATE_ISSUES = Object.freeze({
+ WORKTREE_PRESENT: 'worktree-present',
+ LOCAL_BRANCH_PRESENT: 'local-branch-present',
+ 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.
+ */
+export const REPO_STATE_SKIPS = Object.freeze({
+ DISABLED: 'verification-disabled',
+ NOT_WORKTREE: 'not-a-worktree-run',
+ PERSISTENT_WORKTREE: 'persistent-worktree',
+ DISCARDED_WORKTREE: 'discarded-worktree',
+ FAILED_RUN: 'failed-run',
+ 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.
+ PROBE_FAILED: 'probe-failed',
+});
+
+/**
+ * What the repository should look like now that this agent is done.
+ *
+ * `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".
+ *
+ * The two states 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.
+ *
+ * @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 {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 {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}}
+ */
+export function resolveRepoStateExpectation({
+ enabled,
+ success,
+ isWorktree,
+ isPersistentWorktree = false,
+ discardWorktree = false,
+ followUpPending = false,
+ cleanupWarningCount = 0,
+ prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN,
+ leaveOpen = false,
+ prExpected = false,
+ branchName = null,
+ sourceWorkspace = null,
+} = {}) {
+ const skip = (skipReason) => ({
+ verify: false,
+ skipReason,
+ expectWorktreeGone: false,
+ expectLocalBranchGone: false,
+ expectRemoteBranchGone: false,
+ expectBranchMerged: false,
+ expectPrMerged: false,
+ expectPrExists: false,
+ });
+
+ if (enabled === false) return skip(REPO_STATE_SKIPS.DISABLED);
+ if (!isWorktree) return skip(REPO_STATE_SKIPS.NOT_WORKTREE);
+ if (isPersistentWorktree) return skip(REPO_STATE_SKIPS.PERSISTENT_WORKTREE);
+ 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;
+
+ 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,
+ };
+}
+
+/**
+ * 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.
+ *
+ * @param {ReturnType<typeof resolveRepoStateExpectation>} expectation
+ * @param {object} observed
+ * @param {boolean|null} [observed.worktreePresent]
+ * @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.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 issues = [];
+
+ if (expectation.expectWorktreeGone && 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) {
+ 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) {
+ issues.push({
+ code: REPO_STATE_ISSUES.REMOTE_BRANCH_PRESENT,
+ message: `Remote branch origin/${branch} was never deleted`,
+ });
+ }
+ if (expectation.expectBranchMerged && 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') {
+ issues.push({
+ code: REPO_STATE_ISSUES.PR_UNMERGED,
+ message: `Pull request for ${branch} is ${observed.prState}, not MERGED`,
+ });
+ }
+
+ return issues;
+}
+
+/**
+ * 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.
+ *
+ * @param {object|null} app - managed app record (null for a PortOS-local task)
+ * @returns {boolean}
+ */
+export function repoStateVerificationEnabled(app) {
+ return app?.verifyRepoStateOnCompletion !== false;
+}
diff --git a/server/lib/repoStateExpectations.test.js b/server/lib/repoStateExpectations.test.js
new file mode 100644
index 0000000000..97cbaa2e61
--- /dev/null
+++ b/server/lib/repoStateExpectations.test.js
@@ -0,0 +1,180 @@
+import { describe, it, expect } from 'vitest';
+import {
+ REPO_STATE_ISSUES,
+ REPO_STATE_SKIPS,
+ classifyRepoStateIssues,
+ repoStateVerificationEnabled,
+ resolveRepoStateExpectation,
+} from './repoStateExpectations.js';
+import { PR_COMPLETIONS } from './prDisposition.js';
+
+// The shape a run that SHOULD be audited has: a successful worktree agent whose
+// cleanup reported nothing and whose branch nothing else owns.
+const auditable = {
+ enabled: true,
+ success: true,
+ isWorktree: true,
+ branchName: 'cos/task-abc/agent-1',
+ sourceWorkspace: '/repo',
+};
+
+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);
+ });
+
+ 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) => {
+ 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);
+ });
+
+ it.each([
+ [REPO_STATE_SKIPS.DISABLED, { enabled: false }],
+ [REPO_STATE_SKIPS.NOT_WORKTREE, { isWorktree: false }],
+ [REPO_STATE_SKIPS.PERSISTENT_WORKTREE, { isPersistentWorktree: true }],
+ [REPO_STATE_SKIPS.DISCARDED_WORKTREE, { discardWorktree: true }],
+ [REPO_STATE_SKIPS.FAILED_RUN, { success: false }],
+ [REPO_STATE_SKIPS.CLEANUP_WARNED, { cleanupWarningCount: 1 }],
+ [REPO_STATE_SKIPS.FOLLOW_UP_PENDING, { followUpPending: true }],
+ [REPO_STATE_SKIPS.MISSING_CONTEXT, { branchName: null }],
+ [REPO_STATE_SKIPS.MISSING_CONTEXT, { sourceWorkspace: null }],
+ ])('skips with reason %s', (reason, override) => {
+ 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', () => {
+ // A disabled app on a run that would ALSO skip for another reason must still
+ // report `verification-disabled` — that is the answer an operator is looking
+ // for when they turned it off and want to confirm it took effect.
+ const e = resolveRepoStateExpectation({ ...auditable, enabled: false, success: false, isWorktree: false });
+ expect(e.skipReason).toBe(REPO_STATE_SKIPS.DISABLED);
+ });
+});
+
+describe('classifyRepoStateIssues', () => {
+ const expectation = resolveRepoStateExpectation({ ...auditable, prExpected: true });
+
+ it('reports nothing when the repo is clean', () => {
+ const issues = classifyRepoStateIssues(expectation, {
+ worktreePresent: false,
+ localBranchPresent: false,
+ remoteBranchPresent: false,
+ branchMerged: null,
+ prExists: true,
+ prState: 'MERGED',
+ });
+ expect(issues).toEqual([]);
+ });
+
+ it('reports the leftover worktree, branch, remote branch and open PR', () => {
+ const issues = classifyRepoStateIssues(expectation, {
+ worktreePresent: true,
+ localBranchPresent: true,
+ remoteBranchPresent: true,
+ branchMerged: false,
+ prExists: true,
+ prState: 'OPEN',
+ branchName: 'cos/task-abc/agent-1',
+ });
+ expect(issues.map(i => i.code)).toEqual([
+ REPO_STATE_ISSUES.WORKTREE_PRESENT,
+ REPO_STATE_ISSUES.LOCAL_BRANCH_PRESENT,
+ REPO_STATE_ISSUES.REMOTE_BRANCH_PRESENT,
+ REPO_STATE_ISSUES.BRANCH_UNMERGED,
+ REPO_STATE_ISSUES.PR_UNMERGED,
+ ]);
+ 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.
+ const issues = classifyRepoStateIssues(expectation, {
+ worktreePresent: null,
+ localBranchPresent: null,
+ remoteBranchPresent: null,
+ branchMerged: null,
+ prExists: null,
+ prState: null,
+ });
+ expect(issues).toEqual([]);
+ });
+
+ it('reports nothing for an expectation that was skipped', () => {
+ const skipped = resolveRepoStateExpectation({ ...auditable, success: false });
+ const issues = classifyRepoStateIssues(skipped, {
+ worktreePresent: true,
+ 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', () => {
+ 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([]);
+ });
+});
+
+describe('repoStateVerificationEnabled', () => {
+ it('defaults to on for an unset app and for a PortOS-local task', () => {
+ expect(repoStateVerificationEnabled(null)).toBe(true);
+ expect(repoStateVerificationEnabled({})).toBe(true);
+ expect(repoStateVerificationEnabled({ verifyRepoStateOnCompletion: true })).toBe(true);
+ });
+
+ it('is off only for an explicit false', () => {
+ expect(repoStateVerificationEnabled({ verifyRepoStateOnCompletion: false })).toBe(false);
+ });
+});
diff --git a/server/lib/validation.js b/server/lib/validation.js
index ccd151c2e7..83a7d70d10 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -286,6 +286,11 @@ export const appSchema = z.object({
defaultUseWorktree: z.boolean().optional(),
defaultOpenPR: z.boolean().optional(),
defaultPrCompletion: z.enum(PR_COMPLETION_VALUES).optional(),
+ // After a CoS agent completes against this app, audit the repo for the state the
+ // task asked for (worktree removed, branch deleted, PR merged) and file a recovery
+ // task when it diverges. See lib/repoStateExpectations.js. Unset = ON: an install
+ // that never hears about a leaked branch just accumulates them.
+ verifyRepoStateOnCompletion: z.boolean().optional(),
jira: jiraConfigSchema.optional().nullable(),
datadog: datadogConfigSchema.optional().nullable(),
// Where this app's autonomous work items live (single source per app).
diff --git a/server/services/agentRepoStateVerification.js b/server/services/agentRepoStateVerification.js
new file mode 100644
index 0000000000..95b9a03ed0
--- /dev/null
+++ b/server/services/agentRepoStateVerification.js
@@ -0,0 +1,365 @@
+/**
+ * Agent Repo-State Verification
+ *
+ * The programmatic audit that runs AFTER `cleanupAgentWorktree` and asks a
+ * 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.
+ *
+ * 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.
+ *
+ * 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.
+ */
+
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { emitLog } from './cosEvents.js';
+import { addTask } from './cos.js';
+import * as git from './git.js';
+import { listWorktrees } from './worktreeManager.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 { leavesPrForHuman, resolvePrCompletion } from '../lib/prDisposition.js';
+import {
+ REPO_STATE_ISSUES,
+ REPO_STATE_SKIPS,
+ classifyRepoStateIssues,
+ repoStateVerificationEnabled,
+ 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;
+
+/**
+ * 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.
+ *
+ * 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.
+ *
+ * @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 =>
+ (t.status === 'pending' || t.status === 'in_progress' || t.status === 'blocked') &&
+ t.metadata?.reviewLoopPRBranch === branchName
+ );
+ if (claimedByFollowUp) return true;
+
+ if (!app) return false;
+ const { readPendingMergePrs } = await import('./prWatcher.js');
+ const pending = readPendingMergePrs(app);
+ return Array.isArray(pending) && pending.some(entry => entry?.prBranch === branchName);
+}
+
+/**
+ * Probe the repository for the facts the expectation is judged against.
+ *
+ * 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.
+ *
+ * @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}>}
+ */
+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)
+ );
+ }
+ if (worktreePath && existsSync(worktreePath)) observed.worktreePresent = true;
+
+ observed.localBranchPresent = await 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);
+
+ // 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);
+ }
+
+ 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);
+ }
+
+ 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;
+ }
+ }
+ }
+
+ return observed;
+}
+
+/**
+ * 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.
+ *
+ * @param {object} params
+ * @param {string} params.agentId
+ * @param {object} params.task - the CoS task
+ * @param {object|null} params.agentState - persisted agent record (worktree metadata)
+ * @param {boolean} params.success - effective success of the run
+ * @param {boolean} [params.prExpected] - the task asked for a PR (`openPR`)
+ * @param {string[]} [params.cleanupWarnings] - warnings cleanup already raised
+ * @returns {Promise<{verified: boolean, skipReason: string|null, issues: Array<{code: string, message: string}>, observed: object|null, recoveryTaskId: string|null}>}
+ */
+export async function verifyAgentRepoState({ agentId, task, agentState, success, prExpected = false, cleanupWarnings = [] }) {
+ const metadata = agentState?.metadata || {};
+ const branchName = metadata.worktreeBranch || null;
+ const sourceWorkspace = metadata.sourceWorkspace || null;
+ const appId = task?.metadata?.app || 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,
+ 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,
+ });
+
+ if (!expectation.verify) {
+ return { verified: false, skipReason: expectation.skipReason, issues: [], observed: null, recoveryTaskId: null };
+ }
+
+ const worktreePath = metadata.workspacePath || join(PATHS.worktrees, agentId);
+ const observed = await probeRepoState({
+ sourceWorkspace,
+ branchName,
+ worktreePath,
+ probeRemote: expectation.expectRemoteBranchGone,
+ probePr: expectation.expectPrExists || expectation.expectPrMerged,
+ }).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 };
+ }
+
+ const issues = classifyRepoStateIssues(expectation, { ...observed, branchName });
+ if (issues.length === 0) {
+ emitLog('info', `🔎 Repo state verified clean for ${agentId} (${branchName})`, { agentId, branchName });
+ return { verified: true, skipReason: null, issues: [], observed, recoveryTaskId: null };
+ }
+
+ emitLog('warn', `🔎 Repo state diverged after ${agentId}: ${issues.map(i => i.code).join(', ')}`, { agentId, branchName, taskId: task?.id });
+
+ const recoveryTaskId = await fileRepoStateInvestigation({
+ agentId, task, branchName, sourceWorkspace, worktreePath, issues, observed, appId,
+ }).catch(err => {
+ emitLog('warn', `Failed to file repo-state investigation for ${agentId}: ${err.message}`, { agentId, branchName });
+ return null;
+ });
+
+ await notifyRepoStateDivergence({ agentId, task, branchName, issues, appId }).catch(() => {});
+
+ return { verified: false, skipReason: null, issues, observed, recoveryTaskId };
+}
+
+/**
+ * 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.
+ */
+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}.`;
+ }
+}
+
+/**
+ * File ONE investigation 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
+ */
+async function fileRepoStateInvestigation({ agentId, task, branchName, sourceWorkspace, worktreePath, issues, observed, appId }) {
+ const appName = task?.metadata?.appName || appId || 'PortOS';
+ const base = observed.defaultBranch || 'main';
+
+ const context = [
+ `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`,
+ `Original agent: ${agentId}`,
+ `Original task: ${task?.description || 'unknown'}`,
+ ``,
+ `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 })}`),
+ ``,
+ `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.`,
+ ].join('\n');
+
+ const created = await addTask({
+ description: `${RECOVERY_TASK_PREFIX} Finish incomplete cleanup for branch ${branchName} in ${appName}`,
+ priority: 'HIGH',
+ app: appId || undefined,
+ isRecovery: true,
+ context,
+ useWorktree: false,
+ }, 'user');
+
+ if (created?.duplicate) {
+ emitLog('info', `🔎 Repo-state investigation 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 });
+ 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.
+ */
+async function notifyRepoStateDivergence({ agentId, task, branchName, issues, appId }) {
+ const { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } = await import('./notifications.js');
+ const appName = task?.metadata?.appName || appId || 'PortOS';
+ await addNotification({
+ type: NOTIFICATION_TYPES.AGENT_WARNING,
+ title: `Repo state not clean after agent: ${appName}`,
+ description: `Branch ${branchName}\n${issues.map(i => `• ${i.message}`).join('\n')}`,
+ priority: PRIORITY_LEVELS.HIGH,
+ link: '/cos/agents',
+ metadata: { agentId, taskId: task?.id, branchName, issues: issues.map(i => i.code) },
+ });
+}
diff --git a/server/services/agentRepoStateVerification.test.js b/server/services/agentRepoStateVerification.test.js
new file mode 100644
index 0000000000..8a0fbe50dd
--- /dev/null
+++ b/server/services/agentRepoStateVerification.test.js
@@ -0,0 +1,275 @@
+/**
+ * Tests for the post-completion repo-state audit.
+ *
+ * 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
+ * `verifyAgentRepoState` against mocked git/forge answers and asserts what it
+ * files — an investigation task, or deliberately nothing.
+ */
+
+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([]),
+}));
+vi.mock('./prWatcher.js', () => ({ readPendingMergePrs: vi.fn().mockReturnValue([]) }));
+vi.mock('./worktreeManager.js', () => ({ listWorktrees: vi.fn().mockResolvedValue([]) }));
+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 }),
+}));
+vi.mock('./apps.js', () => ({ getAppById: vi.fn().mockResolvedValue({ id: 'demo-app', name: 'Demo App' }) }));
+vi.mock('./notifications.js', () => ({
+ addNotification: vi.fn().mockResolvedValue({}),
+ 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 { addTask, getAllTasks } from './cos.js';
+import { listWorktrees } from './worktreeManager.js';
+import { isBranchMergedInto } from './git.js';
+import { findPullRequestForBranch, getPullRequestState } from './github.js';
+import { getAppById } from './apps.js';
+import { addNotification } 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 agentState = (overrides = {}) => ({
+ metadata: {
+ isWorktree: true,
+ sourceWorkspace: '/repo',
+ worktreeBranch: BRANCH,
+ workspacePath: '/repo/data/cos/worktrees/agent-1',
+ ...overrides,
+ },
+});
+
+const task = (metadata = {}) => ({
+ id: 'task-1',
+ description: 'Do the thing',
+ 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: '' });
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ listWorktrees.mockResolvedValue([]);
+ existsSync.mockReturnValue(false);
+ isBranchMergedInto.mockResolvedValue(true);
+ getAllTasks.mockResolvedValue([]);
+ getAppById.mockResolvedValue({ id: 'demo-app', name: 'Demo App' });
+ readPendingMergePrs.mockReturnValue([]);
+ findPullRequestForBranch.mockResolvedValue({ status: 'none', url: null, number: null });
+ getPullRequestState.mockResolvedValue({ status: 'unavailable', state: null });
+ 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' });
+
+ const result = await verifyAgentRepoState({
+ agentId: 'agent-1', task: task(), agentState: agentState(), success: true, prExpected: true,
+ });
+
+ expect(result.verified).toBe(true);
+ expect(result.issues).toEqual([]);
+ expect(addTask).not.toHaveBeenCalled();
+ expect(addNotification).not.toHaveBeenCalled();
+ });
+});
+
+describe('verifyAgentRepoState — divergent runs', () => {
+ it('files ONE investigation 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}` }]);
+ localBranch(true);
+ findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/1', number: 1 });
+ getPullRequestState.mockResolvedValue({ status: 'known', state: 'MERGED' });
+
+ const result = await verifyAgentRepoState({
+ agentId: 'agent-1', task: task(), agentState: agentState(), success: true, prExpected: true,
+ });
+
+ expect(result.verified).toBe(false);
+ expect(result.issues.map(i => i.code)).toEqual([
+ REPO_STATE_ISSUES.WORKTREE_PRESENT,
+ REPO_STATE_ISSUES.LOCAL_BRANCH_PRESENT,
+ ]);
+ expect(addTask).toHaveBeenCalledTimes(1);
+ const [payload, kind] = addTask.mock.calls[0];
+ expect(kind).toBe('user');
+ expect(payload.description).toContain(BRANCH);
+ expect(payload.isRecovery).toBe(true);
+ expect(payload.app).toBe('demo-app');
+ // The recovery agent must not run in a worktree of its own — it is cleaning
+ // worktrees up.
+ 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 branch -d ${BRANCH}`);
+ expect(payload.context).toContain(`touch ONLY ${BRANCH}`);
+ expect(addNotification).toHaveBeenCalledTimes(1);
+ });
+
+ 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' });
+
+ 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.LOCAL_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}` }]);
+ addTask.mockResolvedValue({ id: 'task-recovery-1', duplicate: true });
+
+ const result = await verifyAgentRepoState({
+ agentId: 'agent-1', task: task(), agentState: agentState(), success: true, prExpected: false,
+ });
+
+ expect(result.issues.length).toBeGreaterThan(0);
+ expect(result.recoveryTaskId).toBeNull();
+ });
+});
+
+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}` }]);
+
+ const result = await verifyAgentRepoState({
+ agentId: 'agent-1', task: task(), agentState: agentState(), success: true, prExpected: true,
+ });
+
+ 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();
+ });
+
+ 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,
+ });
+ 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}` }]);
+
+ const result = await verifyAgentRepoState({
+ agentId: 'agent-1', task: task({ prCompletion: 'review-then-merge' }), agentState: agentState(), success: true, prExpected: true,
+ });
+
+ expect(result.skipReason).toBe(REPO_STATE_SKIPS.FOLLOW_UP_PENDING);
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
+ 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.
+ readPendingMergePrs.mockReturnValue([{ prBranch: BRANCH, prUrl: 'https://example.com/pr/2' }]);
+ 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: true, prExpected: true,
+ });
+
+ 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,
+ 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,
+ });
+ expect(result.skipReason).toBe(REPO_STATE_SKIPS.NOT_WORKTREE);
+ });
+
+ 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.
+ listWorktrees.mockRejectedValue(new Error('not a git repository'));
+ execGit.mockRejectedValue(new Error('git unavailable'));
+ findPullRequestForBranch.mockResolvedValue({ status: 'unavailable', url: null, number: null });
+
+ const result = await verifyAgentRepoState({
+ agentId: 'agent-1', task: task(), agentState: agentState(), success: true, prExpected: true,
+ });
+
+ expect(result.issues).toEqual([]);
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
+ it('does not treat a GitLab remote as a missing PR', async () => {
+ const { resolveForgeForRepo } = await import('./git.js');
+ resolveForgeForRepo.mockResolvedValue({ cli: 'glab', env: null });
+
+ const result = await verifyAgentRepoState({
+ agentId: 'agent-1', task: task(), agentState: agentState(), success: true, prExpected: true,
+ });
+
+ expect(findPullRequestForBranch).not.toHaveBeenCalled();
+ expect(result.issues).toEqual([]);
+ });
+});
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index edde6de036..ca602a34cb 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -79,11 +79,45 @@ export async function cleanupAgentWorktree(agentId, success, options = {}) {
// 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;
}
+/**
+ * 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.
+ *
+ * Imported lazily so the cleanup graph doesn't pull the verification module (and
+ * its apps/prWatcher/github reach) into every consumer's module-init.
+ */
+async function auditRepoState(agentId, success, options, 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,
+ task: originalTask,
+ agentState,
+ success,
+ prExpected: isTruthyMeta(originalTask?.metadata?.openPR),
+ cleanupWarnings: warnings || [],
+ });
+}
+
async function runCleanupAgentWorktree(agentId, success, { prCreation = PR_CREATION.NEVER, prCompletion = null, requestCopilotReview: legacyRequestCopilotReview = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, reviewerModels = null, reviewerEfforts = null, skipMerge = false, description = null, agentOutput = null, originalTask = null } = {}) {
const { getAgent: getAgentState } = await import('./cos.js');
const agentState = await getAgentState(agentId).catch(() => null);
diff --git a/server/services/agentWorktreeCleanup.repoStateAudit.test.js b/server/services/agentWorktreeCleanup.repoStateAudit.test.js
new file mode 100644
index 0000000000..864f44061b
--- /dev/null
+++ b/server/services/agentWorktreeCleanup.repoStateAudit.test.js
@@ -0,0 +1,113 @@
+/**
+ * Wiring guard: every completion path that cleans a worktree must also audit the
+ * repo state afterwards.
+ *
+ * The audit hangs off `cleanupAgentWorktree` — the coalescing wrapper — rather
+ * than off any single completion path, because the runner, the TUI `finish()`,
+ * the direct-CLI spawn and the manual stop each call cleanup themselves. Moving
+ * the hook back onto one caller would silently skip the others, which is exactly
+ * the shape of the bug it exists to catch, so it is pinned here.
+ */
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));
+vi.mock('./cos.js', () => ({
+ addTask: vi.fn().mockResolvedValue({}),
+ updateTask: vi.fn().mockResolvedValue({}),
+ getAgent: vi.fn().mockResolvedValue(null),
+ getAgentRecord: vi.fn().mockResolvedValue(null),
+ getTaskById: vi.fn().mockResolvedValue(null),
+}));
+vi.mock('./git.js', () => ({
+ getDefaultBranch: vi.fn().mockResolvedValue('main'),
+ resolveForgeForRepo: vi.fn().mockResolvedValue({ cli: 'gh', env: null }),
+ parsePullRequestUrl: vi.fn().mockReturnValue(null),
+ deleteBranch: vi.fn(),
+ push: vi.fn(),
+ createPR: vi.fn(),
+ generatePRDescription: vi.fn(),
+ suggestPRTitle: vi.fn(),
+ requestCopilotReview: vi.fn(),
+ isBranchMergedInto: vi.fn().mockResolvedValue(true),
+}));
+vi.mock('./worktreeManager.js', () => ({
+ removeWorktree: vi.fn().mockResolvedValue({ removed: true, warnings: [] }),
+ classifyWorktreeDirt: vi.fn().mockReturnValue({ clean: true }),
+}));
+vi.mock('./agentRepoStateVerification.js', () => ({
+ verifyAgentRepoState: vi.fn().mockResolvedValue({ verified: true, issues: [] }),
+}));
+
+import { cleanupAgentWorktree } from './agentWorktreeCleanup.js';
+import { verifyAgentRepoState } from './agentRepoStateVerification.js';
+import { getAgent, getAgentRecord } from './cos.js';
+
+const worktreeAgent = {
+ metadata: {
+ isWorktree: true,
+ sourceWorkspace: '/repo',
+ worktreeBranch: 'cos/task-x/agent-1',
+ workspacePath: '/repo/data/cos/worktrees/agent-1',
+ },
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ // A non-worktree agent makes the cleanup itself a no-op, so this exercises the
+ // wrapper's hook rather than the teardown.
+ getAgent.mockResolvedValue({ metadata: { isWorktree: false } });
+ getAgentRecord.mockResolvedValue(worktreeAgent);
+ verifyAgentRepoState.mockResolvedValue({ verified: true, issues: [] });
+});
+
+describe('cleanupAgentWorktree → repo-state audit', () => {
+ it('audits after cleanup, carrying the task, the run verdict and the PR expectation', async () => {
+ const originalTask = { id: 'task-1', metadata: { app: 'demo-app', openPR: true } };
+
+ await cleanupAgentWorktree('agent-1', true, { originalTask });
+
+ expect(verifyAgentRepoState).toHaveBeenCalledTimes(1);
+ expect(verifyAgentRepoState).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ task: originalTask,
+ agentState: worktreeAgent,
+ success: true,
+ prExpected: true,
+ cleanupWarnings: [],
+ });
+ });
+
+ it('audits once when two completion paths race the same agent', async () => {
+ // The runner path and the spawner's `finally` safety net both call cleanup for
+ // one completing agent. They coalesce onto a single run — and must therefore
+ // produce a single audit, not two probes and two recovery tasks.
+ const originalTask = { id: 'task-1', metadata: { openPR: false } };
+
+ const [a, b] = await Promise.all([
+ cleanupAgentWorktree('agent-1', true, { originalTask }),
+ cleanupAgentWorktree('agent-1', true, { originalTask }),
+ ]);
+
+ 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 () => {
+ // 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 },
+ });
+ verifyAgentRepoState.mockRejectedValue(new Error('probe exploded'));
+
+ const warnings = await cleanupAgentWorktree('agent-1', true, {
+ originalTask: { id: 'task-1', metadata: {} },
+ });
+
+ expect(Array.isArray(warnings)).toBe(true);
+ expect(verifyAgentRepoState).toHaveBeenCalled();
+ });
+});