Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: preserve named-branch reconciliation delivery ownership (#8803)
[._.]/ Adam Eivy7f0a35e5fc6c
diff --git a/server/lib/agentCompletionMode.js b/server/lib/agentCompletionMode.jsindex c94ee58b63..bd81e30f69 100644--- a/server/lib/agentCompletionMode.js+++ b/server/lib/agentCompletionMode.js@@ -69,6 +69,8 @@ export const COMPLETION_MODES = Object.freeze({RELEASE_FLOW: 'release-flow',/** Better audits own their worktrees and verified PR delivery. */AUDIT_FLOW: 'audit-flow',+ /** Reconciliation owns delivery of named branches, never the coordinator checkout. */+ RECONCILE_FLOW: 'reconcile-flow',/** 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. */@@ -114,6 +116,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.RECONCILE_FLOW, (f) => f.taskHookType === 'branch-reconcile'],[COMPLETION_MODES.TUI_SLASHDO_FREE, (f) => f.isTui && !f.canRunSlashCommands],[COMPLETION_MODES.TUI, (f) => f.isTui],[COMPLETION_MODES.PORTOS_MERGES, (f) => f.portosMergesBranch],@@ -131,6 +134,7 @@ const COMPLETION_MODE_RULES = Object.freeze([* @param {boolean} [flags.claimFlow]* @param {boolean} [flags.isReadOnly]* @param {boolean} [flags.isReviewLoopFollowUp]+ * @param {string} [flags.taskHookType] - Canonical task identity from resolveTaskHookType.* @param {string} [flags.slashdoCommand]* @param {boolean} [flags.isTui]* @param {boolean} [flags.canRunSlashCommands] - Defaults to `true`; only a TUIdiff --git a/server/lib/agentCompletionMode.test.js b/server/lib/agentCompletionMode.test.jsindex d47f058b1b..6070ff62a6 100644--- a/server/lib/agentCompletionMode.test.js+++ b/server/lib/agentCompletionMode.test.js@@ -82,6 +82,7 @@ describe('resolveCompletionMode', () => {resolveCompletionMode({ isReviewLoopFollowUp: true }),resolveCompletionMode({ slashdoCommand: 'release' }),resolveCompletionMode({ slashdoCommand: 'better' }),+ resolveCompletionMode({ taskHookType: 'branch-reconcile' }),resolveCompletionMode({ isTui: true, canRunSlashCommands: false }),resolveCompletionMode({ isTui: true }),resolveCompletionMode({ worktreeInfo: wt, willOpenPR: false }),diff --git a/server/lib/agentRegistrationRecord.test.js b/server/lib/agentRegistrationRecord.test.jsindex dc2db30cca..4fac8303d4 100644--- a/server/lib/agentRegistrationRecord.test.js+++ b/server/lib/agentRegistrationRecord.test.js@@ -89,3 +89,14 @@ it('projects non-secret provider route provenance for active and archived cards'expect(record).not.toHaveProperty('envVars');expect(record).not.toHaveProperty('credentialBootstrap');});++it('preserves scheduled reconciliation identity through persistence and registration', () => {+ const queued = buildQueuedTask({ description: 'Reconcile named branches', metadata: {+ analysisType: 'branch-reconcile', useWorktree: false, openPR: false,+ } }, 'internal');+ const [task] = parseTasksMarkdown(generateTasksMarkdown([queued]));+ const record = buildAgentRegistration({ ...args({}), task });+ expect(task.metadata.analysisType).toBe('branch-reconcile');+ expect(record.taskAnalysisType).toBe('branch-reconcile');+ expect(record.isWorktree).toBe(false);+});diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex e98ee4df65..4ebee682c1 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -20,7 +20,7 @@ import { getDigitalTwinForPrompt } from './digital-twin.js';import { taskContextBlock } from '../lib/cosTaskPrompt.js';import { PR_COMPLETIONS, leavesPrForHuman, resolvePrCompletion } from '../lib/prDisposition.js';// Shared with cosTaskGenerator.js, which stamps the same set as metadata.claimFlow.-import { isClaimFlowDispatch } from './taskTypeHooks.js';+import { isClaimFlowDispatch, resolveTaskHookType } from './taskTypeHooks.js';import { getCodeReviewDefaults } from './codeReview.js';import { LIGHT_CONTEXT_PROVIDER_TYPES, SIMPLIFY_INLINE_REVIEW } from './promptSections/constants.js';import { detectSkillTemplates, getAgentInstructionsContext, loadSkillTemplates } from './promptSections/instructions.js';@@ -39,6 +39,7 @@ import {buildClaimResumeOverride,claimResumeContext,buildReleaseFlowCompletionSection,+ buildReconcileFlowCompletionSection,buildAuditFlowCompletionSection,buildCliCompletionSection,buildCompletionGuidelineBullet,@@ -525,6 +526,7 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo// THE completion decision, made once. Every section below renders this key;// none re-derives it. See lib/agentCompletionMode.js for the rule order.const completionMode = resolveCompletionMode({+ taskHookType: resolveTaskHookType(task),toolFreeReasoning, sentinelPayloadOutput, noCodeOutput, discardWorktree, claimFlow,isReadOnly, isReviewLoopFollowUp, isTui, canRunSlashCommands, portosMergesBranch,worktreeInfo, willOpenPR, slashdoCommand: task.metadata?.slashdoCommand,@@ -549,7 +551,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].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].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({@@ -610,6 +612,7 @@ ${buildResumeSection(task, worktreeInfo)}` : '';claimResume: claimResumeContext(task, worktreeInfo),}),[COMPLETION_MODES.AUDIT_FLOW]: () => buildAuditFlowCompletionSection({ isTui, sentinelPath }),+ [COMPLETION_MODES.RECONCILE_FLOW]: () => buildReconcileFlowCompletionSection({ sentinelPath }),[COMPLETION_MODES.RELEASE_FLOW]: () => buildReleaseFlowCompletionSection({ isTui, sentinelPath }),[COMPLETION_MODES.TUI_SLASHDO_FREE]: buildFullPathTuiCompletion,[COMPLETION_MODES.TUI]: buildFullPathTuiCompletion,@@ -683,7 +686,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].includes(mode) && simplifyEnabled && !isTui && !discardWorktree && !claimFlow ? `+ const simplifySection = ![COMPLETION_MODES.RELEASE_FLOW, COMPLETION_MODES.AUDIT_FLOW, COMPLETION_MODES.RECONCILE_FLOW].includes(mode) && simplifyEnabled && !isTui && !discardWorktree && !claimFlow ? `## Simplify StepAfter 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`'}.` : '';@@ -977,6 +980,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet// full one, so a fix applied only there is no fix at all for anything a// subscription-quota job can run.const completionMode = resolveCompletionMode({+ taskHookType: resolveTaskHookType(task),toolFreeReasoning, sentinelPayloadOutput, noCodeOutput, discardWorktree, claimFlow,isReadOnly, isReviewLoopFollowUp, isTui, canRunSlashCommands: canTypeSlash,portosMergesBranch, worktreeInfo, willOpenPR, slashdoCommand: task.metadata?.slashdoCommand,@@ -989,7 +993,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet// 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].includes(completionMode) ? null : inlinePrLifecycleSection(task, {+ const inlineSection = claimFlow || [COMPLETION_MODES.RELEASE_FLOW, COMPLETION_MODES.AUDIT_FLOW, COMPLETION_MODES.RECONCILE_FLOW].includes(completionMode) ? null : inlinePrLifecycleSection(task, {providerType: isTui ? PROVIDER_TYPES.TUI : PROVIDER_TYPES.CLI,providerId, providerCommand, leanMode, worktreeInfo, isTruthyMetaFn,});@@ -1129,6 +1133,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet].join('\n'));},[COMPLETION_MODES.AUDIT_FLOW]: () => contractSections.push(buildAuditFlowCompletionSection({ isTui, sentinelPath: lightSentinelPath() })),+ [COMPLETION_MODES.RECONCILE_FLOW]: () => contractSections.push(buildReconcileFlowCompletionSection({ sentinelPath: lightSentinelPath() })),[COMPLETION_MODES.RELEASE_FLOW]: () => contractSections.push(buildReleaseFlowCompletionSection({ isTui, sentinelPath: lightSentinelPath() })),[COMPLETION_MODES.TUI_SLASHDO_FREE]: pushTuiCompletion,[COMPLETION_MODES.TUI]: pushTuiCompletion,@@ -1192,7 +1197,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].includes(mode)+ [COMPLETION_MODES.RELEASE_FLOW, COMPLETION_MODES.AUDIT_FLOW, COMPLETION_MODES.RECONCILE_FLOW].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 donediff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex bb7a3e23d1..701b11a838 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -3593,6 +3593,42 @@ describe('buildAgentPrompt — slashdo-backed tasks', () => {});});+ // Assert the composed prompt: individually correct sections can contradict.+ describe.each([+ { metadata: { analysisType: 'branch-reconcile' } },+ { metadata: { taskAnalysisType: 'branch-reconcile' } },+ { taskType: 'branch-reconcile', metadata: {} },+ ])('reconciliation identity %j', (identity) => {+ it.each(['tui', 'cli', 'api'])('preserves scoped delivery on %s', async (providerType) => {+ const prompt = await buildAgentPrompt(makeTask({+ ...identity,+ description: 'Reconcile only claim/issue-42. Push the named branch, open its PR, and merge after review and CI.',+ metadata: {+ ...sanitizeTaskMetadata({ useWorktree: false, openPR: false, worktreeChangesExpected: false, simplify: true }),+ ...identity.metadata,+ },+ }), {}, '/r', null, isTruthyMeta,+ { providerType, providerId: 'codex', providerCommand: 'codex', agentId: 'reconcile-test' });+ expect(prompt).toContain('Reconcile only claim/issue-42');+ expect(prompt).toContain('## Branch Reconciliation Handoff');+ expect(prompt).toContain('current-head CI');+ expect(prompt).toContain('review-only and superseded no-mutation rules');+ expect(prompt).toContain('no implicit commit, push, or merge-back of the coordinator checkout');+ expect(prompt).toContain('.agent-done-reconcile-test');+ expect(prompt).not.toMatch(/Do NOT push|do NOT push|PortOS will (?:push|merge)|commit directly to the current branch/);+ expect(prompt).not.toContain('## Completion Workflow');+ expect(prompt).not.toContain('## Simplify Step');+ });+ });++ it('keeps explicit read-only reconciliation restricted', async () => {+ const prompt = await buildAgentPrompt(makeTask({+ metadata: { analysisType: 'branch-reconcile', readOnly: true, openPR: false },+ }), {}, '/r', null, isTruthyMeta, { providerType: 'cli', providerId: 'codex' });+ expect(prompt).toMatch(/read.only/i);+ expect(prompt).not.toContain('## Branch Reconciliation Handoff');+ });+it('recovers the bundled release for an older queued task whose command was stripped', async () => {vi.mocked(loadSlashdoFile).mockResolvedValue('# Release\n\nCanonical release procedure.');const prompt = await buildAgentPrompt(diff --git a/server/services/agentWorktreeCleanup.repoStateAudit.test.js b/server/services/agentWorktreeCleanup.repoStateAudit.test.jsindex a4b6ecccdc..484ec3aa01 100644--- a/server/services/agentWorktreeCleanup.repoStateAudit.test.js+++ b/server/services/agentWorktreeCleanup.repoStateAudit.test.js@@ -67,6 +67,14 @@ beforeEach(() => {});describe('cleanupAgentWorktree → repo-state audit', () => {+ it('does not merge or remove a reconciliation coordinator without a worktree', async () => {+ const originalTask = { id: 'reconcile-task', metadata: {+ analysisType: 'branch-reconcile', useWorktree: false, openPR: false,+ } };+ await expect(cleanupAgentWorktree('reconcile-agent', true, { originalTask })).resolves.toEqual([]);+ expect(removeWorktree).not.toHaveBeenCalled();+ });+it('audits after cleanup, carrying the task, the run verdict and the PR expectation', async () => {const originalTask = { id: 'task-1', metadata: { app: 'demo-app', openPR: true } };diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.jsindex 769c991542..790a39c1b3 100644--- a/server/services/promptSections/completion.js+++ b/server/services/promptSections/completion.js@@ -23,6 +23,8 @@ function withNoChangeAuditGuidance(guidance, noChangeSuccess) {const AUDIT_FLOW_GUIDANCE = 'Follow the bundled Better audit workflow through remediation, verification, PR publication, and cleanup. You own delivery: open the category PRs and merge into the repository default branch when current-head CI and configured reviews pass. If no external reviewers are configured, complete the internal review and merge after CI passes. This launch authorizes that merge by default; honor explicit --scan-only, --no-merge, and read-only constraints. Use plain git and the forge CLI when slash commands are unavailable. Do not stop at local commits or hand publication back to PortOS. A clean audit needs no PR. If any required gate is unavailable or fails, retain the work and report INCOMPLETE with the PR or branch and first unverified checkpoint.';+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 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.';/**@@ -124,6 +126,7 @@ export function buildCompletionGuidelineBullet({[COMPLETION_MODES.DISCARD_WORKTREE]: () => REASONING_ONLY_BULLET,[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.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@@ -167,6 +170,7 @@ const NO_COMMIT_TARGET_MODES = new Set([COMPLETION_MODES.ACTION_OUTPUT,COMPLETION_MODES.DISCARD_WORKTREE,COMPLETION_MODES.CLAIM_FLOW,+ COMPLETION_MODES.RECONCILE_FLOW,COMPLETION_MODES.RELEASE_FLOW,COMPLETION_MODES.AUDIT_FLOW,COMPLETION_MODES.READ_ONLY,@@ -234,6 +238,10 @@ export function buildFallbackCompletionInstructions({step4: AUDIT_FLOW_GUIDANCE,gitHygiene: `- ${AUDIT_FLOW_GUIDANCE}`,}),+ [COMPLETION_MODES.RECONCILE_FLOW]: () => ({+ step4: RECONCILE_FLOW_GUIDANCE,+ gitHygiene: `- ${RECONCILE_FLOW_GUIDANCE}`,+ }),[COMPLETION_MODES.RELEASE_FLOW]: () => ({step4: RELEASE_FLOW_GUIDANCE,gitHygiene: `- ${RELEASE_FLOW_GUIDANCE}`,@@ -430,6 +438,17 @@ export function buildActionOutputCompletionSection({ isTui = false, sentinelPath);}+export function buildReconcileFlowCompletionSection({ sentinelPath } = {}) {+ return [+ '## Branch Reconciliation Handoff',+ RECONCILE_FLOW_GUIDANCE,+ '',+ 'After the scoped reconciliation reaches its final outcome, write the completion sentinel and stop:',+ '',+ ...buildSentinelWriteSteps(1, sentinelPath, ' ## Reconciliation outcome\n <verified branch outcomes and PR URLs, or INCOMPLETE with the first unverified checkpoint>'),+ ].join('\n');+}+/** The release procedure is the deliverable; the sentinel only records its verified outcome. */export function buildReleaseFlowCompletionSection({ isTui = false, sentinelPath = null } = {}) {const lines = ['## Release Workflow Handoff', RELEASE_FLOW_GUIDANCE];@@ -597,6 +616,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.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.';