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

feat: add branch update, comparison, and release PR workflow to DevTools Git page

Adam Eivyc83e0f992c13
diff --git a/.changelog/v0.12.x.md b/.changelog/v0.12.x.md
new file mode 100644
index 0000000000..3305196daa
--- /dev/null
+++ b/.changelog/v0.12.x.md
@@ -0,0 +1,24 @@
+# Release v0.12.x - Changelog
+
+Released: YYYY-MM-DD
+
+## Overview
+
+This release adds branch management and automated release workflow capabilities to the DevTools Git page.
+
+## Features
+
+### DevTools Git — Branch Update, Comparison & Release PR Workflow
+- **Update Branches button**: One-click fetch and fast-forward merge of `dev` and `main` from origin, with automatic stash/restore if the working tree is dirty
+- **Branch Comparison panel**: Shows how many commits `dev` is ahead of `main`, with commit list, diff stats (+insertions/-deletions/files changed), displayed as a "Release Status" card
+- **Automated Release PR**: "Create Release PR" button triggers a full CoS agent task that pushes commits, updates the changelog, creates a PR from dev to main, iterates with Copilot review feedback (up to 3 rounds), verifies CI, and merges when approved
+- **Release Confirmation dialog**: Modal listing the exact steps the agent will perform, preventing accidental releases
+- **Push endpoint**: New server endpoint for pushing branches to origin, used by the release workflow
+
+**Server changes**:
+- `server/services/git.js` — Added `fetchOrigin`, `updateBranches`, `getBranchComparison`, `push` functions
+- `server/routes/git.js` — Added `/update-branches`, `/branch-comparison`, `/push` POST endpoints
+
+**Client changes**:
+- `client/src/services/api.js` — Added `updateBranches`, `getBranchComparison`, `pushBranch` API functions
+- `client/src/pages/DevTools.jsx` — Expanded GitPage with Update button, Release Status panel, release confirmation dialog, and CoS task integration
diff --git a/client/src/pages/DevTools.jsx b/client/src/pages/DevTools.jsx
index 68afa75f8c..39f646bfd3 100644
--- a/client/src/pages/DevTools.jsx
+++ b/client/src/pages/DevTools.jsx
@@ -1,6 +1,6 @@
import { useState, useEffect, useRef, Fragment } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
-import { GitBranch, Plus, Minus, FileText, Clock, RefreshCw, Activity, Image, X, XCircle, Cpu, MemoryStick, Terminal, Trash2, MessageSquarePlus, Info, Save, Maximize2, RotateCcw } from 'lucide-react';
+import { GitBranch, Plus, Minus, FileText, Clock, RefreshCw, Activity, Image, X, XCircle, Cpu, MemoryStick, Terminal, Trash2, MessageSquarePlus, Info, Save, Maximize2, RotateCcw, Download, Rocket } from 'lucide-react';
import toast from 'react-hot-toast';
import * as api from '../services/api';
import socket from '../services/socket';
@@ -1675,6 +1675,69 @@ export function ProcessesPage() {
);
}
+function buildReleasePrompt(repoPath, comparison) {
+ const commitList = comparison.commits
+ .map(c => `- ${c.hash} ${c.message}`)
+ .join('\n');
+
+ return `You are performing a release workflow for PortOS. The repo is at: ${repoPath}
+
+## Commits to release (${comparison.ahead} commits ahead of main):
+${commitList}
+
+## Steps
+
+1. **Ensure clean state**:
+ - Check for uncommitted changes. If any, stage, commit with a descriptive message, then run \`git pull --rebase --autostash && git push\`
+ - If no uncommitted changes, still run \`git pull --rebase --autostash && git push\` to ensure we're up to date (CI auto-bumps version)
+
+2. **Changelog management**:
+ - Read version from package.json to determine the minor version series (e.g., 0.12.x)
+ - Check if \`.changelog/v{major}.{minor}.x.md\` exists
+ - If not, create it using the structure from an existing changelog file as template
+ - Update it with entries for the commits being released, categorized by type (Features, Fixes, Improvements)
+ - Keep the version as literal "x" — the release workflow substitutes the actual version
+ - Commit the changelog: \`git add .changelog/ && git commit -m "docs: update changelog for release"\`
+ - Push: \`git pull --rebase --autostash && git push\`
+
+3. **Create PR**:
+ - Check for existing PR: \`gh pr list --base main --head dev --state open\`
+ - If no existing PR, create one: \`gh pr create --base main --head dev --title "Release vX.Y.Z" --body "Release notes..."\`
+ - Include a summary of changes in the PR body
+
+4. **Wait for Copilot review**:
+ - Poll \`gh pr view --json reviews\` every 30 seconds
+ - Timeout after 2 minutes if no review appears
+
+5. **Address review feedback** (if any):
+ - Fetch unresolved threads via GraphQL:
+ \`\`\`
+ gh api graphql -f query='query(\$owner: String!, \$repo: String!, \$pr: Int!) { repository(owner: \$owner, name: \$repo) { pullRequest(number: \$pr) { reviewThreads(first: 100) { nodes { id isResolved comments(first: 10) { nodes { body path line author { login } } } } } } } }'
+ \`\`\`
+ - Make requested changes, commit, push (\`git pull --rebase --autostash && git push\`)
+ - Resolve addressed threads via GraphQL mutation
+
+6. **Re-request review**:
+ - Get repo info: \`gh repo view --json owner,name\`
+ - Get PR number from \`gh pr view --json number\`
+ - Try API: \`gh api repos/{owner}/{repo}/pulls/{pr}/requested_reviewers -f '{"reviewers":["copilot-pull-request-reviewer"]}' --method POST\`
+ - If that fails, use browser MCP to navigate to the PR page and click the re-request review button (the sync icon button with \`name="re_request_reviewer_id"\`)
+
+7. **Iterate**: Repeat steps 4-6 up to 3 times max
+
+8. **Verify CI**: Run \`gh pr checks\` and fix any failures
+
+9. **Merge**: Once approved and CI passes, merge with \`gh pr merge --merge\`
+
+## Important rules:
+- Always \`git pull --rebase --autostash\` before pushing (CI auto-bumps version on dev)
+- No co-author info in commits
+- Keep changelog version as literal "x" (the release workflow substitutes the actual version number)
+- Max 3 review iterations to prevent infinite loops
+- Report clearly if something fails
+- Parse repo owner/name from \`gh repo view --json owner,name\``;
+}
+
export function GitPage() {
const [apps, setApps] = useState([]);
const [selectedApp, setSelectedApp] = useState('');
@@ -1684,6 +1747,10 @@ export function GitPage() {
const [loading, setLoading] = useState(false);
const [commitMessage, setCommitMessage] = useState('');
const [committing, setCommitting] = useState(false);
+ const [branchComparison, setBranchComparison] = useState(null);
+ const [updating, setUpdating] = useState(false);
+ const [releasing, setReleasing] = useState(false);
+ const [showReleaseConfirm, setShowReleaseConfirm] = useState(false);
useEffect(() => {
api.getApps().then(apps => {
@@ -1701,8 +1768,12 @@ export function GitPage() {
const loadGitInfo = async () => {
if (!selectedApp) return;
setLoading(true);
- const info = await api.getGitInfo(selectedApp).catch(() => null);
+ const [info, comparison] = await Promise.all([
+ api.getGitInfo(selectedApp).catch(() => null),
+ api.getBranchComparison(selectedApp).catch(() => null)
+ ]);
setGitInfo(info);
+ setBranchComparison(comparison);
setLoading(false);
};
@@ -1732,6 +1803,39 @@ export function GitPage() {
await loadGitInfo();
};
+ const handleUpdateBranches = async () => {
+ if (!selectedApp) return;
+ setUpdating(true);
+ const result = await api.updateBranches(selectedApp).catch(() => null);
+ setUpdating(false);
+ if (result) {
+ const parts = [];
+ if (result.dev) parts.push(`dev: ${result.dev}`);
+ if (result.main) parts.push(`main: ${result.main}`);
+ if (result.stashed) parts.push(result.stashRestored ? 'stash restored' : 'stash conflict');
+ toast.success(`Branches updated — ${parts.join(', ')}`);
+ }
+ await loadGitInfo();
+ };
+
+ const handleReleasePR = async () => {
+ if (!branchComparison || branchComparison.ahead === 0) return;
+ setShowReleaseConfirm(false);
+ setReleasing(true);
+ const prompt = buildReleasePrompt(selectedApp, branchComparison);
+ const result = await api.addCosTask({
+ description: prompt,
+ context: `Release PR for ${selectedApp}`,
+ priority: 'high',
+ autoApprove: true
+ }).catch(() => null);
+ setReleasing(false);
+ if (result) {
+ toast.success('Release task queued — check CoS Agents tab');
+ await api.forceCosEvaluate().catch(() => null);
+ }
+ };
+
const getStatusIcon = (file) => {
if (file.added) return <Plus size={14} className="text-port-success" />;
if (file.deleted) return <Minus size={14} className="text-port-error" />;
@@ -1752,6 +1856,14 @@ export function GitPage() {
<option key={app.id} value={app.repoPath}>{app.name}</option>
))}
</select>
+ <button
+ onClick={handleUpdateBranches}
+ disabled={updating || !selectedApp}
+ className="flex items-center gap-1.5 px-3 py-2 bg-port-card border border-port-border rounded-lg text-sm text-gray-300 hover:text-white hover:border-port-accent disabled:opacity-50"
+ >
+ <Download size={16} className={updating ? 'animate-bounce' : ''} />
+ {updating ? 'Updating...' : 'Update'}
+ </button>
<button
onClick={loadGitInfo}
className="p-2 text-gray-400 hover:text-white"
@@ -1764,115 +1876,156 @@ export function GitPage() {
{loading ? (
<div className="text-center py-8 text-gray-400">Loading...</div>
) : gitInfo && gitInfo.isRepo ? (
- <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
- {/* Status Panel */}
- <div className="space-y-4">
- {/* Branch Info */}
+ <div className="space-y-6">
+ {/* Branch Comparison / Release Status */}
+ {branchComparison && branchComparison.ahead > 0 && (
<div className="bg-port-card border border-port-border rounded-xl p-4">
- <div className="flex items-center gap-2 mb-3">
- <GitBranch size={18} className="text-port-accent" />
- <span className="font-medium text-white">{gitInfo.branch}</span>
- {gitInfo.status?.clean && (
- <span className="text-xs text-port-success px-2 py-0.5 bg-port-success/20 rounded">Clean</span>
- )}
- </div>
- <div className="flex gap-4 text-sm">
- <div className="text-gray-400">
- <span className="text-port-success">+{gitInfo.diffStats?.insertions || 0}</span>
- <span className="mx-1">/</span>
- <span className="text-port-error">-{gitInfo.diffStats?.deletions || 0}</span>
+ <div className="flex items-center justify-between mb-3">
+ <div className="flex items-center gap-3">
+ <h3 className="text-sm font-medium text-gray-400">Release Status</h3>
+ <span className="text-xs font-medium text-port-accent px-2 py-0.5 bg-port-accent/20 rounded">
+ {branchComparison.ahead} ahead of main
+ </span>
</div>
- <div className="text-gray-500">
- {gitInfo.diffStats?.files || 0} files changed
+ <div className="flex items-center gap-3 text-xs text-gray-400">
+ <span className="text-port-success">+{branchComparison.stats.insertions}</span>
+ <span className="text-port-error">-{branchComparison.stats.deletions}</span>
+ <span>{branchComparison.stats.files} files</span>
</div>
</div>
- </div>
- {/* Changed Files */}
- <div className="bg-port-card border border-port-border rounded-xl p-4">
- <div className="flex items-center justify-between mb-3">
- <h3 className="text-sm font-medium text-gray-400">Changed Files</h3>
+ <div className="space-y-1.5 max-h-48 overflow-auto mb-4">
+ {branchComparison.commits.map((commit, i) => (
+ <div key={i} className="flex items-center gap-2 text-sm">
+ <code className="text-xs text-port-accent shrink-0">{commit.hash}</code>
+ <span className="text-gray-300 truncate">{commit.message}</span>
+ </div>
+ ))}
+ </div>
+
+ {gitInfo.branch === 'dev' && (
<button
- onClick={loadDiff}
- className="text-xs text-port-accent hover:underline"
+ onClick={() => setShowReleaseConfirm(true)}
+ disabled={releasing}
+ className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg text-sm disabled:opacity-50"
>
- View Diff
+ <Rocket size={16} />
+ {releasing ? 'Creating Release Task...' : 'Create Release PR'}
</button>
- </div>
- <div className="space-y-1 max-h-64 overflow-auto">
- {gitInfo.status?.files?.map((file, i) => (
- <div key={i} className="flex items-center gap-2 text-sm py-1 group">
- {getStatusIcon(file)}
- <span className={`flex-1 font-mono text-xs ${file.staged ? 'text-port-success' : 'text-gray-300'}`}>
- {file.path}
- </span>
- <span className="text-xs text-gray-500">{file.status}</span>
- {file.staged ? (
- <button
- onClick={() => handleUnstage(file.path)}
- className="opacity-0 group-hover:opacity-100 text-xs text-gray-400 hover:text-white"
- >
- Unstage
- </button>
- ) : (
- <button
- onClick={() => handleStage(file.path)}
- className="opacity-0 group-hover:opacity-100 text-xs text-gray-400 hover:text-white"
- >
- Stage
- </button>
- )}
+ )}
+ </div>
+ )}
+
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
+ {/* Status Panel */}
+ <div className="space-y-4">
+ {/* Branch Info */}
+ <div className="bg-port-card border border-port-border rounded-xl p-4">
+ <div className="flex items-center gap-2 mb-3">
+ <GitBranch size={18} className="text-port-accent" />
+ <span className="font-medium text-white">{gitInfo.branch}</span>
+ {gitInfo.status?.clean && (
+ <span className="text-xs text-port-success px-2 py-0.5 bg-port-success/20 rounded">Clean</span>
+ )}
+ </div>
+ <div className="flex gap-4 text-sm">
+ <div className="text-gray-400">
+ <span className="text-port-success">+{gitInfo.diffStats?.insertions || 0}</span>
+ <span className="mx-1">/</span>
+ <span className="text-port-error">-{gitInfo.diffStats?.deletions || 0}</span>
</div>
- ))}
- {(!gitInfo.status?.files || gitInfo.status.files.length === 0) && (
- <div className="text-gray-500 text-sm">No changes</div>
- )}
+ <div className="text-gray-500">
+ {gitInfo.diffStats?.files || 0} files changed
+ </div>
+ </div>
</div>
- </div>
- {/* Quick Commit */}
- {gitInfo.status?.staged > 0 && (
+ {/* Changed Files */}
<div className="bg-port-card border border-port-border rounded-xl p-4">
- <h3 className="text-sm font-medium text-gray-400 mb-2">Quick Commit</h3>
- <div className="flex gap-2">
- <input
- type="text"
- value={commitMessage}
- onChange={(e) => setCommitMessage(e.target.value)}
- placeholder="Commit message..."
- className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
- />
+ <div className="flex items-center justify-between mb-3">
+ <h3 className="text-sm font-medium text-gray-400">Changed Files</h3>
<button
- onClick={handleCommit}
- disabled={committing || !commitMessage.trim()}
- className="px-4 py-2 bg-port-success hover:bg-port-success/80 text-white rounded-lg text-sm disabled:opacity-50"
+ onClick={loadDiff}
+ className="text-xs text-port-accent hover:underline"
>
- Commit
+ View Diff
</button>
</div>
+ <div className="space-y-1 max-h-64 overflow-auto">
+ {gitInfo.status?.files?.map((file, i) => (
+ <div key={i} className="flex items-center gap-2 text-sm py-1 group">
+ {getStatusIcon(file)}
+ <span className={`flex-1 font-mono text-xs ${file.staged ? 'text-port-success' : 'text-gray-300'}`}>
+ {file.path}
+ </span>
+ <span className="text-xs text-gray-500">{file.status}</span>
+ {file.staged ? (
+ <button
+ onClick={() => handleUnstage(file.path)}
+ className="opacity-0 group-hover:opacity-100 text-xs text-gray-400 hover:text-white"
+ >
+ Unstage
+ </button>
+ ) : (
+ <button
+ onClick={() => handleStage(file.path)}
+ className="opacity-0 group-hover:opacity-100 text-xs text-gray-400 hover:text-white"
+ >
+ Stage
+ </button>
+ )}
+ </div>
+ ))}
+ {(!gitInfo.status?.files || gitInfo.status.files.length === 0) && (
+ <div className="text-gray-500 text-sm">No changes</div>
+ )}
+ </div>
</div>
- )}
- </div>
- {/* Recent Commits */}
- <div className="bg-port-card border border-port-border rounded-xl p-4">
- <h3 className="text-sm font-medium text-gray-400 mb-3">Recent Commits</h3>
- <div className="space-y-2">
- {gitInfo.recentCommits?.map((commit, i) => (
- <div key={i} className="py-2 border-b border-port-border last:border-0">
- <div className="flex items-center gap-2">
- <code className="text-xs text-port-accent">{commit.hash}</code>
- <span className="text-sm text-white truncate">{commit.message}</span>
- </div>
- <div className="text-xs text-gray-500 mt-1">
- {commit.author} • {new Date(commit.date).toLocaleDateString()}
+ {/* Quick Commit */}
+ {gitInfo.status?.staged > 0 && (
+ <div className="bg-port-card border border-port-border rounded-xl p-4">
+ <h3 className="text-sm font-medium text-gray-400 mb-2">Quick Commit</h3>
+ <div className="flex gap-2">
+ <input
+ type="text"
+ value={commitMessage}
+ onChange={(e) => setCommitMessage(e.target.value)}
+ placeholder="Commit message..."
+ className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
+ />
+ <button
+ onClick={handleCommit}
+ disabled={committing || !commitMessage.trim()}
+ className="px-4 py-2 bg-port-success hover:bg-port-success/80 text-white rounded-lg text-sm disabled:opacity-50"
+ >
+ Commit
+ </button>
</div>
</div>
- ))}
- {(!gitInfo.recentCommits || gitInfo.recentCommits.length === 0) && (
- <div className="text-gray-500 text-sm">No commits</div>
)}
</div>
+
+ {/* Recent Commits */}
+ <div className="bg-port-card border border-port-border rounded-xl p-4">
+ <h3 className="text-sm font-medium text-gray-400 mb-3">Recent Commits</h3>
+ <div className="space-y-2">
+ {gitInfo.recentCommits?.map((commit, i) => (
+ <div key={i} className="py-2 border-b border-port-border last:border-0">
+ <div className="flex items-center gap-2">
+ <code className="text-xs text-port-accent">{commit.hash}</code>
+ <span className="text-sm text-white truncate">{commit.message}</span>
+ </div>
+ <div className="text-xs text-gray-500 mt-1">
+ {commit.author} • {new Date(commit.date).toLocaleDateString()}
+ </div>
+ </div>
+ ))}
+ {(!gitInfo.recentCommits || gitInfo.recentCommits.length === 0) && (
+ <div className="text-gray-500 text-sm">No commits</div>
+ )}
+ </div>
+ </div>
</div>
</div>
) : (
@@ -1902,6 +2055,51 @@ export function GitPage() {
</div>
</div>
)}
+
+ {/* Release Confirmation Dialog */}
+ {showReleaseConfirm && (
+ <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={() => setShowReleaseConfirm(false)}>
+ <div className="bg-port-card border border-port-border rounded-xl w-full max-w-lg overflow-hidden" onClick={e => e.stopPropagation()}>
+ <div className="flex items-center justify-between p-4 border-b border-port-border">
+ <h3 className="font-medium text-white flex items-center gap-2">
+ <Rocket size={18} className="text-port-accent" />
+ Create Release PR
+ </h3>
+ <button onClick={() => setShowReleaseConfirm(false)} className="text-gray-400 hover:text-white">×</button>
+ </div>
+ <div className="p-4 space-y-3">
+ <p className="text-sm text-gray-300">
+ This will create a CoS agent task to automate the full release workflow:
+ </p>
+ <ul className="text-sm text-gray-400 space-y-1.5 ml-4 list-disc">
+ <li>Push local commits to origin/dev</li>
+ <li>Check and update the changelog</li>
+ <li>Create PR from dev to main</li>
+ <li>Wait for Copilot review and address feedback</li>
+ <li>Merge when approved and CI passes</li>
+ </ul>
+ <p className="text-xs text-gray-500">
+ {branchComparison?.ahead || 0} commits will be included in this release.
+ </p>
+ </div>
+ <div className="flex justify-end gap-3 p-4 border-t border-port-border">
+ <button
+ onClick={() => setShowReleaseConfirm(false)}
+ className="px-4 py-2 text-sm text-gray-400 hover:text-white"
+ >
+ Cancel
+ </button>
+ <button
+ onClick={handleReleasePR}
+ className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg text-sm"
+ >
+ <Rocket size={16} />
+ Start Release
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
</div>
);
}
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 2eea77dd66..eb4114d288 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -205,6 +205,18 @@ export const createCommit = (path, message) => request('/git/commit', {
method: 'POST',
body: JSON.stringify({ path, message })
});
+export const updateBranches = (path) => request('/git/update-branches', {
+ method: 'POST',
+ body: JSON.stringify({ path })
+});
+export const getBranchComparison = (path, base, head) => request('/git/branch-comparison', {
+ method: 'POST',
+ body: JSON.stringify({ path, base, head })
+});
+export const pushBranch = (path, branch) => request('/git/push', {
+ method: 'POST',
+ body: JSON.stringify({ path, branch })
+});
// Usage
export const getUsage = () => request('/usage');
diff --git a/server/routes/git.js b/server/routes/git.js
index 74e7602ccb..d6cbb7cdf4 100644
--- a/server/routes/git.js
+++ b/server/routes/git.js
@@ -92,6 +92,42 @@ router.post('/commit', asyncHandler(async (req, res) => {
res.json(result);
}));
+// POST /api/git/update-branches - Fetch and merge latest dev and main
+router.post('/update-branches', asyncHandler(async (req, res) => {
+ const { path } = req.body;
+
+ if (!path) {
+ throw new ServerError('path is required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+
+ const result = await git.updateBranches(path);
+ res.json(result);
+}));
+
+// POST /api/git/branch-comparison - Compare two branches
+router.post('/branch-comparison', asyncHandler(async (req, res) => {
+ const { path, base, head } = req.body;
+
+ if (!path) {
+ throw new ServerError('path is required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+
+ const result = await git.getBranchComparison(path, base || 'main', head || 'dev');
+ res.json(result);
+}));
+
+// POST /api/git/push - Push to origin
+router.post('/push', asyncHandler(async (req, res) => {
+ const { path, branch } = req.body;
+
+ if (!path) {
+ throw new ServerError('path is required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+
+ const result = await git.push(path, branch);
+ res.json(result);
+}));
+
// POST /api/git/info - Get full git info for a path
router.post('/info', asyncHandler(async (req, res) => {
const { path } = req.body;
diff --git a/server/services/git.js b/server/services/git.js
index a315c35d1f..97e7d13763 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -214,6 +214,109 @@ export async function getRemote(dir) {
return origins;
}
+/**
+ * Fetch from origin
+ */
+export async function fetchOrigin(dir) {
+ await execGit(['fetch', 'origin'], dir);
+ return true;
+}
+
+/**
+ * Update dev and main branches from origin
+ */
+export async function updateBranches(dir) {
+ await fetchOrigin(dir);
+
+ const status = await getStatus(dir);
+ const currentBranch = await getBranch(dir);
+ let stashed = false;
+ let stashRestored = false;
+
+ if (!status.clean) {
+ await execGit(['stash', 'push', '-m', 'portos-auto-stash'], dir);
+ stashed = true;
+ }
+
+ const results = { dev: null, main: null, stashed, stashRestored: false, currentBranch };
+
+ // Update current branch if it's dev
+ if (currentBranch === 'dev') {
+ const devResult = await execGit(['merge', 'origin/dev', '--ff-only'], dir, { ignoreExitCode: true });
+ results.dev = devResult.stderr?.includes('fatal') ? 'failed' : 'updated';
+ }
+
+ // Update main
+ await execGit(['checkout', 'main'], dir, { ignoreExitCode: true });
+ const mainResult = await execGit(['merge', 'origin/main', '--ff-only'], dir, { ignoreExitCode: true });
+ results.main = mainResult.stderr?.includes('fatal') ? 'failed' : 'updated';
+
+ // Return to original branch
+ if (currentBranch !== 'main') {
+ await execGit(['checkout', currentBranch], dir);
+ }
+
+ // If we also need to update dev and weren't on it
+ if (currentBranch !== 'dev') {
+ await execGit(['checkout', 'dev'], dir, { ignoreExitCode: true });
+ const devResult = await execGit(['merge', 'origin/dev', '--ff-only'], dir, { ignoreExitCode: true });
+ results.dev = devResult.stderr?.includes('fatal') ? 'failed' : 'updated';
+ if (currentBranch !== 'dev') {
+ await execGit(['checkout', currentBranch], dir);
+ }
+ }
+
+ if (stashed) {
+ const popResult = await execGit(['stash', 'pop'], dir, { ignoreExitCode: true });
+ stashRestored = !popResult.stderr?.includes('CONFLICT');
+ results.stashRestored = stashRestored;
+ }
+
+ return results;
+}
+
+/**
+ * Get branch comparison (how far ahead headBranch is from baseBranch)
+ */
+export async function getBranchComparison(dir, baseBranch = 'main', headBranch = 'dev') {
+ const format = '--format={"hash":"%h","message":"%s","author":"%an","date":"%ci"}';
+ const logResult = await execGit(
+ ['log', format, `${baseBranch}..${headBranch}`], dir, { ignoreExitCode: true }
+ );
+
+ const commits = logResult.stdout.trim()
+ .split('\n')
+ .filter(Boolean)
+ .map(line => JSON.parse(line));
+
+ const statResult = await execGit(
+ ['diff', '--stat', `${baseBranch}...${headBranch}`], dir, { ignoreExitCode: true }
+ );
+ const statsLine = statResult.stdout.trim().split('\n').pop() || '';
+ const filesMatch = statsLine.match(/(\d+) files? changed/);
+ const insertionsMatch = statsLine.match(/(\d+) insertions?/);
+ const deletionsMatch = statsLine.match(/(\d+) deletions?/);
+
+ return {
+ ahead: commits.length,
+ commits,
+ stats: {
+ files: filesMatch ? parseInt(filesMatch[1]) : 0,
+ insertions: insertionsMatch ? parseInt(insertionsMatch[1]) : 0,
+ deletions: deletionsMatch ? parseInt(deletionsMatch[1]) : 0
+ }
+ };
+}
+
+/**
+ * Push to origin
+ */
+export async function push(dir, branch = null) {
+ const args = branch ? ['push', 'origin', branch] : ['push'];
+ const result = await execGit(args, dir);
+ return { success: true, output: result.stdout + result.stderr };
+}
+
/**
* Get comprehensive git info
*/