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
feat(cos): split worktree and PR configs into independent settings
Adam Eivya4fc70cb7378
diff --git a/client/src/components/apps/EditAppModal.jsx b/client/src/components/apps/EditAppModal.jsxindex 035a96632a..c645ea69ab 100644--- a/client/src/components/apps/EditAppModal.jsx+++ b/client/src/components/apps/EditAppModal.jsx@@ -1,6 +1,6 @@import { useState, useEffect } from 'react';import { Link } from 'react-router-dom';-import { ChevronDown, ChevronUp, GitBranch } from 'lucide-react';+import { ChevronDown, ChevronUp, GitBranch, GitPullRequest } from 'lucide-react';import IconPicker from '../IconPicker';import * as api from '../../services/api';@@ -17,6 +17,7 @@ export default function EditAppModal({ app, onClose, onSave }) {pm2ProcessNames: (app.pm2ProcessNames || []).join(', '),editorCommand: app.editorCommand || 'code .',defaultUseWorktree: app.defaultUseWorktree || false,+ defaultOpenPR: app.defaultOpenPR || false,jiraEnabled: app.jira?.enabled || false,jiraInstanceId: app.jira?.instanceId || '',jiraProjectKey: app.jira?.projectKey || '',@@ -91,6 +92,7 @@ export default function EditAppModal({ app, onClose, onSave }) {: undefined,editorCommand: formData.editorCommand || undefined,defaultUseWorktree: formData.defaultUseWorktree,+ defaultOpenPR: formData.defaultOpenPR,jira: formData.jiraEnabled ? {enabled: true,instanceId: formData.jiraInstanceId || undefined,@@ -242,11 +244,26 @@ export default function EditAppModal({ app, onClose, onSave }) {<inputtype="checkbox"checked={formData.defaultUseWorktree}- onChange={e => setFormData({ ...formData, defaultUseWorktree: e.target.checked })}+ onChange={e => {+ const updates = { defaultUseWorktree: e.target.checked };+ if (!e.target.checked) updates.defaultOpenPR = false;+ setFormData(prev => ({ ...prev, ...updates }));+ }}className="rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"/><GitBranch size={14} className="text-emerald-400" />- <span className="text-sm text-white" title="When checked, new tasks default to working in an isolated git worktree on a feature branch, then opening a PR. When unchecked, agents commit directly to the default branch.">Default to Worktree + PR for new tasks</span>+ <span className="text-sm text-white" title="When checked, new tasks default to working in an isolated git worktree on a feature branch. When unchecked, agents commit directly to the default branch.">Default to Worktree for new tasks</span>+ </label>+ <label className="flex items-center gap-2 cursor-pointer ml-6">+ <input+ type="checkbox"+ checked={formData.defaultOpenPR}+ disabled={!formData.defaultUseWorktree}+ onChange={e => setFormData(prev => ({ ...prev, defaultOpenPR: e.target.checked }))}+ className="rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent disabled:opacity-40"+ />+ <GitPullRequest size={14} className="text-blue-400" />+ <span className={`text-sm ${formData.defaultUseWorktree ? 'text-white' : 'text-gray-600'}`} title="When checked, agents open a PR to the default branch. When unchecked with worktree enabled, agents auto-merge to the default branch on completion.">Default to Open PR for new tasks</span></label>{/* JIRA Integration Section */}diff --git a/client/src/components/cos/TaskAddForm.jsx b/client/src/components/cos/TaskAddForm.jsxindex cfdaf9b1bf..5cda3ba556 100644--- a/client/src/components/cos/TaskAddForm.jsx+++ b/client/src/components/cos/TaskAddForm.jsx@@ -1,5 +1,5 @@import { useState, useEffect, useRef, useMemo, useCallback } from 'react';-import { Plus, Image, X, ChevronDown, ChevronRight, Sparkles, Loader2, Paperclip, FileText, Zap, Bookmark, Ticket, GitBranch, Wand2, RefreshCw } from 'lucide-react';+import { Plus, Image, X, ChevronDown, ChevronRight, Sparkles, Loader2, Paperclip, FileText, Zap, Bookmark, Ticket, GitBranch, GitPullRequest, Wand2, RefreshCw } from 'lucide-react';import toast from 'react-hot-toast';import * as api from '../../services/api';import { processScreenshotUploads, processAttachmentUploads } from '../../utils/fileUpload';@@ -11,6 +11,7 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = faconst [enhancePrompt, setEnhancePrompt] = useState(false);const [isEnhancing, setIsEnhancing] = useState(false);const [useWorktree, setUseWorktree] = useState(false);+ const [openPR, setOpenPR] = useState(false);const [simplify, setSimplify] = useState(true);const [reviewLoop, setReviewLoop] = useState(false);const [createJiraTicket, setCreateJiraTicket] = useState(false);@@ -45,11 +46,12 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa);const appHasJira = selectedApp?.jira?.enabled;- // Auto-toggle JIRA and worktree checkboxes when app selection changes+ // Auto-toggle JIRA, worktree, and PR checkboxes when app selection changesuseEffect(() => {const app = apps?.find(a => a.id === newTask.app);setCreateJiraTicket(!!app?.jira?.enabled);setUseWorktree(!!app?.defaultUseWorktree);+ setOpenPR(!!app?.defaultOpenPR);}, [newTask.app, apps]);// Get models for selected provider@@ -184,6 +186,7 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = faapp: newTask.app || undefined,createJiraTicket: createJiraTicket || undefined,useWorktree: useWorktree || undefined,+ openPR: openPR || undefined,simplify: simplify || undefined,reviewLoop: reviewLoop || undefined,screenshots: screenshots.length > 0 ? screenshots.map(s => s.path) : undefined,@@ -211,6 +214,7 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fasetEnhancePrompt(false);setCreateJiraTicket(false);setUseWorktree(false);+ setOpenPR(false);setSimplify(true);setReviewLoop(false);setExpanded(false);@@ -377,12 +381,28 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa<inputtype="checkbox"checked={useWorktree}- onChange={(e) => setUseWorktree(e.target.checked)}+ onChange={(e) => {+ setUseWorktree(e.target.checked);+ if (!e.target.checked) setOpenPR(false);+ }}className="w-4 h-4 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent focus:ring-offset-0"/>- <span className="flex items-center gap-1.5 text-sm text-gray-400" title="Work in an isolated git worktree on a feature branch, then open a PR. If unchecked, commits directly to the default branch.">+ <span className="flex items-center gap-1.5 text-sm text-gray-400" title="Work in an isolated git worktree on a feature branch. If unchecked, commits directly to the default branch."><GitBranch size={14} className="text-emerald-400" />- Worktree + PR+ Worktree+ </span>+ </label>+ <label className="flex items-center gap-2 cursor-pointer select-none whitespace-nowrap min-h-[44px]">+ <input+ type="checkbox"+ checked={openPR}+ disabled={!useWorktree}+ onChange={(e) => setOpenPR(e.target.checked)}+ className="w-4 h-4 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent focus:ring-offset-0 disabled:opacity-40"+ />+ <span className={`flex items-center gap-1.5 text-sm ${useWorktree ? 'text-gray-400' : 'text-gray-600'}`} title="Open a pull request to the default branch. If unchecked with worktree enabled, auto-merges on completion.">+ <GitPullRequest size={14} className={useWorktree ? 'text-blue-400' : 'text-gray-600'} />+ Open PR</span></label><label className="flex items-center gap-2 cursor-pointer select-none whitespace-nowrap min-h-[44px]">diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.jsindex 1f2e89dd22..c90be8fb0e 100644--- a/client/src/components/cos/constants.js+++ b/client/src/components/cos/constants.js@@ -49,9 +49,10 @@ export const STATE_MESSAGES = {ideating: "Analyzing options...",};-// Agent option toggles for task metadata (useWorktree, simplify, reviewLoop)+// Agent option toggles for task metadata (useWorktree, openPR, simplify, reviewLoop)export const AGENT_OPTIONS = [- { field: 'useWorktree', label: 'Worktree + PR', shortLabel: 'WT', description: 'Work in an isolated git worktree on a feature branch, then open a PR. If unchecked, commits directly to the default branch.' },+ { field: 'useWorktree', label: 'Worktree', shortLabel: 'WT', description: 'Work in an isolated git worktree on a feature branch. If unchecked, commits directly to the default branch.' },+ { field: 'openPR', label: 'Open PR', shortLabel: 'PR', description: 'Open a pull request to the default branch (implies worktree). If unchecked with worktree enabled, auto-merges to the default branch on completion.' },{ field: 'simplify', label: 'Run /simplify', shortLabel: '/s', description: 'Review code for reuse and quality before committing' },{ field: 'reviewLoop', label: 'Review Loop', shortLabel: 'RL', description: 'After opening a PR, run review feedback loop until checks pass and PR is approved' }];diff --git a/server/lib/validation.js b/server/lib/validation.jsindex bec21dad49..8d7c0db9b3 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -198,6 +198,7 @@ export const appSchema = z.object({interval: z.string().nullable().optional()})).optional(), // Per-task overrides: { [taskType]: { enabled, interval } }defaultUseWorktree: z.boolean().optional().default(false),+ defaultOpenPR: z.boolean().optional().default(false),jira: jiraConfigSchema.optional().nullable(),datadog: datadogConfigSchema.optional().nullable()});@@ -542,7 +543,7 @@ export function validateRequest(schema, data) {// TASK METADATA SANITIZATION// =============================================================================-const ALLOWED_TASK_METADATA_KEYS = ['useWorktree', 'simplify', 'reviewLoop'];+const ALLOWED_TASK_METADATA_KEYS = ['useWorktree', 'openPR', 'simplify', 'reviewLoop'];/*** Sanitize taskMetadata to only allowed agent-option keys with boolean values.diff --git a/server/routes/cos.js b/server/routes/cos.jsindex dd5c0936d0..7ff3179704 100644--- a/server/routes/cos.js+++ b/server/routes/cos.js@@ -191,13 +191,13 @@ router.post('/tasks/enhance', asyncHandler(async (req, res) => {// POST /api/cos/tasks - Add a new taskrouter.post('/tasks', asyncHandler(async (req, res) => {- const { description, priority, context, model, provider, app, type = 'user', approvalRequired, screenshots, attachments, position = 'bottom', createJiraTicket, jiraTicketId, jiraTicketUrl, useWorktree, simplify, reviewLoop } = req.body;+ const { description, priority, context, model, provider, app, type = 'user', approvalRequired, screenshots, attachments, position = 'bottom', createJiraTicket, jiraTicketId, jiraTicketUrl, useWorktree, openPR, simplify, reviewLoop } = req.body;if (!description) {throw new ServerError('Description is required', { status: 400, code: 'VALIDATION_ERROR' });}- const taskData = { description, priority, context, model, provider, app, approvalRequired, screenshots, attachments, position, createJiraTicket, jiraTicketId, jiraTicketUrl, useWorktree, simplify, reviewLoop };+ const taskData = { description, priority, context, model, provider, app, approvalRequired, screenshots, attachments, position, createJiraTicket, jiraTicketId, jiraTicketUrl, useWorktree, openPR, simplify, reviewLoop };const result = await cos.addTask(taskData, type);if (result?.duplicate) {diff --git a/server/services/cos.js b/server/services/cos.jsindex 30b17331e6..91db3369a3 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -1866,12 +1866,19 @@ Use model: claude-opus-4-5-20251101 for thorough security analysis`* @param {Object} state - Current CoS state* @returns {Object} Generated task*/-// When an app explicitly sets defaultUseWorktree, override per-task-type metadata+// When an app explicitly sets defaultUseWorktree/defaultOpenPR, override per-task-type metadatafunction applyAppWorktreeDefault(metadata, app) {if (app.defaultUseWorktree === true) {metadata.useWorktree = true;} else if (app.defaultUseWorktree === false) {metadata.useWorktree = false;+ metadata.openPR = false;+ }+ if (app.defaultOpenPR === true && metadata.useWorktree !== false) {+ metadata.openPR = true;+ metadata.useWorktree = true; // openPR implies useWorktree+ } else if (app.defaultOpenPR === false) {+ metadata.openPR = false;}}@@ -3191,6 +3198,7 @@ export async function addTask(taskData, taskType = 'user', { raw = false } = {})if (taskData.app) metadata.app = taskData.app;if (taskData.createJiraTicket) metadata.createJiraTicket = true;if (taskData.useWorktree) metadata.useWorktree = true;+ if (taskData.openPR) metadata.openPR = true;if (taskData.simplify) metadata.simplify = true;if (taskData.reviewLoop) metadata.reviewLoop = true;if (taskData.jiraTicketId) metadata.jiraTicketId = taskData.jiraTicketId;diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex 560b911601..6e9bcd1d23 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -39,6 +39,9 @@ const ROOT_DIR = PATHS.root;const AGENTS_DIR = PATHS.cosAgents;const RUNS_DIR = PATHS.runs;+// Metadata booleans may arrive as true or 'true' (from JSON vs form/URL params)+const isTruthyMeta = (value) => value === true || value === 'true';+/*** Extract task type key for learning lookup* Matches the format used in taskLearning.js for consistency@@ -1470,12 +1473,13 @@ export async function spawnAgentForTask(task) {}}- // Determine worktree usage: explicit user flag takes priority, then conflict-based auto-detection.- // The useWorktree metadata flag is set from the task creation UI checkbox.- // When true, always create a worktree (branch + PR). When not set, only create a- // worktree if conflict is detected with other running agents.+ // Determine worktree usage: explicit user flags take priority, then conflict-based auto-detection.+ // useWorktree: work in an isolated worktree branch+ // openPR: open a PR to default branch (implies useWorktree)+ // When neither is set, only create a worktree if conflict is detected with other running agents.let worktreeInfo = null;- const explicitWorktree = task.metadata?.useWorktree === 'true' || task.metadata?.useWorktree === true;+ const explicitOpenPR = isTruthyMeta(task.metadata?.openPR);+ const explicitWorktree = isTruthyMeta(task.metadata?.useWorktree) || explicitOpenPR;// Feature agent tasks: use persistent worktree instead of creating a new oneif (task.metadata?.featureAgentRun && task.metadata?.featureAgentId) {@@ -1939,7 +1943,8 @@ async function handleAgentCompletion(agentId, exitCode, success, duration) {// Clean up worktree if agent was using one (skip merge when JIRA branch — PR handles merge)if (!jiraBranch) {- await cleanupAgentWorktree(agentId, success);+ const taskOpenPR = isTruthyMeta(agent.task?.metadata?.openPR);+ await cleanupAgentWorktree(agentId, success, { openPR: taskOpenPR, description: task?.description });}runnerAgents.delete(agentId);@@ -1948,9 +1953,10 @@ async function handleAgentCompletion(agentId, exitCode, success, duration) {/*** Clean up a worktree for a completed agent.* Reads worktree metadata from the agent's registered state and removes the worktree.- * On success, merges the worktree branch back to the source branch.+ * 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) {+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;@@ -1960,6 +1966,49 @@ async function cleanupAgentWorktree(agentId, success) {const { sourceWorkspace, worktreeBranch } = agentState.metadata;if (!sourceWorkspace || !worktreeBranch) return;+ // When openPR is set and task succeeded, push branch and create PR instead of auto-merging+ if (openPR && success) {+ emitLog('info', `🌳 Opening PR for worktree agent ${agentId} branch ${worktreeBranch}`, { agentId, branchName: worktreeBranch });++ const worktreePath = agentState.metadata.workspacePath || join(PATHS.worktrees, agentId);++ // Push branch and resolve target branch in parallel+ const [pushResult, branchInfo] = await Promise.all([+ git.push(worktreePath, worktreeBranch).then(() => true).catch(err => {+ emitLog('warn', `🌳 Failed to push worktree branch ${worktreeBranch}: ${err.message}`, { agentId });+ return false;+ }),+ git.getRepoBranches(sourceWorkspace).catch(() => ({ baseBranch: null, devBranch: null }))+ ]);++ // Only create PR if push succeeded+ if (pushResult) {+ const targetBranch = branchInfo.devBranch || branchInfo.baseBranch || 'main';+ const taskDesc = description || 'CoS automated task';++ const prResult = await git.createPR(worktreePath, {+ title: taskDesc.substring(0, 100),+ body: `Automated PR created by PortOS Chief of Staff.\n\n**Task:** ${taskDesc}`,+ base: targetBranch,+ head: worktreeBranch+ }).catch(err => {+ emitLog('warn', `🌳 Failed to create PR for ${worktreeBranch}: ${err.message}`, { agentId });+ return null;+ });++ if (prResult?.success) {+ emitLog('success', `🌳 Created PR: ${prResult.url}`, { agentId, branchName: worktreeBranch });+ }+ }++ // Remove worktree without merging (PR handles merge)+ await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: false }).catch(err => {+ emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });+ });+ return;+ }++ // Default: auto-merge on success, just cleanup on failureemitLog('info', `🌳 Cleaning up worktree for agent ${agentId} (merge: ${success})`, {agentId, branchName: worktreeBranch, merge: success});@@ -2620,6 +2669,7 @@ async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo = null)const compactionSection = task.metadata?.compaction?.needed ? buildCompactionSection(task) : '';// Build worktree context section if applicable+ const willOpenPR = isTruthyMeta(task.metadata?.openPR);const worktreeSection = worktreeInfo ? `## Git Worktree ContextYou are working in an **isolated git worktree** to avoid conflicts with other agents working concurrently.@@ -2627,7 +2677,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**: Commit your changes to this branch. Your commits will be automatically merged back to the main development branch when your task completes. Do NOT manually switch branches or modify the worktree configuration.+**Important**: Commit your changes to this branch.${willOpenPR ? ' Your commits will be submitted as a pull request to the default branch when your task completes.' : ' Your commits will be automatically merged back to the main development branch when your task completes.'} Do NOT manually switch branches or modify the worktree configuration.` : '';// Build simplify section if enabled@@ -2739,7 +2789,7 @@ ${skillSection ? `## Task-Type Skill Guidelines\n\n${skillSection}\n` : ''}${pla- Do not make unrelated changes- If blocked, explain clearly why- Never update the PortOS changelog (\`.changelog/\`) for work on managed apps — the PortOS changelog tracks PortOS core changes only-${task.metadata?.app && worktreeInfo ? `- **When done, create a pull request to the repo's default branch** (main/master) instead of committing directly to dev. Use the /pr skill or gh CLI to open the PR.` : `- Commit code after each feature or bug fix using the git tools or /cam skill`}+${task.metadata?.app && worktreeInfo && willOpenPR ? `- **When done, create a pull request to the repo's default branch** (main/master) instead of committing directly to dev. Use the /pr skill or gh CLI to open the PR.` : task.metadata?.app && worktreeInfo ? `- Commit code after each feature or bug fix using the git tools or /cam skill. Your worktree branch will be automatically merged back to the default branch when your task completes — do NOT open a PR.` : `- Commit code after each feature or bug fix using the git tools or /cam skill`}## Git Hygiene (CRITICAL)- **Before starting work**, run \`git status\` to verify a clean working tree. If there are uncommitted changes from a previous agent or manual work, **stash or discard them** before proceeding — do NOT commit someone else's changes.diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex dc958cbb55..3c9c5b8c65 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -872,12 +872,12 @@ const DEFAULT_TASK_INTERVALS = {'documentation': { type: INTERVAL_TYPES.ONCE, enabled: false, providerId: null, model: null, prompt: null },'ui-bugs': { type: INTERVAL_TYPES.ON_DEMAND, enabled: false, providerId: null, model: null, prompt: null },'mobile-responsive': { type: INTERVAL_TYPES.ON_DEMAND, enabled: false, providerId: null, model: null, prompt: null },- 'feature-ideas': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, simplify: true } },+ 'feature-ideas': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: true, simplify: true } },'error-handling': { type: INTERVAL_TYPES.ROTATION, enabled: false, providerId: null, model: null, prompt: null },'typing': { type: INTERVAL_TYPES.ONCE, enabled: false, providerId: null, model: null, prompt: null },'release-check': { type: INTERVAL_TYPES.ON_DEMAND, enabled: false, providerId: null, model: null, prompt: null },'pr-reviewer': { type: INTERVAL_TYPES.CUSTOM, intervalMs: 7200000, enabled: false, weekdaysOnly: true, providerId: null, model: null, prompt: null },- 'jira-sprint-manager': { type: INTERVAL_TYPES.DAILY, enabled: false, weekdaysOnly: true, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, simplify: true } }+ 'jira-sprint-manager': { type: INTERVAL_TYPES.DAILY, enabled: false, weekdaysOnly: true, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: true, simplify: true } }};/**