Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor([issue-742]): tidy re-exports and completion-cleanup arg usage

[._.]/ Adam Eivycfa735836467
diff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.js
index 7492971aba..64839f6f66 100644
--- a/server/services/agentCompletionCleanup.js
+++ b/server/services/agentCompletionCleanup.js
@@ -156,15 +156,15 @@ export async function runAgentCompletionCleanup({ agentId, task, agent, effectiv
const agentState = await getAgentState(agentId).catch(() => null);
// JIRA integration: push branch, create PR, comment on ticket
- const jiraTicketId = agent.task?.metadata?.jiraTicketId;
- const jiraBranch = agent.task?.metadata?.jiraBranch;
- const jiraInstanceId = agent.task?.metadata?.jiraInstanceId;
- const jiraCreatePR = agent.task?.metadata?.jiraCreatePR;
+ const jiraTicketId = task?.metadata?.jiraTicketId;
+ const jiraBranch = task?.metadata?.jiraBranch;
+ const jiraInstanceId = task?.metadata?.jiraInstanceId;
+ const jiraCreatePR = task?.metadata?.jiraCreatePR;
if (jiraTicketId && jiraBranch && effectiveSuccess) {
const workspace = agentState?.metadata?.workspacePath || ROOT_DIR;
- let jiraTicketUrl = agent.task?.metadata?.jiraTicketUrl || null;
+ let jiraTicketUrl = task?.metadata?.jiraTicketUrl || null;
if (!jiraTicketUrl && jiraInstanceId) {
const jiraConfig = await jiraService.getInstances().catch(() => null);
const baseUrl = jiraConfig?.instances?.[jiraInstanceId]?.baseUrl;
@@ -270,12 +270,12 @@ export async function runAgentCompletionCleanup({ agentId, task, agent, effectiv
// Clean up worktree if agent was using one (skip merge when JIRA branch — PR handles merge)
if (!jiraBranch) {
- const taskOpenPR = isTruthyMeta(agent.task?.metadata?.openPR);
- const taskReviewLoop = isTruthyMeta(agent.task?.metadata?.reviewLoop);
+ const taskOpenPR = isTruthyMeta(task?.metadata?.openPR);
+ const taskReviewLoop = isTruthyMeta(task?.metadata?.reviewLoop);
// 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(agent.task?.metadata?.reviewLoopFollowUp);
+ const taskReviewLoopFollowUp = isTruthyMeta(task?.metadata?.reviewLoopFollowUp);
// Claude Code CLI agents run `/simplify` + `/do:pr` themselves (see
// buildCliCompletionSection in agentPromptBuilder.js) — they push the
// branch and open the PR on their own. Mirror the TUI cleanup contract
@@ -286,7 +286,7 @@ export async function runAgentCompletionCleanup({ agentId, task, agent, effectiv
// (AI Providers → Code Review Defaults panel). 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(agent.task?.metadata, { normalize: normalizeReviewers, isTruthyMeta });
+ const reviewOptions = await resolveReviewLoopOptions(task?.metadata, { normalize: normalizeReviewers, isTruthyMeta });
const cleanupWarnings = await cleanupAgentWorktree(agentId, effectiveSuccess, {
openPR: agentOwnsPR ? false : taskOpenPR,
requestCopilotReview: !agentOwnsPR && taskOpenPR && taskReviewLoop,
diff --git a/server/services/agentCompletionCleanup.test.js b/server/services/agentCompletionCleanup.test.js
new file mode 100644
index 0000000000..20ac90942a
--- /dev/null
+++ b/server/services/agentCompletionCleanup.test.js
@@ -0,0 +1,75 @@
+/**
+ * Tests for agentCompletionCleanup.handlePipelineProgression — the
+ * pipeline-stage advancement extracted out of handleAgentCompletion.
+ *
+ * Pins the four branches: not-running (no-op), stage failure (mark failed),
+ * last stage (mark completed), and advance (enqueue the next stage task).
+ * These were previously exercised only indirectly via the agentLifecycle
+ * completion path; the extraction gives them a direct home.
+ */
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));
+vi.mock('./cosAgents.js', () => ({ updateAgent: vi.fn() }));
+vi.mock('./cos.js', () => ({
+ updateTask: vi.fn().mockResolvedValue({}),
+ addTask: vi.fn().mockResolvedValue({}),
+ checkStagePrecondition: vi.fn().mockReturnValue({ passed: true }),
+ getAgent: vi.fn().mockResolvedValue(null),
+}));
+vi.mock('./jira.js', () => ({ getInstances: vi.fn(), addComment: vi.fn() }));
+vi.mock('./git.js', () => ({ push: vi.fn(), getRepoBranches: vi.fn(), generatePRDescription: vi.fn(), suggestPRTitle: vi.fn(), createPR: vi.fn(), checkout: vi.fn() }));
+vi.mock('./codeReview.js', () => ({ resolveReviewLoopOptions: vi.fn().mockResolvedValue({}) }));
+vi.mock('./agentWorktreeCleanup.js', () => ({ cleanupAgentWorktree: vi.fn().mockResolvedValue([]), spawnMergeRecoveryTask: vi.fn() }));
+vi.mock('./taskSchedule.js', () => ({ getStagePrompt: vi.fn().mockResolvedValue('do stage work in {appName}') }));
+
+import { handlePipelineProgression } from './agentCompletionCleanup.js';
+import { updateTask, addTask } from './cos.js';
+
+const runningPipeline = (overrides = {}) => ({
+ id: 'p1',
+ status: 'running',
+ currentStage: 0,
+ stages: [{ name: 'stage-0' }, { name: 'stage-1' }],
+ stageResults: [],
+ ...overrides,
+});
+
+beforeEach(() => { vi.clearAllMocks(); });
+
+describe('handlePipelineProgression', () => {
+ it('is a no-op when the pipeline is not running', async () => {
+ const task = { id: 't', taskType: 'user', metadata: { pipeline: runningPipeline({ status: 'completed' }) } };
+ await handlePipelineProgression(task, 'agent-1', true);
+ expect(updateTask).not.toHaveBeenCalled();
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
+ it('marks the pipeline failed on a failed stage and does not advance', async () => {
+ const task = { id: 't', taskType: 'user', metadata: { pipeline: runningPipeline() } };
+ await handlePipelineProgression(task, 'agent-1', false);
+ expect(updateTask).toHaveBeenCalledTimes(1);
+ expect(updateTask.mock.calls[0][1].metadata.pipeline.status).toBe('failed');
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
+ it('marks the pipeline completed after the last stage', async () => {
+ const task = { id: 't', taskType: 'user', metadata: { pipeline: runningPipeline({ currentStage: 1 }) } };
+ await handlePipelineProgression(task, 'agent-1', true);
+ expect(updateTask).toHaveBeenCalledTimes(1);
+ expect(updateTask.mock.calls[0][1].metadata.pipeline.status).toBe('completed');
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
+ it('enqueues the next stage task when advancing', async () => {
+ const task = { id: 't', taskType: 'user', metadata: { pipeline: runningPipeline() } };
+ await handlePipelineProgression(task, 'agent-1', true);
+ expect(addTask).toHaveBeenCalledTimes(1);
+ const [nextTask, group] = addTask.mock.calls[0];
+ expect(group).toBe('internal');
+ expect(nextTask.metadata.pipeline.currentStage).toBe(1);
+ expect(nextTask.metadata.pipeline.status).toBe('running');
+ expect(nextTask.metadata.pipeline.previousStageAgentId).toBe('agent-1');
+ });
+});
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 7c75478798..e26c00b5d4 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -36,10 +36,16 @@ import { v4 as uuidv4 } from '../lib/uuid.js';
// them from agentLifecycle.js keep working.
import { resolveAgentProviderAndModel } from './agentProviderResolution.js';
import { prepareAgentWorkspace } from './agentWorkspacePrep.js';
-import { cleanupAgentWorktree, spawnReviewLoopFollowUp, spawnMergeRecoveryTask } from './agentWorktreeCleanup.js';
-import { handlePipelineProgression, runAgentCompletionCleanup } from './agentCompletionCleanup.js';
-
-export { cleanupAgentWorktree, spawnReviewLoopFollowUp, spawnMergeRecoveryTask, handlePipelineProgression };
+import { cleanupAgentWorktree } from './agentWorktreeCleanup.js';
+import { runAgentCompletionCleanup } from './agentCompletionCleanup.js';
+
+// Re-export the moved functions so existing consumers (subAgentSpawner,
+// agentManagement) keep importing them from agentLifecycle.js. cleanupAgentWorktree
+// is also used internally (passed as cleanupWorktreeFn to the spawn helpers), so it
+// stays imported above; the rest are pure pass-throughs.
+export { cleanupAgentWorktree };
+export { spawnReviewLoopFollowUp, spawnMergeRecoveryTask } from './agentWorktreeCleanup.js';
+export { handlePipelineProgression } from './agentCompletionCleanup.js';
const ROOT_DIR = PATHS.root;
const AGENTS_DIR = PATHS.cosAgents;