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-2650]): migrate branch-reconcile & issue-reconcile to GitHub-family host gate

[._.]/ Adam Eivyd10472d050d4
diff --git a/server/lib/README.md b/server/lib/README.md
index 93d7627012..3da39b2cf5 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -283,7 +283,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `streamBackpressure.js` | `awaitWritableDrain(res)` — park a streaming-response producer on the socket's next `drain` (or `close`) when `res.write()` returned false, so SSE/NDJSON writes stay bounded for a slow reader. Shared by `routes/ask.js` (SSE) and `routes/localLlm.js` (NDJSON). |
| `uuid.js` | `v4()` thin wrapper over `crypto.randomUUID()`. |
| `versionUtils.js` | `compareSemver(a, b)` — semver ordering (-1/0/1) with pre-release precedence and build-metadata stripping. Shared by the self-update checker (`updateChecker.js`) and the local-LLM Ollama update detector (`localLlm.js`). Inputs must be `v`-stripped. |
-| `workTracker.js` | `WORK_TRACKERS`/`CONCRETE_WORK_TRACKERS`/`DEFAULT_WORK_TRACKER`, `workTrackerLabel`, `hostToWorkTracker`, `forgeCliForTracker`, `trackerToClaimTaskType`, `hostFromOriginUrl` (subgroup-tolerant host parse), pure `resolveWorkTracker({configured,host})`, async `resolveAppWorkTracker(app)` — resolves a managed app's autonomous work source (PLAN.md / GitHub / GitLab / JIRA), defaulting `'auto'` to the git origin host. Consumed by the `claim-work` router in `cosTaskGenerator.js` and `routes/apps.js`. |
+| `workTracker.js` | `WORK_TRACKERS`/`CONCRETE_WORK_TRACKERS`/`DEFAULT_WORK_TRACKER`, `workTrackerLabel`, `hostToWorkTracker`, `isGithubHost` (GitHub-family host test — github.com + enterprise github.*; enterprise-aware replacement for the github.com-only `isGithub` gate, shared by prWatcher/branchReconcile/issueReconcile), `forgeCliForTracker`, `trackerToClaimTaskType`, `hostFromOriginUrl` (subgroup-tolerant host parse), pure `resolveWorkTracker({configured,host})`, async `resolveAppWorkTracker(app)` — resolves a managed app's autonomous work source (PLAN.md / GitHub / GitLab / JIRA), defaulting `'auto'` to the git origin host. Consumed by the `claim-work` router in `cosTaskGenerator.js` and `routes/apps.js`. |
| `workspaceRoots.js` | Shared allow-list for routes that take a caller-supplied filesystem path. `ALLOWED_WORKSPACE_ROOTS` (defaults + `PORTOS_WORKSPACE_ROOTS`, symlink-resolved), `isWithinRoot(resolvedPath, root)` (separator-safe containment), `isWithinAllowedRoots(realPath)`, and `WORKSPACE_ROOTS_CONFIGURED` (true when the operator set the env var — lets a permissive-by-default route like `routes/detect.js` opt into confinement). Used by `routes/commands.js` (always scoped) and `routes/detect.js` (scoped only when configured). |
| `zodCompat.js` | Zod 4 compatibility helpers. `partialWithoutDefaults(objectSchema)` — like `.partial()` but strips inner field defaults first, so a PATCH/update schema doesn't inject (and clobber) the stored values of fields the caller didn't send. Use for any update schema derived from a defaulted base. |
diff --git a/server/lib/workTracker.js b/server/lib/workTracker.js
index 8046227645..2d0ecc7e5d 100644
--- a/server/lib/workTracker.js
+++ b/server/lib/workTracker.js
@@ -53,6 +53,19 @@ export function hostToWorkTracker(host) {
return null;
}
+/**
+ * True when `host` is a GitHub-family host — github.com AND self-hosted GitHub
+ * Enterprise (github.*). This is the enterprise-aware replacement for the
+ * github.com-only `getOriginInfo().isGithub` gate: `isGithub` drives PortOS's
+ * own fork/update flow (upstream lives on github.com), so reusing it to decide
+ * whether a repo's issues/PRs live on GitHub silently excluded enterprise repos.
+ * Shared by prWatcher, branchReconcile, and issueReconcile so the three stay
+ * consistent about what counts as "a GitHub repo".
+ */
+export function isGithubHost(host) {
+ return hostToWorkTracker(host) === 'github';
+}
+
/**
* Which forge CLI a concrete tracker drives: github → `gh`, gitlab → `glab`.
* PLAN.md and JIRA have no forge CLI, so they return null.
diff --git a/server/lib/workTracker.test.js b/server/lib/workTracker.test.js
index 4ce3a0bc6e..e07d71810d 100644
--- a/server/lib/workTracker.test.js
+++ b/server/lib/workTracker.test.js
@@ -5,6 +5,7 @@ import {
DEFAULT_WORK_TRACKER,
workTrackerLabel,
hostToWorkTracker,
+ isGithubHost,
forgeCliForTracker,
trackerToClaimTaskType,
resolveWorkTracker,
@@ -38,6 +39,23 @@ describe('hostToWorkTracker', () => {
});
});
+describe('isGithubHost', () => {
+ it('is true for github.com AND enterprise github.* hosts', () => {
+ expect(isGithubHost('github.com')).toBe(true);
+ expect(isGithubHost('GitHub.com')).toBe(true);
+ expect(isGithubHost('github.mycorp.com')).toBe(true);
+ expect(isGithubHost('github.acme.example')).toBe(true);
+ });
+ it('is false for gitlab, other forges, and empty/invalid hosts', () => {
+ expect(isGithubHost('gitlab.com')).toBe(false);
+ expect(isGithubHost('gitlab.example.com')).toBe(false);
+ expect(isGithubHost('bitbucket.org')).toBe(false);
+ expect(isGithubHost('')).toBe(false);
+ expect(isGithubHost(null)).toBe(false);
+ expect(isGithubHost(undefined)).toBe(false);
+ });
+});
+
describe('forgeCliForTracker', () => {
it('maps forge trackers to their CLI, others to null', () => {
expect(forgeCliForTracker('github')).toBe('gh');
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index e8d597b7e8..cd54d94794 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -22,6 +22,7 @@ import { execGit } from '../lib/execGit.js';
import { listWorktrees, forceRemoveWorktreeDir, classifyWorktreeDirt, isHumanClaimWorktree } from './worktreeManager.js';
import { execGh } from './github.js';
import { getOriginInfo } from '../lib/gitRemote.js';
+import { isGithubHost } from '../lib/workTracker.js';
import { safeJSONParse, PATHS } from '../lib/fileUtils.js';
// Never reconciled — these are long-lived shared branches, not disposable work.
@@ -94,9 +95,15 @@ export function classifyBranches(inputs) {
*/
async function getOpenPrsByHead(repoPath) {
const origin = await getOriginInfo(repoPath).catch(() => null);
- if (!origin?.isGithub || !origin.fullName) return new Map();
+ // Accept any GitHub-family host (github.com AND enterprise github.*), mirroring
+ // prWatcher.checkPullRequests. `origin.isGithub` is github.com-only, so gating
+ // on it silently skipped enterprise repos. The host-qualified `HOST/OWNER/REPO`
+ // selector keeps gh deterministic on a fork+upstream checkout (a bare
+ // OWNER/REPO defaults to github.com) — the same reason prWatcher pins the host.
+ if (!origin?.hasOrigin || !origin.fullName || !isGithubHost(origin.host)) return new Map();
+ const repoSpec = `${origin.host}/${origin.fullName}`;
const raw = await execGh([
- 'pr', 'list', '--repo', origin.fullName, '--state', 'open',
+ 'pr', 'list', '--repo', repoSpec, '--state', 'open',
'--limit', String(PR_LIST_LIMIT),
'--json', 'number,headRefName,mergeable,isDraft,url'
]).catch(() => null);
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index 2c77ff8f40..7adc1695a8 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -28,7 +28,9 @@ vi.mock('./worktreeManager.js', () => ({
}));
vi.mock('./github.js', () => ({ execGh: vi.fn(async () => '[]') }));
vi.mock('../lib/gitRemote.js', () => ({
- getOriginInfo: vi.fn(async () => ({ isGithub: true, fullName: 'atomantic/PortOS' }))
+ getOriginInfo: vi.fn(async () => ({
+ hasOrigin: true, isGithub: true, host: 'github.com', fullName: 'atomantic/PortOS'
+ }))
}));
vi.mock('../lib/fileUtils.js', () => ({
PATHS: { root: '/repo' },
@@ -43,6 +45,7 @@ import * as git from './git.js';
import * as wt from './worktreeManager.js';
import { execGit } from '../lib/execGit.js';
import { execGh } from './github.js';
+import { getOriginInfo } from '../lib/gitRemote.js';
beforeEach(() => {
vi.clearAllMocks();
@@ -211,6 +214,45 @@ describe('gatherBranchState', () => {
expect(i2199.openPr.number).toBe(2206);
expect(inputs.find((i) => i.branch === 'next/issue-2190').isMerged).toBe(true);
});
+
+ it('resolves PRs on a GitHub Enterprise host via a host-qualified --repo selector', async () => {
+ // isGithub is github.com-only, but the enterprise host classifies as GitHub —
+ // the scan must still run, targeting HOST/OWNER/REPO (not a bare OWNER/REPO,
+ // which gh would resolve against github.com).
+ getOriginInfo.mockResolvedValueOnce({
+ hasOrigin: true, isGithub: false, host: 'github.acme.example', fullName: 'acme/app'
+ });
+ git.getBranches.mockResolvedValue([
+ { name: 'next/issue-77', isDefault: false, current: false, tracking: 'origin/next/issue-77', merged: false }
+ ]);
+ wt.listWorktrees.mockResolvedValue([]);
+ git.isBranchMergedInto.mockResolvedValue(false);
+ execGh.mockResolvedValueOnce(JSON.stringify([
+ { number: 77, headRefName: 'next/issue-77', mergeable: 'MERGEABLE', isDraft: false, url: 'u' }
+ ]));
+
+ const inputs = await gatherBranchState('/repo', { defaultBranch: 'main' });
+ expect(inputs.find((i) => i.branch === 'next/issue-77').openPr.number).toBe(77);
+ const args = execGh.mock.calls[0][0];
+ const repoIdx = args.indexOf('--repo');
+ expect(args[repoIdx + 1]).toBe('github.acme.example/acme/app');
+ });
+
+ it('returns no PR facts on a non-GitHub host (GitLab origin)', async () => {
+ getOriginInfo.mockResolvedValueOnce({
+ hasOrigin: true, isGithub: false, host: 'gitlab.com', fullName: 'acme/app'
+ });
+ git.getBranches.mockResolvedValue([
+ { name: 'next/issue-88', isDefault: false, current: false, tracking: 'origin/next/issue-88', merged: false }
+ ]);
+ wt.listWorktrees.mockResolvedValue([]);
+ git.isBranchMergedInto.mockResolvedValue(false);
+ execGh.mockClear();
+
+ const inputs = await gatherBranchState('/repo', { defaultBranch: 'main' });
+ expect(inputs.find((i) => i.branch === 'next/issue-88').openPr).toBeNull();
+ expect(execGh).not.toHaveBeenCalled();
+ });
});
describe('reconcile', () => {
diff --git a/server/services/issueReconcile.js b/server/services/issueReconcile.js
index 80ddc9068f..f920ab378b 100644
--- a/server/services/issueReconcile.js
+++ b/server/services/issueReconcile.js
@@ -55,7 +55,7 @@ import { execGh } from './github.js';
import { execGlab } from './gitlab.js';
import { fetchMyCurrentSprintTickets } from './jira.js';
import { getOriginInfo, readOriginRemoteUrl } from '../lib/gitRemote.js';
-import { hostToWorkTracker, hostFromOriginUrl } from '../lib/workTracker.js';
+import { hostToWorkTracker, hostFromOriginUrl, isGithubHost } from '../lib/workTracker.js';
import { safeJSONParse, PATHS } from '../lib/fileUtils.js';
// Bound the forge queries (single-user repos never realistically truncate at 200).
@@ -258,19 +258,23 @@ function normalizeGithubIssue(issue) {
* on any gh failure (degrade: the caller treats null as "nothing to reconcile /
* transient"). `fullName` is resolved by the dispatcher, not re-queried here.
* Unlike `getGitlabState`, this needs no `repoPath` — `gh` targets the repo via
- * `--repo <fullName>` rather than resolving from the working directory.
- * @param {string} fullName
+ * `--repo <repoSpec>` rather than resolving from the working directory.
+ * `repoSpec` is the host-qualified `HOST/OWNER/REPO` selector (mirroring
+ * prWatcher) so gh targets enterprise repos correctly and stays deterministic on
+ * a fork+upstream checkout; `fullName` is the plain `OWNER/REPO` for display.
+ * @param {string} repoSpec - host-qualified `HOST/OWNER/REPO` selector for gh
+ * @param {string} fullName - plain `OWNER/REPO`, returned for display/logging
* @returns {Promise<{forge:'github', fullName:string, inProgress:object[], mergedPrs:object[], openPrs:object[]}|null>}
*/
-async function getGithubState(fullName) {
+async function getGithubState(repoSpec, fullName) {
const [issuesRaw, mergedRaw, openRaw] = await Promise.all([
- execGh(['issue', 'list', '--repo', fullName, '--state', 'open',
+ execGh(['issue', 'list', '--repo', repoSpec, '--state', 'open',
'--label', IN_PROGRESS_LABEL, '--limit', String(GH_LIST_LIMIT),
'--json', 'number,title,labels,assignees,url']).catch(() => null),
- execGh(['pr', 'list', '--repo', fullName, '--state', 'merged',
+ execGh(['pr', 'list', '--repo', repoSpec, '--state', 'merged',
'--limit', String(GH_LIST_LIMIT),
'--json', 'number,headRefName,body,url,mergedAt']).catch(() => null),
- execGh(['pr', 'list', '--repo', fullName, '--state', 'open',
+ execGh(['pr', 'list', '--repo', repoSpec, '--state', 'open',
'--limit', String(GH_LIST_LIMIT),
'--json', 'number,headRefName,body']).catch(() => null),
]);
@@ -371,11 +375,14 @@ function gitlabProjectPath(originUrl) {
/**
* Resolve the app's forge from its git origin host and fetch the corresponding
- * state. github.com → GitHub, gitlab.* → GitLab; any other remote (or no origin)
+ * state. github.* → GitHub, gitlab.* → GitLab; any other remote (or no origin)
* returns null so the caller skips without parking.
*
- * GitHub uses `getOriginInfo().isGithub` (authoritative, github.com-only — same
- * scope as v1). GitLab is classified straight off the origin HOST via the
+ * GitHub is classified off the origin HOST via `isGithubHost` (github.com AND
+ * enterprise github.*), mirroring prWatcher — `getOriginInfo().isGithub` is
+ * github.com-only and silently skipped enterprise repos. It still needs a parsed
+ * `owner/repo` for the host-qualified `--repo` selector. GitLab is classified
+ * straight off the origin HOST via the
* subgroup-safe `hostFromOriginUrl`, NOT `getOriginInfo().fullName`: the latter's
* strict `owner/repo` parse returns null for a nested `group/subgroup/project`
* remote (the common GitLab layout), which would silently skip the scan even
@@ -385,8 +392,11 @@ function gitlabProjectPath(originUrl) {
*/
async function getForgeState(repoPath) {
const origin = await getOriginInfo(repoPath).catch(() => null);
- // GitHub: authoritative, github.com-only, needs a parsed owner/repo for --repo.
- if (origin?.isGithub && origin.fullName) return getGithubState(origin.fullName);
+ // GitHub (incl. enterprise): needs a parsed owner/repo for the host-qualified
+ // `HOST/OWNER/REPO` --repo selector (deterministic on fork+upstream checkouts).
+ if (isGithubHost(origin?.host) && origin.fullName) {
+ return getGithubState(`${origin.host}/${origin.fullName}`, origin.fullName);
+ }
// GitLab: classify off the host (subgroup-safe). `glab` is cwd-based, so a
// display path is best-effort — prefer getOriginInfo's fullName, else derive the
diff --git a/server/services/issueReconcile.test.js b/server/services/issueReconcile.test.js
index 8777f5d513..c273058770 100644
--- a/server/services/issueReconcile.test.js
+++ b/server/services/issueReconcile.test.js
@@ -32,6 +32,7 @@ vi.mock('../lib/workTracker.js', async (importActual) => {
return {
hostToWorkTracker: actual.hostToWorkTracker,
hostFromOriginUrl: actual.hostFromOriginUrl,
+ isGithubHost: actual.isGithubHost,
};
});
vi.mock('../lib/fileUtils.js', () => ({
@@ -273,6 +274,27 @@ describe('reconcile', () => {
expect(execGlab).not.toHaveBeenCalled();
});
+ it('scans a GitHub Enterprise host (isGithub=false) via a host-qualified --repo selector', async () => {
+ // isGithub is github.com-only, but github.acme.example classifies as GitHub —
+ // the scan must run and target HOST/OWNER/REPO so gh hits the enterprise repo
+ // rather than defaulting a bare OWNER/REPO to github.com.
+ getOriginInfo.mockResolvedValue({ isGithub: false, host: 'github.acme.example', fullName: 'acme/app' });
+ readOriginRemoteUrl.mockResolvedValue('[email protected]:acme/app.git');
+ mockGh({
+ issues: [{ number: 42, title: 't', labels: [{ name: 'in-progress' }], assignees: [], url: 'u' }],
+ merged: [{ number: 50, headRefName: 'x', body: 'Refs #42' }],
+ open: [],
+ });
+ execGit.mockResolvedValue({ stdout: '', exitCode: 0 });
+
+ const result = await reconcile('/repo');
+ expect(result.forge).toBe('github');
+ expect(result.fullName).toBe('acme/app');
+ expect(result.zombies.map((z) => z.number)).toEqual([42]);
+ const repoArgs = execGh.mock.calls.map((c) => c[0][c[0].indexOf('--repo') + 1]);
+ expect(repoArgs.every((r) => r === 'github.acme.example/acme/app')).toBe(true);
+ });
+
it('returns null (transient) when the issue list query fails', async () => {
execGh.mockImplementation(async (argv) => {
if (argv[0] === 'issue') return null; // load-bearing query failed
diff --git a/server/services/prWatcher.js b/server/services/prWatcher.js
index b307468514..46a7f97a58 100644
--- a/server/services/prWatcher.js
+++ b/server/services/prWatcher.js
@@ -27,7 +27,7 @@
import { execGh } from './github.js';
import { getAppById, updateApp } from './apps.js';
import { getOriginInfo } from '../lib/gitRemote.js';
-import { hostToWorkTracker } from '../lib/workTracker.js';
+import { isGithubHost } from '../lib/workTracker.js';
import { PR_AUTHOR_FILTERS } from '../lib/validation.js';
import { safeJSONParse } from '../lib/fileUtils.js';
@@ -196,9 +196,9 @@ export async function checkPullRequests(app, { authorFilter = 'any' } = {}) {
// Accept any GitHub-family host — github.com AND self-hosted GitHub Enterprise
// (github.*) — not just github.com. `origin.isGithub` is github.com-only (it
// drives PortOS's own fork/update flow), so gating on it silently excluded
- // enterprise repos. hostToWorkTracker classifies enterprise GitHub the same
- // way the claim-issue router does; gitlab.* and non-forge hosts fall through.
- if (!origin?.hasOrigin || !origin.fullName || hostToWorkTracker(origin.host) !== 'github') {
+ // enterprise repos. isGithubHost classifies enterprise GitHub the same way the
+ // claim-issue router does; gitlab.* and non-forge hosts fall through.
+ if (!origin?.hasOrigin || !origin.fullName || !isGithubHost(origin.host)) {
return { ok: false, reason: 'not-a-github-repo' };
}
const repoFullName = origin.fullName;