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

share the post-finalize cleanup dispatch between the TUI and direct-CLI spawners, so a TUI pipeline stage advances its pipeline

[._.]/ Adam Eivy198487aa2fa7
diff --git a/server/lib/README.md b/server/lib/README.md
index 2c516933a1..bf5467650c 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -551,7 +551,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `shellReadinessProbe.js` | `buildReadinessProbe(nonce, shell)` — the round-trip "can this shell actually run commands yet?" probe `createShellSession`'s `waitForPromptReady` sends and watches for, in the dialect the session speaks: POSIX `printf '%s\n' 'PORTOSRDY''<nonce>'` (unchanged), PowerShell `Write-Output ('PORTOSRDY' + '<nonce>')`, `cmd.exe` → `null` (no split-literal concatenation operator exists there, so the caller skips straight to the bounded fallback timer instead of risking an always-matching probe). The split-literal property is load-bearing in every dialect: the probe source never contains the assembled marker, so seeing it in the output can only mean the shell executed the probe. |
| `sidecarProcess.js` | `runSidecarProcess({bin,args,env,signal,onStage,onProcess})` + `parseSidecarResult(stdout)` — the shared Python-sidecar STAGE:/RESULT: wire-protocol runner (spawn, tail-capped stdout/stderr, per-STAGE-line callback, abort/SIGTERM → `canceled`, non-zero exit → stderr-tail reason). Used by `pipeline/musicGen.js` (all music backends) and `audioMidiTranscription.js` (MuScriptor). |
| `slashdoCatalog.js` | The single catalog of which bundled slashdo workflows PortOS offers as a one-click agent run — `SLASHDO_WORKFLOWS` (`{command, label, description, icon, templateName, templatePrompt?, settings, appTypes, configurable?}`), `getSlashdoWorkflow()` (the allowlist gate for `POST /api/cos/tasks/slashdo`), `SLASHDO_COMMAND_NAMES`, `slashdoWorkflowsForApp(isSwiftApp)`, `SLASHDO_APP_TYPES`, and the two run-shape postures `WORKFLOW_OWNS_ITS_OWN_GIT` (commit-shaped) / `WORKFLOW_REPORTS_NO_CODE` (report-shaped — carries `worktreeChangesExpected: false` so a filed-issue/printed-report run retains its non-code deliverable posture). Backs the Agent Operations buttons, the CoS quick templates (`taskTemplates.js`), and the route allowlist, replacing two catalogs that had drifted. `client/src/lib/slashdoCatalog.js` decorates this list with button styling rather than restating it. |
-| `slashdoInvocation.js` | Resolves how a bundled slashdo workflow is invoked on a given host CLI. `resolveSlashdoInvocation({command, args, providerId, providerCommand, leanMode})` → `{command, args, style, invocation, skillName}` for the three shapes slashdo's installer produces (`slash-namespaced` `/do:x` for Claude Code, `slash-flat` `/do-x` for OpenCode, `skill` — an Agent Skill selected by name — for codex/grok/antigravity and any unidentified provider). Plus `buildSlashdoSection(resolved, body, {bodyPath, reviewWith})` (pure renderer; the caller loads the body via `loadSlashdoFile`. With a staged `bodyPath` it emits a filesystem pointer for deferred bundles or bodies over `SLASHDO_INLINE_BUDGET_CHARS` (24,000)), `unreachableReviewerIncludes({reviewers, usernames})` → the reviewer-variant lib includes a run can never reach (the `skipIncludes` set for `loadSlashdoFile`; defaults to pruning NOTHING for an unresolved/unrecognized reviewer set, since an over-pruned prompt is worse than a fat one), `SLASHDO_REVIEWER_INCLUDES`/`SLASHDO_REVIEWER_INCLUDE_NAMES`, `slashdoSkillName`, `isValidSlashdoCommand` (the one definition of the safe bare-command shape, also gating the Zod schemas), `agentOwnsPrWorkflow({providerType, leanMode})` — a strictly WEAKER question than typing a slash command: any local `cli`/`tui` harness that is not a lean `--bare` session drives its own commit → push → PR → review → merge (#3733), with `resolveOwnsPrWorkflow({persisted, …})` reading the value stamped on a completed agent record and falling back to the slash-command gate for pre-#3733 records; `oversizedBodyPointer(bodyPath, body)` (the shared "it is on disk, go read it" line); and `canTypeSlashCommands()` — the single predicate behind `agentPromptBuilder.js`'s completion-workflow gates (can this session TYPE `/do:pr` / `/simplify`?), which reads `resolveSlashdoStyle`'s `assumeClaudeWhenUnknown` posture because the spawners resolve a blank command to `claude`. Provider is only known at spawn time, so a task persists the BARE command name — never a rendered `/do:x` string. |
+| `slashdoInvocation.js` | Resolves how a bundled slashdo workflow is invoked on a given host CLI. `resolveSlashdoInvocation({command, args, providerId, providerCommand, leanMode})` → `{command, args, style, invocation, skillName}` for the three shapes slashdo's installer produces (`slash-namespaced` `/do:x` for Claude Code, `slash-flat` `/do-x` for OpenCode, `skill` — an Agent Skill selected by name — for codex/grok/antigravity and any unidentified provider). Plus `buildSlashdoSection(resolved, body, {bodyPath, reviewWith})` (pure renderer; the caller loads the body via `loadSlashdoFile`. With a staged `bodyPath` it emits a filesystem pointer for deferred bundles or bodies over `SLASHDO_INLINE_BUDGET_CHARS` (24,000)), `unreachableReviewerIncludes({reviewers, usernames})` → the reviewer-variant lib includes a run can never reach (the `skipIncludes` set for `loadSlashdoFile`; defaults to pruning NOTHING for an unresolved/unrecognized reviewer set, since an over-pruned prompt is worse than a fat one), `SLASHDO_REVIEWER_INCLUDES`/`SLASHDO_REVIEWER_INCLUDE_NAMES`, `slashdoSkillName`, `isValidSlashdoCommand` (the one definition of the safe bare-command shape, also gating the Zod schemas), `agentOwnsPrWorkflow({providerType, leanMode})` — a strictly WEAKER question than typing a slash command: any local `cli`/`tui` harness that is not a lean `--bare` session drives its own commit → push → PR → review → merge (#3733), with `resolveOwnsPrWorkflow({persisted, …})` reading the value stamped on a completed agent record and falling back to the slash-command gate for pre-#3733 records; `oversizedBodyPointer(bodyPath, body)` (the shared "it is on disk, go read it" line); `resolvePrOwnership({task, isTruthyMeta, providerType, providerId, providerCommand, leanMode})` → `{taskOpenPR, agentOwnsPR, prClaimExpected}` — the one reading of the task plus LIVE provider descriptor that both in-process spawners (TUI `finish()`, direct-CLI `close`) hand to `runSpawnerCompletionCleanup`, so the ownership question and the cleanup acting on it cannot disagree; and `canTypeSlashCommands()` — the single predicate behind `agentPromptBuilder.js`'s completion-workflow gates (can this session TYPE `/do:pr` / `/simplify`?), which reads `resolveSlashdoStyle`'s `assumeClaudeWhenUnknown` posture because the spawners resolve a blank command to `claude`. Provider is only known at spawn time, so a task persists the BARE command name — never a rendered `/do:x` string. |
| `slashdoLoader.js` | Shared slashdo renderer adapter: `loadSlashdoBundle(cmd, {stripFrontmatter, skipIncludes, defer})` returns an entrypoint and supporting files using the bundled transformer; `loadSlashdoFile` returns a self-contained command; `loadSlashdoLib` expands explicit reads for legacy recipes without traversing see-also links. `writeResolvedSlashdoBody(cmd, body, {files})` stages immutable content-addressed bundles under `PATHS.slashdoResolved`, with relative library paths and the entrypoint written last. Missing required references fail dispatch rather than silently removing workflow gates. |
| `singleFlight.js` | `createSingleFlight()` → `run(key, fn)` — keyed in-flight coalescer: concurrent calls for the same key share one `fn()` execution and result; the slot auto-clears on settle. Minimal by design (no TTL/result cache layered on top, doesn't reject concurrent callers). Used by `services/promptRunner.js`'s fallback mark-and-pick. |
| `staleWhileRevalidate.js` | `createStaleWhileRevalidate({ ttlMs, failureBackoffMs?, isComplete?, partialTtlMs? })` → `read(key, produce, { wait })` / `clear(key?)` — TTL cache that serves a STALE value immediately and revalidates behind the caller, for readings too slow to block on (10-20s CLI/PTY spawns). `wait`: `'fresh'` bypasses and blocks, `'cached'` (default) blocks only on a cold cache, `'never'` returns the `PENDING` symbol on a cold cache for UIs that render "still reading" and poll. Failures keep the last good value and back off; a cold cache whose producer failed throws rather than promising a reading that isn't coming. Used by `providerUsage.js` (TUI scrapes) and `claudeCodeUsage.js`. |
diff --git a/server/lib/slashdoInvocation.js b/server/lib/slashdoInvocation.js
index 3d4daf577b..e0c9db627e 100644
--- a/server/lib/slashdoInvocation.js
+++ b/server/lib/slashdoInvocation.js
@@ -540,6 +540,47 @@ export function resolveOwnsPrWorkflow({ persisted, providerId = null, providerCo
return canTypeSlashCommands({ providerId, providerCommand, leanMode });
}
+/**
+ * The three PR answers a spawned run needs, from ONE reading of the task and
+ * the LIVE provider descriptor. Both in-process spawners call this once — the
+ * TUI `finish()` path up front, because its merge-gate contract check (#5876)
+ * reads `agentOwnsPR` before the run completes; the direct-CLI `close` handler
+ * at exit — and hand the result to `runSpawnerCompletionCleanup`, so the
+ * ownership question and the cleanup that acts on it can never read different
+ * answers (#3733).
+ *
+ * `agentOwnsPR` (does the harness drive its own push → PR → merge?) and
+ * `prClaimExpected` (does finalize verify a PR claim for it?) are deliberately
+ * two predicates: a harness that owns the workflow but cannot TYPE `/do:pr` is
+ * backstopped by cleanup, which re-checks the forge and opens the PR itself
+ * when the agent skipped it — failing it at finalize for a PR that is about to
+ * exist would turn a recovered hand-off into a false needs-attention (#3358).
+ *
+ * The runner-event path answers the same question from the PERSISTED record
+ * via `resolveOwnsPrWorkflow` — see `runCompletionCleanupSteps`. That record
+ * is stamped at spawn time from the prompt's own gate (`metadata.ownsPrWorkflow`,
+ * task-shape aware), which the spawners do not read yet: `agentOwnsPR` here is
+ * still provider-only, as both spawners derived it before this helper existed.
+ * Converging the two is #6551.
+ *
+ * @param {Object} opts
+ * @param {Object} opts.task
+ * @param {(value: unknown) => boolean} opts.isTruthyMeta
+ * @param {string|null} [opts.providerType] - `'tui' | 'cli'`
+ * @param {string|null} [opts.providerId]
+ * @param {string|null} [opts.providerCommand]
+ * @param {boolean} [opts.leanMode]
+ * @returns {{ taskOpenPR: boolean, agentOwnsPR: boolean, prClaimExpected: boolean }}
+ */
+export function resolvePrOwnership({ task, isTruthyMeta, providerType = null, providerId = null, providerCommand = null, leanMode = false }) {
+ const taskOpenPR = isTruthyMeta(task?.metadata?.openPR);
+ return {
+ taskOpenPR,
+ agentOwnsPR: taskOpenPR && agentOwnsPrWorkflow({ providerType, leanMode }),
+ prClaimExpected: taskOpenPR && canTypeSlashCommands({ providerId, providerCommand, leanMode }),
+ };
+}
+
/**
* Resolve the concrete invocation for a slashdo-backed task.
*
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index ffa7de42b2..4fe8baaa0e 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -22,9 +22,8 @@ import { analyzeAgentFailure } from './agentErrorAnalysis.js';
import { completeAgentRun } from './agentRunTracking.js';
import { appendRunEvent } from './agentRunEventLog.js';
import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';
+import { runSpawnerCompletionCleanup } from './agentCompletionCleanup.js';
import { activeAgents, userTerminatedAgents, pausedAgents, consumePausedAgentExit, registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';
-import { normalizeReviewers } from '../lib/validation.js';
-import { resolveReviewLoopOptions } from './codeReview.js';
import { safeJSONParse, PATHS, writeFileGuarded } from '../lib/fileUtils.js';
import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';
import { isKnownCliStderrNoise } from '../lib/cliStderrNoise.js';
@@ -41,8 +40,8 @@ import { resolveForgeTokenEnv } from './git.js';
import { resolveAgentCliCwd } from '../lib/spawnCwd.js';
import { prepareCliSpawn, killProcessTree, guardChildStdin, deliverChildStdin } from '../lib/bufferedSpawn.js';
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
-import { prClaimWasVerified, resolvePrCompletion, resolvePrCreation } from '../lib/prDisposition.js';
-import { canTypeSlashCommands, agentOwnsPrWorkflow } from '../lib/slashdoInvocation.js';
+import { prClaimWasVerified } from '../lib/prDisposition.js';
+import { resolvePrOwnership } from '../lib/slashdoInvocation.js';
import { doneSentinelPath } from '../lib/agentSentinel.js';
import { isHostShuttingDown, shouldAbandonForHostShutdown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';
import { ensureOllamaAgentContext } from './ollamaAgentContext.js';
@@ -330,15 +329,10 @@ export async function getClaudeSettingsEnv() {
/**
* Spawn agent directly (fallback when runner not available).
- * `cleanupWorktreeFn` and `isTruthyMetaFn` are passed in rather than
- * imported directly. The agentLifecycle.js ↔ agentCliSpawning.js import
- * graph is bidirectional (agentLifecycle calls `spawnDirectly`, this file
- * calls `finalizeAgent`) and ES module hoisting handles it for top-level
- * function references — but importing `cleanupAgentWorktree` /
- * `isTruthyMeta` at module top level would force their `agentLifecycle`
- * and `subAgentSpawner` modules to initialize before this one, racing
- * the cycle in ways that surfaced as `undefined` reads on cold start.
- * Passing them via the options object defers the lookup to call time.
+ * `isTruthyMetaFn` is the lifecycle's shared metadata predicate, passed in by
+ * the caller and threaded on to `finalizeAgent`. Completion cleanup is not
+ * injected: `runSpawnerCompletionCleanup` is imported at top level, since
+ * nothing in its static closure reaches this module or agentLifecycle.js.
*/
export async function spawnDirectly({
agentId,
@@ -352,7 +346,6 @@ export async function spawnDirectly({
agentDir,
executionId,
laneName,
- cleanupWorktreeFn,
isTruthyMetaFn,
safetyProfile = null,
}) {
@@ -859,7 +852,7 @@ export async function spawnDirectly({
// portos-server's descendants). Abandon rather than finalize, for the same
// reasons as the TUI path (#3202): finalizing would charge the task's
// failure budget — and possibly file an investigation task — for a fault the
- // agent didn't have, and its cleanup hands the worktree to `cleanupWorktreeFn`,
+ // agent didn't have, and its cleanup hands the worktree to `cleanupAgentWorktree`,
// which removes a clean tree, discarding the state a resume needs. Leaving
// the record `running` is what lets the next boot's orphan sweep see this
// agent in the host-shutdown marker and requeue it as interrupted.
@@ -906,33 +899,29 @@ export async function spawnDirectly({
// review → merge (#3733): a slashdo-capable Claude runs `/simplify` +
// `/do:pr`, codex/grok/agy/OpenCode run the plain `git`/`gh` equivalent from
// the same prompt (see buildCliCompletionSection in agentPromptBuilder.js).
- // Mirror that here so PortOS doesn't double-fire push+PR creation.
- const directOpenPR = isTruthyMetaFn(task.metadata?.openPR);
- const directLeanMode = isOllamaClaudeProvider(provider);
- const directAgentOwnsPR = directOpenPR && agentOwnsPrWorkflow({
+ // Resolved from the live provider descriptor — the same reading the TUI
+ // path takes up front — so PortOS doesn't double-fire push+PR creation; see
+ // `resolvePrOwnership` for why finalize's `prClaimExpected` and cleanup's
+ // `agentOwnsPR` are two predicates (#3358).
+ const prOwnership = resolvePrOwnership({
+ task,
+ isTruthyMeta: isTruthyMetaFn,
providerType: PROVIDER_TYPES.CLI,
- leanMode: directLeanMode,
- });
- // PR-claim verification (#3358) stays on the SLASH-command predicate: it runs
- // BEFORE the cleanup below, and cleanup now backstops a harness that skipped
- // its own PR step — failing the run here for a PR that is about to exist
- // would turn a recovered handoff into a false needs-attention.
- const directPrClaimExpected = directOpenPR && canTypeSlashCommands({
providerId: provider?.id,
providerCommand: provider?.command,
- leanMode: directLeanMode,
+ leanMode: isOllamaClaudeProvider(provider),
});
// Whether finalize's check ACTUALLY produced a forge answer (filled in from
// its return below) — not the same question as whether one was expected.
// Finalize substitutes `{ok:true}` for a user-terminated run and for a check
// that threw, and a throw from finalize skips the assignment entirely; in all
// three cases nothing was verified, so cleanup must ask rather than stand down.
- let directPrClaimVerified = false;
+ let prClaimVerified = false;
let noChangesToShip = false;
- // try/finally so a throw from finalizeAgent still runs the local
- // cleanup (worktree, pid unregister, activeAgents delete). Mirrors the
- // TUI path's pattern.
+ // try/finally so a throw from finalizeAgent still runs the local cleanup
+ // (the shared completion dispatch, pid unregister, activeAgents delete).
+ // Mirrors the TUI path's pattern.
// See the TUI path: a PR-claim downgrade must reach cleanup, or a run that
// opened no PR is cleaned up as a success and loses its retry state (#3358).
let cleanupSuccess = finalSuccess;
@@ -952,60 +941,27 @@ export async function spawnDirectly({
error: finalError || undefined,
completionReason: terminatedByUser ? 'user-terminated' : undefined,
workspacePath: cwd,
- prExpected: directPrClaimExpected,
+ prExpected: prOwnership.prClaimExpected,
// The run window the commit criterion is evaluated against (#3637).
startedAt: agentData?.startedAt ?? null,
});
if (finalized && typeof finalized.success === 'boolean') cleanupSuccess = finalized.success;
- directPrClaimVerified = prClaimWasVerified(finalized?.prVerdict);
+ prClaimVerified = prClaimWasVerified(finalized?.prVerdict);
noChangesToShip = finalized?.prVerdict?.noChangesToShip === true;
} finally {
- // Advance a staged pipeline exactly as the runner/TUI path does through
- // runAgentCompletionCleanup. This path only ever ran finalize + worktree
- // cleanup, so a stage that spawned directly — every public-review stage,
- // any cli-typed provider — completed without queuing its successor: the
- // pr-reviewer Eligibility Gate recorded its decision and the pipeline
- // simply stopped. Before the worktree goes, since a stage precondition
- // may read it. Lazy import for the same module-cycle reason as
- // cleanupWorktreeFn; sanctioned try/catch — this is a child 'close'
- // handler, not a request.
- if (task?.metadata?.pipeline) {
- try {
- const { handlePipelineProgression } = await import('./agentCompletionCleanup.js');
- await handlePipelineProgression(task, agentId, cleanupSuccess);
- } catch (err) {
- console.error(`❌ Pipeline progression failed for ${agentId}: ${err.message}`);
- }
- }
- const directPrCompletion = resolvePrCompletion(task.metadata);
- const directReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);
- const reviewOptions = await resolveReviewLoopOptions(task.metadata, { normalize: normalizeReviewers, isTruthyMeta: isTruthyMetaFn });
- await cleanupWorktreeFn(agentId, cleanupSuccess, {
- prCreation: resolvePrCreation({
- taskOpenPR: directOpenPR,
- agentOwnsPr: directAgentOwnsPR,
- prClaimVerified: directPrClaimVerified,
- noChangesToShip,
- }),
- prCompletion: directPrCompletion,
- ...reviewOptions,
- skipMerge: directReviewLoopFollowUp || directAgentOwnsPR,
- description: task.description,
- agentOutput: outputBuffer,
- originalTask: task
- }).catch(err => console.error(`❌ CLI worktree cleanup failed for ${agentId}: ${err.message}`));
-
- // Release the retry hold: flip the failed task back to `pending` carrying a
- // pointer at whatever the run left behind — the branch (or whole worktree)
- // `cleanupWorktreeFn` just preserved because the run failed with commits on
- // it. Without the pointer the retry starts clean and redoes work already
- // sitting on disk (#3368); without the hold that release replaces, the retry
- // could be dequeued before the pointer landed (#3373). Imported lazily for the
- // same reason `cleanupWorktreeFn` is injected: pulling the cleanup graph in at
- // module top level races this file's own init in the agentLifecycle cycle.
- await import('./agentWorktreeCleanup.js')
- .then(({ releaseRetryHold }) => releaseRetryHold({ agentId, task, success: cleanupSuccess }))
- .catch(err => console.error(`❌ CLI retry-hold release failed for ${agentId}: ${err.message}`));
+ // Pipeline progression → worktree cleanup with the PR disposition →
+ // retry-hold release, in the one owner both in-process spawners share.
+ // Caught so a throw there cannot skip the in-memory teardown below — this
+ // is a child 'close' handler, outside any request lifecycle.
+ await runSpawnerCompletionCleanup({
+ agentId,
+ task,
+ success: cleanupSuccess,
+ prOwnership,
+ prClaimVerified,
+ noChangesToShip,
+ outputBuffer,
+ }).catch(err => console.error(`❌ CLI completion cleanup failed for ${agentId}: ${err.message}`));
unregisterSpawnedAgent(agentData?.pid || claudeProcess.pid);
activeAgents.delete(agentId);
diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.js
index e1c478b6bc..6c2d328188 100644
--- a/server/services/agentCliSpawning.test.js
+++ b/server/services/agentCliSpawning.test.js
@@ -56,8 +56,15 @@ vi.mock('./agentFinalization.js', () => ({
finalizeAgent: vi.fn().mockResolvedValue(undefined),
releaseAgentLane: vi.fn(),
}));
+// The close handler hands the run to the shared completion dispatch (pipeline
+// progression → worktree cleanup with the PR disposition → retry-hold release).
+// Doubled at that boundary: what this suite owns is that the direct-CLI path
+// dispatches with the right verdict and PR ownership, and only when it should —
+// the dispatch's own sequence is pinned in agentCompletionCleanup.test.js.
+// Mocking it also keeps the real cleanup graph (cos.js, git.js, worktreeManager)
+// out of this suite.
vi.mock('./agentCompletionCleanup.js', () => ({
- handlePipelineProgression: vi.fn().mockResolvedValue(undefined),
+ runSpawnerCompletionCleanup: vi.fn().mockResolvedValue(undefined),
}));
vi.mock('./agentState.js', () => ({
activeAgents: new Map(),
@@ -105,12 +112,6 @@ vi.mock('../lib/childProcess.js', () => ({
execFile: vi.fn(),
}));
-// Lazily imported by the close handler's cleanup block to record a failed run's
-// resume pointer (#3368). Mocked so the test doesn't pull the real cleanup graph
-// (cos.js, git.js, worktreeManager) in behind it.
-vi.mock('./agentWorktreeCleanup.js', () => ({
- releaseRetryHold: vi.fn().mockResolvedValue({}),
-}));
vi.mock('./ollamaAgentContext.js', () => ({
ensureOllamaAgentContext: vi.fn(async () => ({ skipped: true })),
}));
@@ -122,7 +123,7 @@ vi.mock('../lib/privateSecuritySandbox.js', () => ({
}));
import { buildCliSpawnConfig, createStreamJsonParser, spawnDirectly } from './agentCliSpawning.js';
-import { releaseRetryHold } from './agentWorktreeCleanup.js';
+import { runSpawnerCompletionCleanup } from './agentCompletionCleanup.js';
import { ensureOllamaAgentContext } from './ollamaAgentContext.js';
import { isOllamaBackedProvider } from './providers.js';
// Real module — the flag is a plain process-local boolean, so driving it
@@ -568,7 +569,6 @@ describe('stream error containment', () => {
agentDir: '/tmp',
executionId: null,
laneName: null,
- cleanupWorktreeFn: vi.fn().mockResolvedValue(undefined),
isTruthyMetaFn: vi.fn().mockReturnValue(false),
};
@@ -586,7 +586,8 @@ describe('stream error containment', () => {
(await import('./agentRunTracking.js')).completeAgentRun.mockResolvedValue(undefined);
(await import('./agentFinalization.js')).finalizeAgent.mockResolvedValue(undefined);
// Completion waits must observe this test, not a previous cleanup call.
- minimalArgs.cleanupWorktreeFn.mockClear().mockResolvedValue(undefined);
+ runSpawnerCompletionCleanup.mockClear();
+ runSpawnerCompletionCleanup.mockResolvedValue(undefined);
vi.mocked(existsSync).mockReturnValue(false);
vi.mocked(isOllamaBackedProvider).mockReturnValue(false);
vi.mocked(ensureOllamaAgentContext).mockResolvedValue({ skipped: true });
@@ -731,7 +732,7 @@ describe('stream error containment', () => {
});
await expect(spawnDirectly(minimalArgs)).resolves.toBe('agent-test');
- await vi.waitFor(() => expect(minimalArgs.cleanupWorktreeFn).toHaveBeenCalled(), { interval: 5 });
+ await vi.waitFor(() => expect(runSpawnerCompletionCleanup).toHaveBeenCalled(), { interval: 5 });
expect(finalizeAgent).toHaveBeenCalledWith(expect.objectContaining({
agentId: 'agent-test',
@@ -865,7 +866,7 @@ describe('stream error containment', () => {
fakeProcess.emit('close', 0);
await spawnPromise;
- await vi.waitFor(() => expect(minimalArgs.cleanupWorktreeFn).toHaveBeenCalled(), { interval: 5 });
+ await vi.waitFor(() => expect(runSpawnerCompletionCleanup).toHaveBeenCalled(), { interval: 5 });
expect(agentStateMocks.appendAgentOutputLines).toHaveBeenCalledWith('agent-test', [
'⚠️ Example context warning',
@@ -1250,71 +1251,57 @@ describe('stream error containment', () => {
});
});
- it('threads the ordered reviewer list while forcing public review into non-applying mode', async () => {
- const cleanupWorktreeFn = vi.fn().mockResolvedValue(undefined);
- const args = {
- ...minimalArgs,
- task: {
- id: 'task-rv',
- description: 'do stuff',
- metadata: { reviewers: ['codex', 'antigravity'], reviewStopMode: 'on-clean', reviewerApplies: true },
- },
- cleanupWorktreeFn,
- isTruthyMetaFn: (v) => v === true,
+ it('hands a slashdo-capable harness to the dispatch as owning its PR, with the claim expected', async () => {
+ const task = {
+ id: 'task-rv',
+ description: 'do stuff',
+ metadata: { openPR: true, reviewers: ['codex', 'antigravity'], reviewStopMode: 'on-clean' },
};
- spawnDirectly(args);
+ spawnDirectly({ ...minimalArgs, task, isTruthyMetaFn: (v) => v === true });
await new Promise((r) => setTimeout(r, 10));
fakeProcess.stdout.emit('data', Buffer.from('{"type":"result","result":"ok"}\n'));
await new Promise((r) => setTimeout(r, 50));
fakeProcess.emit('close', 0);
// spawnDirectly returns before the close handler's async cleanup finishes.
- await vi.waitFor(() => expect(cleanupWorktreeFn).toHaveBeenCalled(), { interval: 5 });
-
- expect(cleanupWorktreeFn).toHaveBeenCalledTimes(1);
- const opts = cleanupWorktreeFn.mock.calls[0][2];
- expect(opts.reviewers).toEqual(['codex', 'antigravity']);
- expect(opts.reviewStopMode).toBe('on-clean');
- expect(opts.reviewerApplies).toBe(false);
- // The removed singular key must NOT be passed.
- expect(opts.reviewer).toBeUndefined();
+ await vi.waitFor(() => expect(runSpawnerCompletionCleanup).toHaveBeenCalledTimes(1), { interval: 5 });
+
+ // A claude-code CLI both owns its PR workflow and can type `/do:pr`, so
+ // finalize was expected to verify the claim (its mock here verified none).
+ // The reviewer metadata travels on the task; the dispatch resolves it against
+ // the Code Review Defaults (agentCompletionCleanup.test.js).
+ expect(runSpawnerCompletionCleanup).toHaveBeenCalledWith(expect.objectContaining({
+ agentId: minimalArgs.agentId,
+ task,
+ success: true,
+ prOwnership: { taskOpenPR: true, agentOwnsPR: true, prClaimExpected: true },
+ prClaimVerified: false,
+ }));
});
- // A failed direct-CLI run's branch is preserved by cleanup when it holds commits;
- // without this call nothing ever points the retry at it and the work is redone
- // from scratch (#3368). Runs after cleanup so it reflects what actually survived.
- it('records a resume pointer after cleanup when the run failed', async () => {
- releaseRetryHold.mockClear();
- const cleanupWorktreeFn = vi.fn().mockResolvedValue(undefined);
+ // The dispatch releases the retry hold with this verdict (#3368 — its ordering
+ // after worktree cleanup is pinned in agentCompletionCleanup.test.js). What
+ // this pins is that the close handler hands it the REAL verdict: a hardcoded
+ // value would stamp resume pointers on every completed run, or on none.
+ it('hands the dispatch the run verdict — failure on a non-zero exit, success on a clean one', async () => {
const task = { id: 'task-rp', description: 'do stuff', metadata: {} };
-
- spawnDirectly({ ...minimalArgs, task, cleanupWorktreeFn, isTruthyMetaFn: (v) => v === true });
+ spawnDirectly({ ...minimalArgs, task, isTruthyMetaFn: (v) => v === true });
await new Promise((r) => setTimeout(r, 10));
fakeProcess.emit('close', 1);
- await vi.waitFor(() => expect(releaseRetryHold).toHaveBeenCalled(), { interval: 5 });
+ await vi.waitFor(() => expect(runSpawnerCompletionCleanup).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: minimalArgs.agentId, task, success: false }),
+ ), { interval: 5 });
- expect(releaseRetryHold).toHaveBeenCalledWith({
- agentId: minimalArgs.agentId, task, success: false,
- });
- expect(cleanupWorktreeFn.mock.invocationCallOrder[0])
- .toBeLessThan(releaseRetryHold.mock.invocationCallOrder[0]);
- });
-
- // The helper no-ops on success (unit-tested in cleanupAgentWorktree.test.js) —
- // what this pins is that the close handler hands it the real verdict, not a
- // hardcoded false that would stamp pointers on every completed run.
- it('passes the success verdict through on a clean run', async () => {
- releaseRetryHold.mockClear();
- const task = { id: 'task-rp-ok', description: 'do stuff', metadata: {} };
-
- spawnDirectly({ ...minimalArgs, task, cleanupWorktreeFn: vi.fn().mockResolvedValue(undefined), isTruthyMetaFn: (v) => v === true });
+ runSpawnerCompletionCleanup.mockClear();
+ fakeProcess = makeFakeProcess();
+ spawnDirectly({ ...minimalArgs, task: { id: 'task-rp-ok', description: 'do stuff', metadata: {} }, isTruthyMetaFn: (v) => v === true });
await new Promise((r) => setTimeout(r, 10));
fakeProcess.stdout.emit('data', Buffer.from('{"type":"result","result":"ok"}\n'));
await new Promise((r) => setTimeout(r, 50));
fakeProcess.emit('close', 0);
- await vi.waitFor(() => expect(releaseRetryHold).toHaveBeenCalled(), { interval: 5 });
-
- expect(releaseRetryHold).toHaveBeenCalledWith(expect.objectContaining({ success: true }));
+ await vi.waitFor(() => expect(runSpawnerCompletionCleanup).toHaveBeenCalledWith(
+ expect.objectContaining({ success: true }),
+ ), { interval: 5 });
});
// pm2's TreeKill takes direct-CLI children down with portos-server exactly as
@@ -1323,41 +1310,6 @@ describe('stream error containment', () => {
// didn't have, and hand its worktree to cleanup, discarding the state a resume
// needs. The run is abandoned instead, leaving the record `running` for the
// next boot's orphan sweep to reconcile from the host-shutdown marker.
- describe('pipeline progression on close', () => {
- // The runner/TUI completion path advances a staged pipeline through
- // runAgentCompletionCleanup; this direct path only ran finalize + worktree
- // cleanup, so every directly-spawned stage (all public-review stages)
- // completed without queuing its successor.
- it('advances the pipeline before the worktree is cleaned up', async () => {
- const { handlePipelineProgression } = await import('./agentCompletionCleanup.js');
- handlePipelineProgression.mockClear();
- const order = [];
- handlePipelineProgression.mockImplementation(async () => { order.push('pipeline'); });
- minimalArgs.cleanupWorktreeFn.mockImplementation(async () => { order.push('worktree'); });
- const task = { id: 'task-1', description: 'stage', metadata: { pipeline: { status: 'running', currentStage: 1, stages: [{}, {}, {}] } } };
-
- const spawnPromise = spawnDirectly({ ...minimalArgs, task });
- await new Promise((r) => setTimeout(r, 10));
- fakeProcess.emit('close', 0);
- await spawnPromise.catch(() => {});
- await vi.waitFor(() => expect(minimalArgs.cleanupWorktreeFn).toHaveBeenCalled(), { interval: 5 });
-
- expect(handlePipelineProgression).toHaveBeenCalledWith(task, 'agent-test', true);
- expect(order).toEqual(['pipeline', 'worktree']);
- });
-
- it('does not touch pipeline progression for an ordinary task', async () => {
- const { handlePipelineProgression } = await import('./agentCompletionCleanup.js');
- handlePipelineProgression.mockClear();
- const spawnPromise = spawnDirectly(minimalArgs);
- await new Promise((r) => setTimeout(r, 10));
- fakeProcess.emit('close', 0);
- await spawnPromise.catch(() => {});
- await vi.waitFor(() => expect(minimalArgs.cleanupWorktreeFn).toHaveBeenCalled(), { interval: 5 });
- expect(handlePipelineProgression).not.toHaveBeenCalled();
- });
- });
-
describe('host restart (#3202)', () => {
// The outer beforeEach re-sets implementations but not call history, and the
// mocks are module-scoped — clear so "was it called" reads only this test.
@@ -1376,18 +1328,17 @@ describe('stream error containment', () => {
fakeProcess.emit('close', code);
};
- it('abandons without finalizing or cleaning up the worktree', async () => {
- const cleanupWorktreeFn = vi.fn().mockResolvedValue(undefined);
+ it('abandons without finalizing or dispatching cleanup', async () => {
const { finalizeAgent } = await import('./agentFinalization.js');
- await runToClose({ ...minimalArgs, cleanupWorktreeFn });
+ await runToClose({ ...minimalArgs });
await vi.waitFor(() => expect(agentStateMocks.updateAgent).toHaveBeenCalledWith(
minimalArgs.agentId,
{ metadata: { phase: 'interrupted', interruptedBy: 'host-shutdown' } },
), { interval: 5 });
expect(finalizeAgent).not.toHaveBeenCalled();
- expect(cleanupWorktreeFn).not.toHaveBeenCalled();
+ expect(runSpawnerCompletionCleanup).not.toHaveBeenCalled();
// The breadcrumb the orphan sweep falls back on when no marker names the agent.
expect(agentStateMocks.updateAgent).toHaveBeenCalledWith(
minimalArgs.agentId,
@@ -1401,7 +1352,7 @@ describe('stream error containment', () => {
userTerminatedAgents.add(minimalArgs.agentId);
await runToClose({ ...minimalArgs });
- await vi.waitFor(() => expect(minimalArgs.cleanupWorktreeFn).toHaveBeenCalled(), { interval: 5 });
+ await vi.waitFor(() => expect(runSpawnerCompletionCleanup).toHaveBeenCalled(), { interval: 5 });
expect(finalizeAgent).toHaveBeenCalledWith(
expect.objectContaining({ terminatedByUser: true, success: false }),
@@ -1417,7 +1368,7 @@ describe('stream error containment', () => {
path === join(minimalArgs.workspacePath, '.agent-done-agent-test'));
await runToClose({ ...minimalArgs }, null);
- await vi.waitFor(() => expect(minimalArgs.cleanupWorktreeFn).toHaveBeenCalled(), { interval: 5 });
+ await vi.waitFor(() => expect(runSpawnerCompletionCleanup).toHaveBeenCalled(), { interval: 5 });
expect(finalizeAgent).toHaveBeenCalledWith(
expect.objectContaining({
diff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.js
index 6cec40ba8c..2c117509b6 100644
--- a/server/services/agentCompletionCleanup.js
+++ b/server/services/agentCompletionCleanup.js
@@ -1,19 +1,31 @@
/**
* Agent Completion Cleanup
*
- * The post-finalize orchestration that runs after `finalizeAgent` inside
- * `handleAgentCompletion`: JIRA branch push + PR + ticket comment, the
- * plan-question notification marker, pipeline-stage progression, the Creative
- * Director chain hook, and worktree cleanup (with cleanup-warning
- * notifications + merge-recovery task). Extracted from agentLifecycle.js to
- * keep `handleAgentCompletion`'s try/finally guard small and obvious.
+ * The post-finalize orchestration that runs after `finalizeAgent`, for every
+ * path a CoS run can complete on:
*
- * `handlePipelineProgression` lives here too — it's only invoked from this
- * cleanup flow (agentLifecycle.js re-exports it for subAgentSpawner).
+ * - `runAgentCompletionCleanup` — the runner-event path (`handleAgentCompletion`
+ * in agentLifecycle.js): JIRA branch push + PR + ticket comment, the
+ * plan-question notification marker, pipeline-stage progression, the
+ * Creative Director chain hook, and worktree cleanup (with cleanup-warning
+ * notifications + merge-recovery task). Extracted from agentLifecycle.js to
+ * keep `handleAgentCompletion`'s try/finally guard small and obvious.
+ * - `runSpawnerCompletionCleanup` — the two in-process spawners, whose child
+ * process (or PTY relay) this server owns: the TUI `finish()` handler
+ * (agentTuiSpawning.js) and the direct-CLI `close` handler
+ * (agentCliSpawning.js). Pipeline progression, worktree cleanup with the PR
+ * disposition, and the retry-hold release.
+ *
+ * Both hand `cleanupAgentWorktree` the options `resolveWorktreeCleanupOptions`
+ * builds, so the PR-disposition shape has one owner. `handlePipelineProgression`
+ * lives here too — it's only invoked from these cleanup flows (agentLifecycle.js
+ * re-exports it for subAgentSpawner).
*
* This module imports the worktree-cleanup leaf (agentWorktreeCleanup.js)
* directly; it must NOT import from agentLifecycle.js, which imports this
- * module — that would form a cycle.
+ * module — that would form a cycle. Nothing in this module's static closure
+ * reaches agentLifecycle.js or either spawner, which is what lets the spawners
+ * import it at top level.
*/
import { join, relative, resolve, sep } from 'path';
@@ -28,7 +40,7 @@ import * as git from './git.js';
import { isTruthyMeta } from './agentState.js';
import { resolveReviewLoopOptions } from './codeReview.js';
import { cleanupAgentWorktree, spawnMergeRecoveryTask, releaseRetryHold } from './agentWorktreeCleanup.js';
-import { resolvePrCompletion, resolvePrCreation } from '../lib/prDisposition.js';
+import { PR_CREATION, resolvePrCompletion, resolvePrCreation } from '../lib/prDisposition.js';
import { resolveOwnsPrWorkflow } from '../lib/slashdoInvocation.js';
import { isPublicReviewRestrictedProfile, publicReviewPostureForProfile } from '../lib/agentExecutionProfiles.js';
@@ -201,6 +213,61 @@ export async function handlePipelineProgression(task, agentId, success) {
emitLog('info', `🔗 Pipeline ${pipeline.id} advancing to stage ${nextStageIndex}: ${nextStage.name}`, { pipelineId: pipeline.id, agentId });
}
+/**
+ * The options `cleanupAgentWorktree` decides a completing run's PR on — who
+ * opens it (`prCreation`), how it lands (`prCompletion`), which reviewers gate
+ * it, and whether the worktree branch may auto-merge — resolved from the task
+ * and the caller's PR-ownership verdict. ONE owner for the shape, shared by the
+ * runner-event path (`runCompletionCleanupSteps`) and both in-process spawners
+ * (`runSpawnerCompletionCleanup`). It used to be three inline copies, and the
+ * reviewer-resolve hardening below reached only one of them.
+ *
+ * `taskOpenPR` / `agentOwnsPR` are the CALLER's: the spawners read them off the
+ * live provider descriptor (`resolvePrOwnership`), the runner path off the
+ * persisted agent record (`resolveOwnsPrWorkflow`) — see #3358 for why the two
+ * sources exist. `prClaimVerified` likewise carries whether finalize's check
+ * ACTUALLY produced a forge answer for this run, which is a different question
+ * from whether one was expected.
+ *
+ * Only the two `prCreation` modes that can still open a PR (and thus spawn a
+ * follow-up that needs reviewer options) pay for the reviewer resolve. `never`
+ * — the dominant path, a harness that opened and landed its own PR — discards
+ * them, and a resolve that throws degrades to the follow-up's defaults rather
+ * than skipping the worktree cleanup this runs inside of.
+ *
+ * @returns {Promise<Object>} the third argument to `cleanupAgentWorktree`
+ */
+async function resolveWorktreeCleanupOptions({ agentId, task, outputBuffer, taskOpenPR, agentOwnsPR, prClaimVerified = false, noChangesToShip = false }) {
+ // `if-missing` for an agent-owned PR that finalize did NOT verify: cleanup
+ // asks the forge once and only stands down when a PR actually exists, so a
+ // harness that skipped its completion workflow can't strand the branch.
+ const prCreation = resolvePrCreation({ taskOpenPR, agentOwnsPr: agentOwnsPR, prClaimVerified, noChangesToShip });
+ // Merge per-task reviewer metadata with the user's Code Review Defaults
+ // (Settings → Code Reviewers page). Settings I/O is cached inside the
+ // resolver, so this is effectively free even when invoked from a tight CoS
+ // sweep.
+ const reviewOptions = prCreation !== PR_CREATION.NEVER
+ ? await resolveReviewLoopOptions(task?.metadata, { normalize: normalizeReviewers })
+ .catch(err => {
+ emitLog('warn', `Review options unavailable for ${agentId}: ${err.message}`, { agentId, taskId: task?.id });
+ return {};
+ })
+ : {};
+ return {
+ prCreation,
+ prCompletion: resolvePrCompletion(task?.metadata),
+ ...reviewOptions,
+ // Review-loop follow-up agents already merged via `gh pr merge` in the agent
+ // body — re-merging the worktree branch into the source workspace would
+ // duplicate the squashed commits — and a harness that owns its PR workflow
+ // lands its own PR; suppress the auto-merge fallback for both.
+ skipMerge: isTruthyMeta(task?.metadata?.reviewLoopFollowUp) || agentOwnsPR,
+ description: task?.description,
+ agentOutput: outputBuffer,
+ originalTask: task,
+ };
+}
+
/**
* Run the post-finalize cleanup for a completed agent: JIRA push/PR/comment,
* the plan-question notification marker, pipeline progression, the Creative
@@ -359,11 +426,6 @@ async function runCompletionCleanupSteps({ agentId, task, agent, agentState, eff
// Clean up worktree if agent was using one (skip merge when JIRA branch — PR handles merge)
if (!jiraBranch) {
const taskOpenPR = isTruthyMeta(task?.metadata?.openPR);
- const taskPrCompletion = resolvePrCompletion(task?.metadata);
- // Review-loop follow-up agents already merged via `gh pr merge` in the agent
- // body — re-merging the worktree branch into the source workspace would
- // duplicate the squashed commits, so suppress the auto-merge fallback.
- const taskReviewLoopFollowUp = isTruthyMeta(task?.metadata?.reviewLoopFollowUp);
// Who opens the PR, and whether finalize already checked that they did.
// These two must match what the prompt actually told the agent or PortOS
// double-fires `gh pr create` ("a pull request already exists" would then
@@ -387,23 +449,15 @@ async function runCompletionCleanupSteps({ agentId, task, agent, agentState, eff
// `canTypeSlashCommands` would answer a different question ("was one
// expected?") off a different expression than the one finalize used, and the
// two silently disagree the moment a run's check throws or its finalize does.
- // Merge per-task reviewer metadata with the user's Code Review Defaults
- // (Settings → Code Reviewers page). Settings I/O is cached
- // inside the resolver, so this is effectively free even when invoked
- // from a tight CoS sweep.
- const reviewOptions = await resolveReviewLoopOptions(task?.metadata, { normalize: normalizeReviewers, isTruthyMeta });
- const cleanupWarnings = await cleanupAgentWorktree(agentId, effectiveSuccess, {
- // `if-missing` for an agent-owned PR that finalize did NOT verify: cleanup
- // asks the forge once and only stands down when a PR actually exists, so a
- // harness that skipped its completion workflow can't strand the branch.
- prCreation: resolvePrCreation({ taskOpenPR, agentOwnsPr: agentOwnsPR, prClaimVerified, noChangesToShip }),
- prCompletion: taskPrCompletion,
- ...reviewOptions,
- skipMerge: taskReviewLoopFollowUp || agentOwnsPR,
- description: task?.description,
- agentOutput: outputBuffer,
- originalTask: task
- });
+ const cleanupWarnings = await cleanupAgentWorktree(agentId, effectiveSuccess, await resolveWorktreeCleanupOptions({
+ agentId,
+ task,
+ outputBuffer,
+ taskOpenPR,
+ agentOwnsPR,
+ prClaimVerified,
+ noChangesToShip,
+ }));
if (cleanupWarnings?.length > 0) {
const { getAgent: getAgentForResult } = await import('./cos.js');
@@ -429,3 +483,56 @@ async function runCompletionCleanupSteps({ agentId, task, agent, agentState, eff
}
}
}
+
+/**
+ * The post-finalize dispatch for a run whose child process this server itself
+ * owns — the TUI `finish()` handler (agentTuiSpawning.js) and the direct-CLI
+ * `close` handler (agentCliSpawning.js) — and the counterpart of
+ * `runAgentCompletionCleanup` above, which serves the runner-event path.
+ *
+ * Runs from the spawner's `finally`, after `finalizeAgent` has settled or
+ * thrown. In order:
+ * 1. advance a staged pipeline (`handlePipelineProgression`) BEFORE the
+ * worktree goes, since a stage precondition may read it;
+ * 2. worktree cleanup with the PR disposition (`resolveWorktreeCleanupOptions`);
+ * 3. release the retry hold — in a `finally`, as `runAgentCompletionCleanup`
+ * does, so no throw above can skip it. A failed task is left held by
+ * `finalizeAgent` so nothing can dequeue its retry before the resume
+ * pointer is written; the release flips it back to `pending` pointing at
+ * whatever cleanup preserved — the branch (or whole worktree) kept because
+ * the run failed with commits on it (#3368, #3373).
+ * A failed step is logged and does not block the next one.
+ *
+ * Both spawners used to inline this sequence and mirror each other by hand, and
+ * the mirror drifted in both directions: pipeline progression reached the CLI
+ * copy (cd1d21211) but never the TUI one — so an attachable pipeline stage run
+ * as a TUI (#6062) completed without advancing, or closing, its pipeline —
+ * while the reviewer-resolve hardening reached the TUI copy (708c5e473) but not
+ * the CLI one.
+ *
+ * `prOwnership` is `resolvePrOwnership`'s answer for this run;
+ * `prClaimVerified` / `noChangesToShip` are read off finalize's return.
+ * `success` is the verdict finalize actually persisted — a PR-claim downgrade
+ * must reach cleanup, or a run that opened no PR is cleaned up as a success and
+ * loses its retry state (#3358).
+ */
+export async function runSpawnerCompletionCleanup({ agentId, task, success, prOwnership, prClaimVerified = false, noChangesToShip = false, outputBuffer }) {
+ try {
+ await handlePipelineProgression(task, agentId, success)
+ .catch(err => emitLog('warn', `Pipeline progression failed for ${agentId}: ${err.message}`, { agentId, taskId: task?.id }));
+ const cleanupOptions = await resolveWorktreeCleanupOptions({
+ agentId,
+ task,
+ outputBuffer,
+ taskOpenPR: prOwnership.taskOpenPR,
+ agentOwnsPR: prOwnership.agentOwnsPR,
+ prClaimVerified,
+ noChangesToShip,
+ });
+ await cleanupAgentWorktree(agentId, success, cleanupOptions)
+ .catch(err => emitLog('warn', `Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId, taskId: task?.id }));
+ } finally {
+ await releaseRetryHold({ agentId, task, success })
+ .catch(err => emitLog('warn', `Retry-hold release failed for ${agentId}: ${err.message}`, { agentId, taskId: task?.id }));
+ }
+}
diff --git a/server/services/agentCompletionCleanup.test.js b/server/services/agentCompletionCleanup.test.js
index c959cc0943..14e7997090 100644
--- a/server/services/agentCompletionCleanup.test.js
+++ b/server/services/agentCompletionCleanup.test.js
@@ -29,9 +29,10 @@ vi.mock('./agentWorktreeCleanup.js', () => ({
}));
vi.mock('./taskPromptService.js', () => ({ getStagePrompt: vi.fn().mockResolvedValue('do stage work in {appName}') }));
-import { handlePipelineProgression, runAgentCompletionCleanup } from './agentCompletionCleanup.js';
+import { handlePipelineProgression, runAgentCompletionCleanup, runSpawnerCompletionCleanup } from './agentCompletionCleanup.js';
import { updateTask, addTask, reviveBlockedTask, getAgent } from './cos.js';
import { cleanupAgentWorktree, releaseRetryHold } from './agentWorktreeCleanup.js';
+import { resolveReviewLoopOptions } from './codeReview.js';
const runningPipeline = (overrides = {}) => ({
id: 'p1',
@@ -399,3 +400,88 @@ describe('runAgentCompletionCleanup — resume pointer', () => {
expect(releaseRetryHold).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'a1' }));
});
});
+
+// The dispatch the TUI `finish()` and direct-CLI `close` handlers hand off to
+// from their `finally`. It replaced two hand-mirrored inline copies that had
+// drifted in both directions, so what these pin is the sequence itself, the PR
+// disposition it derives from the spawner's ownership verdict, and the two
+// behaviors each copy was missing. The spawner suites pin only the hand-off.
+describe('runSpawnerCompletionCleanup — the in-process spawners\' dispatch', () => {
+ const spawnerArgs = (overrides = {}) => ({
+ agentId: 'a1',
+ task: { id: 't', taskType: 'user', description: 'do it', metadata: { openPR: true } },
+ success: true,
+ // A task that asked for a PR from a harness that does not own the workflow.
+ prOwnership: { taskOpenPR: true, agentOwnsPR: false, prClaimExpected: false },
+ prClaimVerified: false,
+ noChangesToShip: false,
+ outputBuffer: 'out',
+ ...overrides,
+ });
+
+ it('advances a running pipeline, cleans the worktree with the PR disposition, then releases the hold', async () => {
+ const order = [];
+ updateTask.mockImplementationOnce(async () => { order.push('pipeline'); });
+ cleanupAgentWorktree.mockImplementationOnce(async () => { order.push('worktree'); });
+ releaseRetryHold.mockImplementationOnce(async () => { order.push('hold'); });
+ const task = { id: 't', taskType: 'user', description: 'stage', metadata: { openPR: true, pipeline: runningPipeline({ currentStage: 1 }) } };
+
+ await runSpawnerCompletionCleanup(spawnerArgs({ task }));
+
+ expect(order).toEqual(['pipeline', 'worktree', 'hold']);
+ expect(updateTask.mock.calls[0][1].metadata.pipeline.status).toBe('completed');
+ // PortOS opens the PR itself (`always`) and may auto-merge the branch.
+ expect(cleanupAgentWorktree).toHaveBeenCalledWith('a1', true, expect.objectContaining({
+ prCreation: 'always', skipMerge: false, agentOutput: 'out', originalTask: task,
+ }));
+ expect(releaseRetryHold).toHaveBeenCalledWith({ agentId: 'a1', task, success: true });
+ });
+
+ it('threads the resolved reviewer options through to the worktree cleanup', async () => {
+ resolveReviewLoopOptions.mockResolvedValueOnce({ reviewers: ['codex', 'antigravity'], reviewStopMode: 'on-clean', reviewerApplies: false });
+
+ await runSpawnerCompletionCleanup(spawnerArgs());
+
+ expect(cleanupAgentWorktree).toHaveBeenCalledWith('a1', true, expect.objectContaining({
+ prCreation: 'always', reviewers: ['codex', 'antigravity'], reviewStopMode: 'on-clean', reviewerApplies: false,
+ }));
+ });
+
+ // The hardening the TUI copy had and the CLI copy lacked: a reviewer-defaults
+ // read that throws must not skip the worktree cleanup and hold release behind
+ // it — that strands the worktree and leaves the task held until the orphan
+ // sweep notices.
+ it('still cleans the worktree and releases the hold when the reviewer resolve throws', async () => {
+ resolveReviewLoopOptions.mockRejectedValueOnce(new Error('settings unreadable'));
+ const args = spawnerArgs({ success: false });
+
+ await runSpawnerCompletionCleanup(args);
+
+ expect(cleanupAgentWorktree).toHaveBeenCalledWith('a1', false, expect.objectContaining({ prCreation: 'always' }));
+ expect(cleanupAgentWorktree.mock.calls[0][2]).not.toHaveProperty('reviewers');
+ expect(releaseRetryHold).toHaveBeenCalledWith({ agentId: 'a1', task: args.task, success: false });
+ });
+
+ // ...and a worktree cleanup that rejects must not either (#3373): the hold is
+ // released in a `finally`, not by the previous step's success.
+ it('releases the hold even when the worktree cleanup rejects', async () => {
+ cleanupAgentWorktree.mockRejectedValueOnce(new Error('git exploded'));
+ const args = spawnerArgs({ success: false });
+
+ await expect(runSpawnerCompletionCleanup(args)).resolves.toBeUndefined();
+
+ expect(releaseRetryHold).toHaveBeenCalledWith({ agentId: 'a1', task: args.task, success: false });
+ });
+
+ // The dominant path: a harness that opened and landed its own PR. Cleanup can
+ // spawn no follow-up, so the reviewer defaults are never even read.
+ it('skips the reviewer resolve for a run whose own PR claim finalize verified', async () => {
+ await runSpawnerCompletionCleanup(spawnerArgs({
+ prOwnership: { taskOpenPR: true, agentOwnsPR: true, prClaimExpected: true },
+ prClaimVerified: true,
+ }));
+
+ expect(resolveReviewLoopOptions).not.toHaveBeenCalled();
+ expect(cleanupAgentWorktree).toHaveBeenCalledWith('a1', true, expect.objectContaining({ prCreation: 'never', skipMerge: true }));
+ });
+});
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 5169d9b09c..12f040c2a4 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -87,11 +87,7 @@ import { resolveAgentProviderAndModel } from './agentProviderResolution.js';
import { cloudSwarmThreadCapacity, localEndpointOfProvider, providerBaseUrl } from './cosLocalEndpointSlots.js';
import { describeLocalPromptBudget, planLocalPromptBudget } from '../lib/localPromptBudget.js';
import { prepareAgentWorkspace } from './agentWorkspacePrep.js';
-// `releaseRetryHold` is imported STATICALLY here (the TUI/direct-CLI spawners
-// reach for it via `await import()` only because they sit BELOW this module and
-// a top-level import there would race the cycle) — this module already imports
-// `cleanupAgentWorktree` from the same file, so there is no new edge.
-import { cleanupAgentWorktree, releaseRetryHold } from './agentWorktreeCleanup.js';
+import { releaseRetryHold } from './agentWorktreeCleanup.js';
import { runAgentCompletionCleanup } from './agentCompletionCleanup.js';
import { dispatchRecoveredTaskOutputHook, finalizeAgent, releaseAgentLane, stampLiExecutionVerdict } from './agentFinalization.js';
import { extractFinalSummary } from './agentSummaryExtraction.js';
@@ -1039,7 +1035,6 @@ async function runAgentSpawn(task) {
agentDir,
executionId: toolExecution.id,
laneName,
- cleanupWorktreeFn: cleanupAgentWorktree,
isTruthyMetaFn: isTruthyMeta,
leanMode,
useDurableRunner: dispatchUseRunner,
@@ -1062,7 +1057,6 @@ async function runAgentSpawn(task) {
agentDir,
executionId: toolExecution.id,
laneName,
- cleanupWorktreeFn: cleanupAgentWorktree,
isTruthyMetaFn: isTruthyMeta,
safetyProfile,
});
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index e07ba47f75..6a537ba906 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -15,20 +15,19 @@ import { updateAgent } from './cosAgentLifecycle.js';
import { createOutputSpooler } from './agentTuiSpawning/outputSpooler.js';
import { resolveErrorAnalysis } from './agentTuiSpawning/finalizeHelpers.js';
import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';
+import { runSpawnerCompletionCleanup } from './agentCompletionCleanup.js';
import { activeAgents, userTerminatedAgents, pausedAgents, consumePausedAgentExit, registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';
import { PATHS, watchForFile } from '../lib/fileUtils.js';
import { resolveAgentCliCwd } from '../lib/spawnCwd.js';
import { doneSentinelName, doneSentinelPath as resolveDoneSentinelPath, parseSentinelPayload } from '../lib/agentSentinel.js';
import { shouldAbandonForHostShutdown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';
import { SENTINEL_COMPLETION_MARKER } from '../lib/agentOutputMarkers.js';
-import { PR_CREATION, prClaimWasVerified, resolvePrCompletion, resolvePrCreation, leavesPrForHuman } from '../lib/prDisposition.js';
-import { canTypeSlashCommands, agentOwnsPrWorkflow } from '../lib/slashdoInvocation.js';
+import { prClaimWasVerified, leavesPrForHuman } from '../lib/prDisposition.js';
+import { resolvePrOwnership } from '../lib/slashdoInvocation.js';
import { mergeGateOwed, resolveMergeGateVerdict, buildMergeGateReprompt } from '../lib/mergeGateContract.js';
import { probePrForBranch } from './prProbe.js';
import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
-import { normalizeReviewers } from '../lib/validation.js';
import * as git from './git.js';
-import { resolveReviewLoopOptions } from './codeReview.js';
import { spawnTuiSessionViaRunner, classifyRunnerSpawnFailure, RUNNER_SPAWN_REFUSED, RUNNER_SPAWN_AMBIGUOUS } from './cosRunnerClient.js';
import { resolveInteractiveShell } from '../lib/interactiveShellResolver.js';
import { formatShellCommandLine } from '../lib/shellCd.js';
@@ -666,7 +665,6 @@ export async function spawnTuiAgent({
agentDir,
executionId,
laneName,
- cleanupWorktreeFn,
isTruthyMetaFn,
leanMode = false,
useDurableRunner = false,
@@ -707,16 +705,26 @@ export async function spawnTuiAgent({
// → merge, whether or not it can type `/do:pr` (#3733) — a Claude TUI runs
// the slashdo command, codex/antigravity/grok/OpenCode run the plain
// `git`/`gh` equivalent from the same prompt. Only a lean `--bare` session
- // still hands the lifecycle back to PortOS. Computed once up front (rather
- // than inside finish()) so the merge-gate contract check below and finish()
- // itself read the same answer.
- const taskOpenPR = isTruthyMetaFn(task.metadata?.openPR);
- const agentOwnsPR = taskOpenPR && agentOwnsPrWorkflow({ providerType: PROVIDER_TYPES.TUI, leanMode });
+ // still hands the lifecycle back to PortOS. Resolved once up front (rather
+ // than inside finish()) so the merge-gate contract check below and the
+ // completion dispatch finish() hands off to read the same answer.
+ const prOwnership = resolvePrOwnership({
+ task,
+ isTruthyMeta: isTruthyMetaFn,
+ providerType: PROVIDER_TYPES.TUI,
+ providerId: provider?.id,
+ providerCommand: provider?.command,
+ leanMode,
+ });
// Does this run's own task shape say it owed a merge (#5876)? A run PortOS
// still backstops (no PR at all, or a lean session) or one whose prompt
// hands the PR to a human (JIRA, claim flow) never owed one, so the
// contract check below is inert for those — see mergeGateContract.js.
- const mergeGateIsOwed = mergeGateOwed({ taskOpenPR, ownsPrWorkflow: agentOwnsPR, leaveOpen: leavesPrForHuman(task) });
+ const mergeGateIsOwed = mergeGateOwed({
+ taskOpenPR: prOwnership.taskOpenPR,
+ ownsPrWorkflow: prOwnership.agentOwnsPR,
+ leaveOpen: leavesPrForHuman(task),
+ });
const promptPreview = prompt.replace(/\s+/g, ' ').slice(0, 100);
const commandName = tuiConfig.command.split('/').pop();
let finalized = false;
@@ -1125,20 +1133,11 @@ export async function spawnTuiAgent({
completionError: finalError,
});
- // `taskOpenPR` / `agentOwnsPR` are computed once, up front, near
- // `doneSentinelPath` — the merge-gate contract check above reads the same
- // answer this cleanup path does, so neither side can believe the other
- // owns the PR (#3733).
- const taskReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);
- // …but PR-claim verification (#3358) stays keyed on the SLASH-command
- // predicate. A run PortOS still backstops (it re-checks the forge at cleanup
- // and opens the PR itself when the agent skipped it) must not be failed here
- // for a PR that is about to exist — finalize runs before that net.
- const prClaimExpected = taskOpenPR && canTypeSlashCommands({
- providerId: provider?.id,
- providerCommand: provider?.command,
- leanMode,
- });
+ // `prOwnership` was resolved once, up front, near `doneSentinelPath`, so the
+ // merge-gate contract check above and the completion dispatch below read the
+ // same answer (#3733); see `resolvePrOwnership` for why finalize's
+ // `prClaimExpected` and cleanup's `agentOwnsPR` are two predicates (#3358).
+ //
// Whether finalize's check ACTUALLY produced a forge answer, filled in from
// its return below. Deliberately not `prClaimExpected`: finalize substitutes
// `{ok:true}` for a user-terminated run and for a check that threw, and a
@@ -1148,10 +1147,10 @@ export async function spawnTuiAgent({
let noChangesToShip = false;
// try/finally so a throw from finalizeAgent (e.g. processAgentCompletion
- // hook crash) still runs the local cleanup — sentinel removal, worktree
- // cleanup, pid unregister, activeAgents delete, session kill. Without
- // this, a memory-extraction crash would strand the worktree and the
- // shell session on disk.
+ // hook crash) still runs the local cleanup — sentinel removal, the shared
+ // completion dispatch (pipeline, worktree, retry hold), pid unregister,
+ // activeAgents delete, session kill. Without this, a memory-extraction
+ // crash would strand the worktree and the shell session on disk.
// The verdict finalizeAgent actually persisted. A PR-claim downgrade (#3358)
// must reach cleanup too — cleaning up as a success removes the worktree and
// deletes the local branch, destroying the state the retry needs. Left at
@@ -1174,7 +1173,7 @@ export async function spawnTuiAgent({
error: finalError || undefined,
completionReason: reason,
workspacePath: cwd,
- prExpected: prClaimExpected,
+ prExpected: prOwnership.prClaimExpected,
// The run window the commit criterion is evaluated against (#3637).
startedAt: agentData?.startedAt ?? null,
});
@@ -1186,38 +1185,19 @@ export async function spawnTuiAgent({
// its own file and may still be running.
if (doneSentinelPath) await rm(doneSentinelPath).catch(() => {});
- const prCreation = resolvePrCreation({ taskOpenPR, agentOwnsPr: agentOwnsPR, prClaimVerified, noChangesToShip });
- // Only the two modes that can still open a PR (and thus spawn a follow-up
- // that needs these) pay for the resolve. `never` — the dominant path, an
- // agent that opened and landed its own PR — discards them.
- const reviewOptions = prCreation !== PR_CREATION.NEVER
- ? await resolveReviewLoopOptions(task.metadata, { normalize: normalizeReviewers, isTruthyMeta: isTruthyMetaFn })
- .catch(err => {
- emitLog('warn', `TUI review options unavailable for ${agentId}: ${err.message}`, { agentId });
- return {};
- })
- : {};
- await cleanupWorktreeFn(agentId, cleanupSuccess, {
- prCreation,
- prCompletion: resolvePrCompletion(task.metadata),
- ...reviewOptions,
- skipMerge: taskReviewLoopFollowUp || agentOwnsPR,
- description: task.description,
- agentOutput: getOutputBuffer(),
- originalTask: task
- }).catch(err => emitLog('warn', `TUI worktree cleanup failed for ${agentId}: ${err.message}`, { agentId }));
-
- // Release the retry hold: flip the failed task back to `pending` carrying a
- // pointer at whatever the run left behind — the branch (or whole worktree)
- // `cleanupWorktreeFn` just preserved because the run failed with commits on
- // it. Without the pointer the retry starts clean and redoes work already
- // sitting on disk (#3368); without the hold that release replaces, the retry
- // could be dequeued before the pointer landed (#3373). Imported lazily for the
- // same reason `cleanupWorktreeFn` is injected: pulling the cleanup graph in at
- // module top level races this file's own init in the agentLifecycle cycle.
- await import('./agentWorktreeCleanup.js')
- .then(({ releaseRetryHold }) => releaseRetryHold({ agentId, task, success: cleanupSuccess }))
- .catch(err => emitLog('warn', `TUI retry-hold release failed for ${agentId}: ${err.message}`, { agentId }));
+ // Pipeline progression → worktree cleanup with the PR disposition →
+ // retry-hold release, in the one owner both in-process spawners share.
+ // Caught so a throw there cannot skip the in-memory teardown below — this
+ // runs off a PTY exit, outside any request lifecycle.
+ await runSpawnerCompletionCleanup({
+ agentId,
+ task,
+ success: cleanupSuccess,
+ prOwnership,
+ prClaimVerified,
+ noChangesToShip,
+ outputBuffer: getOutputBuffer(),
+ }).catch(err => emitLog('warn', `TUI completion cleanup failed for ${agentId}: ${err.message}`, { agentId }));
if (agentData?.pid) unregisterSpawnedAgent(agentData.pid);
activeAgents.delete(agentId);
@@ -1230,7 +1210,7 @@ export async function spawnTuiAgent({
*
* Deliberately NOT `finish()`: finalizing here would record an outcome for a
* run that never reached one, and its cleanup path removes the `.agent-done`
- * sentinel and hands the worktree to `cleanupWorktreeFn` — destroying exactly
+ * sentinel and hands the worktree to `cleanupAgentWorktree` — destroying exactly
* the state a resume needs. So this only stops the machinery and flushes what
* was captured; the agent record stays `running` and the worktree stays on
* disk. The next boot's orphan sweep reads the host-shutdown marker, sees this
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index 10db2ce24d..39108712b1 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -123,11 +123,15 @@ vi.mock('./prProbe.js', () => ({
probePrForBranch: vi.fn().mockResolvedValue({ prState: null, prUrl: null, prNumber: null, cli: null, readable: true }),
}));
-// Lazily imported by finish()'s cleanup block to record a failed run's resume
-// pointer (#3368). Mocked so the test doesn't pull the real cleanup graph
-// (cos.js, worktreeManager, recoveryTasks) in behind it.
-vi.mock('./agentWorktreeCleanup.js', () => ({
- releaseRetryHold: vi.fn().mockResolvedValue({}),
+// finish() hands the run to the shared completion dispatch (pipeline
+// progression → worktree cleanup with the PR disposition → retry-hold release).
+// Doubled at that boundary: what this suite owns is that the TUI path dispatches
+// with the right verdict and PR ownership, and only when it should — the
+// dispatch's own sequence is pinned in agentCompletionCleanup.test.js. Mocking
+// it also keeps the real cleanup graph (cos.js, worktreeManager, recoveryTasks)
+// out of this suite.
+vi.mock('./agentCompletionCleanup.js', () => ({
+ runSpawnerCompletionCleanup: vi.fn().mockResolvedValue(undefined),
}));
vi.mock('fs', () => ({
@@ -234,7 +238,7 @@ import {
PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE,
PUBLIC_REVIEW_GATE_EXECUTION_PROFILE,
} from '../lib/agentExecutionProfiles.js';
-import { releaseRetryHold } from './agentWorktreeCleanup.js';
+import { runSpawnerCompletionCleanup } from './agentCompletionCleanup.js';
import { spawnTuiSessionViaRunner, RUNNER_SPAWN_REFUSED, RUNNER_SPAWN_AMBIGUOUS } from './cosRunnerClient.js';
import * as shellService from './shell.js';
import * as agentLifecycle from './agentFinalization.js';
@@ -640,10 +644,7 @@ describe('spawnTuiAgent runtime', () => {
const agentDir = overrides.agentDir ?? '/tmp/agentdir';
const executionId = overrides.executionId ?? null;
const laneName = overrides.laneName ?? null;
- const helpers = overrides.helpers ?? {
- cleanupWorktreeFn: vi.fn().mockResolvedValue(undefined),
- isTruthyMetaFn: (v) => !!v
- };
+ const helpers = overrides.helpers ?? { isTruthyMetaFn: (v) => !!v };
return spawnTuiAgent({
agentId,
task,
@@ -941,34 +942,35 @@ describe('spawnTuiAgent runtime', () => {
await completeDone;
});
- it('backstops a slashdo-free TUI PR instead of creating one outright (#3733)', async () => {
- const cleanupWorktreeFn = vi.fn().mockResolvedValue(undefined);
+ it('hands a slashdo-free TUI to the dispatch as owning its PR with nothing verified (#3733)', async () => {
+ const task = {
+ id: 'task-1',
+ description: 'do the thing',
+ metadata: { openPR: true, prCompletion: 'review-then-merge', reviewers: ['codex'] },
+ };
const spawnPromise = runSpawn({
provider: { id: 'codex-tui', name: 'Codex TUI', type: 'tui', command: 'codex', envVars: {} },
- task: {
- id: 'task-1',
- description: 'do the thing',
- metadata: { openPR: true, prCompletion: 'review-then-merge', reviewers: ['codex'] },
- },
- helpers: { cleanupWorktreeFn, isTruthyMetaFn: (value) => value === true || value === 'true' },
+ task,
+ helpers: { isTruthyMetaFn: (value) => value === true || value === 'true' },
});
await flushMicrotasks();
await capturedOnExit({ exitCode: 0, killed: false });
await spawnPromise;
- // The codex TUI drives its own push → PR → review → merge, so PortOS only
- // steps in when the forge says no PR exists — hence prCreation: if-missing.
- expect(cleanupWorktreeFn).toHaveBeenCalledWith('agent-1', true, expect.objectContaining({
- prCreation: 'if-missing',
- prCompletion: 'review-then-merge',
- reviewers: ['codex'],
- skipMerge: true,
+ // The codex TUI drives its own push → PR → review → merge but cannot type
+ // `/do:pr`, so finalize verified no claim — the dispatch maps that to a
+ // forge-checked `if-missing` backstop (pinned in agentCompletionCleanup.test.js).
+ expect(runSpawnerCompletionCleanup).toHaveBeenCalledWith(expect.objectContaining({
+ agentId: 'agent-1',
+ task,
+ success: true,
+ prOwnership: { taskOpenPR: true, agentOwnsPR: true, prClaimExpected: false },
+ prClaimVerified: false,
}));
});
it('a lean --bare TUI still hands its PR to PortOS outright', async () => {
- const cleanupWorktreeFn = vi.fn().mockResolvedValue(undefined);
const spawnPromise = runSpawn({
provider: { id: 'claude-ollama-tui', name: 'Lean Claude TUI', type: 'tui', command: 'claude', ollamaBacked: true, envVars: {} },
leanMode: true,
@@ -977,16 +979,17 @@ describe('spawnTuiAgent runtime', () => {
description: 'do the thing',
metadata: { openPR: true, prCompletion: 'review-then-merge' },
},
- helpers: { cleanupWorktreeFn, isTruthyMetaFn: (value) => value === true || value === 'true' },
+ helpers: { isTruthyMetaFn: (value) => value === true || value === 'true' },
});
await flushMicrotasks();
await capturedOnExit({ exitCode: 0, killed: false });
await spawnPromise;
- expect(cleanupWorktreeFn).toHaveBeenCalledWith('agent-1', true, expect.objectContaining({
- prCreation: 'always',
- skipMerge: false,
+ // Neither predicate holds for a `--bare` session, so the dispatch opens the
+ // PR itself (`always`) and may auto-merge the branch.
+ expect(runSpawnerCompletionCleanup).toHaveBeenCalledWith(expect.objectContaining({
+ prOwnership: { taskOpenPR: true, agentOwnsPR: false, prClaimExpected: false },
}));
});
@@ -1008,7 +1011,6 @@ describe('spawnTuiAgent runtime', () => {
});
it('does not double-fire a PR owned by a slashdo-capable Claude TUI', async () => {
- const cleanupWorktreeFn = vi.fn().mockResolvedValue(undefined);
// finalize asked the forge and got an answer for a real branch — the only
// shape that lets cleanup skip its own query (see `prClaimWasVerified`).
vi.mocked(agentLifecycle.finalizeAgent).mockResolvedValueOnce({
@@ -1021,52 +1023,39 @@ describe('spawnTuiAgent runtime', () => {
description: 'do the thing',
metadata: { openPR: true, prCompletion: 'review-then-merge' },
},
- helpers: { cleanupWorktreeFn, isTruthyMetaFn: (value) => value === true || value === 'true' },
+ helpers: { isTruthyMetaFn: (value) => value === true || value === 'true' },
});
await flushMicrotasks();
await capturedOnExit({ exitCode: 0, killed: false });
await spawnPromise;
- // `never`, not `if-missing`: finalize already ran `verifyPrClaim` for a
- // slashdo-capable session, so a second forge query would be pure duplication.
- expect(cleanupWorktreeFn).toHaveBeenCalledWith('agent-1', true, expect.objectContaining({
- prCreation: 'never',
- prCompletion: 'review-then-merge',
- skipMerge: true,
+ // finalize ran `verifyPrClaim` for a slashdo-capable session and the verdict
+ // reaches the dispatch as verified, so it never queries the forge again.
+ expect(runSpawnerCompletionCleanup).toHaveBeenCalledWith(expect.objectContaining({
+ prOwnership: { taskOpenPR: true, agentOwnsPR: true, prClaimExpected: true },
+ prClaimVerified: true,
}));
});
- // A failed TUI run's branch is preserved by cleanup when it holds commits; without
- // this call nothing ever points the retry at it and the work is redone from
- // scratch (#3368). Runs after cleanup so it reflects what actually survived.
- it('records a resume pointer after cleanup when the run failed', async () => {
- vi.mocked(releaseRetryHold).mockClear();
- const cleanupWorktreeFn = vi.fn().mockResolvedValue(undefined);
+ // The dispatch releases the retry hold with this verdict (#3368 — its ordering
+ // after worktree cleanup is pinned in agentCompletionCleanup.test.js). What
+ // this pins is that finish() hands it the REAL verdict: a hardcoded value
+ // would stamp resume pointers on every completed run, or on none.
+ it('hands the dispatch the run verdict — failure on a non-zero exit, success on a clean one', async () => {
const task = { id: 'task-1', description: 'do the thing', metadata: {} };
- const spawnPromise = runSpawn({ task, helpers: { cleanupWorktreeFn, isTruthyMetaFn: (v) => !!v } });
+ const failed = runSpawn({ task });
await flushMicrotasks();
-
await capturedOnExit({ exitCode: 1, killed: false });
- await spawnPromise;
-
- expect(releaseRetryHold).toHaveBeenCalledWith({ agentId: 'agent-1', task, success: false });
- expect(cleanupWorktreeFn.mock.invocationCallOrder[0])
- .toBeLessThan(vi.mocked(releaseRetryHold).mock.invocationCallOrder[0]);
- });
+ await failed;
+ expect(runSpawnerCompletionCleanup).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'agent-1', task, success: false }));
- // The helper no-ops on success (unit-tested in cleanupAgentWorktree.test.js) —
- // what this pins is that finish() hands it the real verdict, not a hardcoded
- // false that would stamp pointers on every completed run.
- it('passes the success verdict through on a clean run', async () => {
- vi.mocked(releaseRetryHold).mockClear();
- const spawnPromise = runSpawn({ helpers: { cleanupWorktreeFn: vi.fn().mockResolvedValue(undefined), isTruthyMetaFn: (v) => !!v } });
+ vi.mocked(runSpawnerCompletionCleanup).mockClear();
+ const clean = runSpawn();
await flushMicrotasks();
-
await capturedOnExit({ exitCode: 0, killed: false });
- await spawnPromise;
-
- expect(releaseRetryHold).toHaveBeenCalledWith(expect.objectContaining({ success: true }));
+ await clean;
+ expect(runSpawnerCompletionCleanup).toHaveBeenCalledWith(expect.objectContaining({ success: true }));
});
// ── CoS agents stay alive while provider output is silent ────────────────────
@@ -2492,14 +2481,13 @@ describe('spawnTuiAgent runtime', () => {
// Reported in #3202: `pm2 restart portos-server` TreeKills the agent's PTY.
// node-pty reports that as exit code 0, so `success: code === 0 && !killed`
// recorded a run that had produced nothing as SUCCESSFUL — and worse, finalize
- // handed the worktree to cleanupWorktreeFn, destroying the state a resume
- // needs. Both halves are asserted here.
+ // handed the worktree to cleanup, destroying the state a resume needs. Both
+ // halves are asserted here.
describe('host restart (#3202)', () => {
afterEach(() => resetHostShutdownFlagForTests());
it('abandons instead of finalizing when the PTY dies during shutdown', async () => {
- const cleanupWorktreeFn = vi.fn().mockResolvedValue(undefined);
- const spawnPromise = runSpawn({ helpers: { cleanupWorktreeFn, isTruthyMetaFn: (v) => !!v } });
+ const spawnPromise = runSpawn();
await flushMicrotasks();
markHostShuttingDown();
@@ -2510,7 +2498,7 @@ describe('spawnTuiAgent runtime', () => {
// No outcome recorded, and — critically — the worktree is left alone.
expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();
- expect(cleanupWorktreeFn).not.toHaveBeenCalled();
+ expect(runSpawnerCompletionCleanup).not.toHaveBeenCalled();
// The record stays `running`; only the phase label is refined, so boot
// recovery still sees it as an agent to reconcile from the marker.
expect(vi.mocked(cosAgentLifecycle.updateAgent).mock.calls.some(
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index 25ab23bef3..a29adefc15 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -757,8 +757,9 @@ export async function recordTaskResumePointer({ task, agentId, agentMetadata })
* agent that began the shipped work over.
*
* Call this AFTER `cleanupAgentWorktree` so it reflects what actually survived, and
- * from all three spawn sites — `spawnDirectly` (agentCliSpawning.js), the TUI
- * `finish()` (agentTuiSpawning.js), and `handleAgentCompletion`
+ * from all three completion paths — the two in-process spawners (`spawnDirectly` in
+ * agentCliSpawning.js and the TUI `finish()` in agentTuiSpawning.js, both through
+ * `runSpawnerCompletionCleanup`) and `handleAgentCompletion`
* (agentCompletionCleanup.js, runner mode). Only the runner path used to do it, so a
* failed direct-CLI/TUI run left a branch full of commits nothing would ever point a
* retry at.