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(cos): address round 4 Copilot review feedback

Adam Eivy5e36e87f35d0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 2d5ffb736e..8475b2fa47 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -17,6 +17,7 @@
- Personal Goals dashboard widget: shows top-level goals with progress bars, category icons, horizon labels, and stall detection (14+ days idle) — replaces broken CoS task-based goal widget that never rendered
## Changed
+- Exported `cleanupAgentWorktree` from `subAgentSpawner.js` with dedicated test file covering the openPR completion path (push, PR creation, failure preservation, auto-merge fallback)
- Exported `isTruthyMeta` from `subAgentSpawner.js` and `applyAppWorktreeDefault` from `cos.js`; tests now import production helpers instead of duplicating their logic inline
- Consolidated 5 duplicate `timeAgo`/`formatTimeAgo` implementations into a single `timeAgo()` in `utils/formatters.js`
- Deduplicated `stripCodeFences` from insightsService — now imports from shared `lib/aiProvider.js`
diff --git a/client/src/components/apps/EditAppModal.jsx b/client/src/components/apps/EditAppModal.jsx
index c645ea69ab..29d2e46a92 100644
--- a/client/src/components/apps/EditAppModal.jsx
+++ b/client/src/components/apps/EditAppModal.jsx
@@ -16,8 +16,8 @@ export default function EditAppModal({ app, onClose, onSave }) {
startCommands: (app.startCommands || []).join('\n'),
pm2ProcessNames: (app.pm2ProcessNames || []).join(', '),
editorCommand: app.editorCommand || 'code .',
- defaultUseWorktree: app.defaultUseWorktree || false,
defaultOpenPR: app.defaultOpenPR || false,
+ defaultUseWorktree: app.defaultUseWorktree || app.defaultOpenPR || false,
jiraEnabled: app.jira?.enabled || false,
jiraInstanceId: app.jira?.instanceId || '',
jiraProjectKey: app.jira?.projectKey || '',
@@ -91,7 +91,7 @@ export default function EditAppModal({ app, onClose, onSave }) {
? formData.pm2ProcessNames.split(',').map(s => s.trim()).filter(Boolean)
: undefined,
editorCommand: formData.editorCommand || undefined,
- defaultUseWorktree: formData.defaultUseWorktree,
+ defaultUseWorktree: formData.defaultUseWorktree || formData.defaultOpenPR,
defaultOpenPR: formData.defaultOpenPR,
jira: formData.jiraEnabled ? {
enabled: true,
diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.js
index c170bfd10b..8927f80c0f 100644
--- a/client/src/components/cos/constants.js
+++ b/client/src/components/cos/constants.js
@@ -59,6 +59,8 @@ export const AGENT_OPTIONS = [
// Compute new taskMetadata after toggling a field in a per-app override.
// Returns null when all overrides are cleared (inherit everything).
+// Enforces invariant: openPR implies useWorktree (turning on openPR forces
+// useWorktree on; turning off useWorktree forces openPR off).
export function toggleAppMetadataOverride(overrideMetadata, globalMetadata, field) {
const current = overrideMetadata || {};
const newMeta = { ...current };
@@ -68,6 +70,24 @@ export function toggleAppMetadataOverride(overrideMetadata, globalMetadata, fiel
const effective = overrideMetadata?.[field] ?? globalMetadata?.[field] ?? false;
newMeta[field] = !effective;
}
+
+ const resolve = (f) => newMeta[f] ?? globalMetadata?.[f] ?? false;
+
+ // openPR requires useWorktree
+ if (resolve('openPR') && !resolve('useWorktree')) {
+ newMeta.useWorktree = true;
+ }
+ // useWorktree off means openPR must be off
+ if (!resolve('useWorktree') && resolve('openPR')) {
+ newMeta.openPR = false;
+ }
+
+ // Clean entries that match the global value (revert to inherit)
+ for (const key of Object.keys(newMeta)) {
+ if (newMeta[key] === (globalMetadata?.[key] ?? false)) {
+ delete newMeta[key];
+ }
+ }
return Object.keys(newMeta).length ? newMeta : null;
}
diff --git a/client/src/components/cos/tabs/ScheduleTab.jsx b/client/src/components/cos/tabs/ScheduleTab.jsx
index 203a3290d6..9844842e25 100644
--- a/client/src/components/cos/tabs/ScheduleTab.jsx
+++ b/client/src/components/cos/tabs/ScheduleTab.jsx
@@ -23,9 +23,18 @@ const INTERVAL_DESCRIPTIONS = {
custom: 'Custom interval'
};
+// Toggle a global taskMetadata field, enforcing the openPR→useWorktree invariant.
function toggleMetadataField(metadata, field) {
const current = metadata || {};
const newMeta = { ...current, [field]: !current[field] };
+ // openPR requires useWorktree
+ if (newMeta.openPR && !newMeta.useWorktree) {
+ newMeta.useWorktree = true;
+ }
+ // useWorktree off means openPR must be off
+ if (newMeta.useWorktree === false && newMeta.openPR) {
+ newMeta.openPR = false;
+ }
const active = Object.fromEntries(Object.entries(newMeta).filter(([, v]) => v));
return Object.keys(active).length ? active : null;
}
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
new file mode 100644
index 0000000000..7446ae8bb4
--- /dev/null
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -0,0 +1,371 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// --- Mock every dependency subAgentSpawner.js imports ---
+
+vi.mock('child_process', () => ({
+ spawn: vi.fn(),
+ execSync: vi.fn()
+}));
+
+vi.mock('fs/promises', () => ({
+ writeFile: vi.fn().mockResolvedValue(undefined),
+ mkdir: vi.fn().mockResolvedValue(undefined),
+ readFile: vi.fn().mockResolvedValue(''),
+ readdir: vi.fn().mockResolvedValue([]),
+ rm: vi.fn().mockResolvedValue(undefined),
+ stat: vi.fn().mockResolvedValue({ isDirectory: () => true })
+}));
+
+vi.mock('fs', () => ({
+ existsSync: vi.fn(() => false)
+}));
+
+vi.mock('uuid', () => ({
+ v4: vi.fn(() => 'mock-uuid')
+}));
+
+vi.mock('./cos.js', () => ({
+ cosEvents: { on: vi.fn(), emit: vi.fn() },
+ registerAgent: vi.fn().mockResolvedValue(undefined),
+ updateAgent: vi.fn().mockResolvedValue(undefined),
+ completeAgent: vi.fn().mockResolvedValue(undefined),
+ appendAgentOutput: vi.fn().mockResolvedValue(undefined),
+ getConfig: vi.fn().mockResolvedValue({}),
+ updateTask: vi.fn().mockResolvedValue(undefined),
+ addTask: vi.fn().mockResolvedValue(undefined),
+ emitLog: vi.fn(),
+ getTaskById: vi.fn().mockResolvedValue(null),
+ getAgent: vi.fn().mockResolvedValue(null)
+}));
+
+vi.mock('./appActivity.js', () => ({
+ startAppCooldown: vi.fn(),
+ markAppReviewCompleted: vi.fn()
+}));
+
+vi.mock('./cosRunnerClient.js', () => ({
+ isRunnerAvailable: vi.fn(() => false),
+ spawnAgentViaRunner: vi.fn(),
+ terminateAgentViaRunner: vi.fn(),
+ killAgentViaRunner: vi.fn(),
+ getAgentStatsFromRunner: vi.fn(),
+ initCosRunnerConnection: vi.fn(),
+ onCosRunnerEvent: vi.fn(),
+ getActiveAgentsFromRunner: vi.fn(() => []),
+ getRunnerHealth: vi.fn()
+}));
+
+vi.mock('./providers.js', () => ({
+ getActiveProvider: vi.fn(),
+ getProviderById: vi.fn(),
+ getAllProviders: vi.fn(() => [])
+}));
+
+vi.mock('./usage.js', () => ({
+ recordSession: vi.fn(),
+ recordMessages: vi.fn()
+}));
+
+vi.mock('./providerStatus.js', () => ({
+ isProviderAvailable: vi.fn(() => true),
+ markProviderUsageLimit: vi.fn(),
+ markProviderRateLimited: vi.fn(),
+ getFallbackProvider: vi.fn(),
+ getProviderStatus: vi.fn(),
+ initProviderStatus: vi.fn()
+}));
+
+vi.mock('./promptService.js', () => ({
+ buildPrompt: vi.fn()
+}));
+
+vi.mock('./agents.js', () => ({
+ registerSpawnedAgent: vi.fn(),
+ unregisterSpawnedAgent: vi.fn()
+}));
+
+vi.mock('./memoryRetriever.js', () => ({
+ getMemorySection: vi.fn()
+}));
+
+vi.mock('./memoryExtractor.js', () => ({
+ extractAndStoreMemories: vi.fn()
+}));
+
+vi.mock('./digital-twin.js', () => ({
+ getDigitalTwinForPrompt: vi.fn()
+}));
+
+vi.mock('./taskLearning.js', () => ({
+ suggestModelTier: vi.fn()
+}));
+
+vi.mock('../lib/fileUtils.js', () => ({
+ ensureDir: vi.fn().mockResolvedValue(undefined),
+ readJSONFile: vi.fn().mockResolvedValue({}),
+ PATHS: {
+ root: '/mock/root',
+ cosAgents: '/mock/root/data/cos/agents',
+ runs: '/mock/root/data/runs',
+ worktrees: '/mock/root/data/cos/worktrees',
+ data: '/mock/root/data',
+ cos: '/mock/root/data/cos'
+ }
+}));
+
+vi.mock('./apps.js', () => ({
+ getAppById: vi.fn()
+}));
+
+vi.mock('./toolStateMachine.js', () => ({
+ createToolExecution: vi.fn(),
+ startExecution: vi.fn(),
+ updateExecution: vi.fn(),
+ completeExecution: vi.fn(),
+ errorExecution: vi.fn(),
+ getExecution: vi.fn(),
+ getStats: vi.fn()
+}));
+
+vi.mock('./thinkingLevels.js', () => ({
+ resolveThinkingLevel: vi.fn(),
+ getModelForLevel: vi.fn(),
+ isLocalPreferred: vi.fn(() => false)
+}));
+
+vi.mock('./executionLanes.js', () => ({
+ determineLane: vi.fn(),
+ acquire: vi.fn(),
+ release: vi.fn(),
+ hasCapacity: vi.fn(() => true),
+ waitForLane: vi.fn()
+}));
+
+vi.mock('./taskConflict.js', () => ({
+ detectConflicts: vi.fn(() => [])
+}));
+
+vi.mock('./worktreeManager.js', () => ({
+ createWorktree: vi.fn(),
+ removeWorktree: vi.fn().mockResolvedValue(undefined),
+ cleanupOrphanedWorktrees: vi.fn()
+}));
+
+vi.mock('./jira.js', () => ({
+ default: {}
+}));
+
+vi.mock('./git.js', () => ({
+ push: vi.fn(),
+ getRepoBranches: vi.fn(),
+ createPR: vi.fn()
+}));
+
+vi.mock('./runner.js', () => ({
+ executeApiRun: vi.fn(),
+ executeCliRun: vi.fn(),
+ createRun: vi.fn()
+}));
+
+// --- Import the function under test and the mocked dependencies ---
+
+import { cleanupAgentWorktree } from './subAgentSpawner.js';
+import { getAgent } from './cos.js';
+import { removeWorktree } from './worktreeManager.js';
+import * as git from './git.js';
+
+// Helper: build a mock agent state for worktree agents
+function mockWorktreeAgent(overrides = {}) {
+ return {
+ metadata: {
+ isWorktree: true,
+ isPersistentWorktree: false,
+ sourceWorkspace: '/mock/workspace',
+ worktreeBranch: 'cos/task-abc123',
+ workspacePath: '/mock/root/data/cos/worktrees/agent-1',
+ ...overrides
+ }
+ };
+}
+
+describe('cleanupAgentWorktree - openPR path', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ // Default: agent is a worktree agent with valid metadata
+ getAgent.mockResolvedValue(mockWorktreeAgent());
+ git.getRepoBranches.mockResolvedValue({ baseBranch: 'main', devBranch: null });
+ });
+
+ it('should run PR flow when openPR is true and success is true', async () => {
+ git.push.mockResolvedValue(undefined);
+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/1' });
+
+ await cleanupAgentWorktree('agent-1', true, { openPR: true, description: 'Test task' });
+
+ expect(git.push).toHaveBeenCalledWith('/mock/root/data/cos/worktrees/agent-1', 'cos/task-abc123');
+ expect(git.createPR).toHaveBeenCalledWith('/mock/root/data/cos/worktrees/agent-1', {
+ title: 'Test task',
+ body: expect.stringContaining('Test task'),
+ base: 'main',
+ head: 'cos/task-abc123'
+ });
+ expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: false });
+ });
+
+ it('should call removeWorktree with merge: false after successful push and PR', async () => {
+ git.push.mockResolvedValue(undefined);
+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/2' });
+
+ await cleanupAgentWorktree('agent-1', true, { openPR: true });
+
+ expect(removeWorktree).toHaveBeenCalledTimes(1);
+ expect(removeWorktree).toHaveBeenCalledWith(
+ 'agent-1',
+ '/mock/workspace',
+ 'cos/task-abc123',
+ { merge: false }
+ );
+ });
+
+ it('should preserve worktree when push fails (no removeWorktree call)', async () => {
+ git.push.mockRejectedValue(new Error('push rejected'));
+
+ await cleanupAgentWorktree('agent-1', true, { openPR: true, description: 'Test task' });
+
+ expect(git.push).toHaveBeenCalled();
+ expect(git.createPR).not.toHaveBeenCalled();
+ expect(removeWorktree).not.toHaveBeenCalled();
+ });
+
+ it('should preserve worktree when createPR returns { success: false }', async () => {
+ git.push.mockResolvedValue(undefined);
+ git.createPR.mockResolvedValue({ success: false, error: 'PR already exists' });
+
+ await cleanupAgentWorktree('agent-1', true, { openPR: true, description: 'Test task' });
+
+ expect(git.createPR).toHaveBeenCalled();
+ expect(removeWorktree).not.toHaveBeenCalled();
+ });
+
+ it('should use auto-merge path when openPR is false (success)', async () => {
+ await cleanupAgentWorktree('agent-1', true, { openPR: false });
+
+ expect(git.push).not.toHaveBeenCalled();
+ expect(git.createPR).not.toHaveBeenCalled();
+ expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: true });
+ });
+
+ it('should use auto-merge path when openPR is not provided (defaults to false)', async () => {
+ await cleanupAgentWorktree('agent-1', true);
+
+ expect(git.push).not.toHaveBeenCalled();
+ expect(git.createPR).not.toHaveBeenCalled();
+ expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: true });
+ });
+
+ it('should skip PR flow when openPR is true but success is false', async () => {
+ await cleanupAgentWorktree('agent-1', false, { openPR: true });
+
+ expect(git.push).not.toHaveBeenCalled();
+ expect(git.createPR).not.toHaveBeenCalled();
+ // Falls through to auto-merge path with merge: false (failure cleanup)
+ expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: false });
+ });
+
+ it('should use devBranch as PR base when available', async () => {
+ git.push.mockResolvedValue(undefined);
+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/3' });
+ git.getRepoBranches.mockResolvedValue({ baseBranch: 'main', devBranch: 'develop' });
+
+ await cleanupAgentWorktree('agent-1', true, { openPR: true, description: 'Test' });
+
+ expect(git.createPR).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({
+ base: 'develop'
+ }));
+ });
+
+ it('should fall back to "main" when getRepoBranches fails', async () => {
+ git.push.mockResolvedValue(undefined);
+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/4' });
+ git.getRepoBranches.mockRejectedValue(new Error('not a git repo'));
+
+ await cleanupAgentWorktree('agent-1', true, { openPR: true, description: 'Test' });
+
+ expect(git.createPR).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({
+ base: 'main'
+ }));
+ });
+
+ it('should still remove worktree when createPR throws (null result)', async () => {
+ git.push.mockResolvedValue(undefined);
+ git.createPR.mockRejectedValue(new Error('network error'));
+
+ await cleanupAgentWorktree('agent-1', true, { openPR: true, description: 'Test' });
+
+ // createPR catches the error and returns null; null?.success is undefined (not false),
+ // so it proceeds to removeWorktree
+ expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: false });
+ });
+
+ it('should truncate long descriptions to 100 chars for PR title', async () => {
+ const longDesc = 'A'.repeat(200);
+ git.push.mockResolvedValue(undefined);
+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/5' });
+
+ await cleanupAgentWorktree('agent-1', true, { openPR: true, description: longDesc });
+
+ expect(git.createPR).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({
+ title: 'A'.repeat(100)
+ }));
+ });
+
+ it('should use default description when none provided', async () => {
+ git.push.mockResolvedValue(undefined);
+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/6' });
+
+ await cleanupAgentWorktree('agent-1', true, { openPR: true });
+
+ expect(git.createPR).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({
+ title: 'CoS automated task',
+ body: expect.stringContaining('CoS automated task')
+ }));
+ });
+
+ // --- Early-exit guard tests ---
+
+ it('should no-op when agent is not a worktree agent', async () => {
+ getAgent.mockResolvedValue({ metadata: { isWorktree: false } });
+
+ await cleanupAgentWorktree('agent-1', true, { openPR: true });
+
+ expect(git.push).not.toHaveBeenCalled();
+ expect(removeWorktree).not.toHaveBeenCalled();
+ });
+
+ it('should no-op when agent state is null', async () => {
+ getAgent.mockResolvedValue(null);
+
+ await cleanupAgentWorktree('agent-1', true, { openPR: true });
+
+ expect(git.push).not.toHaveBeenCalled();
+ expect(removeWorktree).not.toHaveBeenCalled();
+ });
+
+ it('should no-op for persistent worktree agents', async () => {
+ getAgent.mockResolvedValue(mockWorktreeAgent({ isPersistentWorktree: true }));
+
+ await cleanupAgentWorktree('agent-1', true, { openPR: true });
+
+ expect(git.push).not.toHaveBeenCalled();
+ expect(removeWorktree).not.toHaveBeenCalled();
+ });
+
+ it('should no-op when sourceWorkspace or worktreeBranch is missing', async () => {
+ getAgent.mockResolvedValue(mockWorktreeAgent({ sourceWorkspace: null }));
+
+ await cleanupAgentWorktree('agent-1', true, { openPR: true });
+
+ expect(git.push).not.toHaveBeenCalled();
+ expect(removeWorktree).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index 28e27cef1f..780724b0ca 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -1957,7 +1957,7 @@ async function handleAgentCompletion(agentId, exitCode, success, duration) {
* When openPR is true, pushes the branch and creates a PR instead of auto-merging.
* Otherwise, merges the worktree branch back to the source branch on success.
*/
-async function cleanupAgentWorktree(agentId, success, { openPR = false, description = null } = {}) {
+export async function cleanupAgentWorktree(agentId, success, { openPR = false, description = null } = {}) {
const { getAgent: getAgentState } = await import('./cos.js');
const agentState = await getAgentState(agentId).catch(() => null);
if (!agentState?.metadata?.isWorktree) return;