Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: verify reviewer identities on the target forge before dispatch (#13115)

Adam Eivyb4a72b4d2469
diff --git a/client/src/components/settings/CodeReviewersTab.jsx b/client/src/components/settings/CodeReviewersTab.jsx
index 0f24c2368a..7c9b00bf98 100644
--- a/client/src/components/settings/CodeReviewersTab.jsx
+++ b/client/src/components/settings/CodeReviewersTab.jsx
@@ -75,6 +75,7 @@ export default function CodeReviewersTab({ view } = {}) {
const [providerReviewUnsupported, setProviderReviewUnsupported] = useState({});
const [reviewerHealth, setReviewerHealth] = useState({});
const [reviewerConfigFaults, setReviewerConfigFaults] = useState({});
+ const [reviewerIdentities, setReviewerIdentities] = useState([]);
const [reviewerFallbackGroups, setReviewerFallbackGroups] = useState([]);
const modelOptions = useReviewerModelOptions();
const loadVersion = useRef(0);
@@ -138,6 +139,21 @@ export default function CodeReviewersTab({ view } = {}) {
return () => { loadVersion.current += 1; };
}, [loadDefaults]);
+ // Existence of the saved @login/@team reviewers on the forge. Lookups run
+ // server-side and are cached, so this is a one-shot read after load and after
+ // a save (the roster only changes through those), never a poll. A failed read
+ // leaves the list empty: no warning is better than a fabricated one.
+ const loadIdentities = useCallback(() => {
+ // Same-reference bail-out when nothing changed (the common empty case).
+ const apply = (next) => setReviewerIdentities((prev) => (prev.length === 0 && next.length === 0 ? prev : next));
+ api.getReviewerIdentities({ silent: true })
+ .then((result) => apply(Array.isArray(result?.identities) ? result.identities : []))
+ .catch(() => apply([]));
+ }, []);
+ useEffect(() => {
+ if (!loading && !loadError) loadIdentities();
+ }, [loading, loadError, loadIdentities]);
+
useEffect(() => {
if (pathView && pathView !== 'chain' && pathView !== 'follow-up') {
navigate({ pathname: CHAIN_PATH, search: location.search }, { replace: true });
@@ -198,6 +214,7 @@ export default function CodeReviewersTab({ view } = {}) {
if (ok) {
setReviewerFallbackGroups(groups);
toast.success('Code Review Defaults saved');
+ loadIdentities();
}
};
@@ -267,6 +284,13 @@ export default function CodeReviewersTab({ view } = {}) {
{reviewer}: the last review attempt failed ({fault.code}). {CONFIG_FAULT_REMEDIES[fault.code] || 'Enable or configure the reviewer in Settings → Code Reviewers.'} The next successful review clears this warning.
</Banner>
))}
+ {reviewerIdentities.filter((entry) => entry.status === 'missing').map((entry) => (
+ <Banner key={`identity-${entry.token}`} tone="warning" size="sm" align="left">
+ @{entry.token}: {entry.reason}. {entry.required
+ ? 'It is a required reviewer, so review-loop runs that use it are refused until you correct or remove this entry.'
+ : 'It is optional, so runs skip it and continue without its review.'} Your saved list is unchanged.
+ </Banner>
+ ))}
{activeView === 'chain' ? (
<div role="tabpanel" id="code-review-task-chain" aria-labelledby="tab-chain">
<ReviewerGroupsEditor
diff --git a/client/src/components/settings/CodeReviewersTab.test.jsx b/client/src/components/settings/CodeReviewersTab.test.jsx
index 78e6f7ee37..18db06b3d8 100644
--- a/client/src/components/settings/CodeReviewersTab.test.jsx
+++ b/client/src/components/settings/CodeReviewersTab.test.jsx
@@ -8,6 +8,7 @@ import toast from '../ui/Toast';
vi.mock('../../services/api', () => ({
getCodeReviewDefaults: vi.fn(),
updateSettings: vi.fn(),
+ getReviewerIdentities: vi.fn(),
}));
const pickerData = vi.hoisted(() => ({ current: { ctxById: {} } }));
@@ -32,6 +33,7 @@ describe('CodeReviewersTab', () => {
beforeEach(() => {
vi.clearAllMocks();
pickerData.current = { ctxById: {} };
+ api.getReviewerIdentities.mockResolvedValue({ identities: [] });
});
afterEach(() => {
@@ -423,4 +425,21 @@ describe('CodeReviewersTab', () => {
expect(await screen.findByRole('region', { name: 'Primary' })).toBeInTheDocument();
expect(screen.getByRole('tab', { name: 'Review chain' })).toHaveAttribute('aria-selected', 'true');
});
+
+ it('names a saved reviewer the forge does not know, without touching the roster', async () => {
+ api.getCodeReviewDefaults.mockResolvedValue({ reviewers: ['codex'], usernames: ['ghost-user', 'flaky-user'] });
+ api.getReviewerIdentities.mockResolvedValue({ identities: [
+ { token: 'ghost-user', kind: 'user', status: 'missing', required: true, reason: 'GitHub user "ghost-user" does not exist' },
+ { token: 'flaky-user', kind: 'user', status: 'unavailable', required: true, reason: 'gh command timed out' },
+ ] });
+ api.updateSettings.mockResolvedValue({});
+ renderTab(<CodeReviewersTab />);
+ expect(await screen.findByText(/@ghost-user: GitHub user "ghost-user" does not exist/)).toBeInTheDocument();
+ expect(screen.getByText(/required reviewer/)).toBeInTheDocument();
+ // An inconclusive lookup is not a fault to show.
+ expect(screen.queryByText(/flaky-user:/)).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Save defaults' }));
+ await waitFor(() => expect(api.updateSettings).toHaveBeenCalledTimes(1));
+ expect(api.updateSettings.mock.calls[0][0].codeReview.usernames).toEqual(['ghost-user', 'flaky-user']);
+ });
});
diff --git a/client/src/services/apiCodeReview.js b/client/src/services/apiCodeReview.js
index f72953780a..9bca9fe4e3 100644
--- a/client/src/services/apiCodeReview.js
+++ b/client/src/services/apiCodeReview.js
@@ -5,3 +5,8 @@ import { request } from './apiCore.js';
// Surfaced on the Models → Code Reviewers page; persisted under
// `settings.codeReview` via PUT /api/settings.
export const getCodeReviewDefaults = (options) => request('/code-review/defaults', options);
+
+// Per-entry existence check of the saved `@login` / `@org/team` reviewers on the
+// target forge. Kept off getCodeReviewDefaults so the settings load never waits
+// on forge lookups.
+export const getReviewerIdentities = (options) => request('/code-review/reviewer-identities', options);
diff --git a/server/routes/codeReview.js b/server/routes/codeReview.js
index d73eb870d1..f66079b31a 100644
--- a/server/routes/codeReview.js
+++ b/server/routes/codeReview.js
@@ -4,6 +4,7 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js'
import { validateRequest, cliReviewerOutcomeSchema, reportReviewerFailureSchema, isToolFreeReviewer, isProviderReviewer, isReviewerConfigFault, reviewerModelsFromDefaults, normalizeReviewerEffort, reviewerEffortLevels, reviewerEffortsFromDefaults } from '../lib/validation.js'
import { reviewerAccessFailureCode } from '../lib/reviewerHealth.js'
import { getSettings } from '../services/settings.js'
+import { verifyReviewerIdentities } from '../services/reviewerIdentity.js'
import { runLocalCodeReview, getCodeReviewDefaults, getReviewerCliInstalled, getProviderReviewCapability, withoutResolvedUnsupportedFaults, reportReviewerFailure, reportReviewerSuccess } from '../services/codeReview.js'
const router = Router()
@@ -65,6 +66,30 @@ router.get('/defaults', asyncHandler(async (_req, res) => {
res.json({ ...defaults, reviewerConfigFaults, installed, providerReviewUnsupported: unsupported })
}))
+// GET /api/code-review/reviewer-identities — does each saved `@login` /
+// `@org/team` reviewer exist on the target forge? Separate from /defaults so the
+// settings load never waits on forge lookups. Entries come back as the operator
+// saved them (nothing is dropped or rewritten) with a status of verified,
+// missing (the forge answered 404), unavailable (lookup failed — not a 404), or
+// skipped (forge without a lookup). `required` mirrors dispatch: a username is
+// blocking unless its `@token` is in the optional set.
+const reviewerIdentityQuerySchema = z.object({
+ forge: z.enum(['github', 'gitlab']).default('github'),
+ host: z.string().regex(/^[A-Za-z0-9.-]{1,253}$/).optional(),
+}).strict()
+
+router.get('/reviewer-identities', asyncHandler(async (req, res) => {
+ const { forge, host } = validateRequest(reviewerIdentityQuerySchema, req.query)
+ const defaults = await getCodeReviewDefaults()
+ // `defaults` is already normalized (see pickCodeReviewDefaults).
+ const usernames = defaults.usernames || []
+ const optionalLogins = (defaults.optionalReviewers || []).filter(r => r.startsWith('@')).map(r => r.slice(1))
+ const optionalSet = new Set(optionalLogins.map(r => r.toLowerCase()))
+ const identities = (await verifyReviewerIdentities([...usernames, ...optionalLogins], { forge, host }))
+ .map(entry => ({ ...entry, required: !optionalSet.has(entry.token.toLowerCase()) }))
+ res.json({ forge, identities })
+}))
+
// POST /api/code-review/local — run a single review pass against the
// configured local-LLM backend (LM Studio, Ollama, or MTPLX) and return the findings
// text the agent will act on. Synchronous: keeps the agent's `curl` step
diff --git a/server/routes/codeReview.test.js b/server/routes/codeReview.test.js
index ce35596409..59bcc3a90e 100644
--- a/server/routes/codeReview.test.js
+++ b/server/routes/codeReview.test.js
@@ -17,6 +17,9 @@ vi.mock('../services/codeReview.js', () => ({
reportReviewerSuccess: vi.fn(),
}))
+const execGhMock = vi.hoisted(() => vi.fn())
+vi.mock('../services/github.js', () => ({ execGh: (...args) => execGhMock(...args) }))
+
vi.mock('../services/settings.js', () => ({
getSettings: vi.fn(),
}))
@@ -24,6 +27,7 @@ vi.mock('../services/settings.js', () => ({
const codeReviewSvc = await import('../services/codeReview.js')
const settingsSvc = await import('../services/settings.js')
const { default: routes } = await import('./codeReview.js')
+const { __resetReviewerIdentityCache } = await import('../services/reviewerIdentity.js')
const makeApp = () => {
const app = express()
@@ -35,6 +39,7 @@ const makeApp = () => {
beforeEach(() => {
vi.clearAllMocks()
+ __resetReviewerIdentityCache()
// Default settings stub — tests override as needed
settingsSvc.getSettings.mockResolvedValue({})
codeReviewSvc.getCodeReviewDefaults.mockResolvedValue({
@@ -334,3 +339,54 @@ describe('POST /api/code-review/report-failure', () => {
})
})
+
+describe('GET /api/code-review/reviewer-identities (#13115)', () => {
+ const notFound = () => Object.assign(new Error('gh: Not Found (HTTP 404)'), { ghNoAccess: true, ghStderr: 'gh: Not Found (HTTP 404)' })
+ const configure = (defaults) => codeReviewSvc.getCodeReviewDefaults.mockResolvedValue({ reviewers: ['copilot'], ...defaults })
+
+ it('separates verified, missing, unavailable and team results without altering the roster', async () => {
+ configure({ usernames: ['real-user', 'ghost-user', 'flaky-user', 'acme/core-team'], optionalReviewers: ['@ghost-user'] })
+ execGhMock.mockImplementation(async (args) => {
+ const path = args.at(-1)
+ if (path === 'users/ghost-user') throw notFound()
+ if (path === 'users/flaky-user') throw new Error('gh command timed out after 8000ms')
+ return '{}'
+ })
+ const res = await request(makeApp()).get('/api/code-review/reviewer-identities')
+ expect(res.status).toBe(200)
+ const byToken = Object.fromEntries(res.body.identities.map(e => [e.token, e]))
+ expect(byToken['real-user']).toMatchObject({ status: 'verified', required: true })
+ expect(byToken['ghost-user']).toMatchObject({ status: 'missing', required: false })
+ // A transport failure is never reported as a fabricated 404.
+ expect(byToken['flaky-user']).toMatchObject({ status: 'unavailable' })
+ expect(byToken['acme/core-team']).toMatchObject({ status: 'verified', kind: 'team' })
+ })
+
+ it('does not call a team missing just because the caller cannot see it', async () => {
+ configure({ usernames: ['acme/hidden-team'] })
+ execGhMock.mockImplementation(async (args) => {
+ if (args.at(-1).startsWith('orgs/')) throw notFound()
+ return '{}'
+ })
+ const res = await request(makeApp()).get('/api/code-review/reviewer-identities')
+ expect(res.body.identities[0]).toMatchObject({ token: 'acme/hidden-team', status: 'unavailable' })
+ })
+
+ it('reports a team of a nonexistent organization as missing', async () => {
+ configure({ usernames: ['nowhere/team'] })
+ execGhMock.mockRejectedValue(notFound())
+ const res = await request(makeApp()).get('/api/code-review/reviewer-identities')
+ expect(res.body.identities[0]).toMatchObject({ status: 'missing' })
+ })
+
+ it('skips lookups for a GitLab target and caches GitHub answers', async () => {
+ configure({ usernames: ['someone'] })
+ const gitlab = await request(makeApp()).get('/api/code-review/reviewer-identities?forge=gitlab')
+ expect(gitlab.body.identities[0].status).toBe('skipped')
+ expect(execGhMock).not.toHaveBeenCalled()
+ execGhMock.mockResolvedValue('{}')
+ await request(makeApp()).get('/api/code-review/reviewer-identities')
+ await request(makeApp()).get('/api/code-review/reviewer-identities')
+ expect(execGhMock).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index 9fb6fd43bd..1bdab22dd6 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -29,6 +29,7 @@ import { execGit } from '../lib/execGit.js';
import { isRetryHoldOwner, clearedRetryHoldMetadata } from '../lib/taskRetryHold.js';
import { resolveTaskTargetBranch, resolveTaskRemoteBranch, shouldStripTaskTargetBranch } from '../lib/taskTargetBranch.js';
import { RECOVERY_TASK_PREFIX } from './recoveryTasks.js';
+import { ServerError } from '../lib/errorHandler.js';
import { detectForgeCli } from '../lib/gitForge.js';
import { normalizeForkHead } from '../lib/forkHead.js';
import { PR_COMPLETIONS, resolvePrCompletion, PR_COMPLETION_VALUES, PR_CREATION, PR_MISSING_CATEGORY, leavesPrForHuman, prClaimWasVerified } from '../lib/prDisposition.js';
@@ -1154,10 +1155,39 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p
// GitHub reviewer usernames are forge-agnostic requested reviewers, so they are
// NOT stripped on a non-GitHub forge — a username reviewer alone can drive the
// loop even when copilot was dropped.
- const effectiveUsernames = selfReview ? [] : normalizeReviewUsernames(usernames);
+ let effectiveUsernames = selfReview ? [] : normalizeReviewUsernames(usernames);
// Non-blocking (`~opt`) marker set — forge-agnostic, threaded verbatim so the
// follow-up's `--review-with` marks the same reviewers optional.
- const effectiveOptionalReviewers = selfReview ? [] : (normalizeOptionalReviewers(optionalReviewers) || []);
+ let effectiveOptionalReviewers = selfReview ? [] : (normalizeOptionalReviewers(optionalReviewers) || []);
+ // Target-forge identity preflight (#13115). A handle the forge verifiably does
+ // not have would fail every PR-side request. A REQUIRED one fails closed (the
+ // run must not merge without the review the operator demanded); an OPTIONAL one
+ // is left out of this run's emitted roster and recorded, never reported clean.
+ // Lookups that merely fail (auth/transport) are inconclusive and change nothing.
+ // The saved roster is never rewritten.
+ let reviewerIdentityFaults = [];
+ if (effectiveUsernames.length || effectiveOptionalReviewers.length) {
+ const { preflightReviewerIdentities } = await import('./reviewerIdentity.js');
+ const preflight = await preflightReviewerIdentities({
+ usernames: effectiveUsernames,
+ optionalReviewers: effectiveOptionalReviewers,
+ forge: isNonGithubForge ? 'gitlab' : 'github',
+ host: parsedPr?.host,
+ });
+ if (preflight.requiredMissing.length) {
+ const detail = preflight.requiredMissing.map((e) => `@${e.token}: ${e.reason}`).join('; ');
+ throw new ServerError(`Required reviewer not found on the target forge — ${detail}. Fix it in Settings → Code Reviewers.`, {
+ status: 409, code: 'REVIEWER_IDENTITY_NOT_FOUND', context: { reviewers: preflight.requiredMissing.map((e) => e.token) },
+ });
+ }
+ if (preflight.optionalMissing.length) {
+ const dropped = new Set(preflight.optionalMissing.map((e) => e.token.toLowerCase()));
+ reviewerIdentityFaults = preflight.optionalMissing.map(({ token, reason }) => ({ token, reason }));
+ effectiveUsernames = effectiveUsernames.filter((u) => !dropped.has(u.toLowerCase()));
+ effectiveOptionalReviewers = effectiveOptionalReviewers.filter((r) => !dropped.has(r.replace(/^@/, '').toLowerCase()));
+ console.log(`🚫 Optional reviewer(s) not found on the target forge, skipped for this run: ${reviewerIdentityFaults.map((f) => `@${f.token}`).join(', ')}`);
+ }
+ }
// Per-reviewer iteration caps (`~max=<n>`) — forge-agnostic, threaded verbatim
// so the follow-up's `--review-with` carries the same budgets. Entries for
// reviewers that were stripped are inert (the emitter only marks tokens it
@@ -1294,6 +1324,7 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p
// and gates the merge on (appended to `--review-with` as `@user`).
reviewLoopReviewerUsernames: effectiveUsernames,
reviewLoopOptionalReviewers: effectiveOptionalReviewers,
+ ...(reviewerIdentityFaults.length ? { reviewLoopReviewerIdentityFaults: reviewerIdentityFaults } : {}),
// Per-reviewer `~max=<n>` caps, keyed by emitted token. Empty object = no
// caps (leaves slashdo's per-loop built-in default in place); an absent key
// is NOT `0`, which slashdo reads as "loop until clean".
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 4b397115e2..a93556766b 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -217,7 +217,10 @@ vi.mock('./prWatcher.js', () => ({
// before it died, and cleanup hands that orphan to the same follow-up machinery.
const getPullRequestStateMock = vi.fn();
const findPullRequestForBranchMock = vi.fn().mockResolvedValue({ status: 'unavailable' });
+// Reviewer-identity preflight lookups: resolves = the forge knows the login.
+const execGhMock = vi.fn().mockResolvedValue('{}');
vi.mock('./github.js', () => ({
+ execGh: (...args) => execGhMock(...args),
findPullRequestForBranch: (...args) => findPullRequestForBranchMock(...args),
getPullRequestState: (...args) => getPullRequestStateMock(...args)
}));
@@ -1259,6 +1262,51 @@ describe('cleanupAgentWorktree - PR-creation path', () => {
expect(followUp.metadata.reviewLoopReviewerUsernames).toEqual(['CodeReviewbot']);
});
+ describe('reviewer identity preflight (#13115)', () => {
+ const missing = (login) => (args) => (args.includes(`users/${login}`)
+ ? Promise.reject(Object.assign(new Error('gh: Not Found (HTTP 404)'), { ghNoAccess: true, ghStderr: 'gh: Not Found (HTTP 404)' }))
+ : Promise.resolve('{}'));
+ const run = (extra) => cleanupAgentWorktree('agent-1', true, {
+ prCreation: 'always', requestCopilotReview: true, reviewers: ['copilot'], description: 'Build',
+ originalTask: { id: 'task-orig', priority: 'MEDIUM', metadata: { app: 'sparsetree' }, description: 'Build' },
+ ...extra
+ });
+ beforeEach(async () => {
+ const { __resetReviewerIdentityCache } = await import('./reviewerIdentity.js');
+ __resetReviewerIdentityCache();
+ git.push.mockResolvedValue(undefined);
+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/61' });
+ git.requestCopilotReview.mockResolvedValue({ success: true });
+ addTask.mockResolvedValue({ id: 'sys-rl-id' });
+ });
+
+ it('refuses a follow-up whose REQUIRED reviewer verifiably does not exist', async () => {
+ execGhMock.mockImplementation((args) => missing('ghost-reviewer')(args));
+ const result = await run({ usernames: ['ghost-reviewer'] });
+ expect(addTask).not.toHaveBeenCalled();
+ expect(result.join(' ')).toMatch(/Required reviewer not found.*ghost-reviewer/);
+ });
+
+ it('skips a missing OPTIONAL reviewer for the run, records it, and keeps the others', async () => {
+ execGhMock.mockImplementation((args) => missing('ghost-reviewer')(args));
+ await run({ usernames: ['ghost-reviewer', 'real-reviewer'], optionalReviewers: ['@ghost-reviewer'] });
+ const [followUp] = addTask.mock.calls[0];
+ expect(followUp.metadata.reviewLoopReviewerUsernames).toEqual(['real-reviewer']);
+ expect(followUp.metadata.reviewLoopOptionalReviewers).toEqual([]);
+ expect(followUp.metadata.reviewLoopReviewerIdentityFaults).toEqual([
+ expect.objectContaining({ token: 'ghost-reviewer' })
+ ]);
+ });
+
+ it('treats a failed lookup as inconclusive: the roster goes out untouched', async () => {
+ execGhMock.mockRejectedValue(Object.assign(new Error('gh: HTTP 401 Bad credentials'), { ghStderr: 'gh: HTTP 401 Bad credentials' }));
+ await run({ usernames: ['ghost-reviewer'] });
+ const [followUp] = addTask.mock.calls[0];
+ expect(followUp.metadata.reviewLoopReviewerUsernames).toEqual(['ghost-reviewer']);
+ expect(followUp.metadata.reviewLoopReviewerIdentityFaults).toBeUndefined();
+ });
+ });
+
it('spawns a username-only follow-up on a non-GitHub forge (copilot stripped, username drives the loop)', async () => {
git.push.mockResolvedValue(undefined);
git.createPR.mockResolvedValue({ success: true, url: 'https://gitlab.com/group/proj/-/merge_requests/13' });
diff --git a/server/services/reviewerIdentity.js b/server/services/reviewerIdentity.js
new file mode 100644
index 0000000000..077940a1b4
--- /dev/null
+++ b/server/services/reviewerIdentity.js
@@ -0,0 +1,125 @@
+/**
+ * Target-forge identity check for requested-reviewer tokens (`@login`,
+ * `@org/team-slug`).
+ *
+ * `normalizeReviewUsernames` only proves a token is syntactically safe; a
+ * handle that does not exist on the forge passes it and then fails on every
+ * unattended PR-side request. This answers "does the identity exist on the
+ * TARGET forge?" with three outcomes that must never collapse into each other:
+ * verified — the forge confirmed it
+ * missing — the forge answered 404 for it (a verified configuration fault)
+ * unavailable — transport/auth/rate-limit failure; says nothing about the
+ * identity, so it is never reported as missing
+ * `skipped` covers a forge with no lookup here (GitLab): existence rules for
+ * GitHub are not applied to other forges.
+ *
+ * Results are cached briefly so a polling dispatcher does not turn one saved
+ * roster into a lookup per tick. The stored roster is never touched.
+ */
+import { execGh } from './github.js';
+import { isForgeNoAccessMessage } from '../lib/forgeAccessErrors.js';
+
+export const IDENTITY_STATUS = Object.freeze({
+ VERIFIED: 'verified', MISSING: 'missing', UNAVAILABLE: 'unavailable', SKIPPED: 'skipped',
+});
+
+const LOOKUP_TIMEOUT_MS = 8000;
+const LOOKUP_CONCURRENCY = 4;
+// A confirmed identity rarely vanishes; a missing one is re-checked soon so a
+// freshly created account or a fixed roster stops warning quickly; an
+// unavailable answer is retried almost immediately.
+const TTL_MS = { verified: 10 * 60_000, missing: 2 * 60_000, unavailable: 15_000 };
+
+const cache = new Map();
+export function __resetReviewerIdentityCache() { cache.clear(); }
+
+const isNotFound = (err) => err?.ghNoAccess === true || isForgeNoAccessMessage(err?.ghStderr || err?.message);
+
+async function lookup(ghApi, host, path) {
+ const args = ['api', ...(host && host !== 'github.com' ? ['--hostname', host] : []), path];
+ try {
+ await ghApi(args, LOOKUP_TIMEOUT_MS);
+ return 'found';
+ } catch (err) {
+ return isNotFound(err) ? 'not-found' : { error: err?.message || 'lookup failed' };
+ }
+}
+
+async function resolveToken(ghApi, host, token) {
+ const bare = token.replace(/^@+/, '');
+ const [owner, team] = bare.split('/');
+ if (!team) {
+ const r = await lookup(ghApi, host, `users/${encodeURIComponent(owner)}`);
+ if (r === 'found') return { status: IDENTITY_STATUS.VERIFIED };
+ if (r === 'not-found') return { status: IDENTITY_STATUS.MISSING, reason: `GitHub user "${owner}" does not exist` };
+ return { status: IDENTITY_STATUS.UNAVAILABLE, reason: r.error };
+ }
+ const t = await lookup(ghApi, host, `orgs/${encodeURIComponent(owner)}/teams/${encodeURIComponent(team)}`);
+ if (t === 'found') return { status: IDENTITY_STATUS.VERIFIED };
+ if (t !== 'not-found') return { status: IDENTITY_STATUS.UNAVAILABLE, reason: t.error };
+ // GitHub answers 404 for a team the caller cannot see, so a team 404 only
+ // proves absence when the owning organization itself does not exist.
+ const o = await lookup(ghApi, host, `users/${encodeURIComponent(owner)}`);
+ if (o === 'not-found') return { status: IDENTITY_STATUS.MISSING, reason: `GitHub organization "${owner}" does not exist` };
+ return {
+ status: IDENTITY_STATUS.UNAVAILABLE,
+ reason: o === 'found' ? `Team "${bare}" is not visible to the signed-in gh account` : o.error,
+ };
+}
+
+/**
+ * @param {string[]} tokens reviewer tokens with or without a leading `@`
+ * @param {{ forge?: 'github'|'gitlab', host?: string, ghApi?: Function, now?: number }} [opts]
+ * @returns {Promise<Array<{ token: string, kind: 'user'|'team', status: string, reason?: string }>>}
+ * in input order, one entry per distinct (case-insensitive) token
+ */
+export async function verifyReviewerIdentities(tokens, { forge = 'github', host = 'github.com', ghApi = execGh, now = Date.now() } = {}) {
+ const seen = new Set();
+ const distinct = [];
+ for (const raw of Array.isArray(tokens) ? tokens : []) {
+ const token = String(raw || '').trim().replace(/^@+/, '');
+ if (!token || seen.has(token.toLowerCase())) continue;
+ seen.add(token.toLowerCase());
+ distinct.push(token);
+ }
+ const results = new Array(distinct.length);
+ let next = 0;
+ const worker = async () => {
+ while (next < distinct.length) {
+ const i = next++;
+ const token = distinct[i];
+ const kind = token.includes('/') ? 'team' : 'user';
+ if (forge !== 'github') {
+ results[i] = { token, kind, status: IDENTITY_STATUS.SKIPPED, reason: 'Identity lookup is only available for GitHub targets' };
+ continue;
+ }
+ const key = `${host}\0${token.toLowerCase()}`;
+ const hit = cache.get(key);
+ if (hit && hit.expiresAt > now) { results[i] = { token, kind, ...hit.value }; continue; }
+ const value = await resolveToken(ghApi, host, token);
+ cache.set(key, { value, expiresAt: now + TTL_MS[value.status] });
+ results[i] = { token, kind, ...value };
+ }
+ };
+ await Promise.all(Array.from({ length: Math.min(LOOKUP_CONCURRENCY, distinct.length) }, worker));
+ return results;
+}
+
+/**
+ * Preflight a resolved roster for dispatch. `usernames` are the blocking
+ * reviewers except those whose `@token` is in `optionalReviewers`.
+ * @returns {Promise<{ identities: object[], requiredMissing: object[], optionalMissing: object[] }>}
+ */
+export async function preflightReviewerIdentities({ usernames = [], optionalReviewers = [], forge, host, ghApi } = {}) {
+ const optional = new Set(optionalReviewers.filter((r) => typeof r === 'string' && r.startsWith('@')).map((r) => r.slice(1).toLowerCase()));
+ const tokens = [...usernames, ...optional];
+ if (!tokens.length) return { identities: [], requiredMissing: [], optionalMissing: [] };
+ const identities = (await verifyReviewerIdentities(tokens, { forge, host, ghApi }))
+ .map((entry) => ({ ...entry, required: !optional.has(entry.token.toLowerCase()) }));
+ const missing = identities.filter((entry) => entry.status === IDENTITY_STATUS.MISSING);
+ return {
+ identities,
+ requiredMissing: missing.filter((entry) => entry.required),
+ optionalMissing: missing.filter((entry) => !entry.required),
+ };
+}