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): createPR auto-detects forge (GitHub gh / GitLab glab) from remote
Adam Eivya4d2ec460e53
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 21ef13e72c..86b67c72c4 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -1182,17 +1182,19 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, dreturn warnings;}+ const cliName = prResult?.cli || 'gh';const authHint = prResult?.ghAccount- ? ` (gh authed as ${prResult.ghAccount} for ${prResult.ghOwner})`+ ? ` (${cliName} authed as ${prResult.ghAccount} for ${prResult.ghOwner})`: prResult?.ghOwner- ? ` (no gh account matches owner ${prResult.ghOwner} — fell back to active user)`+ ? ` (${cliName} on ${prResult.ghHost || prResult.ghOwner} — no account auto-pinned)`: '';- emitLog('error', `🌳 PR creation failed for ${worktreeBranch}${authHint}: ${reason}`, { agentId, branchName: worktreeBranch, ghAccount: prResult?.ghAccount, ghOwner: prResult?.ghOwner });+ emitLog('error', `🌳 PR creation failed for ${worktreeBranch}${authHint}: ${reason}`, { agentId, branchName: worktreeBranch, cli: prResult?.cli, ghAccount: prResult?.ghAccount, ghOwner: prResult?.ghOwner, ghHost: prResult?.ghHost });warnings.push(`PR creation failed for branch ${worktreeBranch}: ${reason}. Worktree preserved for manual PR creation.`);return warnings;}- emitLog('success', `🌳 Created PR: ${prResult.url} (gh authed as ${prResult.ghAccount || 'active user'})`, { agentId, branchName: worktreeBranch, ghAccount: prResult.ghAccount, ghOwner: prResult.ghOwner });+ const cliName = prResult.cli || 'gh';+ emitLog('success', `🌳 Created PR: ${prResult.url} (${cliName}${prResult.ghAccount ? ` authed as ${prResult.ghAccount}` : ''})`, { agentId, branchName: worktreeBranch, cli: prResult.cli, ghAccount: prResult.ghAccount, ghOwner: prResult.ghOwner, ghHost: prResult.ghHost });const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: false }).catch(err => {emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });diff --git a/server/services/git.js b/server/services/git.jsindex a708c5281a..d560678880 100644--- a/server/services/git.js+++ b/server/services/git.js@@ -324,23 +324,34 @@ export async function checkout(dir, branchName) {}/**- * Parse the GitHub owner login from a remote URL.- * Returns null for non-github.com remotes or unparseable inputs.+ * Parse a git remote URL into `{ host, owner }`. Returns null for unparseable input.* Examples:- * [email protected]:atomantic/PortOS.git → 'atomantic'- * https://github.com/atomantic/PortOS → 'atomantic'+ * [email protected]:atomantic/PortOS.git → { host: 'github.com', owner: 'atomantic' }+ * https://gitlab.com/group/sub/proj.git → { host: 'gitlab.com', owner: 'group' }+ * [email protected]:foo/bar.git → { host: 'gitlab.example.com', owner: 'foo' }*/-export function parseGitHubOwnerFromRemote(url) {+export function parseGitRemote(url) {if (!url) return null;- const ssh = url.match(/^git@github\.com:([^/]+)\/[^/]+?(?:\.git)?$/);- if (ssh) return ssh[1];- const https = url.match(/^https?:\/\/github\.com\/([^/]+)\/[^/]+?(?:\.git)?$/);- if (https) return https[1];+ // SSH: git@HOST:OWNER/REPO[.git] (REPO can contain '/' for GitLab subgroups,+ // but we only need the top-level owner here)+ const ssh = url.match(/^git@([^:]+):([^/]+)\/.+?(?:\.git)?$/);+ if (ssh) return { host: ssh[1], owner: ssh[2] };+ // HTTPS: https://HOST/OWNER/REPO[.git]+ const https = url.match(/^https?:\/\/([^/]+)\/([^/]+)\/.+?(?:\.git)?$/);+ if (https) return { host: https[1], owner: https[2] };return null;}/**- * Pick which logged-in gh account should auth against a repo owned by `ownerLogin`.+ * Back-compat: returns just the owner login when the remote is on github.com.+ */+export function parseGitHubOwnerFromRemote(url) {+ const parsed = parseGitRemote(url);+ return parsed?.host === 'github.com' ? parsed.owner : null;+}++/**+ * Pick which logged-in gh/glab account should auth against a repo owned by `ownerLogin`.* Case-insensitive exact match; returns null if no logged-in account matches the owner.*/export function pickGhAccountForOwner(ownerLogin, availableAccounts) {@@ -349,9 +360,22 @@ export function pickGhAccountForOwner(ownerLogin, availableAccounts) {return availableAccounts.find(a => a.toLowerCase() === lower) || null;}-function spawnGh(args, options = {}) {+/**+ * Pick which forge CLI to use for a given remote host.+ * github.com → 'gh'+ * gitlab.com / *gitlab* → 'glab' (covers self-hosted GitLab like gitlab.example.com)+ * anything else → 'gh' (default; harmless when gh isn't authed for that host)+ */+export function detectForgeCli(host) {+ if (!host) return 'gh';+ if (host === 'github.com') return 'gh';+ if (host === 'gitlab.com' || /(^|\.)gitlab\./i.test(host)) return 'glab';+ return 'gh';+}++function spawnCli(cmd, args, options = {}) {return new Promise((resolve) => {- const child = spawn('gh', args, { shell: false, windowsHide: true, ...options });+ const child = spawn(cmd, args, { shell: false, windowsHide: true, ...options });let stdout = '', stderr = '';child.stdout.on('data', (d) => { stdout += d.toString(); });child.stderr.on('data', (d) => { stderr += d.toString(); });@@ -361,7 +385,7 @@ function spawnGh(args, options = {}) {}async function listGhAccounts() {- const { stdout, stderr } = await spawnGh(['auth', 'status', '-h', 'github.com']);+ const { stdout, stderr } = await spawnCli('gh', ['auth', 'status', '-h', 'github.com']);// gh writes status to stderr in older versions, stdout in newer — search both.const text = `${stdout}\n${stderr}`;const accounts = [];@@ -372,51 +396,66 @@ async function listGhAccounts() {}async function getGhTokenForAccount(login) {- const { code, stdout } = await spawnGh(['auth', 'token', '-u', login, '-h', 'github.com']);+ const { code, stdout } = await spawnCli('gh', ['auth', 'token', '-u', login, '-h', 'github.com']);return code === 0 ? stdout.trim() : null;}/**- * Resolve the right gh auth env for a given repo directory.- * Auto-detects the owner from `origin`, picks the matching logged-in gh account,- * and returns an env override pinning `GH_TOKEN` so gh doesn't depend on- * `~/.config/gh/hosts.yml`'s mutable `user:` field.+ * Resolve the forge CLI + auth env for a given repo directory.+ * - For GitHub repos: auto-pins `GH_TOKEN` to the logged-in gh account whose login+ * matches the repo owner, so PR creation doesn't depend on `hosts.yml`'s mutable+ * `user:` field (avoids the multi-account "must be a collaborator" failure mode).+ * - For GitLab repos: uses glab as-is. glab is single-user-per-host, so its keyring+ * already disambiguates by host without the mutable-active-user pitfall.* Falls back to ambient env when no match is possible.*/-export async function resolveGhEnvForRepo(dir) {+export async function resolveForgeForRepo(dir) {const remote = await execGitSafe(['remote', 'get-url', 'origin'], dir);- const owner = parseGitHubOwnerFromRemote(remote.stdout?.trim());- if (!owner) return { env: process.env, owner: null, account: null };+ const parsed = parseGitRemote(remote.stdout?.trim());+ if (!parsed) {+ return { cli: 'gh', env: process.env, host: null, owner: null, account: null };+ }++ const cli = detectForgeCli(parsed.host);++ if (cli !== 'gh') {+ return { cli, env: process.env, host: parsed.host, owner: parsed.owner, account: null };+ }const accounts = await listGhAccounts();- const account = pickGhAccountForOwner(owner, accounts);- if (!account) return { env: process.env, owner, account: null };+ const account = pickGhAccountForOwner(parsed.owner, accounts);+ if (!account) return { cli, env: process.env, host: parsed.host, owner: parsed.owner, account: null };const token = await getGhTokenForAccount(account);- if (!token) return { env: process.env, owner, account };+ if (!token) return { cli, env: process.env, host: parsed.host, owner: parsed.owner, account };- return { env: { ...process.env, GH_TOKEN: token }, owner, account };+ return { cli, env: { ...process.env, GH_TOKEN: token }, host: parsed.host, owner: parsed.owner, account };}/**- * Create a pull request using the `gh` CLI.- * Auto-pins gh identity to the account whose login matches the repo's owner- * (so PR creation works correctly when multiple gh accounts are logged in).- * Fails gracefully if `gh` is not installed.+ * Create a pull request (GitHub) or merge request (GitLab) using `gh` / `glab`.+ * Forge is auto-detected from the repo's `origin` URL; gh identity is auto-pinned+ * to the matching account when multiple gh accounts are logged in.+ * Fails gracefully if the relevant CLI is not installed.* @param {string} dir - Working directory (repo root)* @param {object} options - PR options- * @param {string} options.title - PR title- * @param {string} options.body - PR description+ * @param {string} options.title - PR/MR title+ * @param {string} options.body - PR/MR description* @param {string} options.base - Base branch (target)- * @param {string} options.head - Head branch (source)- * @returns {Promise<{success: boolean, url?: string, error?: string, ghAccount?: string|null, ghOwner?: string|null}>}+ * @param {string} options.head - Head branch (source, must be pushed to remote)+ * @returns {Promise<{success: boolean, url?: string, error?: string, cli?: string, ghAccount?: string|null, ghOwner?: string|null, ghHost?: string|null}>}*/export async function createPR(dir, { title, body, base, head }) {- const { env, owner, account } = await resolveGhEnvForRepo(dir);+ const { cli, env, host, owner, account } = await resolveForgeForRepo(dir);++ const args = cli === 'glab'+ ? ['mr', 'create', '--title', title, '--description', body || '', '--target-branch', base, '--source-branch', head]+ : ['pr', 'create', '--title', title, '--body', body || '', '--base', base, '--head', head];++ const meta = { cli, ghAccount: account, ghOwner: owner, ghHost: host };return new Promise((resolve) => {- const args = ['pr', 'create', '--title', title, '--body', body || '', '--base', base, '--head', head];- const child = spawn('gh', args, { cwd: dir, env, shell: false, windowsHide: true });+ const child = spawn(cli, args, { cwd: dir, env, shell: false, windowsHide: true });let stdout = '';let stderr = '';@@ -426,15 +465,18 @@ export async function createPR(dir, { title, body, base, head }) {child.on('close', (code) => {if (code === 0) {- const url = stdout.trim();- resolve({ success: true, url, ghAccount: account, ghOwner: owner });+ // Both gh and glab print the resulting URL on stdout (gh: just the URL;+ // glab: a couple lines ending in the URL — extract the last http(s)-looking line).+ const urlMatch = stdout.trim().match(/(https?:\/\/\S+)\s*$/);+ const url = urlMatch ? urlMatch[1] : stdout.trim();+ resolve({ success: true, url, ...meta });} else {- resolve({ success: false, error: stderr || `gh exited with code ${code}`, ghAccount: account, ghOwner: owner });+ resolve({ success: false, error: stderr || `${cli} exited with code ${code}`, ...meta });}});child.on('error', (err) => {- resolve({ success: false, error: `gh not available: ${err.message}`, ghAccount: account, ghOwner: owner });+ resolve({ success: false, error: `${cli} not available: ${err.message}`, ...meta });});});}diff --git a/server/services/git.test.js b/server/services/git.test.jsindex cc609d28fa..ccfb5cead0 100644--- a/server/services/git.test.js+++ b/server/services/git.test.js@@ -1,16 +1,36 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';-import { createPR, extractAgentSummary, parseGitHubOwnerFromRemote, pickGhAccountForOwner } from './git.js';+import { createPR, extractAgentSummary, parseGitHubOwnerFromRemote, pickGhAccountForOwner, parseGitRemote, detectForgeCli } from './git.js';-describe('parseGitHubOwnerFromRemote', () => {- it('parses SSH urls (with and without .git suffix)', () => {- expect(parseGitHubOwnerFromRemote('[email protected]:atomantic/PortOS.git')).toBe('atomantic');- expect(parseGitHubOwnerFromRemote('[email protected]:atomantic/PortOS')).toBe('atomantic');+describe('parseGitRemote', () => {+ it('parses GitHub SSH urls', () => {+ expect(parseGitRemote('[email protected]:atomantic/PortOS.git')).toEqual({ host: 'github.com', owner: 'atomantic' });+ expect(parseGitRemote('[email protected]:atomantic/PortOS')).toEqual({ host: 'github.com', owner: 'atomantic' });+ });++ it('parses GitHub HTTPS urls', () => {+ expect(parseGitRemote('https://github.com/atomantic/PortOS.git')).toEqual({ host: 'github.com', owner: 'atomantic' });+ expect(parseGitRemote('https://github.com/atomantic/PortOS')).toEqual({ host: 'github.com', owner: 'atomantic' });+ });++ it('parses GitLab SSH and HTTPS urls (including subgroup paths)', () => {+ expect(parseGitRemote('[email protected]:my-group/my-project.git')).toEqual({ host: 'gitlab.com', owner: 'my-group' });+ expect(parseGitRemote('https://gitlab.com/my-group/sub/proj.git')).toEqual({ host: 'gitlab.com', owner: 'my-group' });+ expect(parseGitRemote('[email protected]:team/repo.git')).toEqual({ host: 'gitlab.example.com', owner: 'team' });+ });++ it('returns null for empty, null, or malformed input', () => {+ expect(parseGitRemote('')).toBeNull();+ expect(parseGitRemote(null)).toBeNull();+ expect(parseGitRemote(undefined)).toBeNull();+ expect(parseGitRemote('github.com:atomantic/PortOS')).toBeNull();+ expect(parseGitRemote('[email protected]:noslash')).toBeNull();});+});- it('parses HTTPS urls (with and without .git suffix)', () => {- expect(parseGitHubOwnerFromRemote('https://github.com/atomantic/PortOS.git')).toBe('atomantic');+describe('parseGitHubOwnerFromRemote (back-compat wrapper)', () => {+ it('returns owner only for github.com hosts', () => {+ expect(parseGitHubOwnerFromRemote('[email protected]:atomantic/PortOS.git')).toBe('atomantic');expect(parseGitHubOwnerFromRemote('https://github.com/atomantic/PortOS')).toBe('atomantic');- expect(parseGitHubOwnerFromRemote('http://github.com/atomantic/PortOS')).toBe('atomantic');});it('returns null for non-github hosts', () => {@@ -18,15 +38,28 @@ describe('parseGitHubOwnerFromRemote', () => {expect(parseGitHubOwnerFromRemote('https://bitbucket.org/foo/bar')).toBeNull();});- it('returns null for empty or null input', () => {+ it('returns null for empty or malformed input', () => {expect(parseGitHubOwnerFromRemote('')).toBeNull();expect(parseGitHubOwnerFromRemote(null)).toBeNull();- expect(parseGitHubOwnerFromRemote(undefined)).toBeNull();+ expect(parseGitHubOwnerFromRemote('[email protected]:noslash')).toBeNull();});+});- it('returns null for malformed urls', () => {- expect(parseGitHubOwnerFromRemote('github.com:atomantic/PortOS')).toBeNull();- expect(parseGitHubOwnerFromRemote('[email protected]:noslash')).toBeNull();+describe('detectForgeCli', () => {+ it('routes github.com to gh', () => {+ expect(detectForgeCli('github.com')).toBe('gh');+ });++ it('routes gitlab.com and self-hosted gitlab to glab', () => {+ expect(detectForgeCli('gitlab.com')).toBe('glab');+ expect(detectForgeCli('gitlab.example.com')).toBe('glab');+ expect(detectForgeCli('GitLab.Internal.Co')).toBe('glab');+ });++ it('defaults to gh for unknown or empty hosts', () => {+ expect(detectForgeCli('bitbucket.org')).toBe('gh');+ expect(detectForgeCli(null)).toBe('gh');+ expect(detectForgeCli('')).toBe('gh');});});