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

refactor([issue-748]): extract pure git builders/parsers into server/lib

[._.]/ Adam Eivyb0381585c2b9
diff --git a/server/lib/README.md b/server/lib/README.md
index 4709da5b56..c623739602 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -113,6 +113,9 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `commandSecurity.js` | Allowlist of safe shell commands. |
| `execGit.js` | `execGit` utility imported by `git.js` + worktree manager. |
| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). |
+| `gitArgs.js` | `PROTECTED_BRANCHES`, `validateFilePaths(files)` — pure command-arg builders/validators for `git.js` (reject injection/traversal in staged paths). |
+| `gitForge.js` | `parseGitRemote`, `parseGitHubOwnerFromRemote`, `pickGhAccountForOwner`, `detectForgeCli`, `parsePullRequestUrl` — pure GitHub/GitLab remote + PR/MR URL parsers and forge/account selectors used by `git.js`. |
+| `gitOutputParsers.js` | `parseStatus`, `parseDiffStat`, `parseBranchVerboseLine`, `parseSubmoduleStatusLine`/`SUBMODULE_STATUS_RE`, `extractAgentSummary` — pure parsers turning git command output into structured data for `git.js`. |
| `gitRemote.js` | `getOriginInfo`, `parseGitRemoteUrl`, `UPSTREAM_OWNER`/`UPSTREAM_REPO` — classifies the local `origin` remote vs the upstream atomantic/PortOS repo. Used by the update flow to detect forks. |
| `processEnv.js` | `stripDebugMallocEnv(env)` — drop macOS `Malloc*` debug env vars before spawning a child. Pinokio-launched PortOS exports `MallocStackLogging`/`MallocScribble`/etc. that flood Python subprocess stderr with `can't turn off malloc stack logging` lines; route every Node→Python spawn through this. No-op on Linux/Windows. |
| `pythonSetup.js` | Python venv / runner setup helpers. |
diff --git a/server/lib/gitArgs.js b/server/lib/gitArgs.js
new file mode 100644
index 0000000000..63ef09eeac
--- /dev/null
+++ b/server/lib/gitArgs.js
@@ -0,0 +1,28 @@
+// Pure command-argument builders and validators for git operations. No
+// child-process access — these sanitize/shape the inputs that
+// server/services/git.js passes to execGit.
+
+// Branches that must never be deleted by the branch-cleanup paths.
+export const PROTECTED_BRANCHES = ['main', 'master', 'dev', 'develop', 'release'];
+
+/**
+ * Validate file paths to prevent command injection and path traversal.
+ * Throws on null bytes / shell metacharacters, absolute paths, or `..` traversal.
+ * Accepts a single path or an array; always returns an array of the sanitized paths.
+ * @param {string|string[]} files - File path(s)
+ * @returns {string[]} - Sanitized file paths
+ */
+export function validateFilePaths(files) {
+ const fileList = Array.isArray(files) ? files : [files];
+ return fileList.map(f => {
+ // Reject paths with null bytes or command separators
+ if (/[\0;|&`$]/.test(f)) {
+ throw new Error(`Invalid character in file path: ${f}`);
+ }
+ // Reject absolute paths or parent directory traversal
+ if (f.startsWith('/') || f.includes('..')) {
+ throw new Error(`Invalid file path: ${f}`);
+ }
+ return f;
+ });
+}
diff --git a/server/lib/gitArgs.test.js b/server/lib/gitArgs.test.js
new file mode 100644
index 0000000000..997a23f17d
--- /dev/null
+++ b/server/lib/gitArgs.test.js
@@ -0,0 +1,32 @@
+import { describe, it, expect } from 'vitest';
+import { PROTECTED_BRANCHES, validateFilePaths } from './gitArgs.js';
+
+describe('PROTECTED_BRANCHES', () => {
+ it('lists the branches that must never be deleted', () => {
+ expect(PROTECTED_BRANCHES).toEqual(['main', 'master', 'dev', 'develop', 'release']);
+ });
+});
+
+describe('validateFilePaths', () => {
+ it('passes through clean relative paths', () => {
+ expect(validateFilePaths(['src/a.js', 'docs/b.md'])).toEqual(['src/a.js', 'docs/b.md']);
+ });
+
+ it('accepts a single string and returns an array', () => {
+ expect(validateFilePaths('src/a.js')).toEqual(['src/a.js']);
+ });
+
+ it('rejects shell metacharacters and null bytes', () => {
+ expect(() => validateFilePaths(['a.js; rm -rf /'])).toThrow(/Invalid character/);
+ expect(() => validateFilePaths(['a.js`whoami`'])).toThrow(/Invalid character/);
+ expect(() => validateFilePaths(['a.js|cat'])).toThrow(/Invalid character/);
+ expect(() => validateFilePaths(['a$.js'])).toThrow(/Invalid character/);
+ expect(() => validateFilePaths(['a\0.js'])).toThrow(/Invalid character/);
+ });
+
+ it('rejects absolute paths and parent-directory traversal', () => {
+ expect(() => validateFilePaths(['/etc/passwd'])).toThrow(/Invalid file path/);
+ expect(() => validateFilePaths(['../secrets'])).toThrow(/Invalid file path/);
+ expect(() => validateFilePaths(['a/../b'])).toThrow(/Invalid file path/);
+ });
+});
diff --git a/server/lib/gitForge.js b/server/lib/gitForge.js
new file mode 100644
index 0000000000..4501582217
--- /dev/null
+++ b/server/lib/gitForge.js
@@ -0,0 +1,122 @@
+// Pure helpers for resolving forge (GitHub/GitLab) identity from git remote
+// and PR/MR URLs. No child-process or network access — these are string
+// parsers and selectors. The orchestration that shells out to `gh`/`glab`
+// (resolveForgeForRepo, createPR, requestCopilotReview) lives in
+// server/services/git.js and composes these.
+
+/**
+ * Parse a git remote URL into `{ host, owner }`. Returns null for unparseable input.
+ * Examples:
+ * [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 parseGitRemote(url) {
+ if (!url) return null;
+ // 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;
+}
+
+/**
+ * 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) {
+ if (!ownerLogin || !availableAccounts?.length) return null;
+ const lower = ownerLogin.toLowerCase();
+ return availableAccounts.find(a => a.toLowerCase() === lower) || null;
+}
+
+/**
+ * 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';
+}
+
+/**
+ * Parse a PR / MR URL into { host, owner, repo, number }. Returns null on bad input.
+ * Handles GitHub (`/pull/N`) and GitLab (`/-/merge_requests/N`) URLs, including
+ * GitLab projects nested in subgroups (the entire group path becomes `owner`)
+ * and URLs with trailing segments such as `/files`, `/commits`, `?query`, `#hash`.
+ */
+export function parsePullRequestUrl(url) {
+ if (!url || typeof url !== 'string') return null;
+
+ let parsed;
+ // new URL throws on malformed input; we want a structured null instead so a try
+ // wrapper here is the right call (the project's "no try/catch" rule covers
+ // request handlers, not URL validation helpers).
+ try { parsed = new URL(url); } catch { return null; }
+
+ // Only forge web URLs are valid input — reject file://, ftp://, javascript:,
+ // etc., which can otherwise sneak through to downstream `gh api --hostname`
+ // or `glab` calls with a misleading or empty host.
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
+
+ // `new URL` accepts `https:///path` and `http://:8080/...` — both yield an
+ // empty hostname. Reject those: a host-less PR URL is meaningless.
+ if (!parsed.hostname) return null;
+
+ // Reject explicit ports (`https://github.com:8443/...`). We use
+ // `parsed.hostname` below (not `host`), so a custom port would be silently
+ // dropped and route the request to the wrong server. Custom-port forges
+ // aren't supported until the port is plumbed through a separate field.
+ if (parsed.port) return null;
+
+ const host = parsed.hostname;
+ const segments = parsed.pathname.split('/').filter(Boolean);
+
+ // GitHub: /<owner>/<repo>/pull/<number>[/<more>]
+ // GitHub PR URLs are STRICTLY two segments before `pull` — anything else
+ // (e.g. /owner/repo/extra/pull/1) is invalid and would silently mis-parse
+ // if we just took the last segment as `repo`. Require segments[2] === 'pull'.
+ if (segments.length >= 4 && segments[2] === 'pull') {
+ const number = Number(segments[3]);
+ if (Number.isInteger(number) && number > 0) {
+ return { host, owner: segments[0], repo: segments[1], number };
+ }
+ }
+
+ // GitLab: /<group>[/<subgroup>...]/<project>/-/merge_requests/<number>[/<more>]
+ // Locate the `-/merge_requests/<n>` triple anchored at any depth.
+ for (let i = segments.length - 3; i >= 2; i--) {
+ if (segments[i] === '-' && segments[i + 1] === 'merge_requests') {
+ const number = Number(segments[i + 2]);
+ if (Number.isInteger(number) && number > 0) {
+ const project = segments.slice(0, i);
+ if (project.length >= 2) {
+ // owner = full group/subgroup path, repo = final project segment
+ return {
+ host,
+ owner: project.slice(0, -1).join('/'),
+ repo: project[project.length - 1],
+ number,
+ };
+ }
+ }
+ }
+ }
+
+ return null;
+}
diff --git a/server/lib/gitForge.test.js b/server/lib/gitForge.test.js
new file mode 100644
index 0000000000..72e25d5efe
--- /dev/null
+++ b/server/lib/gitForge.test.js
@@ -0,0 +1,154 @@
+import { describe, it, expect } from 'vitest';
+import {
+ parseGitRemote,
+ parseGitHubOwnerFromRemote,
+ pickGhAccountForOwner,
+ detectForgeCli,
+ parsePullRequestUrl
+} from './gitForge.js';
+
+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();
+ });
+});
+
+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');
+ });
+
+ it('returns null for non-github hosts', () => {
+ expect(parseGitHubOwnerFromRemote('[email protected]:foo/bar.git')).toBeNull();
+ expect(parseGitHubOwnerFromRemote('https://bitbucket.org/foo/bar')).toBeNull();
+ });
+
+ it('returns null for empty or malformed input', () => {
+ expect(parseGitHubOwnerFromRemote('')).toBeNull();
+ expect(parseGitHubOwnerFromRemote(null)).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');
+ });
+});
+
+describe('pickGhAccountForOwner', () => {
+ it('matches owner to account case-insensitively', () => {
+ expect(pickGhAccountForOwner('atomantic', ['atomantic', 'ClawedCode'])).toBe('atomantic');
+ expect(pickGhAccountForOwner('Atomantic', ['atomantic', 'ClawedCode'])).toBe('atomantic');
+ expect(pickGhAccountForOwner('clawedcode', ['atomantic', 'ClawedCode'])).toBe('ClawedCode');
+ expect(pickGhAccountForOwner('CLAWEDCODE', ['atomantic', 'ClawedCode'])).toBe('ClawedCode');
+ });
+
+ it('returns null when no account matches the owner', () => {
+ expect(pickGhAccountForOwner('someorg', ['atomantic', 'ClawedCode'])).toBeNull();
+ });
+
+ it('returns null with empty inputs', () => {
+ expect(pickGhAccountForOwner('atomantic', [])).toBeNull();
+ expect(pickGhAccountForOwner('atomantic', null)).toBeNull();
+ expect(pickGhAccountForOwner(null, ['atomantic'])).toBeNull();
+ expect(pickGhAccountForOwner('', ['atomantic'])).toBeNull();
+ });
+});
+
+describe('parsePullRequestUrl', () => {
+ it('parses GitHub PR URLs', () => {
+ expect(parsePullRequestUrl('https://github.com/atomantic/PortOS/pull/185')).toEqual({
+ host: 'github.com', owner: 'atomantic', repo: 'PortOS', number: 185
+ });
+ expect(parsePullRequestUrl('http://github.example.com/org/repo/pull/1')).toEqual({
+ host: 'github.example.com', owner: 'org', repo: 'repo', number: 1
+ });
+ });
+
+ it('parses GitLab MR URLs', () => {
+ expect(parsePullRequestUrl('https://gitlab.com/group/project/-/merge_requests/42')).toEqual({
+ host: 'gitlab.com', owner: 'group', repo: 'project', number: 42
+ });
+ });
+
+ it('parses GitLab MR URLs with subgroups (owner = full group path)', () => {
+ expect(parsePullRequestUrl('https://gitlab.com/group/subgroup/project/-/merge_requests/7')).toEqual({
+ host: 'gitlab.com', owner: 'group/subgroup', repo: 'project', number: 7
+ });
+ expect(parsePullRequestUrl('https://gitlab.example.com/g1/g2/g3/proj/-/merge_requests/100')).toEqual({
+ host: 'gitlab.example.com', owner: 'g1/g2/g3', repo: 'proj', number: 100
+ });
+ });
+
+ it('tolerates trailing path segments and query/hash fragments', () => {
+ expect(parsePullRequestUrl('https://github.com/atomantic/PortOS/pull/186/files')).toEqual({
+ host: 'github.com', owner: 'atomantic', repo: 'PortOS', number: 186
+ });
+ expect(parsePullRequestUrl('https://github.com/atomantic/PortOS/pull/186/commits/abc')).toEqual({
+ host: 'github.com', owner: 'atomantic', repo: 'PortOS', number: 186
+ });
+ expect(parsePullRequestUrl('https://github.com/atomantic/PortOS/pull/186?diff=split')).toEqual({
+ host: 'github.com', owner: 'atomantic', repo: 'PortOS', number: 186
+ });
+ expect(parsePullRequestUrl('https://gitlab.com/group/sub/proj/-/merge_requests/9/diffs')).toEqual({
+ host: 'gitlab.com', owner: 'group/sub', repo: 'proj', number: 9
+ });
+ });
+
+ it('returns null for invalid input', () => {
+ expect(parsePullRequestUrl(null)).toBeNull();
+ expect(parsePullRequestUrl('')).toBeNull();
+ expect(parsePullRequestUrl(undefined)).toBeNull();
+ expect(parsePullRequestUrl('https://github.com/atomantic/PortOS')).toBeNull();
+ expect(parsePullRequestUrl('not a url')).toBeNull();
+ expect(parsePullRequestUrl('https://github.com/atomantic/PortOS/pull/notanumber')).toBeNull();
+ expect(parsePullRequestUrl('https://github.com/atomantic/PortOS/pull/0')).toBeNull();
+ });
+
+ it('rejects GitHub URLs with extra path segments before /pull/ (no silent mis-parse)', () => {
+ expect(parsePullRequestUrl('https://github.com/owner/repo/extra/pull/1')).toBeNull();
+ expect(parsePullRequestUrl('https://github.com/owner/repo/extra/more/pull/1')).toBeNull();
+ });
+
+ it('rejects non-http(s) protocols, empty hosts, and explicit ports', () => {
+ expect(parsePullRequestUrl('file:///atomantic/PortOS/pull/1')).toBeNull();
+ expect(parsePullRequestUrl('ftp://github.com/atomantic/PortOS/pull/1')).toBeNull();
+ expect(parsePullRequestUrl('javascript:alert(1)')).toBeNull();
+ expect(parsePullRequestUrl('https://github.com:8443/atomantic/PortOS/pull/1')).toBeNull();
+ expect(parsePullRequestUrl('http://gitlab.example.com:9000/group/proj/-/merge_requests/1')).toBeNull();
+ });
+});
diff --git a/server/lib/gitOutputParsers.js b/server/lib/gitOutputParsers.js
new file mode 100644
index 0000000000..28a7d8544e
--- /dev/null
+++ b/server/lib/gitOutputParsers.js
@@ -0,0 +1,131 @@
+// Pure parsers for git / CLI command output. No child-process or filesystem
+// access — these turn the text git prints into structured data. The
+// orchestration that actually runs git lives in server/services/git.js.
+
+/**
+ * Map a 2-char porcelain status code to a human-readable label.
+ * Falls back to the trimmed code for unmapped combinations.
+ * @param {string} status - Two-character porcelain status (e.g. ' M', '??')
+ * @returns {string}
+ */
+export function parseStatus(status) {
+ const map = {
+ '??': 'untracked',
+ 'A ': 'added',
+ 'M ': 'modified (staged)',
+ ' M': 'modified',
+ 'MM': 'modified (partial)',
+ 'D ': 'deleted (staged)',
+ ' D': 'deleted',
+ 'R ': 'renamed',
+ 'C ': 'copied',
+ 'AM': 'added (modified)',
+ 'AD': 'added (deleted)'
+ };
+ return map[status] || status.trim();
+}
+
+/**
+ * Parse the summary line of `git diff --stat` into counts.
+ * Accepts the full multi-line diff-stat output (or its trailing summary line)
+ * and extracts files/insertions/deletions. Missing pieces default to 0.
+ * @param {string} statOutput - Raw `git diff --stat` stdout
+ * @returns {{ files: number, insertions: number, deletions: number }}
+ */
+export function parseDiffStat(statOutput) {
+ const statsLine = (statOutput || '').trim().split('\n').pop() || '';
+ const filesMatch = statsLine.match(/(\d+) files? changed/);
+ const insertionsMatch = statsLine.match(/(\d+) insertions?/);
+ const deletionsMatch = statsLine.match(/(\d+) deletions?/);
+ return {
+ files: filesMatch ? parseInt(filesMatch[1], 10) : 0,
+ insertions: insertionsMatch ? parseInt(insertionsMatch[1], 10) : 0,
+ deletions: deletionsMatch ? parseInt(deletionsMatch[1], 10) : 0
+ };
+}
+
+/**
+ * Parse one line of the pipe-delimited
+ * `git branch -vv --format=%(HEAD)|%(refname:short)|%(upstream:short)|%(upstream:track)`
+ * output into a structured branch record.
+ * @param {string} line
+ * @returns {{ name: string, current: boolean, tracking: string|null, ahead: number, behind: number }}
+ */
+export function parseBranchVerboseLine(line) {
+ const [head, name, upstream, track] = line.split('|');
+ const aheadMatch = track?.match(/ahead (\d+)/);
+ const behindMatch = track?.match(/behind (\d+)/);
+ return {
+ name,
+ current: head === '*',
+ tracking: upstream || null,
+ ahead: aheadMatch ? parseInt(aheadMatch[1], 10) : 0,
+ behind: behindMatch ? parseInt(behindMatch[1], 10) : 0
+ };
+}
+
+export const SUBMODULE_STATUS_RE = /^([+ \-U])([0-9a-f]+)\s+(\S+)/;
+
+/**
+ * Parse one line of `git submodule status` into `{ statusChar, commit, path }`.
+ * Returns null for lines that don't match the expected shape.
+ * @param {string} line
+ * @returns {{ statusChar: string, commit: string, path: string }|null}
+ */
+export function parseSubmoduleStatusLine(line) {
+ const match = line.match(SUBMODULE_STATUS_RE);
+ if (!match) return null;
+ return { statusChar: match[1], commit: match[2], path: match[3] };
+}
+
+/**
+ * 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;
+ }
+ }
+
+ // 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();
+
+ // Strip a leading "Summary" heading the agent may have written itself
+ // (e.g. "## Summary", "# Summary", "Summary:"). Without this, the PR body
+ // ends up with two stacked "Summary" headings — generatePRDescription wraps
+ // the extracted text in its own "## Summary" section.
+ while (summaryLines.length && /^\s*(#{1,6}\s*)?summary\s*:?\s*$/i.test(summaryLines[0])) {
+ summaryLines.shift();
+ while (summaryLines.length && !summaryLines[0].trim()) summaryLines.shift();
+ }
+
+ const summary = summaryLines.join('\n').trim();
+
+ // Must have meaningful content (at least a sentence)
+ if (summary.length < 30) return null;
+
+ return summary;
+}
diff --git a/server/lib/gitOutputParsers.test.js b/server/lib/gitOutputParsers.test.js
new file mode 100644
index 0000000000..997255fb2c
--- /dev/null
+++ b/server/lib/gitOutputParsers.test.js
@@ -0,0 +1,142 @@
+import { describe, it, expect } from 'vitest';
+import {
+ parseStatus,
+ parseDiffStat,
+ parseBranchVerboseLine,
+ parseSubmoduleStatusLine,
+ SUBMODULE_STATUS_RE,
+ extractAgentSummary
+} from './gitOutputParsers.js';
+
+describe('parseStatus', () => {
+ it('maps known porcelain codes to labels', () => {
+ expect(parseStatus('??')).toBe('untracked');
+ expect(parseStatus('A ')).toBe('added');
+ expect(parseStatus('M ')).toBe('modified (staged)');
+ expect(parseStatus(' M')).toBe('modified');
+ expect(parseStatus('MM')).toBe('modified (partial)');
+ expect(parseStatus('D ')).toBe('deleted (staged)');
+ expect(parseStatus(' D')).toBe('deleted');
+ expect(parseStatus('R ')).toBe('renamed');
+ expect(parseStatus('C ')).toBe('copied');
+ expect(parseStatus('AM')).toBe('added (modified)');
+ expect(parseStatus('AD')).toBe('added (deleted)');
+ });
+
+ it('falls back to the trimmed code for unmapped combinations', () => {
+ expect(parseStatus('UU')).toBe('UU');
+ expect(parseStatus(' R')).toBe('R');
+ });
+});
+
+describe('parseDiffStat', () => {
+ it('extracts files/insertions/deletions from the summary line', () => {
+ const out = ' file.js | 3 +-\n 1 file changed, 2 insertions(+), 1 deletion(-)';
+ expect(parseDiffStat(out)).toEqual({ files: 1, insertions: 2, deletions: 1 });
+ });
+
+ it('handles plural and singular grammar', () => {
+ const out = ' 5 files changed, 10 insertions(+), 4 deletions(-)';
+ expect(parseDiffStat(out)).toEqual({ files: 5, insertions: 10, deletions: 4 });
+ });
+
+ it('defaults missing pieces to 0', () => {
+ expect(parseDiffStat(' 1 file changed, 3 insertions(+)')).toEqual({ files: 1, insertions: 3, deletions: 0 });
+ expect(parseDiffStat('')).toEqual({ files: 0, insertions: 0, deletions: 0 });
+ expect(parseDiffStat(null)).toEqual({ files: 0, insertions: 0, deletions: 0 });
+ });
+});
+
+describe('parseBranchVerboseLine', () => {
+ it('parses a current branch with ahead/behind tracking', () => {
+ expect(parseBranchVerboseLine('*|main|origin/main|ahead 2, behind 1')).toEqual({
+ name: 'main', current: true, tracking: 'origin/main', ahead: 2, behind: 1
+ });
+ });
+
+ it('parses a non-current branch with no tracking', () => {
+ expect(parseBranchVerboseLine(' |feature||')).toEqual({
+ name: 'feature', current: false, tracking: null, ahead: 0, behind: 0
+ });
+ });
+
+ it('parses ahead-only and behind-only tracking', () => {
+ expect(parseBranchVerboseLine(' |dev|origin/dev|ahead 3')).toMatchObject({ ahead: 3, behind: 0 });
+ expect(parseBranchVerboseLine(' |dev|origin/dev|behind 4')).toMatchObject({ ahead: 0, behind: 4 });
+ });
+});
+
+describe('parseSubmoduleStatusLine', () => {
+ it('parses up-to-date, out-of-sync, and uninitialized lines', () => {
+ expect(parseSubmoduleStatusLine(' abc1234 lib/slashdo (heads/main)')).toEqual({
+ statusChar: ' ', commit: 'abc1234', path: 'lib/slashdo'
+ });
+ expect(parseSubmoduleStatusLine('+abc1234 lib/slashdo (heads/main)')).toMatchObject({ statusChar: '+' });
+ expect(parseSubmoduleStatusLine('-abc1234 lib/slashdo')).toMatchObject({ statusChar: '-' });
+ expect(parseSubmoduleStatusLine('Uabc1234 lib/slashdo')).toMatchObject({ statusChar: 'U' });
+ });
+
+ it('returns null for non-matching lines', () => {
+ expect(parseSubmoduleStatusLine('')).toBeNull();
+ expect(parseSubmoduleStatusLine('not a submodule line')).toBeNull();
+ });
+
+ it('exports the underlying regex', () => {
+ expect(SUBMODULE_STATUS_RE).toBeInstanceOf(RegExp);
+ });
+});
+
+describe('extractAgentSummary', () => {
+ it('returns null for short output', () => {
+ expect(extractAgentSummary(null)).toBeNull();
+ expect(extractAgentSummary('')).toBeNull();
+ expect(extractAgentSummary('too short')).toBeNull();
+ });
+
+ it('extracts trailing summary after last tool-call line', () => {
+ const output = [
+ 'Investigating the bug.',
+ '🔧 Using Read tool',
+ ' → /path/to/file.js',
+ '',
+ 'Implemented the fix by adding the missing null check on line 42.',
+ 'All tests pass: 187/187.'
+ ].join('\n');
+
+ const summary = extractAgentSummary(output);
+ expect(summary).toContain('Implemented the fix');
+ expect(summary).toContain('All tests pass');
+ expect(summary).not.toContain('🔧');
+ });
+
+ it('strips leading "## Summary" heading so the PR body does not double it up', () => {
+ const output = [
+ '🔧 Using Edit tool',
+ ' → /path/to/file.js',
+ '',
+ '## Summary',
+ '',
+ 'Added a Run Backup Now button and default-exclusions display.',
+ 'All tests pass.'
+ ].join('\n');
+
+ const summary = extractAgentSummary(output);
+ expect(summary).not.toMatch(/^#{1,6}?\s*summary/i);
+ expect(summary?.split('\n')[0]).toContain('Added a Run Backup Now button');
+ });
+
+ it('strips leading "Summary:" (no markdown prefix) too', () => {
+ const output = [
+ '🔧 Using Edit tool',
+ ' → /path/to/file.js',
+ '',
+ 'Summary:',
+ '',
+ 'Added a Run Backup Now button and default-exclusions display.',
+ 'All tests pass.'
+ ].join('\n');
+
+ const summary = extractAgentSummary(output);
+ expect(summary?.split('\n')[0]).toContain('Added a Run Backup Now button');
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index e407e55c78..18477abb84 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -101,6 +101,9 @@ export * from './zipStream.js';
export * from './commandSecurity.js';
export * from './execGit.js';
export * from './ffmpeg.js';
+export * from './gitArgs.js';
+export * from './gitForge.js';
+export * from './gitOutputParsers.js';
export * from './gitRemote.js';
export * from './processEnv.js';
export * from './pythonSetup.js';
diff --git a/server/services/git.js b/server/services/git.js
index 2be65d9a0a..3837e0f1aa 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -4,11 +4,35 @@ import { join } from 'path';
import { safeJSONParse, PATHS } from '../lib/fileUtils.js';
import { listWorktrees } from './worktreeManager.js';
import { execGit } from '../lib/execGit.js';
+import {
+ parseStatus,
+ parseDiffStat,
+ parseBranchVerboseLine,
+ parseSubmoduleStatusLine,
+ extractAgentSummary
+} from '../lib/gitOutputParsers.js';
+import {
+ parseGitRemote,
+ parseGitHubOwnerFromRemote,
+ pickGhAccountForOwner,
+ detectForgeCli,
+ parsePullRequestUrl
+} from '../lib/gitForge.js';
+import { PROTECTED_BRANCHES, validateFilePaths } from '../lib/gitArgs.js';
// Re-export so callers that used to import from services/git.js keep working.
export { execGit };
-
-const PROTECTED_BRANCHES = ['main', 'master', 'dev', 'develop', 'release'];
+// Re-export the extracted pure helpers so existing
+// `import { … } from 'services/git.js'` call sites keep working.
+export {
+ parseStatus,
+ parseGitRemote,
+ parseGitHubOwnerFromRemote,
+ pickGhAccountForOwner,
+ detectForgeCli,
+ parsePullRequestUrl,
+ extractAgentSummary
+};
// Like execGit but catches rejections (e.g. timeout) into a failed-result shape
const execGitSafe = (args, cwd, options) =>
@@ -43,23 +67,6 @@ export async function getStatus(dir) {
};
}
-function parseStatus(status) {
- const map = {
- '??': 'untracked',
- 'A ': 'added',
- 'M ': 'modified (staged)',
- ' M': 'modified',
- 'MM': 'modified (partial)',
- 'D ': 'deleted (staged)',
- ' D': 'deleted',
- 'R ': 'renamed',
- 'C ': 'copied',
- 'AM': 'added (modified)',
- 'AD': 'added (deleted)'
- };
- return map[status] || status.trim();
-}
-
/**
* Get current branch name
*/
@@ -98,37 +105,7 @@ export async function getDiff(dir, staged = false) {
*/
export async function getDiffStats(dir) {
const result = await execGit(['diff', '--stat'], dir);
- const statsLine = result.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 {
- files: filesMatch ? parseInt(filesMatch[1], 10) : 0,
- insertions: insertionsMatch ? parseInt(insertionsMatch[1], 10) : 0,
- deletions: deletionsMatch ? parseInt(deletionsMatch[1], 10) : 0
- };
-}
-
-/**
- * Validate file paths to prevent command injection and path traversal
- * @param {string[]} files - Array of file paths
- * @returns {string[]} - Sanitized file paths
- */
-function validateFilePaths(files) {
- const fileList = Array.isArray(files) ? files : [files];
- return fileList.map(f => {
- // Reject paths with null bytes or command separators
- if (/[\0;|&`$]/.test(f)) {
- throw new Error(`Invalid character in file path: ${f}`);
- }
- // Reject absolute paths or parent directory traversal
- if (f.startsWith('/') || f.includes('..')) {
- throw new Error(`Invalid file path: ${f}`);
- }
- return f;
- });
+ return parseDiffStat(result.stdout);
}
/**
@@ -250,19 +227,11 @@ export async function getBranchComparison(dir, baseBranch = 'main', headBranch =
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], 10) : 0,
- insertions: insertionsMatch ? parseInt(insertionsMatch[1], 10) : 0,
- deletions: deletionsMatch ? parseInt(deletionsMatch[1], 10) : 0
- }
+ stats: parseDiffStat(statResult.stdout)
};
}
@@ -323,56 +292,6 @@ export async function checkout(dir, branchName) {
return { success: true, branch: branchName };
}
-/**
- * Parse a git remote URL into `{ host, owner }`. Returns null for unparseable input.
- * Examples:
- * [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 parseGitRemote(url) {
- if (!url) return null;
- // 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;
-}
-
-/**
- * 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) {
- if (!ownerLogin || !availableAccounts?.length) return null;
- const lower = ownerLogin.toLowerCase();
- return availableAccounts.find(a => a.toLowerCase() === lower) || null;
-}
-
-/**
- * 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(cmd, args, { shell: false, windowsHide: true, ...options });
@@ -481,73 +400,6 @@ export async function createPR(dir, { title, body, base, head }) {
});
}
-/**
- * Parse a PR / MR URL into { host, owner, repo, number }. Returns null on bad input.
- * Handles GitHub (`/pull/N`) and GitLab (`/-/merge_requests/N`) URLs, including
- * GitLab projects nested in subgroups (the entire group path becomes `owner`)
- * and URLs with trailing segments such as `/files`, `/commits`, `?query`, `#hash`.
- */
-export function parsePullRequestUrl(url) {
- if (!url || typeof url !== 'string') return null;
-
- let parsed;
- // new URL throws on malformed input; we want a structured null instead so a try
- // wrapper here is the right call (the project's "no try/catch" rule covers
- // request handlers, not URL validation helpers).
- try { parsed = new URL(url); } catch { return null; }
-
- // Only forge web URLs are valid input — reject file://, ftp://, javascript:,
- // etc., which can otherwise sneak through to downstream `gh api --hostname`
- // or `glab` calls with a misleading or empty host.
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
-
- // `new URL` accepts `https:///path` and `http://:8080/...` — both yield an
- // empty hostname. Reject those: a host-less PR URL is meaningless.
- if (!parsed.hostname) return null;
-
- // Reject explicit ports (`https://github.com:8443/...`). We use
- // `parsed.hostname` below (not `host`), so a custom port would be silently
- // dropped and route the request to the wrong server. Custom-port forges
- // aren't supported until the port is plumbed through a separate field.
- if (parsed.port) return null;
-
- const host = parsed.hostname;
- const segments = parsed.pathname.split('/').filter(Boolean);
-
- // GitHub: /<owner>/<repo>/pull/<number>[/<more>]
- // GitHub PR URLs are STRICTLY two segments before `pull` — anything else
- // (e.g. /owner/repo/extra/pull/1) is invalid and would silently mis-parse
- // if we just took the last segment as `repo`. Require segments[2] === 'pull'.
- if (segments.length >= 4 && segments[2] === 'pull') {
- const number = Number(segments[3]);
- if (Number.isInteger(number) && number > 0) {
- return { host, owner: segments[0], repo: segments[1], number };
- }
- }
-
- // GitLab: /<group>[/<subgroup>...]/<project>/-/merge_requests/<number>[/<more>]
- // Locate the `-/merge_requests/<n>` triple anchored at any depth.
- for (let i = segments.length - 3; i >= 2; i--) {
- if (segments[i] === '-' && segments[i + 1] === 'merge_requests') {
- const number = Number(segments[i + 2]);
- if (Number.isInteger(number) && number > 0) {
- const project = segments.slice(0, i);
- if (project.length >= 2) {
- // owner = full group/subgroup path, repo = final project segment
- return {
- host,
- owner: project.slice(0, -1).join('/'),
- repo: project[project.length - 1],
- number,
- };
- }
- }
- }
- }
-
- return null;
-}
-
/**
* Request a Copilot code review on a GitHub PR. The reviewer login MUST include
* the `[bot]` suffix or GitHub returns 422 "must be a collaborator". GitLab has
@@ -666,58 +518,6 @@ export async function suggestPRTitle(dir, baseBranch, headBranch, fallbackText)
return firstLine.trim().substring(0, 100) || 'CoS automated task';
}
-/**
- * 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;
- }
- }
-
- // 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();
-
- // Strip a leading "Summary" heading the agent may have written itself
- // (e.g. "## Summary", "# Summary", "Summary:"). Without this, the PR body
- // ends up with two stacked "Summary" headings — generatePRDescription wraps
- // the extracted text in its own "## Summary" section.
- while (summaryLines.length && /^\s*(#{1,6}\s*)?summary\s*:?\s*$/i.test(summaryLines[0])) {
- summaryLines.shift();
- while (summaryLines.length && !summaryLines[0].trim()) summaryLines.shift();
- }
-
- const summary = summaryLines.join('\n').trim();
-
- // Must have meaningful content (at least a sentence)
- if (summary.length < 30) return null;
-
- return summary;
-}
-
export async function getDefaultBranch(dir, { allowRemote = true } = {}) {
const symRef = await execGitSafe(['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'], dir);
if (symRef.stdout?.trim()) {
@@ -799,19 +599,7 @@ export async function getBranches(dir) {
{ ignoreExitCode: true }
);
- const branches = result.stdout.trim().split('\n').filter(Boolean).map(line => {
- const [head, name, upstream, track] = line.split('|');
- const aheadMatch = track?.match(/ahead (\d+)/);
- const behindMatch = track?.match(/behind (\d+)/);
-
- return {
- name,
- current: head === '*',
- tracking: upstream || null,
- ahead: aheadMatch ? parseInt(aheadMatch[1], 10) : 0,
- behind: behindMatch ? parseInt(behindMatch[1], 10) : 0
- };
- });
+ const branches = result.stdout.trim().split('\n').filter(Boolean).map(parseBranchVerboseLine);
return branches;
}
@@ -1270,14 +1058,6 @@ export async function getGitInfo(dir) {
};
}
-const SUBMODULE_STATUS_RE = /^([+ \-U])([0-9a-f]+)\s+(\S+)/;
-
-function parseSubmoduleStatusLine(line) {
- const match = line.match(SUBMODULE_STATUS_RE);
- if (!match) return null;
- return { statusChar: match[1], commit: match[2], path: match[3] };
-}
-
/**
* Get submodule status for the PortOS repo
*/