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

fix: preserve app checkout recovery lifecycle ownership (#10071)

[._.]/ Adam Eivyb1bd40bd8fe5
diff --git a/client/src/components/apps/tabs/GitRecoveryAction.jsx b/client/src/components/apps/tabs/GitRecoveryAction.jsx
index 82fda379fe..15fed4333f 100644
--- a/client/src/components/apps/tabs/GitRecoveryAction.jsx
+++ b/client/src/components/apps/tabs/GitRecoveryAction.jsx
@@ -40,7 +40,7 @@ Finally fetch again and verify the actual app checkout is on the default branch,
provider: selection.providerId || activeProviderId,
model: selection.model || undefined,
effort: selection.effort || undefined,
- whenDone: 'commit-push',
+ workflow: 'app-checkout-recovery',
useWorktree: false,
openPR: false,
autoApprove: true,
diff --git a/client/src/components/apps/tabs/RepositorySourcePanel.test.jsx b/client/src/components/apps/tabs/RepositorySourcePanel.test.jsx
index 922d32856b..8f9367288c 100644
--- a/client/src/components/apps/tabs/RepositorySourcePanel.test.jsx
+++ b/client/src/components/apps/tabs/RepositorySourcePanel.test.jsx
@@ -438,6 +438,6 @@ describe('PortOS self-update restart handoff', () => {
fireEvent.change(screen.getByLabelText('Model'), { target: { value: 'example-model' } });
fireEvent.click(start);
await screen.findByRole('link', { name: 'Recovery queued · View agents' });
- expect(api.addCosTask).toHaveBeenCalledWith(expect.objectContaining({ app: 'app-example', provider: 'example-cli', model: 'example-model', useWorktree: false, openPR: false, whenDone: 'commit-push', prompt: expect.stringMatching(/including untracked files and the index[\s\S]*never an acceptable resting place[\s\S]*empty stash list/) }), { silent: true });
+ expect(api.addCosTask).toHaveBeenCalledWith(expect.objectContaining({ app: 'app-example', provider: 'example-cli', model: 'example-model', useWorktree: false, openPR: false, workflow: 'app-checkout-recovery', prompt: expect.stringMatching(/including untracked files and the index[\s\S]*never an acceptable resting place[\s\S]*empty stash list/) }), { silent: true });
expect(useAppOperation().startUpdate).not.toHaveBeenCalled();
});
diff --git a/server/lib/agentCompletionMode.js b/server/lib/agentCompletionMode.js
index bd81e30f69..72d0780e9d 100644
--- a/server/lib/agentCompletionMode.js
+++ b/server/lib/agentCompletionMode.js
@@ -71,6 +71,8 @@ export const COMPLETION_MODES = Object.freeze({
AUDIT_FLOW: 'audit-flow',
/** Reconciliation owns delivery of named branches, never the coordinator checkout. */
RECONCILE_FLOW: 'reconcile-flow',
+ /** Recovery owns preservation and reconciliation of the actual app checkout. */
+ CHECKOUT_RECOVERY: 'checkout-recovery',
/** TUI host that cannot type a `/do:*` command — commit, then hand off. */
TUI_SLASHDO_FREE: 'tui-slashdo-free',
/** TUI host that drives its own `/do:pr` | `/do:push` completion workflow. */
@@ -116,6 +118,7 @@ const COMPLETION_MODE_RULES = Object.freeze([
[COMPLETION_MODES.REVIEW_LOOP_FOLLOW_UP, (f) => f.isReviewLoopFollowUp],
[COMPLETION_MODES.RELEASE_FLOW, (f) => f.slashdoCommand === 'release'],
[COMPLETION_MODES.AUDIT_FLOW, (f) => ['better', 'better-swift'].includes(f.slashdoCommand)],
+ [COMPLETION_MODES.CHECKOUT_RECOVERY, (f) => f.taskHookType === 'app-checkout-recovery'],
[COMPLETION_MODES.RECONCILE_FLOW, (f) => f.taskHookType === 'branch-reconcile'],
[COMPLETION_MODES.TUI_SLASHDO_FREE, (f) => f.isTui && !f.canRunSlashCommands],
[COMPLETION_MODES.TUI, (f) => f.isTui],
diff --git a/server/lib/agentCompletionMode.test.js b/server/lib/agentCompletionMode.test.js
index 6070ff62a6..3366dd3b1e 100644
--- a/server/lib/agentCompletionMode.test.js
+++ b/server/lib/agentCompletionMode.test.js
@@ -83,6 +83,7 @@ describe('resolveCompletionMode', () => {
resolveCompletionMode({ slashdoCommand: 'release' }),
resolveCompletionMode({ slashdoCommand: 'better' }),
resolveCompletionMode({ taskHookType: 'branch-reconcile' }),
+ resolveCompletionMode({ taskHookType: 'app-checkout-recovery' }),
resolveCompletionMode({ isTui: true, canRunSlashCommands: false }),
resolveCompletionMode({ isTui: true }),
resolveCompletionMode({ worktreeInfo: wt, willOpenPR: false }),
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index 89f95a8d23..6bf2b8ae52 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -242,6 +242,8 @@ export const createCosTaskSchema = z.object({
v => v === 'true' ? true : v === 'false' ? false : v,
z.boolean().optional()
),
+ // A self-managed recovery of the configured checkout, rather than CoS delivery.
+ workflow: z.enum(['app-checkout-recovery']).optional(),
whenDone: z.enum(['commit-push', 'leave-uncommitted']).optional(),
// Read-only planning mode: investigate the codebase and file the issue, but
// do not start implementation delivery. The task store expands this into
diff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.js
index 3fa8027c68..e6bb9a2355 100644
--- a/server/services/agentCompletionCleanup.js
+++ b/server/services/agentCompletionCleanup.js
@@ -27,6 +27,7 @@
* import it at top level.
*/
+import { resolveTaskHookType } from './taskTypeHooks.js';
import { join, relative, resolve, sep } from 'path';
import { unlink, rm } from 'fs/promises';
import { emitLog } from './cosEvents.js';
@@ -392,6 +393,7 @@ function resolveRunnerPrOwnership({ task, agent, agentState }) {
}
async function completeJiraHandOff({ agentId, task, agentState, effectiveSuccess, outputBuffer }) {
+ if (resolveTaskHookType(task) === 'app-checkout-recovery') return;
// JIRA integration: push branch, create PR, comment on ticket
const jiraTicketId = task?.metadata?.jiraTicketId;
const jiraBranch = task?.metadata?.jiraBranch;
@@ -546,6 +548,9 @@ export async function removeCompletionSentinel({ agentId, agent, agentState }) {
}
async function completeWorktreeCleanup({ agentId, task, effectiveSuccess, prOwnership, outputBuffer, prClaimVerified, branchProvenEmpty }) {
+ // This task owns the actual checkout and its preservation branches.
+ // No CoS coordinator worktree exists to publish, merge, or remove.
+ if (resolveTaskHookType(task) === 'app-checkout-recovery') return;
if (task?.metadata?.jiraBranch) return;
return cleanupAgentWorktree(agentId, effectiveSuccess, await resolveWorktreeCleanupOptions({
agentId, task, outputBuffer,
diff --git a/server/services/agentCompletionCleanup.test.js b/server/services/agentCompletionCleanup.test.js
index 1239ed9adf..488d4a3a3d 100644
--- a/server/services/agentCompletionCleanup.test.js
+++ b/server/services/agentCompletionCleanup.test.js
@@ -520,6 +520,85 @@ describe('runSpawnerCompletionCleanup — the in-process spawners\' dispatch', (
...overrides,
});
+ it('leaves recovery-owned preservation and publication to the agent even with stale delivery flags', async () => {
+ const task = { id: 't', taskType: 'user', description: 'recover checkout', metadata: {
+ analysisType: 'app-checkout-recovery', openPR: true,
+ jiraTicketId: 'EX-1', jiraBranch: 'preserved-work', jiraCreatePR: true,
+ } };
+ await runSpawnerCompletionCleanup(spawnerArgs({ task }));
+ expect(cleanupAgentWorktree).not.toHaveBeenCalled();
+ expect(git.push).not.toHaveBeenCalled();
+ expect(git.createPR).not.toHaveBeenCalled();
+ });
+
+ // Real Git preservation/checkout fixture; forge publication is a controlled
+ // adapter so this regression never touches a live repo or external account.
+ it('preserves an existing unique commit on a published PR branch and leaves the live checkout current', async () => {
+ const { execFileSync } = await import('node:child_process');
+ const { mkdtempSync, writeFileSync, rmSync } = await import('node:fs');
+ const { tmpdir } = await import('node:os');
+ const { join } = await import('node:path');
+ const root = mkdtempSync(join(tmpdir(), 'portos-checkout-recovery-'));
+ const remote = join(root, 'origin.git');
+ const checkout = join(root, 'checkout');
+ const writer = join(root, 'remote-writer');
+ const runGit = (cwd, ...args) => execFileSync('git', ['-C', cwd, ...args], {
+ encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'],
+ env: { ...process.env, GIT_AUTHOR_NAME: 'Fixture', GIT_COMMITTER_NAME: 'Fixture',
+ GIT_AUTHOR_EMAIL: '[email protected]', GIT_COMMITTER_EMAIL: '[email protected]' },
+ }).trim();
+ try {
+ runGit(root, 'init', '--bare', '--initial-branch=main', remote);
+ runGit(root, 'clone', remote, checkout);
+ writeFileSync(join(checkout, 'base.txt'), 'base');
+ runGit(checkout, 'add', 'base.txt');
+ runGit(checkout, 'commit', '-m', 'fixture base');
+ runGit(checkout, 'push', 'origin', 'main');
+ runGit(root, 'clone', remote, writer);
+ writeFileSync(join(checkout, 'unique.txt'), 'unique pending work');
+ runGit(checkout, 'add', 'unique.txt');
+ runGit(checkout, 'commit', '-m', 'fixture unique work');
+ const unique = runGit(checkout, 'rev-parse', 'HEAD');
+ writeFileSync(join(writer, 'remote.txt'), 'remote advancement');
+ runGit(writer, 'add', 'remote.txt');
+ runGit(writer, 'commit', '-m', 'fixture remote advance');
+ runGit(writer, 'push', 'origin', 'main');
+ const latest = runGit(writer, 'rev-parse', 'HEAD');
+ runGit(checkout, 'update-ref', 'refs/backup/recovery-original', unique);
+ expect(runGit(checkout, 'rev-parse', 'refs/backup/recovery-original')).toBe(unique);
+ runGit(checkout, 'switch', '-c', 'recovery/preserved-work');
+ runGit(checkout, 'push', 'origin', 'recovery/preserved-work');
+ const forge = { createPR: vi.fn(async head => {
+ // The fake forge admits only a branch already present on origin.
+ expect(runGit(remote, 'rev-parse', `refs/heads/${head}`)).toBe(unique);
+ return { state: 'OPEN', head, url: 'https://example.invalid/pull/1' };
+ }) };
+ const pr = await forge.createPR('recovery/preserved-work');
+ expect(pr.state).toBe('OPEN');
+ runGit(checkout, 'fetch', 'origin', 'main');
+ // Move only the accounted-for default branch; the original commit is
+ // verified on both the backup ref and the published preservation ref.
+ runGit(checkout, 'branch', '-f', 'main', 'origin/main');
+ runGit(checkout, 'switch', 'main');
+ const task = { id: 't', taskType: 'user', metadata: {
+ analysisType: 'app-checkout-recovery', useWorktree: false, openPR: false,
+ } };
+ await runSpawnerCompletionCleanup(spawnerArgs({ task,
+ prOwnership: { taskOpenPR: false, agentOpensOwnPr: false },
+ }));
+ expect(cleanupAgentWorktree).not.toHaveBeenCalled();
+ expect(git.push).not.toHaveBeenCalled();
+ expect(git.createPR).not.toHaveBeenCalled();
+ expect(runGit(checkout, 'branch', '--show-current')).toBe('main');
+ expect(runGit(checkout, 'status', '--porcelain')).toBe('');
+ expect(runGit(checkout, 'stash', 'list')).toBe('');
+ expect(runGit(checkout, 'rev-parse', 'HEAD')).toBe(latest);
+ expect(runGit(remote, 'rev-parse', 'refs/heads/recovery/preserved-work')).toBe(unique);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
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'); });
diff --git a/server/services/agentFinalization.successCriteria.test.js b/server/services/agentFinalization.successCriteria.test.js
index 45e98e8a24..9f29236f54 100644
--- a/server/services/agentFinalization.successCriteria.test.js
+++ b/server/services/agentFinalization.successCriteria.test.js
@@ -462,7 +462,7 @@ describe('evaluateSuccessCriteria — gh/git coordinator exemption (#2696)', ()
it('declares NO commit criterion for every non-committing coordinator type', async () => {
// The structurally-no-commit coordinators: they run in the live checkout and deliver a
// git/gh/external side effect, never a commit.
- for (const analysisType of ['branch-reconcile', 'issue-reconcile', 'branch-cleanup', 'jira-status-report']) {
+ for (const analysisType of ['app-checkout-recovery', 'branch-reconcile', 'issue-reconcile', 'branch-cleanup', 'jira-status-report']) {
const task = { id: 't1', taskType: 'internal', metadata: { analysisType } };
expect(await evaluateSuccessCriteria({ task, workspacePath: '/w', success: true })).toBeNull();
}
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 00fb73ed9b..031091c05a 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -42,6 +42,7 @@ import {
claimResumeContext,
buildReleaseFlowCompletionSection,
buildReconcileFlowCompletionSection,
+ buildCheckoutRecoveryCompletionSection,
buildAuditFlowCompletionSection,
buildCliCompletionSection,
buildCompletionGuidelineBullet,
@@ -515,7 +516,7 @@ You are working in an **isolated git worktree** to avoid conflicts with other ag
- **Worktree Path**: \`${worktreeInfo.worktreePath}\`
${worktreeInfo.baseBranch ? `- **Based on**: \`${worktreeInfo.baseBranch}\` (latest from origin)` : ''}
-**Important**: ${worktreeCommitNote} ${[COMPLETION_MODES.RELEASE_FLOW, COMPLETION_MODES.AUDIT_FLOW, COMPLETION_MODES.RECONCILE_FLOW].includes(completionMode) ? 'Follow the bundled workflow branch instructions while preserving unrelated work.' : 'Do NOT manually switch branches or modify the worktree configuration.'}
+**Important**: ${worktreeCommitNote} ${[COMPLETION_MODES.RELEASE_FLOW, COMPLETION_MODES.AUDIT_FLOW, COMPLETION_MODES.RECONCILE_FLOW, COMPLETION_MODES.CHECKOUT_RECOVERY].includes(completionMode) ? 'Follow the bundled workflow branch instructions while preserving unrelated work.' : 'Do NOT manually switch branches or modify the worktree configuration.'}
${buildResumeSection(task, worktreeInfo)}` : '';
const simplifySection = buildSimplifySection({
@@ -554,6 +555,7 @@ ${buildResumeSection(task, worktreeInfo)}` : '';
}),
[COMPLETION_MODES.AUDIT_FLOW]: () => buildAuditFlowCompletionSection({ isTui, sentinelPath }),
[COMPLETION_MODES.RECONCILE_FLOW]: () => buildReconcileFlowCompletionSection({ sentinelPath }),
+ [COMPLETION_MODES.CHECKOUT_RECOVERY]: () => buildCheckoutRecoveryCompletionSection({ sentinelPath }),
[COMPLETION_MODES.RELEASE_FLOW]: () => buildReleaseFlowCompletionSection({ isTui, sentinelPath }),
}[completionMode] || (() => ''))();
const tuiCompletionSection = [completionSection, buildAuditOutputCompletionSection(task, sentinelPath)]
@@ -588,7 +590,7 @@ ${buildResumeSection(task, worktreeInfo)}` : '';
issueFilingSection, simplifySection, tuiCompletionSection,
reviewLoopSection, reviewLoopFollowUpSection, compactionSection, skillSection,
toolsSection, planningContextSection, uiAuditRuntimeSection,
- completionBullet, completionInstructions, noChangeSuccess,
+ completionBullet, completionInstructions, noChangeSuccess, completionMode,
});
}
@@ -660,7 +662,7 @@ function buildSimplifySection({
? 'run `/simplify` to review the changed code for reuse, quality, and efficiency'
: SIMPLIFY_INLINE_REVIEW;
// Discard tasks don't commit, so the simplify-before-commit step is moot.
- const simplifySection = ![COMPLETION_MODES.RELEASE_FLOW, COMPLETION_MODES.AUDIT_FLOW, COMPLETION_MODES.RECONCILE_FLOW].includes(mode) && simplifyEnabled && !isTui && !discardWorktree && !claimFlow ? `
+ const simplifySection = ![COMPLETION_MODES.RELEASE_FLOW, COMPLETION_MODES.AUDIT_FLOW, COMPLETION_MODES.RECONCILE_FLOW, COMPLETION_MODES.CHECKOUT_RECOVERY].includes(mode) && simplifyEnabled && !isTui && !discardWorktree && !claimFlow ? `
## Simplify Step
After completing your work and before committing, ${simplifyInstruction}. Fix any issues found, then ${worktreeInfo && willOpenPR ? 'commit your changes (do NOT push — on a successful run the system will push and open the PR after you exit; if the run fails, no push or PR happens)' : portosMergesBranch ? 'commit your changes (do NOT push — PortOS merges this branch back into the source checkout after you exit; a pushed copy would only be left behind on origin)' : 'commit and push using `/do:push`'}.
` : '';
@@ -790,7 +792,7 @@ function buildFullAgentPrompt({
issueFilingSection, simplifySection, tuiCompletionSection,
reviewLoopSection, reviewLoopFollowUpSection, compactionSection, skillSection,
toolsSection, planningContextSection, uiAuditRuntimeSection,
- completionBullet, completionInstructions, noChangeSuccess,
+ completionBullet, completionInstructions, noChangeSuccess, completionMode,
}) {
const taskBlock = buildTaskBlock(task, { screenshotsAsList: false });
@@ -831,9 +833,10 @@ ${skillSection ? `## Task-Type Skill Guidelines\n\n${skillSection}\n` : ''}${too
${completionBullet}
## Git Hygiene (CRITICAL)
-- **Before starting work**, run \`git status\` to verify a clean working tree. Do NOT stash or discard uncommitted changes — other agents may be working concurrently and expecting those changes to be present. If the tree is dirty, only commit files YOU changed for this task.
+${completionMode === COMPLETION_MODES.CHECKOUT_RECOVERY ? `- Inspect pending work and active ownership before changing the checkout. Account for pre-existing unique work only within this recovery task's scope, with verified backups and explicit preservation branches. Stage specific files; never use \`git add -A\` or \`git add .\`.
+- Never create or pop a stash. Inspect existing stashes and retire only entries accounted for by SHA after publication or proven redundancy; preserve every unaccounted entry and active owner's work.` : `- **Before starting work**, run \`git status\` to verify a clean working tree. Do NOT stash or discard uncommitted changes — other agents may be working concurrently and expecting those changes to be present. If the tree is dirty, only commit files YOU changed for this task.
- **NEVER use \`git stash\`** in any form (\`git stash push\`, \`git stash pop\`, etc.). This is a multi-agent system — stashing can silently destroy or corrupt another agent's or the user's in-progress work. Work around uncommitted changes instead. (Note: the backend may use \`--autostash\` in user-triggered pull operations — that is safe because those are single-user UI actions, not concurrent agent operations.)
-- **Only commit files YOU changed** for this task. Never use \`git add -A\` or \`git add .\` — always stage specific files by name.
+- **Only commit files YOU changed** for this task. Never use \`git add -A\` or \`git add .\` — always stage specific files by name.`}
${noChangeSuccess ? `- **No-change audits may exit cleanly.** ${NO_CHANGE_AUDIT_GUIDANCE}` : ''}
${completionInstructions.gitHygiene}
${completionInstructions.commitTarget}
@@ -938,7 +941,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, { isTui = t
// a JIRA run be told to open a PR whose merge section was suppressed — and
// PortOS opened that PR too. `inlineSection` also names WHICH section follows,
// so the completion step's cross-reference can't name the wrong one.
- const inlineSection = claimFlow || [COMPLETION_MODES.RELEASE_FLOW, COMPLETION_MODES.AUDIT_FLOW, COMPLETION_MODES.RECONCILE_FLOW].includes(completionMode) ? null : inlinePrLifecycleSection(task, {
+ const inlineSection = claimFlow || [COMPLETION_MODES.RELEASE_FLOW, COMPLETION_MODES.AUDIT_FLOW, COMPLETION_MODES.RECONCILE_FLOW, COMPLETION_MODES.CHECKOUT_RECOVERY].includes(completionMode) ? null : inlinePrLifecycleSection(task, {
providerType: isTui ? PROVIDER_TYPES.TUI : PROVIDER_TYPES.CLI,
providerId, providerCommand, leanMode, worktreeInfo,
});
@@ -1077,6 +1080,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, { isTui = t
},
[COMPLETION_MODES.AUDIT_FLOW]: () => contractSections.push(buildAuditFlowCompletionSection({ isTui, sentinelPath: lightSentinelPath() })),
[COMPLETION_MODES.RECONCILE_FLOW]: () => contractSections.push(buildReconcileFlowCompletionSection({ sentinelPath: lightSentinelPath() })),
+ [COMPLETION_MODES.CHECKOUT_RECOVERY]: () => contractSections.push(buildCheckoutRecoveryCompletionSection({ sentinelPath: lightSentinelPath() })),
[COMPLETION_MODES.RELEASE_FLOW]: () => contractSections.push(buildReleaseFlowCompletionSection({ isTui, sentinelPath: lightSentinelPath() })),
[COMPLETION_MODES.TUI_SLASHDO_FREE]: pushTuiCompletion,
[COMPLETION_MODES.TUI]: pushTuiCompletion,
@@ -1133,7 +1137,7 @@ function buildLightTaskContextSections({
worktreeInfo.baseBranch ? `- **Based on**: \`${worktreeInfo.baseBranch}\`` : null,
'',
worktreeCommitGuidance({ isTui, mode, canTypeSlashCommands, rendersInlinePrLifecycle, isWorktreeOnExistingBranch, willOpenPR, discardWorktree, claimFlow, noChangeSuccess }),
- [COMPLETION_MODES.RELEASE_FLOW, COMPLETION_MODES.AUDIT_FLOW, COMPLETION_MODES.RECONCILE_FLOW].includes(mode)
+ [COMPLETION_MODES.RELEASE_FLOW, COMPLETION_MODES.AUDIT_FLOW, COMPLETION_MODES.RECONCILE_FLOW, COMPLETION_MODES.CHECKOUT_RECOVERY].includes(mode)
? 'Follow the bundled workflow branch instructions while preserving unrelated work.'
: 'Do NOT manually switch branches or modify the worktree configuration.',
// Resuming a previous failed agent's branch: establish what's already done
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index 52f45c3d92..ce562f6d74 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -3534,6 +3534,60 @@ describe('buildAgentPrompt — slashdo-backed tasks', () => {
});
});
+ // Read the actual UI request as data: a renamed/stripped workflow must fail
+ // the end-to-end intake/composed-prompt regression, not just a helper test.
+ it.each(['tui', 'cli', 'api'])('preserves UI checkout recovery ownership on %s', async (providerType) => {
+ const { readFile } = await import('fs/promises');
+ const { parse } = await import('@babel/parser');
+ const { createCosTaskSchema } = await import('../lib/cosValidation.js');
+ const { buildQueuedTask } = await import('./cosTaskIntake.js');
+ const source = await readFile(join(PATHS.root, 'client/src/components/apps/tabs/GitRecoveryAction.jsx'), 'utf8');
+ const ast = parse(source, { sourceType: 'module', plugins: ['jsx'] });
+ let request;
+ const walk = node => {
+ if (!node || typeof node !== 'object') return;
+ if (node.type === 'CallExpression' && node.callee?.object?.name === 'api'
+ && node.callee?.property?.name === 'addCosTask') request = node.arguments[0];
+ Object.values(node).forEach(value => {
+ if (Array.isArray(value)) value.forEach(walk);
+ else if (value && typeof value === 'object') walk(value);
+ });
+ };
+ walk(ast);
+ expect(request?.type).toBe('ObjectExpression');
+ const payload = { app: 'example-app', provider: 'example-provider' };
+ for (const property of request.properties) {
+ const value = property.value;
+ if (['StringLiteral', 'BooleanLiteral'].includes(value.type)) payload[property.key.name] = value.value;
+ if (value.type === 'TemplateLiteral') payload[property.key.name] = value.quasis.map(part => part.value.cooked).join('Example App');
+ }
+ const task = buildQueuedTask(createCosTaskSchema.parse(payload), 'user');
+ expect(task.metadata).toMatchObject({ analysisType: 'app-checkout-recovery', useWorktree: false, openPR: false });
+ expect(task.metadata).not.toHaveProperty('whenDone');
+ const prompt = await buildAgentPrompt(task, {}, '/r', null, {
+ providerType, providerId: 'codex', providerCommand: 'codex', agentId: 'checkout-recovery-test',
+ });
+ expect(prompt).toContain('## App Checkout Recovery Handoff');
+ expect(prompt).toContain('actual configured checkout');
+ expect(prompt).toContain('Existing commits may be preserved and published without making a new commit');
+ expect(prompt).toContain('named branch with an open or merged PR');
+ expect(prompt).toContain('current-head required CI');
+ expect(prompt).toContain('stash accounting');
+ expect(prompt).toContain('keep private paths and data out of public artifacts');
+ expect(prompt).toContain('.agent-done-checkout-recovery-test');
+ expect(prompt).toContain('Writing that one file is ALWAYS permitted');
+ expect(prompt).not.toMatch(/Do NOT push|do NOT push|PortOS will (?:push|merge)|commit directly to the current branch|[Cc]ommit only —/);
+ expect(prompt).not.toContain('## Completion Workflow');
+ expect(prompt).not.toContain('## Simplify Step');
+ expect(prompt).not.toContain('## Branch Reconciliation Handoff');
+ if (providerType === 'api') {
+ expect(prompt).toContain('Never create or pop a stash');
+ expect(prompt).toContain('preserve every unaccounted entry');
+ expect(prompt).not.toContain('Only commit files YOU changed');
+ expect(prompt).not.toContain('NEVER use `git stash`');
+ }
+ });
+
// Assert the composed prompt: individually correct sections can contradict.
describe.each([
{ metadata: { analysisType: 'branch-reconcile' } },
diff --git a/server/services/cosTaskIntake.js b/server/services/cosTaskIntake.js
index 2ef5cc6da4..323ae1362f 100644
--- a/server/services/cosTaskIntake.js
+++ b/server/services/cosTaskIntake.js
@@ -273,6 +273,16 @@ export function buildTaskMetadata(taskData, taskType, { now = Date.now() } = {})
delete metadata.reviewStopMode;
delete metadata.reviewerApplies;
}
+ // Recovery owns the actual checkout and every preservation PR. Do not let
+ // generic delivery defaults create a coordinator worktree or publish it.
+ if (taskData.workflow === 'app-checkout-recovery' && !planOnly) {
+ metadata.analysisType = taskData.workflow;
+ metadata.useWorktree = false;
+ metadata.openPR = false;
+ metadata.simplify = false;
+ metadata.reviewLoop = false;
+ delete metadata.whenDone;
+ }
// Content-edit timestamp for cross-peer newest-edit-wins LWW (#1714). Stamped
// at creation so a freshly-added task always carries a stamp; the merge treats
// an absent stamp as oldest, so this also keeps a stamped task from losing a
diff --git a/server/services/cosTaskIntake.test.js b/server/services/cosTaskIntake.test.js
index 4820dd995c..3a6f41cf6e 100644
--- a/server/services/cosTaskIntake.test.js
+++ b/server/services/cosTaskIntake.test.js
@@ -48,6 +48,7 @@ const METADATA_SAMPLES = {
jiraTicketUrl: 'https://example.com/browse/EX-1',
useWorktree: true,
isInvestigation: true,
+ workflow: 'app-checkout-recovery',
whenDone: 'commit-push',
planOnly: true,
openPR: true,
@@ -124,3 +125,16 @@ describe('buildTaskMetadata worktree PR defaults', () => {
expect(metadata.prCompletion).toBe(PR_COMPLETIONS.REVIEW_THEN_MERGE);
});
});
+
+// A stale client's generic delivery flags cannot override recovery ownership.
+describe('checkout recovery intake', () => {
+ it('keeps recovery on the real checkout and removes generic delivery steps', () => {
+ expect(buildTaskMetadata(createCosTaskSchema.parse({
+ description: 'recover', workflow: 'app-checkout-recovery',
+ useWorktree: true, openPR: true, simplify: true, reviewLoop: true, whenDone: 'commit-push',
+ }), 'user')).toMatchObject({
+ analysisType: 'app-checkout-recovery', useWorktree: false,
+ openPR: false, simplify: false, reviewLoop: false,
+ });
+ });
+});
diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.js
index dcab95c54e..6612f88c96 100644
--- a/server/services/promptSections/completion.js
+++ b/server/services/promptSections/completion.js
@@ -29,6 +29,8 @@ const AUDIT_FLOW_GUIDANCE = 'Follow the bundled Better audit workflow through re
const RECONCILE_FLOW_GUIDANCE = 'Follow the branch reconciliation task above for the named branches only, including its branch allowlist, author checks, review-only and superseded no-mutation rules, configured reviews, current-head CI, and merge gates. The task owns any authorized commit, push, PR creation, merge, and cleanup of those branches. There is no implicit commit, push, or merge-back of the coordinator checkout. Report each verified outcome or the retained branch and first unverified checkpoint before signaling completion.';
+const CHECKOUT_RECOVERY_GUIDANCE = 'Follow the app checkout recovery task above in the actual configured checkout. You own verified backups, backup refs, preservation branches and PRs, configured reviews, current-head required CI and merge gates, stash accounting, and final checkout verification against the latest origin default branch. Preserve active work and retain backups when blocked. Publish every unique change on a named branch with an open or merged PR; never push preservation work directly to the default branch. Existing commits may be preserved and published without making a new commit. PortOS performs no implicit commit, push, or worktree merge-back for this task. Report verified outcomes and PR URLs, or INCOMPLETE with retained work and the first unverified checkpoint; keep private paths and data out of public artifacts.';
+
const RELEASE_FLOW_GUIDANCE = 'Follow the bundled release workflow through its final verification and report. It owns release delivery; do not stop at a prepared commit or hand publication back to PortOS. If it cannot complete, report INCOMPLETE and the first unverified checkpoint instead of claiming a successful release.';
/**
@@ -131,6 +133,7 @@ export function buildCompletionGuidelineBullet({
[COMPLETION_MODES.CLAIM_FLOW]: () => '**This is a self-managed claim flow.** Follow the claim prompt above through its phase-specific worktree, PR/MR, review, merge or human-handoff, and cleanup steps. Do NOT stop after committing or hand the lifecycle back to PortOS.',
[COMPLETION_MODES.AUDIT_FLOW]: () => AUDIT_FLOW_GUIDANCE,
[COMPLETION_MODES.RECONCILE_FLOW]: () => RECONCILE_FLOW_GUIDANCE,
+ [COMPLETION_MODES.CHECKOUT_RECOVERY]: () => CHECKOUT_RECOVERY_GUIDANCE,
[COMPLETION_MODES.RELEASE_FLOW]: () => RELEASE_FLOW_GUIDANCE,
[COMPLETION_MODES.READ_ONLY]: () => '**This is a read-only task.** Do NOT commit, push, or modify any files in the repository. Only read data and generate reports.',
// A PR follow-up already carries its own PRIMARY OBJECTIVE section with the
@@ -175,6 +178,7 @@ const NO_COMMIT_TARGET_MODES = new Set([
COMPLETION_MODES.DISCARD_WORKTREE,
COMPLETION_MODES.CLAIM_FLOW,
COMPLETION_MODES.RECONCILE_FLOW,
+ COMPLETION_MODES.CHECKOUT_RECOVERY,
COMPLETION_MODES.RELEASE_FLOW,
COMPLETION_MODES.AUDIT_FLOW,
COMPLETION_MODES.READ_ONLY,
@@ -242,6 +246,10 @@ export function buildFallbackCompletionInstructions({
step4: AUDIT_FLOW_GUIDANCE,
gitHygiene: `- ${AUDIT_FLOW_GUIDANCE}`,
}),
+ [COMPLETION_MODES.CHECKOUT_RECOVERY]: () => ({
+ step4: CHECKOUT_RECOVERY_GUIDANCE,
+ gitHygiene: `- ${CHECKOUT_RECOVERY_GUIDANCE}`,
+ }),
[COMPLETION_MODES.RECONCILE_FLOW]: () => ({
step4: RECONCILE_FLOW_GUIDANCE,
gitHygiene: `- ${RECONCILE_FLOW_GUIDANCE}`,
@@ -442,6 +450,17 @@ export function buildActionOutputCompletionSection({ isTui = false, sentinelPath
);
}
+export function buildCheckoutRecoveryCompletionSection({ sentinelPath } = {}) {
+ return [
+ '## App Checkout Recovery Handoff',
+ CHECKOUT_RECOVERY_GUIDANCE,
+ '',
+ 'After recovery reaches its verified final outcome or a precise blocker, write the completion sentinel and stop:',
+ '',
+ ...buildSentinelWriteSteps(1, sentinelPath, ' ## Recovery outcome\n <verified checkout and preservation PR outcomes, or INCOMPLETE with the first unverified checkpoint>'),
+ ].join('\n');
+}
+
export function buildReconcileFlowCompletionSection({ sentinelPath } = {}) {
return [
'## Branch Reconciliation Handoff',
@@ -642,6 +661,7 @@ export function buildAutoMergeCommitStep(baseBranch = null) {
export function worktreeCommitGuidance({ isTui, mode = null, canTypeSlashCommands = false, rendersInlinePrLifecycle = false, isWorktreeOnExistingBranch, willOpenPR, discardWorktree, claimFlow = false, noChangeSuccess = false }) {
if (mode === COMPLETION_MODES.AUDIT_FLOW) return AUDIT_FLOW_GUIDANCE;
if (mode === COMPLETION_MODES.RECONCILE_FLOW) return RECONCILE_FLOW_GUIDANCE;
+ if (mode === COMPLETION_MODES.CHECKOUT_RECOVERY) return CHECKOUT_RECOVERY_GUIDANCE;
if (mode === COMPLETION_MODES.RELEASE_FLOW) return RELEASE_FLOW_GUIDANCE;
if (discardWorktree) return DISCARD_WORKTREE_NOTE;
if (claimFlow) return 'The claim workflow in the Completion section owns the push, PR/MR, review, merge or human-handoff, and cleanup steps.';
diff --git a/server/services/taskTypeHooks.js b/server/services/taskTypeHooks.js
index 199132ef62..614831f54b 100644
--- a/server/services/taskTypeHooks.js
+++ b/server/services/taskTypeHooks.js
@@ -167,7 +167,7 @@ export function resolveTaskHookType(task) {
* buckets these already poisoned on existing installs.
*/
export const NON_COMMITTING_COORDINATOR_TASK_TYPES = new Set([
- 'branch-reconcile', 'issue-reconcile', 'branch-cleanup', 'jira-status-report', 'do-release',
+ 'app-checkout-recovery', 'branch-reconcile', 'issue-reconcile', 'branch-cleanup', 'jira-status-report', 'do-release',
'stash-cleanup', 'repo-sync', 'pr-reviewer', 'model-comparison-refresh',
// Pre-rename name of do-release (migration 417): queued and archived tasks
// still carry it, and their buckets must keep the coordinator exemption.