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): use agent output summary for PR descriptions instead of task prompt
Adam Eivy864028ad6b1b
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.jsindex 5e474e910d..efc523ee9b 100644--- a/server/services/cleanupAgentWorktree.test.js+++ b/server/services/cleanupAgentWorktree.test.js@@ -195,9 +195,9 @@ describe('cleanupAgentWorktree - openPR path', () => {// Default: agent is a worktree agent with valid metadatagetAgent.mockResolvedValue(mockWorktreeAgent());git.getRepoBranches.mockResolvedValue({ baseBranch: 'main', devBranch: null });- // generatePRDescription returns a rich body that includes the task description- git.generatePRDescription.mockImplementation((_dir, _base, _head, desc) =>- Promise.resolve(`Automated PR created by PortOS Chief of Staff.\n\n## Changes\n- feat: implemented task\n\n**1 file changed** (+10 -2)\n\n<details><summary>Original task</summary>\n\n${desc || 'CoS automated task'}\n\n</details>`)+ // generatePRDescription returns a rich body from agent output summary+ git.generatePRDescription.mockImplementation(() =>+ Promise.resolve('Automated PR created by PortOS Chief of Staff.\n\n## Summary\n\nImplemented the requested feature with new API endpoints and UI components.'));});@@ -210,7 +210,7 @@ describe('cleanupAgentWorktree - openPR path', () => {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'),+ body: expect.stringContaining('Summary'),base: 'main',head: 'cos/task-abc123'});@@ -331,7 +331,7 @@ describe('cleanupAgentWorktree - openPR path', () => {expect(git.createPR).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({title: 'CoS automated task',- body: expect.stringContaining('CoS automated task')+ body: expect.stringContaining('Chief of Staff')}));});diff --git a/server/services/git.js b/server/services/git.jsindex ba6977839e..1dab1fe84f 100644--- a/server/services/git.js+++ b/server/services/git.js@@ -410,57 +410,75 @@ export async function createPR(dir, { title, body, base, head }) {}/**- * Generate a rich PR description from branch commits and diff stats.- * Falls back to a simple description if git data is unavailable.+ * Generate a rich PR description from the agent's output summary.+ * Extracts the implementation summary from the tail of the agent output,+ * stripping tool-call artifacts and keeping only the meaningful explanation+ * of what was implemented (new APIs, UI elements, behaviors, etc.).+ * Falls back to commit messages when no agent output is available.* @param {string} dir - Working directory (repo root)* @param {string} baseBranch - Base branch (e.g., 'main')* @param {string} headBranch - Head branch (agent's branch)- * @param {string} taskDescription - Original task prompt+ * @param {string} agentOutput - Raw agent output text* @returns {Promise<string>} Formatted PR body*/-export async function generatePRDescription(dir, baseBranch, headBranch, taskDescription) {- const sections = ['Automated PR created by PortOS Chief of Staff.'];+export async function generatePRDescription(dir, baseBranch, headBranch, agentOutput) {+ const summary = extractAgentSummary(agentOutput);- const [comparison, changedFiles] = await Promise.all([- getBranchComparison(dir, baseBranch, headBranch).catch(() => null),- execGit(['diff', '--name-only', `${baseBranch}...${headBranch}`], dir, { ignoreExitCode: true })- .then(r => r.stdout.trim().split('\n').filter(Boolean)).catch(() => [])- ]);+ if (summary) {+ return `Automated PR created by PortOS Chief of Staff.\n\n## Summary\n\n${summary}`;+ }+ // Fallback: build from commit messages when no usable agent output+ const comparison = await getBranchComparison(dir, baseBranch, headBranch).catch(() => null);if (comparison?.commits?.length) {- sections.push('\n## Changes');- for (const c of comparison.commits) {- sections.push(`- ${c.message}`);- }+ const commitLines = comparison.commits.map(c => `- ${c.message}`).join('\n');+ return `Automated PR created by PortOS Chief of Staff.\n\n## Changes\n\n${commitLines}`;}- if (comparison?.stats) {- const { files, insertions, deletions } = comparison.stats;- if (files > 0) {- sections.push(`\n**${files} file${files === 1 ? '' : 's'} changed** (+${insertions} -${deletions})`);- }- }+ return 'Automated PR created by PortOS Chief of Staff.';+}- if (changedFiles.length > 0 && changedFiles.length <= 30) {- sections.push('\n<details><summary>Files changed</summary>\n');- for (const f of changedFiles) {- sections.push(`- \`${f}\``);- }- sections.push('\n</details>');- } else if (changedFiles.length > 30) {- sections.push(`\n<details><summary>Files changed (${changedFiles.length})</summary>\n`);- for (const f of changedFiles.slice(0, 30)) {- sections.push(`- \`${f}\``);+/**+ * Extract a meaningful implementation summary from raw agent output.+ * Agents typically end their output with a summary of what was implemented.+ * This function finds the last tool-call artifact in the tail of the output+ * and returns everything after it, cleaned up.+ * @param {string} output - Raw agent output+ * @returns {string|null} Cleaned summary text, or null if nothing usable+ */+export function extractAgentSummary(output) {+ if (!output || output.length < 50) return null;++ // Take the last ~4000 chars where the summary typically lives+ const tail = output.slice(-4000);+ const lines = tail.split('\n');++ // Find the last tool-call artifact line index.+ // Everything after it is the agent's final summary.+ let lastToolLine = -1;+ for (let i = lines.length - 1; i >= 0; i--) {+ const trimmed = lines[i].trimStart();+ if (trimmed.startsWith('→') || trimmed.startsWith('🔧') || /^\s*\$ /.test(lines[i])) {+ lastToolLine = i;+ break;}- sections.push(`- ... and ${changedFiles.length - 30} more`);- sections.push('\n</details>');}- if (taskDescription) {- sections.push(`\n<details><summary>Original task</summary>\n\n${taskDescription}\n\n</details>`);- }+ // Extract everything after the last tool line+ const summaryLines = lastToolLine >= 0+ ? lines.slice(lastToolLine + 1)+ : lines;++ // Trim leading/trailing blank lines+ while (summaryLines.length && !summaryLines[0].trim()) summaryLines.shift();+ while (summaryLines.length && !summaryLines[summaryLines.length - 1].trim()) summaryLines.pop();++ const summary = summaryLines.join('\n').trim();++ // Must have meaningful content (at least a sentence)+ if (summary.length < 30) return null;- return sections.join('\n');+ return summary;}/**diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex 382845cdb4..c46d39a6c7 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -1934,7 +1934,7 @@ async function handleAgentCompletion(agentId, exitCode, success, duration) {const { baseBranch, devBranch } = await git.getRepoBranches(workspace).catch(() => ({ baseBranch: null, devBranch: null }));const targetBranch = devBranch || baseBranch || 'main';- const jiraPrBody = await git.generatePRDescription(workspace, targetBranch, jiraBranch, task.description);+ const jiraPrBody = await git.generatePRDescription(workspace, targetBranch, jiraBranch, outputBuffer);const jiraPrBodyWithRef = `Resolves ${jiraTicketRef}\n\n${jiraPrBody}`;const prResult = await git.createPR(workspace, {@@ -2010,7 +2010,7 @@ async function handleAgentCompletion(agentId, exitCode, success, duration) {const taskOpenPR = isTruthyMeta(agent.task?.metadata?.openPR);const taskReviewLoop = isTruthyMeta(agent.task?.metadata?.reviewLoop);// When reviewLoop + openPR are both enabled, the agent handles the PR during its run — skip post-exit PR creation- await cleanupAgentWorktree(agentId, success, { openPR: taskOpenPR && !taskReviewLoop, description: task?.description });+ await cleanupAgentWorktree(agentId, success, { openPR: taskOpenPR && !taskReviewLoop, description: task?.description, agentOutput: outputBuffer });}runnerAgents.delete(agentId);@@ -2022,7 +2022,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.*/-export async function cleanupAgentWorktree(agentId, success, { openPR = false, description = null } = {}) {+export async function cleanupAgentWorktree(agentId, success, { openPR = false, description = null, agentOutput = null } = {}) {const { getAgent: getAgentState } = await import('./cos.js');const agentState = await getAgentState(agentId).catch(() => null);if (!agentState?.metadata?.isWorktree) return;@@ -2054,7 +2054,7 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, dconst taskDesc = description || 'CoS automated task';const prTitle = taskDesc.replace(/[\r\n]+/g, ' ').trim().substring(0, 100);- const prBody = await git.generatePRDescription(worktreePath, targetBranch, worktreeBranch, taskDesc);+ const prBody = await git.generatePRDescription(worktreePath, targetBranch, worktreeBranch, agentOutput);const prResult = await git.createPR(worktreePath, {title: prTitle,@@ -2320,7 +2320,8 @@ async function spawnDirectly(agentId, task, prompt, workspacePath, model, provid// Clean up worktree if agent was using oneawait cleanupAgentWorktree(agentId, success, {openPR: isTruthyMeta(task.metadata?.openPR),- description: task.description+ description: task.description,+ agentOutput: outputBuffer});unregisterSpawnedAgent(agentData?.pid || claudeProcess.pid);