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

refactor: share cleanup verdict and cover disposition policy (#7056)

[._.]/ Adam Eivya3f6e8af3b94
diff --git a/server/lib/README.md b/server/lib/README.md
index 29d03bad89..2002bd7259 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -568,7 +568,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `apiToolResource.js` | Builds the minimized semantic tool resource served at `/api/api-docs/tools.min.json` — only `x-portos-tool`-annotated operations, flattened to provider-neutral tool records with an HTTP binding and a shared error vocabulary. |
| `asyncApiSpec.js` | Builds the AsyncAPI 3 Socket.IO document from the generated event catalog with direction-aware operations and explicit modeled/generated payload status. |
| `mergeGateContract.js` | `mergeGateOwed({taskOpenPR, rendersInlinePrLifecycle, leaveOpen})` decides whether a completing run actually owed its own PR merge — only the INLINE (`git`/`gh`) prompt renders a Merge Gate section, so a `/do:pr` run is inert here; `resolveMergeGateVerdict({prProbe, summary, alreadyReprompted})` classifies a run that did (`merged` / `unreadable` / `leave-open-stated` / `needs-reprompt` / `reprompt-exhausted`) from the PR's live state and the agent's own sentinel text; `summaryStatesLeaveOpen` and `buildMergeGateReprompt` are its text-matching and corrective-prompt helpers. Pure — the PR lookup lives in `../services/prProbe.js`, the re-prompt delivery in `agentTuiSpawning.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, agentOpensOwnPr, 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`. |
+| `prDisposition.js` | `PR_MISSING_CATEGORY` shares the missing-PR verdict between finalization and cleanup. `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, agentOpensOwnPr, 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`. |
| `prHandbackPolicy.js` | Whose turn it is on a public PR the pr-reviewer coordinator reviewed but did not merge. `resolvePullRequestWriteAccess(pr)` reads `isCrossRepository`/`maintainerCanModify` into a `PR_WRITE_ACCESS` reason, failing closed on an unknown head-repository relationship; `resolveHandbackDisposition({requestedChanges, notMergeReady, downgraded, deferred, canEdit, remediationExhausted})` returns a `PR_HANDBACK` verdict — `remediate` (PortOS pushes the fixes and lands it), `assign-opener` (the PR goes to its author queue), or `none`. A deferred or unanchorable review never becomes an agent work order. Pure. |
| `prReviewReport.js` | Owns the structured PR-decision contract end to end: `PR_REVIEW_DECISION_CONTRACT` is the envelope both review producers (pr-reviewer stage 3, issue-watcher reasoning pass) interpolate into their prompts, `normalizeReviewReport` bounds what comes back, `reviewReportText` hands every model-authored string to the abuse scan, and `renderReviewBody`/`renderFinding` turn it into the markdown a human reads on the PR page — verdict banner, scope line, blocking/non-blocking index anchored to `path:line`, test-evidence bullets (`TEST_EVIDENCE_STATUSES` keeps `fail` for "the change is broken", with `expected-fail` and `blocked` for the non-zero exits that say nothing about it), notes, collapsed verified-claims list, and inline comments with an optional GitHub suggestion block. Bounded by `MAX_REVIEW_BODY_CHARS`, dropping whole low-priority sections instead of truncating mid-sentence. Pure. |
| `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`. |
diff --git a/server/lib/prDisposition.js b/server/lib/prDisposition.js
index abca442df7..5d6c055b89 100644
--- a/server/lib/prDisposition.js
+++ b/server/lib/prDisposition.js
@@ -69,6 +69,9 @@ export function leavesPrForHuman(task) {
return PR_STAYS_OPEN_SET.has(metadata.analysisType) || !!metadata.jiraTicketId;
}
+// Shared by the PR-claim producer and cleanup classifier.
+export const PR_MISSING_CATEGORY = 'pr-missing';
+
/**
* Who opens the change request for a completing worktree agent (#3733).
*
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index a295aee0ec..cd8a90cc76 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -1,3 +1,4 @@
+import { PR_MISSING_CATEGORY } from '../lib/prDisposition.js';
import { isAuditTaskType } from '../lib/auditCatalog.js';
import { isPrivateSecurityTask } from '../lib/privateSecurityPolicy.js';
/**
@@ -256,7 +257,7 @@ const HOOK_ABORTED_BEFORE_EVALUATION = new Set(['no-app', 'app-not-found']);
* `taskLearning/store.js#ENVIRONMENTAL_ERROR_CATEGORIES` so a firewalled `gh`
* can't drag a task type's measured success rate down (or auto-park it).
*/
-export const PR_MISSING_CATEGORY = 'pr-missing';
+export { PR_MISSING_CATEGORY };
export const FORGE_UNREACHABLE_CATEGORY = 'forge-unreachable';
export const ISSUE_TRAILER_MISSING_CATEGORY = 'issue-trailer-missing';
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index 9089d8c796..a405c88e18 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -25,7 +25,7 @@ import { resolveTaskTargetBranch, shouldStripTaskTargetBranch } from '../lib/tas
import { RECOVERY_TASK_PREFIX } from './recoveryTasks.js';
import { detectForgeCli } from '../lib/gitForge.js';
import { normalizeForkHead } from '../lib/forkHead.js';
-import { PR_COMPLETIONS, PR_COMPLETION_VALUES, PR_CREATION, leavesPrForHuman, prClaimWasVerified } from '../lib/prDisposition.js';
+import { PR_COMPLETIONS, PR_COMPLETION_VALUES, PR_CREATION, PR_MISSING_CATEGORY, leavesPrForHuman, prClaimWasVerified } from '../lib/prDisposition.js';
import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, MODEL_SELECTABLE_REVIEWERS, EFFORT_SELECTABLE_REVIEWERS, normalizeReviewers, normalizeReviewUsernames, normalizeOptionalReviewers, normalizeReviewerMaxRounds, prioritizeToolFreeReviewers } from '../lib/reviewerConfig.js';
// In-flight cleanup per agentId, so two completion paths racing to clean the
@@ -150,7 +150,7 @@ export function resolveWorktreeDisposition({ isWorktree, success, prCreation, di
else if (discardWorktree) name = 'discard';
else if (prCreation === PR_CREATION.IF_MISSING) {
if (success) {
- if (prClaimVerdict?.category === 'pr-missing') name = 'open-pr';
+ if (prClaimVerdict?.category === PR_MISSING_CATEGORY) name = 'open-pr';
else name = prClaimWasVerified(prClaimVerdict) ? 'stand-down' : 'stand-down-uncertain';
} else if (prClaimVerdict?.status === 'found' && prClaimVerdict.url) {
name = 'stranded-pr-handoff';
@@ -169,12 +169,12 @@ async function worktreeCleanupContext(agentId, options) {
const { getAgent } = await import('./cos.js');
const agentState = await getAgent(agentId).catch(() => null);
const metadata = agentState?.metadata;
- if (!metadata?.isWorktree || metadata.isPersistentWorktree) return null;
+ if (!metadata?.isWorktree || metadata.isPersistentWorktree) return { isWorktree: false };
const { sourceWorkspace, worktreeBranch } = metadata;
- if (!sourceWorkspace || !worktreeBranch) return null;
+ if (!sourceWorkspace || !worktreeBranch) return { isWorktree: false };
const normalized = cleanupOptions(options);
return {
- ...normalized, agentId, sourceWorkspace, worktreeBranch,
+ ...normalized, isWorktree: true, agentId, sourceWorkspace, worktreeBranch,
discardWorktree: isTruthyMeta(normalized.originalTask?.metadata?.discardWorktree),
worktreePath: metadata.workspacePath || join(PATHS.worktrees, agentId),
warnings: [],
@@ -182,7 +182,7 @@ async function worktreeCleanupContext(agentId, options) {
}
async function probeWorktreePr(context, success) {
- if (context.discardWorktree || context.prCreation !== PR_CREATION.IF_MISSING) return null;
+ if (!context.isWorktree || context.discardWorktree || context.prCreation !== PR_CREATION.IF_MISSING) return null;
const { worktreePath, worktreeBranch } = context;
if (success) {
const { verifyPrClaim } = await import('./agentFinalization.js');
@@ -197,11 +197,12 @@ async function probeWorktreePr(context, success) {
async function runCleanupAgentWorktree(agentId, success, options = {}) {
const context = await worktreeCleanupContext(agentId, options);
- if (!context) return [];
const verdict = await probeWorktreePr(context, success);
const disposition = resolveWorktreeDisposition({ ...context, success, prClaimVerdict: verdict });
reportWorktreeDisposition(context, disposition, verdict);
switch (disposition.disposition) {
+ case 'not-a-worktree':
+ return [];
case 'discard':
return discardAgentWorktree(context);
case 'open-pr':
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 1556a845b3..6dc3df918e 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -2203,25 +2203,26 @@ describe('cleanupAgentWorktree - remote copy of a locally merged branch', () =>
// In particular, no branch identity is uncertainty even when ok is true.
describe('resolveWorktreeDisposition', () => {
it.each([
- [true, 'always', null, {}, 'open-pr'],
- [false, 'always', null, {}, 'merge-or-preserve'],
- [true, 'never', null, {}, 'merge-or-preserve'],
- [false, 'never', null, {}, 'merge-or-preserve'],
- [true, 'if-missing', { category: 'pr-missing' }, {}, 'open-pr'],
- [true, 'if-missing', { ok: true, branch: 'example' }, {}, 'stand-down'],
- [true, 'if-missing', { ok: true, branch: 'example', noChangesToShip: true }, {}, 'stand-down'],
- [true, 'if-missing', { ok: true, branch: null }, {}, 'stand-down-uncertain'],
- [true, 'if-missing', { category: 'forge-unreachable' }, {}, 'stand-down-uncertain'],
- [true, 'if-missing', null, {}, 'stand-down-uncertain'],
- [false, 'if-missing', { status: 'found', url: 'https://github.com/test/repo/pull/1' }, {}, 'stranded-pr-handoff'],
- [false, 'if-missing', { status: 'found' }, {}, 'merge-or-preserve'],
- [false, 'if-missing', { status: 'unavailable' }, {}, 'merge-or-preserve'],
- [false, 'if-missing', { status: 'none' }, {}, 'merge-or-preserve'],
- [true, 'always', null, { discardWorktree: true }, 'discard'],
- [false, 'if-missing', { status: 'found', url: 'https://github.com/test/repo/pull/1' }, { discardWorktree: true }, 'discard'],
- [true, 'always', null, { isWorktree: false, discardWorktree: true }, 'not-a-worktree'],
- [true, 'never', null, { skipMerge: true }, 'merge-or-preserve'],
- ])('success=%s creation=%s verdict=%j overrides=%j → %s', (success, prCreation, prClaimVerdict, overrides, expected) => {
- expect(resolveWorktreeDisposition({ success, prCreation, prClaimVerdict, ...overrides }).disposition).toBe(expected);
+ [true, 'always', null, {}, 'open-pr', false, false],
+ [false, 'always', null, {}, 'merge-or-preserve', false, true],
+ [true, 'never', null, {}, 'merge-or-preserve', true, false],
+ [false, 'never', null, {}, 'merge-or-preserve', false, true],
+ [true, 'if-missing', { category: 'pr-missing' }, {}, 'open-pr', false, false],
+ [true, 'if-missing', { ok: true, branch: 'example' }, {}, 'stand-down', true, false],
+ [true, 'if-missing', { ok: true, branch: 'example', noChangesToShip: true }, {}, 'stand-down', true, false],
+ [true, 'if-missing', { ok: true, branch: null }, {}, 'stand-down-uncertain', true, true],
+ [true, 'if-missing', { category: 'forge-unreachable' }, {}, 'stand-down-uncertain', true, true],
+ [true, 'if-missing', null, {}, 'stand-down-uncertain', true, true],
+ [false, 'if-missing', { status: 'found', url: 'https://github.com/test/repo/pull/1' }, {}, 'stranded-pr-handoff', false, true],
+ [false, 'if-missing', { status: 'found' }, {}, 'merge-or-preserve', false, true],
+ [false, 'if-missing', { status: 'unavailable' }, {}, 'merge-or-preserve', false, true],
+ [false, 'if-missing', { status: 'none' }, {}, 'merge-or-preserve', false, true],
+ [true, 'always', null, { discardWorktree: true }, 'discard', false, false],
+ [false, 'if-missing', { status: 'found', url: 'https://github.com/test/repo/pull/1' }, { discardWorktree: true }, 'discard', false, false],
+ [true, 'always', null, { isWorktree: false, discardWorktree: true }, 'not-a-worktree', false, false],
+ [true, 'never', null, { skipMerge: true }, 'merge-or-preserve', false, false],
+ ])('success=%s creation=%s verdict=%j overrides=%j → %s', (success, prCreation, prClaimVerdict, overrides, disposition, merge, preserveBranch) => {
+ expect(resolveWorktreeDisposition({ success, prCreation, prClaimVerdict, ...overrides }))
+ .toEqual({ disposition, merge, preserveBranch });
});
});