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

fix: pr-watcher enterprise-host support + claim-issue owner-is-org detection

Adam Eivy2f5eab43b2af
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 6cd1a8bb81..383015fd0f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -37,6 +37,8 @@
## Fixed
- **claim-issue no longer reports "no open issues" when an author filter is hiding a full queue.** The perpetual `claim-issue` / `claim-issue-gitlab` work-detector runs `gh`/`glab issue list` with an author filter (`self`→`@me`, or `owner`→the repo owner), and an empty *filtered* result was flattened to the reason `no-open-issues` — so a repo with open issues that simply don't match the filter parked for a full recheck cadence claiming there was nothing to do. The two failure modes this hid: `owner` resolves to an **org** (e.g. a GHE repo owned by a team), which is never an issue author, so the filter matches nothing; and `self`/`@me` is the wrong identity when the forge session differs from whoever filed the issues. The detector now re-probes without the author filter when the filtered list is empty, and if open issues exist it parks with a new `no-authored-issues` reason carrying the real open count. The on-demand "Run" toast now says *"open issues exist, but none match the author filter — set it to \"any\" (0 of N open)"* instead of the misleading "no open issues", pointing the user at the fix. A genuinely empty repo still reports `no-open-issues`, and the `any` filter is unaffected (no wasted re-probe). New private helper `countOpenIssuesUnfiltered`; covered by `perpetualWork.test.js` and `useOnDemandTaskToast.test.jsx`.
+- **claim-issue distinguishes the "owner filter matches an org" trap from a personal-username mismatch.** Building on the fix above: when the `owner` author filter resolves to an **organization** login (the common case for team/enterprise repos), `--author <org>` can only ever match zero issues — an org is never an issue author. The detector now recognizes an org owner up front (`gh repo view --json owner,isInOrganization`), skips the guaranteed-empty query entirely, and parks with a distinct `owner-is-org` reason carrying the real open count. The toast now reads *"the \"owner\" filter matches an org, which can't author issues — set it to \"self\" or \"any\" (0 of N open)"* instead of the generic "set it to any", so the user isn't left thinking their own username is mismatched. `owner` mode on a user-owned repo is unchanged. Covered by `perpetualWork.test.js` and `useOnDemandTaskToast.test.jsx`.
+- **pr-watcher now works on GitHub Enterprise hosts and resolves "self" against the repo's actual host.** The `pr-watcher` task gated on `getOriginInfo().isGithub`, which is github.com-only, so it silently no-op'd (`not-a-github-repo`) on self-hosted GitHub Enterprise (`github.*`) repos. Worse, its self/others author gate resolved the operator login via `gh api user` with no `--hostname` — which always targets github.com regardless of the repo — and cached one login process-wide, so on an enterprise repo it compared PR authors against the wrong identity (a user is commonly a different login per host). The gate now classifies GitHub-family hosts via the shared `hostToWorkTracker` (the same rule the claim-issue router uses; `gitlab.*` still falls through as not-a-github-repo), the default-branch and PR-list `gh` calls run inside the repo checkout so gh auto-detects the host, and `getSelfLogin(host)` resolves identity with an explicit `--hostname` and caches per host. `execGh` gained an optional `cwd` argument. Covered by `prWatcher.test.js`.
- **Retry lazy route chunks before failing on flaky mobile networks.** Lazy-loaded pages fetch their JS chunk on demand, and on a weak cellular/Wi-Fi link that fetch can fail on a transient blip ("Importing a module script failed" on Safari, "Failed to fetch dynamically imported module" on Chrome) even though the chunk still exists — a page reload can't fix a network hiccup, so once the one-shot stale-chunk reload was spent for a build, the next blip stranded the user on the error screen. `lazyWithReload` now retries the dynamic import twice with a short backoff before treating the failure as terminal, so a transient mobile-network failure recovers silently without a jarring reload; a genuinely stale chunk (renamed by a rebuild) still 404s on each quick retry and falls through to the existing reload-once path. New `importWithRetry` helper with unit coverage.
- **[issue-2643] De-flake the Wiki vault-default test under full-suite load.** `Wiki.test.jsx`'s "defaults to the first vault" (and the sibling "restores the selected vault") assertions checked `scanNotesVault` synchronously right after `await waitFor(...)` on the rendered vault id. That mock call is fired by a *separate* `useEffect` keyed on the selected vault, so the committed overview render can land before the passive effect flushes — reliably true in isolation, but on a CPU-saturated full client run the bare assertion raced ahead of the effect and failed (`expected vi.fn() to be called with arguments`). The two mock-call assertions now sit inside their own `waitFor`, awaiting the async side-effect instead of sampling it. Test-only change (no `test.retry` or timeout inflation) — no runtime behavior change.
diff --git a/client/src/hooks/useOnDemandTaskToast.js b/client/src/hooks/useOnDemandTaskToast.js
index 46a2dcb7ad..da4512e30f 100644
--- a/client/src/hooks/useOnDemandTaskToast.js
+++ b/client/src/hooks/useOnDemandTaskToast.js
@@ -12,6 +12,7 @@ const PARK_REASON_LABELS = {
'no-actionable-issues': 'no claimable issues',
'no-open-issues': 'no open issues',
'no-authored-issues': 'open issues exist, but none match the author filter — set it to "any"',
+ 'owner-is-org': 'the "owner" filter matches an org, which can\'t author issues — set it to "self" or "any"',
'no-in-flight-branches': 'no branches in flight',
'no-zombie-issues': 'no stale issues to reconcile',
'no-actionable-plan-items': 'no unblocked PLAN items',
diff --git a/client/src/hooks/useOnDemandTaskToast.test.jsx b/client/src/hooks/useOnDemandTaskToast.test.jsx
index 13fcb2163d..55ac08a375 100644
--- a/client/src/hooks/useOnDemandTaskToast.test.jsx
+++ b/client/src/hooks/useOnDemandTaskToast.test.jsx
@@ -82,4 +82,19 @@ describe('useOnDemandTaskToast — parked outcome', () => {
expect(msg).not.toMatch(/filtered/);
expect(msg).not.toMatch(/re-checked now — no open issues/);
});
+
+ it('explains the owner-filter org trap distinctly (owner matches an org, cannot author issues)', () => {
+ renderHook(() => useOnDemandTaskToast());
+ fire({
+ taskType: 'claim-issue', appName: 'App One', outcome: 'parked',
+ parkReason: 'owner-is-org', counts: { open: 10, inFlight: 0, filtered: 0 },
+ parkedUntil: new Date(Date.now() + 23 * 3600 * 1000).toISOString()
+ });
+ const [msg] = toastSpy.mock.calls[0];
+ // Steers the user to a working filter without implying a username mismatch.
+ expect(msg).toMatch(/matches an org/);
+ expect(msg).toMatch(/set it to "self" or "any"/);
+ expect(msg).toMatch(/0 of 10 open/);
+ expect(msg).not.toMatch(/re-checked now — no open issues/);
+ });
});
diff --git a/server/services/github.js b/server/services/github.js
index d1d39988f0..040aeeb652 100644
--- a/server/services/github.js
+++ b/server/services/github.js
@@ -36,11 +36,14 @@ async function save(data) {
}
/**
- * Execute a gh CLI command safely using spawn
+ * Execute a gh CLI command safely using spawn. Pass `cwd` to run inside a repo
+ * checkout so gh auto-detects the forge host from that repo's git remote (how
+ * `gh pr list` / `gh repo view` target an enterprise host). `gh api` is the
+ * exception — it ignores cwd and needs an explicit `--hostname` in `args`.
*/
-export function execGh(args) {
+export function execGh(args, cwd) {
return new Promise((resolve, reject) => {
- const child = spawn('gh', args, { shell: false, windowsHide: true });
+ const child = spawn('gh', args, { cwd, shell: false, windowsHide: true });
let stdout = '';
let stderr = '';
child.stdout.on('data', (d) => { stdout += d.toString(); });
diff --git a/server/services/perpetualWork.js b/server/services/perpetualWork.js
index 52486e8db9..dd2b642d5b 100644
--- a/server/services/perpetualWork.js
+++ b/server/services/perpetualWork.js
@@ -154,12 +154,22 @@ const FORGE_ISSUE_CONFIG = {
listArgs: ['issue', 'list', '--state', 'open', '--search', 'sort:created-asc', '--json', 'number,assignees,labels,title', '--limit', '100'],
listFail: 'gh-list-failed',
parseFail: 'gh-parse-failed',
- // Authoritative repo owner (org or user) via gh; transient if gh is
- // unauthenticated / not a GitHub remote.
+ // Authoritative repo owner (org or user) + whether that owner is an org, via
+ // gh; transient if gh is unauthenticated / not a GitHub remote. `isOrg` lets
+ // detectForgeIssues short-circuit the owner-filter org trap — an org login is
+ // never an issue author, so `--author <org>` is guaranteed to match nothing.
resolveOwner: async (repoPath) => {
- const r = await runCli('gh', ['repo', 'view', '--json', 'owner', '-q', '.owner.login'], repoPath);
- const owner = (r.stdout || '').trim();
- return (r.code !== 0 || !owner) ? { error: 'gh-unavailable' } : { owner };
+ const r = await runCli('gh', ['repo', 'view', '--json', 'owner,isInOrganization'], repoPath);
+ if (r.code !== 0) return { error: 'gh-unavailable' };
+ let parsed;
+ try {
+ parsed = JSON.parse(r.stdout || '{}');
+ } catch {
+ return { error: 'gh-unavailable' };
+ }
+ const owner = (parsed?.owner?.login || '').trim();
+ if (!owner) return { error: 'gh-unavailable' };
+ return { owner, isOrg: parsed?.isInOrganization === true };
},
// `--self` mode: gh natively understands the `@me` token for `--author`, so
// no extra lookup is needed — the API resolves it to the authenticated user.
@@ -229,6 +239,15 @@ async function detectForgeIssues(forgeKey, app, { issueAuthorFilter = 'self' } =
const repoPath = app?.repoPath;
if (!repoPath) return { actionable: false, count: 0, reason: 'no-repo-path' };
+ // Shared shape for a "parked" (no actionable work) result where only `reason`
+ // and `total` (the open-issue denominator) vary. `count`/`inFlightCount`/
+ // `filteredCount` are always 0 on these paths — the issues are excluded
+ // upstream (author filter / empty repo), never by the skip-list — so the toast
+ // reads a clean "0 of N open" with no redundant "N filtered".
+ const parked = (reason, total = 0) => ({
+ actionable: false, count: 0, total, inFlightCount: 0, filteredCount: 0, reason
+ });
+
const args = [...cfg.listArgs];
// Resolve the author filter symmetrically with resolveIssueAuthorFilterBlock:
// 'any' = no filter; 'owner' = repo/project owner; everything else (the 'self'
@@ -239,8 +258,17 @@ async function detectForgeIssues(forgeKey, app, { issueAuthorFilter = 'self' } =
if (issueAuthorFilter === 'any') {
// no --author filter
} else if (issueAuthorFilter === 'owner') {
- const { owner, error } = await cfg.resolveOwner(repoPath);
+ const { owner, isOrg, error } = await cfg.resolveOwner(repoPath);
if (error) return { actionable: false, count: 0, reason: error, transient: true };
+ if (isOrg) {
+ // The owner filter resolved to an ORG login, which can never be an issue
+ // author — `--author <org>` is guaranteed to match zero. Skip that empty
+ // query and report the real open count with a distinct `owner-is-org`
+ // reason, so the toast steers the user to 'self'/'any' instead of implying
+ // a personal-username mismatch (the failure that motivated this branch).
+ const openCount = await countOpenIssuesUnfiltered(cfg, repoPath);
+ return parked('owner-is-org', openCount);
+ }
args.push('--author', owner);
authorApplied = true;
} else {
@@ -262,9 +290,9 @@ async function detectForgeIssues(forgeKey, app, { issueAuthorFilter = 'self' } =
if (raw.length === 0) {
// An empty *filtered* list is ambiguous: the repo may truly have no open
// issues, OR it has open issues that just don't match the author filter —
- // the common trap being `owner`, which resolves to an ORG (never an issue
- // author, so the filter matches nothing), or `self`/@me when the server's
- // forge session is a different identity than whoever filed the issues.
+ // e.g. `self`/@me resolving to a different identity than whoever filed the
+ // issues, or a non-org `owner` who simply filed none. (The org-owner trap is
+ // caught earlier with the distinct `owner-is-org` reason.)
// Reporting a flat "no open issues" there hid a claimable queue behind a
// full recheck park (the "open issues exist but the task still parked"
// failure this fixes). Re-probe WITHOUT the author filter; if issues exist,
@@ -276,22 +304,9 @@ async function detectForgeIssues(forgeKey, app, { issueAuthorFilter = 'self' } =
// claimable ones would cost the full normalize + skip-list scan here.
if (authorApplied) {
const openCount = await countOpenIssuesUnfiltered(cfg, repoPath);
- if (openCount > 0) {
- return {
- actionable: false,
- count: 0,
- total: openCount,
- inFlightCount: 0,
- // These issues were excluded by the author filter upstream, not by
- // the skip-list — the `reason` conveys that cause, so leave the
- // skip-list "filtered" tally at 0 (the toast reads a clean
- // "0 of N open" rather than a redundant "N filtered").
- filteredCount: 0,
- reason: 'no-authored-issues'
- };
- }
+ if (openCount > 0) return parked('no-authored-issues', openCount);
}
- return { actionable: false, count: 0, total: 0, inFlightCount: 0, filteredCount: 0, reason: 'no-open-issues' };
+ return parked('no-open-issues');
}
const inFlight = await inFlightIssueNumbers(repoPath, cfg.inFlightForge);
diff --git a/server/services/perpetualWork.test.js b/server/services/perpetualWork.test.js
index 114e4e45ab..f947cdc7c6 100644
--- a/server/services/perpetualWork.test.js
+++ b/server/services/perpetualWork.test.js
@@ -211,21 +211,43 @@ describe('perpetualWork', () => {
expect(issueCalls.some(([, a]) => !a.includes('--author'))).toBe(true);
});
- it('owner filter that resolves to an org (never an issue author) reports no-authored-issues with the real open count', async () => {
- // The exact owner-filter trap: `gh repo view` owner is the ORG, so
- // `--author <org>` matches nothing even though the repo has open issues.
+ it('owner filter on an org-owned repo reports owner-is-org with the real open count (never queries --author <org>)', async () => {
+ // The exact owner-filter trap: the repo owner is an ORG, and an org login
+ // can never be an issue author, so `--author <org>` is guaranteed empty.
+ // The detector short-circuits to `owner-is-org` and reports the true count.
spawn.mockImplementation((cmd, args = []) => {
- if (cmd === 'gh' && args[0] === 'repo') return fakeChild('AcmeOrg\n'); // owner login → org
+ if (cmd === 'gh' && args[0] === 'repo') {
+ return fakeChild(JSON.stringify({ owner: { login: 'AcmeOrg' }, isInOrganization: true }));
+ }
if (cmd === 'gh' && args[0] === 'issue') {
- const filtered = args.includes('--author');
- return fakeChild(filtered ? '[]' : JSON.stringify([
- { number: 5, title: 'x', assignees: [], labels: [] }
- ]));
+ return fakeChild(JSON.stringify([{ number: 5, title: 'x', assignees: [], labels: [] }]));
+ }
+ return fakeChild('');
+ });
+ const out = await detectGithubIssues(app, { issueAuthorFilter: 'owner' });
+ expect(out).toMatchObject({ reason: 'owner-is-org', total: 1, count: 0, filteredCount: 0 });
+ // The guaranteed-empty `--author <org>` query is skipped entirely — only
+ // the unfiltered count re-probe runs.
+ const issueCalls = spawn.mock.calls.filter(([cmd, a]) => cmd === 'gh' && a[0] === 'issue');
+ expect(issueCalls.every(([, a]) => !a.includes('--author'))).toBe(true);
+ });
+
+ it('owner filter on a user-owned repo passes --author <login> and detects normally', async () => {
+ spawn.mockImplementation((cmd, args = []) => {
+ if (cmd === 'gh' && args[0] === 'repo') {
+ return fakeChild(JSON.stringify({ owner: { login: 'alice' }, isInOrganization: false }));
}
+ if (cmd === 'gh' && args[0] === 'issue') {
+ return fakeChild(JSON.stringify([{ number: 5, title: 'x', assignees: [], labels: [] }]));
+ }
+ if (cmd === 'git' && args[0] === 'branch') return fakeChild('main\n');
return fakeChild('');
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'owner' });
- expect(out).toMatchObject({ reason: 'no-authored-issues', total: 1, filteredCount: 0 });
+ expect(out.actionable).toBe(true);
+ const listCall = spawn.mock.calls.find(([cmd, a]) => cmd === 'gh' && a[0] === 'issue');
+ expect(listCall[1]).toContain('--author');
+ expect(listCall[1]).toContain('alice');
});
it('still reports no-open-issues when the repo is genuinely empty under an author filter', async () => {
diff --git a/server/services/prWatcher.js b/server/services/prWatcher.js
index 8802262aca..dbd4aa1e1a 100644
--- a/server/services/prWatcher.js
+++ b/server/services/prWatcher.js
@@ -27,6 +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 { PR_AUTHOR_FILTERS } from '../lib/validation.js';
import { safeJSONParse } from '../lib/fileUtils.js';
@@ -41,53 +42,64 @@ import { safeJSONParse } from '../lib/fileUtils.js';
// the cap. 200 matches the limit github.js#syncRepos already uses.
const PR_LIST_LIMIT = 200;
-// Cache the gh-authenticated login for the process lifetime. It's the PortOS
-// operator's identity and effectively never changes within a run; re-resolving
-// it on every scheduler tick would add a gh round-trip per watched app.
-let _selfLoginCache;
+// Cache the gh-authenticated login PER HOST, for the process lifetime. Host-keyed
+// for two reasons: (1) `gh api` does NOT infer the host from the working
+// directory's git remote the way `gh pr list` / `gh issue list` do — it hits the
+// default host (github.com) unless given an explicit `--hostname`; (2) the
+// operator is commonly a DIFFERENT login on github.com vs a self-hosted
+// enterprise host, so one process-wide login would gate enterprise PRs against
+// the wrong identity. Each host resolves once and is cached independently.
+const _selfLoginCache = new Map();
/**
- * Resolve the gh-authenticated user's login (e.g. "atomantic"). Returns null
- * when gh isn't authenticated / installed — callers that need it for an
- * author gate must treat null as "can't gate, don't fire blindly".
+ * Resolve the gh-authenticated user's login on `host` (e.g. "alice" on
+ * github.com, "alice_corp" on an enterprise host). Returns null when `host` is
+ * falsy or gh isn't authenticated there — callers that need it for an author
+ * gate must treat null as "can't gate, don't fire blindly".
*/
-export async function getSelfLogin() {
- if (_selfLoginCache) return _selfLoginCache;
- const login = await execGh(['api', 'user', '--jq', '.login']).catch(() => null);
+export async function getSelfLogin(host) {
+ if (!host) return null;
+ if (_selfLoginCache.has(host)) return _selfLoginCache.get(host);
+ // `--hostname` is required: without it `gh api` targets github.com regardless
+ // of cwd, resolving the wrong identity for an enterprise repo.
+ const login = await execGh(['api', 'user', '--hostname', host, '--jq', '.login']).catch(() => null);
// Only memoize a SUCCESSFUL lookup. Caching a null from a transient gh/auth
// failure (keychain locked mid-tick, gh re-auth in progress) would wedge every
- // later self/others gate into 'self-login-unavailable' until process restart;
- // leaving the cache unset lets the next tick retry once auth recovers.
+ // later self/others gate on this host into 'self-login-unavailable' until
+ // process restart; leaving it unset lets the next tick retry once auth recovers.
const trimmed = login && login.trim();
- if (trimmed) _selfLoginCache = trimmed;
- return _selfLoginCache || null;
+ if (trimmed) _selfLoginCache.set(host, trimmed);
+ return trimmed || null;
}
-// Test seam — reset the memoized login between cases.
+// Test seam — reset the memoized logins between cases.
export function __resetSelfLoginCache() {
- _selfLoginCache = undefined;
+ _selfLoginCache.clear();
}
/**
- * Resolve a repo's default branch via gh. Returns null on failure.
+ * Resolve a repo's default branch via gh. Runs inside `repoPath` so gh
+ * auto-detects the forge host from the repo's remote (works for github.com AND
+ * enterprise). Returns null on failure.
*/
-async function getDefaultBranch(repoFullName) {
- const name = await execGh(['repo', 'view', repoFullName, '--json', 'defaultBranchRef', '-q', '.defaultBranchRef.name'])
+async function getDefaultBranch(repoPath) {
+ const name = await execGh(['repo', 'view', '--json', 'defaultBranchRef', '-q', '.defaultBranchRef.name'], repoPath)
.catch(() => null);
return name ? name.trim() : null;
}
/**
- * List open PRs targeting `baseBranch` for `repoFullName`. Returns an array of
- * normalized PR objects, or null when the gh call fails.
+ * List open PRs targeting `baseBranch` for the repo at `repoPath`. Runs inside
+ * `repoPath` so gh auto-detects the host (no `--repo`, which would default to
+ * github.com). Returns an array of normalized PR objects, or null on failure.
*/
-async function listOpenPullRequests(repoFullName, baseBranch) {
+async function listOpenPullRequests(repoPath, baseBranch) {
const raw = await execGh([
- 'pr', 'list', '--repo', repoFullName,
+ 'pr', 'list',
'--base', baseBranch, '--state', 'open',
'--limit', String(PR_LIST_LIMIT),
'--json', 'number,title,author,url,createdAt,isDraft,headRefName'
- ]).catch(() => null);
+ ], repoPath).catch(() => null);
if (raw === null) return null;
// Guard the parse: a success-exit gh that emits empty/malformed stdout would
// otherwise throw a SyntaxError, breaking this module's "never throws"
@@ -178,27 +190,33 @@ export async function checkPullRequests(app, { authorFilter = 'any' } = {}) {
const filter = PR_AUTHOR_FILTERS.includes(authorFilter) ? authorFilter : 'any';
const origin = await getOriginInfo(app.repoPath).catch(() => null);
- if (!origin?.hasOrigin || !origin.isGithub || !origin.fullName) {
+ // 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') {
return { ok: false, reason: 'not-a-github-repo' };
}
const repoFullName = origin.fullName;
+ const { repoPath } = app;
- const defaultBranch = await getDefaultBranch(repoFullName);
+ const defaultBranch = await getDefaultBranch(repoPath);
if (!defaultBranch) {
return { ok: false, reason: 'default-branch-unresolved', repoFullName };
}
// Resolve self up front when the gate needs it — bail rather than firing
- // blindly if gh can't tell us who "self" is.
+ // blindly if gh can't tell us who "self" is on THIS repo's host.
let selfLogin = null;
if (filter !== 'any') {
- selfLogin = await getSelfLogin();
+ selfLogin = await getSelfLogin(origin.host);
if (!selfLogin) {
return { ok: false, reason: 'self-login-unavailable', repoFullName, defaultBranch };
}
}
- const prs = await listOpenPullRequests(repoFullName, defaultBranch);
+ const prs = await listOpenPullRequests(repoPath, defaultBranch);
if (prs === null) {
return { ok: false, reason: 'pr-list-failed', repoFullName, defaultBranch };
}
diff --git a/server/services/prWatcher.test.js b/server/services/prWatcher.test.js
index 7bde8f6517..89be954b4a 100644
--- a/server/services/prWatcher.test.js
+++ b/server/services/prWatcher.test.js
@@ -134,22 +134,45 @@ describe('formatPullRequestsForPrompt', () => {
});
describe('getSelfLogin', () => {
- it('caches the resolved login', async () => {
+ it('resolves against the given host (via --hostname) and caches per host', async () => {
execGhMock.mockResolvedValueOnce('bob\n');
- expect(await getSelfLogin()).toBe('bob');
- expect(await getSelfLogin()).toBe('bob');
+ expect(await getSelfLogin('github.com')).toBe('bob');
+ expect(await getSelfLogin('github.com')).toBe('bob');
expect(execGhMock).toHaveBeenCalledTimes(1);
+ // --hostname is required: without it `gh api` hits github.com regardless of
+ // cwd and would resolve the wrong identity on an enterprise repo.
+ expect(execGhMock).toHaveBeenCalledWith(['api', 'user', '--hostname', 'github.com', '--jq', '.login']);
});
+
+ it('caches each host independently — a different login per host', async () => {
+ execGhMock
+ .mockResolvedValueOnce('alice\n') // github.com
+ .mockResolvedValueOnce('alice_corp\n'); // enterprise
+ expect(await getSelfLogin('github.com')).toBe('alice');
+ expect(await getSelfLogin('github.enterprise.test')).toBe('alice_corp');
+ // Both cached — no re-resolve for either host.
+ expect(await getSelfLogin('github.com')).toBe('alice');
+ expect(await getSelfLogin('github.enterprise.test')).toBe('alice_corp');
+ expect(execGhMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('returns null with no host and never shells out', async () => {
+ expect(await getSelfLogin()).toBe(null);
+ expect(await getSelfLogin('')).toBe(null);
+ expect(execGhMock).not.toHaveBeenCalled();
+ });
+
it('returns null when gh fails', async () => {
execGhMock.mockRejectedValueOnce(new Error('not authed'));
- expect(await getSelfLogin()).toBe(null);
+ expect(await getSelfLogin('github.com')).toBe(null);
});
+
it('does not cache a failed lookup — retries on the next call', async () => {
execGhMock.mockRejectedValueOnce(new Error('keychain locked'));
- expect(await getSelfLogin()).toBe(null);
+ expect(await getSelfLogin('github.com')).toBe(null);
// A transient failure must not wedge the cache: the next call retries.
execGhMock.mockResolvedValueOnce('bob');
- expect(await getSelfLogin()).toBe('bob');
+ expect(await getSelfLogin('github.com')).toBe('bob');
expect(execGhMock).toHaveBeenCalledTimes(2);
});
});
@@ -164,7 +187,7 @@ describe('checkPullRequests', () => {
});
it('bails when the default branch cannot be resolved', async () => {
- getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, fullName: 'o/r' });
+ getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, host: 'github.com', fullName: 'o/r' });
execGhMock.mockResolvedValueOnce(''); // repo view → empty
const r = await checkPullRequests(app, { authorFilter: 'any' });
expect(r.ok).toBe(false);
@@ -172,7 +195,7 @@ describe('checkPullRequests', () => {
});
it('bails when an author gate is set but self login is unavailable', async () => {
- getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, fullName: 'o/r' });
+ getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, host: 'github.com', fullName: 'o/r' });
execGhMock
.mockResolvedValueOnce('main') // repo view → default branch
.mockRejectedValueOnce(new Error('no auth')); // api user → fails
@@ -182,7 +205,7 @@ describe('checkPullRequests', () => {
});
it('bails when the PR list call fails', async () => {
- getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, fullName: 'o/r' });
+ getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, host: 'github.com', fullName: 'o/r' });
execGhMock
.mockResolvedValueOnce('main') // repo view
.mockRejectedValueOnce(new Error('list failed')); // pr list
@@ -192,7 +215,7 @@ describe('checkPullRequests', () => {
});
it('first run baselines without dispatching', async () => {
- getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, fullName: 'o/r' });
+ getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, host: 'github.com', fullName: 'o/r' });
execGhMock
.mockResolvedValueOnce('main') // repo view
.mockResolvedValueOnce(JSON.stringify([
@@ -206,7 +229,7 @@ describe('checkPullRequests', () => {
});
it('dispatches new PRs above the mark, honoring the author gate', async () => {
- getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, fullName: 'o/r' });
+ getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, host: 'github.com', fullName: 'o/r' });
execGhMock
.mockResolvedValueOnce('main') // repo view
.mockResolvedValueOnce('bob') // api user
@@ -222,4 +245,29 @@ describe('checkPullRequests', () => {
expect(r.repoFullName).toBe('o/r');
expect(r.defaultBranch).toBe('main');
});
+
+ it('accepts a GitHub Enterprise host (isGithub false) and resolves self against THAT host', async () => {
+ // The core fix: an enterprise repo (github.* but not github.com, so
+ // origin.isGithub is false) must still be watched, and the self gate must
+ // resolve identity on the enterprise host — not github.com.
+ getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: false, host: 'github.enterprise.test', fullName: 'o/r' });
+ execGhMock
+ .mockResolvedValueOnce('main') // repo view (default branch)
+ .mockResolvedValueOnce('alice_corp') // api user --hostname github.enterprise.test
+ .mockResolvedValueOnce(JSON.stringify([
+ { number: 7, title: 'mine', author: { login: 'alice_corp' }, url: 'u7', createdAt: '2026-06-04T00:00:00Z', isDraft: false, headRefName: 'h7' }
+ ]));
+ const r = await checkPullRequests({ id: 'ent', repoPath: '/repos/ent', prWatcherState: { lastSeenPrNumber: 6 } }, { authorFilter: 'self' });
+ expect(r.ok).toBe(true);
+ expect(r.newPrs.map(p => p.number)).toEqual([7]);
+ // self was resolved on the enterprise host, so the enterprise-login PR matches.
+ expect(execGhMock).toHaveBeenCalledWith(['api', 'user', '--hostname', 'github.enterprise.test', '--jq', '.login']);
+ });
+
+ it('rejects a non-GitHub (GitLab) host as not-a-github-repo', async () => {
+ getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: false, host: 'gitlab.enterprise.test', fullName: 'o/r' });
+ const r = await checkPullRequests({ id: 'gl', repoPath: '/repos/gl' }, { authorFilter: 'any' });
+ expect(r).toEqual({ ok: false, reason: 'not-a-github-repo' });
+ expect(execGhMock).not.toHaveBeenCalled();
+ });
});