Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { EventEmitter } from 'events';
vi.mock('./cosEvents.js', () => ({
cosEvents: { emit: vi.fn() },
emitLog: vi.fn()
}));
vi.mock('../lib/childProcess.js', async (importOriginal) => {
const actual = await importOriginal();
return { ...actual, spawn: vi.fn() };
});
vi.mock('./forgeAuth.js', () => ({
resolveForgeTokenEnv: vi.fn(async () => ({}))
}));
import { spawn } from '../lib/childProcess.js';
import { resolveForgeTokenEnv } from './forgeAuth.js';
import {
isActionableIssue,
titleMarksEpic,
issueNumberFromRef,
detectActionableWork,
detectGithubIssues,
listConfiguredForgeIssues,
detectGitlabIssues,
registerWorkDetector,
getWorkDetector,
hasWorkDetector,
NON_ACTIONABLE_ISSUE_LABELS,
EPIC_DECOMPOSED_LABEL,
CLI_TIMEOUT_MS
} from './perpetualWork.js';
// A fake child process that emits canned stdout/stderr then closes — enough for
// the best-effort runCli() in perpetualWork.js (stdout/close/error + kill).
function fakeChild(stdout, code = 0, stderr = '') {
const child = new EventEmitter();
child.stdout = new EventEmitter();
child.stderr = new EventEmitter();
child.kill = () => {};
setImmediate(() => {
if (stdout) child.stdout.emit('data', Buffer.from(stdout));
if (stderr) child.stderr.emit('data', Buffer.from(stderr));
child.emit('close', code);
});
return child;
}
// A fake child process that emits stderr and then a spawn `error` event
// (never closes) — exercises runCli's error path rather than its close path.
function fakeErrorChild(stderr) {
const child = new EventEmitter();
child.stdout = new EventEmitter();
child.stderr = new EventEmitter();
child.kill = () => {};
setImmediate(() => {
if (stderr) child.stderr.emit('data', Buffer.from(stderr));
child.emit('error', new Error('spawn failed'));
});
return child;
}
// A fake child process that emits stderr and then HANGS — never closes and
// never errors — so only runCli's CLI_TIMEOUT_MS timer can settle it.
function fakeHangingChild(stderr) {
const child = new EventEmitter();
child.stdout = new EventEmitter();
child.stderr = new EventEmitter();
child.kill = () => {};
setImmediate(() => {
if (stderr) child.stderr.emit('data', Buffer.from(stderr));
});
return child;
}
const prPages = rows => JSON.stringify([{ data: { repository: { pullRequests: {
nodes: rows.map((pr, index) => ({ ...pr, number: pr.number || index + 1, commits: {
nodes: (pr.commits || []).map(commit => ({ commit: { message: `${commit.messageHeadline || ''}\n${commit.messageBody || ''}` } })),
pageInfo: { hasNextPage: (pr.commits || []).length >= 100 },
} })), pageInfo: { hasNextPage: false, endCursor: null },
} } } }]);
function fakePrChild(rows) {
return fakeChild(prPages(typeof rows === 'string' ? JSON.parse(rows) : rows));
}
// Route spawn calls to canned output by command + first arg.
function routeSpawn(routes) {
spawn.mockImplementation((cmd, args = []) => {
const key = cmd === 'gh' && args[0] === 'api' && args.includes('graphql') ? 'gh pr' : `${cmd} ${args[0] || ''}`;
const r = routes[key] ?? (key === 'gh api' ? { stdout: 'alice\n' } : key === 'glab mr' ? { stdout: '[]' } : undefined);
let stdout = r?.stdout ?? '';
if (key === 'gh pr' && !stdout.startsWith('[') && !stdout.startsWith('{')) {
stdout = JSON.stringify(stdout.split('\n').filter(Boolean).map(headRefName => ({ headRefName, body: '', commits: [] })));
}
if (key === 'gh pr' && stdout.startsWith('[')) stdout = prPages(JSON.parse(stdout));
return fakeChild(stdout, r?.code ?? 0, r?.stderr ?? '');
});
}
describe('perpetualWork', () => {
it.each([
['claim-issue', 'gh'], ['claim-issue-gitlab', 'glab'], ['claim-work', 'gh']
])('excludes structural and user labels before rendering %s agent inputs', async (taskType, cli) => {
const { resolveTaskDataInputs } = await import('./taskDataInputs.js');
const labels = ['in-progress', 'blocked', 'needs-input', 'future', 'wontfix', 'question', 'discussion', 'Human-Only'];
const issues = labels.map((label, index) => ({
number: index + 1, iid: index + 1, title: `Excluded ${index}`,
labels: [index % 2 ? { name: label.toUpperCase() } : label]
}));
issues.push({ number: 20, iid: 20, title: 'Eligible work', labels: ['bug'] });
routeSpawn({ [`${cli} issue`]: { stdout: JSON.stringify(issues) } });
const options = {
app: { repoPath: '/repo' }, taskType,
taskMetadata: { issueAuthorFilter: 'any', issueExcludeLabels: [' human-only '] },
dependencies: {
resolveTracker: async () => ({ forge: cli, host: cli === 'gh' ? 'github.com' : 'gitlab.com' }),
resolveTokenEnv: async () => ({})
}
};
const [section] = await resolveTaskDataInputs(['open-issues'], options);
expect(section.content).toContain('#20 Eligible work');
expect(section.content).not.toContain('Excluded');
routeSpawn({ [`${cli} issue`]: { stdout: JSON.stringify(issues.slice(0, -1)) } });
const [empty] = await resolveTaskDataInputs(['open-issues'], options);
expect(empty.content).toContain('No open issues match');
expect(empty.content).not.toContain('Excluded');
});
describe('isActionableIssue', () => {
const base = { number: 7, title: 'Fix the thing', assignees: [], labels: [] };
it('accepts a plain open unassigned issue', () => {
expect(isActionableIssue(base)).toBe(true);
});
it('rejects an assigned issue', () => {
expect(isActionableIssue({ ...base, assignees: [{ login: 'someone' }] })).toBe(false);
});
it('rejects an in-flight issue number', () => {
expect(isActionableIssue(base, new Set([7]))).toBe(false);
});
it.each([...NON_ACTIONABLE_ISSUE_LABELS])('rejects a %s-labelled issue', (label) => {
expect(isActionableIssue({ ...base, labels: [{ name: label }] })).toBe(false);
});
it('treats the needs-input park label as non-actionable (drain convergence)', () => {
expect(isActionableIssue({ ...base, labels: [{ name: 'needs-input' }] })).toBe(false);
});
it('rejects an epic ONLY once it is decomposed — by label, by "(epic)" title suffix, or by "[epic]" title prefix', () => {
const decomposed = { name: EPIC_DECOMPOSED_LABEL };
expect(isActionableIssue({ ...base, labels: [{ name: 'epic' }, decomposed] })).toBe(false);
expect(isActionableIssue({ ...base, title: 'Big rollup (epic)', labels: [decomposed] })).toBe(false);
// An epic titled "[Epic] …" with NO `epic` label is still an epic: the
// title convention alone has to reach the decomposed skip, or the drain
// re-splits it every tick.
expect(isActionableIssue({
...base,
labels: [{ name: 'enhancement' }, decomposed],
title: '[Epic] Redesign the billing dashboard'
})).toBe(false);
});
it('accepts an UNdecomposed epic — decomposing it is the claim agent\'s Phase 1b work', () => {
expect(isActionableIssue({ ...base, labels: [{ name: 'epic' }] })).toBe(true);
expect(isActionableIssue({ ...base, title: 'Big rollup (epic)' })).toBe(true);
expect(isActionableIssue({
...base,
labels: [{ name: 'enhancement' }],
title: '[Epic] Redesign the billing dashboard'
})).toBe(true);
});
it('still rejects an undecomposed epic that carries a blocking label', () => {
expect(isActionableIssue({ ...base, labels: [{ name: 'epic' }, { name: 'blocked' }] })).toBe(false);
expect(isActionableIssue(
{ ...base, labels: [{ name: 'epic' }] },
new Set(),
new Set(['epic'])
)).toBe(false);
});
it('does not let the decomposed label block an ordinary (non-epic) issue', () => {
expect(isActionableIssue({ ...base, labels: [{ name: EPIC_DECOMPOSED_LABEL }] })).toBe(true);
});
it('accepts a plan-labelled issue (plan is the claimable queue, not a skip)', () => {
expect(isActionableIssue({ ...base, labels: [{ name: 'plan' }] })).toBe(true);
});
it('handles string labels as well as objects', () => {
expect(isActionableIssue({ ...base, labels: ['blocked'] })).toBe(false);
});
it('rejects malformed issues', () => {
expect(isActionableIssue(null)).toBe(false);
expect(isActionableIssue({ title: 'no number' })).toBe(false);
});
it('rejects an issue carrying a configured excludeLabels entry', () => {
const excludeLabels = new Set(['good first issue']);
expect(isActionableIssue({ ...base, labels: [{ name: 'good first issue' }] }, new Set(), excludeLabels)).toBe(false);
});
it('accepts an excluded-label issue when no excludeLabels set is passed', () => {
expect(isActionableIssue({ ...base, labels: [{ name: 'good first issue' }] })).toBe(true);
});
it('still rejects the fixed NON_ACTIONABLE_ISSUE_LABELS set when an excludeLabels set is active', () => {
const excludeLabels = new Set(['good first issue']);
expect(isActionableIssue({ ...base, labels: [{ name: 'blocked' }] }, new Set(), excludeLabels)).toBe(false);
});
});
describe('titleMarksEpic', () => {
it.each([
'Big rollup (epic)',
'Big rollup (EPIC)',
'[Epic] Redesign the billing dashboard',
'[EPIC] all caps prefix',
'[epic] lower prefix',
'[Epic: theme] with a colon',
'[ epic ] padded brackets',
'Epic: Redesign the nav', // unbracketed colon tag
'EPIC: all caps colon'
])('recognizes %j as an epic', (title) => {
expect(titleMarksEpic(title)).toBe(true);
});
it.each([
'Fix the login bug',
'[epicenter] telemetry module', // `\b` guard: "epicenter" starts with "epic" but is a different word
'Epicurean recipe importer', // "epic" as a substring, no bracket/paren tag
'Add an epic-scale test (not a tag)',
'Epic rework of the nav', // bare adjective — no bracket/colon terminator, not a tag
'[epic vision that never closes', // unclosed bracket, no colon terminator
'',
null,
undefined
])('does not flag %j as an epic', (title) => {
expect(titleMarksEpic(title)).toBe(false);
});
});
describe('issueNumberFromRef', () => {
it('extracts from a claim/issue-<num> ref', () => {
expect(issueNumberFromRef('claim/issue-123')).toBe(123);
expect(issueNumberFromRef('origin/claim/issue-99')).toBe(99);
});
it('extracts from a cos/<task>/issue-<num>/<agent> ref', () => {
expect(issueNumberFromRef('cos/claim-issue/issue-45/agent-x')).toBe(45);
});
it('extracts from a next/issue-<num> ref (slashdo /do:next, #8161)', () => {
expect(issueNumberFromRef('next/issue-8149')).toBe(8149);
expect(issueNumberFromRef('origin/next/issue-8149')).toBe(8149);
});
it('returns null for non-claim refs', () => {
expect(issueNumberFromRef('feature/foo')).toBe(null);
expect(issueNumberFromRef('main')).toBe(null);
expect(issueNumberFromRef('claim/some-slug')).toBe(null); // slug, not issue-<num>
});
});
describe('registry', () => {
it('claim-issue, claim-issue-gitlab and plan-task are registered by default', () => {
expect(hasWorkDetector('claim-issue')).toBe(true);
expect(hasWorkDetector('claim-issue-gitlab')).toBe(true);
expect(hasWorkDetector('plan-task')).toBe(true);
expect(typeof getWorkDetector('claim-issue')).toBe('function');
});
it('detectActionableWork reports no-detector for an unregistered type (e.g. JIRA)', async () => {
const out = await detectActionableWork('claim-issue-jira', { id: 'a' });
expect(out).toEqual({ actionable: false, count: 0, reason: 'no-detector', hasDetector: false });
});
it('detectActionableWork normalizes a registered detector result', async () => {
registerWorkDetector('__test-type__', async () => ({ actionable: true, count: 3, reason: 'actionable-issues' }));
const out = await detectActionableWork('__test-type__', { id: 'a' });
expect(out).toMatchObject({ actionable: true, count: 3, reason: 'actionable-issues', hasDetector: true });
});
it('detectActionableWork catches a detector throw as a transient failure', async () => {
registerWorkDetector('__throwing__', async () => { throw new Error('boom'); });
const out = await detectActionableWork('__throwing__', { id: 'a' });
expect(out.actionable).toBe(false);
expect(out.transient).toBe(true);
expect(out.reason).toContain('boom');
});
});
describe('detectGithubIssues (spawn-mocked)', () => {
beforeEach(() => {
spawn.mockReset();
resolveForgeTokenEnv.mockReset();
resolveForgeTokenEnv.mockResolvedValue({});
});
const app = { id: 'a', repoPath: '/repo' };
it('counts actionable issues, excluding labelled/assigned/in-flight', async () => {
routeSpawn({
'gh issue': { stdout: JSON.stringify([
{ number: 1, title: 'plain', assignees: [], labels: [] },
{ number: 2, title: 'needs a decision', assignees: [], labels: [{ name: 'needs-input' }] },
{ number: 3, title: 'taken', assignees: [{ login: 'x' }], labels: [] },
{ number: 4, title: 'in flight', assignees: [], labels: [] },
{ number: 5, title: 'also plain', assignees: [], labels: [{ name: 'plan' }] }
]) },
'git branch': { stdout: 'main\norigin/claim/issue-4\n' },
'gh pr': { stdout: '' }
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'any' });
expect(out.actionable).toBe(true);
expect(out.count).toBe(2); // #1 and #5 (plan is claimable); #2 #3 #4 excluded
expect(out.sample).toEqual([1, 5]);
// Breakdown surfaced for the UI: 5 open, 1 in-flight (#4), 2 filtered
// (#2 needs-input, #3 assigned), 2 actionable.
expect(out.total).toBe(5);
expect(out.inFlightCount).toBe(1);
expect(out.filteredCount).toBe(2);
// The claimable items themselves, for the /do:next "pick a specific issue"
// picker — the same scan, so the list can't advertise work the run skips.
expect(out.items).toEqual([
{ ref: '1', title: 'plain' },
{ ref: '5', title: 'also plain' }
]);
expect(out.signature).toBe('["1","5"]');
});
it('reports the "[Epic]"-prefixed issue as actionable while it is still undecomposed', async () => {
// The queue holds nothing but needs-input/blocked issues plus one "[Epic]
// …" umbrella with no `epic` label. Parking here is what left epics to rot
// and reported an empty queue: decomposing that epic IS work, so the
// detector must dispatch a claim agent (which runs Phase 1b) for it.
routeSpawn({
'gh issue': { stdout: JSON.stringify([
{ number: 1, title: '[Epic] Redesign the billing dashboard', assignees: [], labels: [{ name: 'enhancement' }] },
{ number: 2, title: 'Add a dark-mode toggle', assignees: [], labels: [{ name: 'needs-input' }] },
{ number: 3, title: 'Document the export API', assignees: [], labels: [{ name: 'blocked' }] }
]) },
'git branch': { stdout: 'main\n' },
'gh pr': { stdout: '' }
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'any' });
expect(out).toMatchObject({ actionable: true, count: 1, reason: 'actionable-issues', sample: [1] });
expect(out.signature).toBe('["1"]');
expect(out.filteredCount).toBe(2);
});
it('canonicalizes candidate order and removes duplicate issue IDs from the signature', async () => {
routeSpawn({
'gh issue': { stdout: JSON.stringify([
{ number: 10, title: 'later', assignees: [], labels: [] },
{ number: 2, title: 'first', assignees: [], labels: [] },
{ number: 10, title: 'duplicate', assignees: [], labels: [] }
]) },
'git branch': { stdout: 'main\n' },
'gh pr': { stdout: '' }
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'any' });
expect(out.sample).toEqual([10, 2, 10]);
expect(out.signature).toBe('["2","10"]');
});
it('converges (0 actionable) once that epic carries the decomposed label', async () => {
// The convergence marker: the claim agent stamps `decomposed` on an epic
// after filing its slices, so the drain stops re-picking the parent and
// works the children instead. Without it the drain would re-split forever.
routeSpawn({
'gh issue': { stdout: JSON.stringify([
{ number: 1, title: '[Epic] Redesign the billing dashboard', assignees: [], labels: [{ name: 'enhancement' }, { name: EPIC_DECOMPOSED_LABEL }] },
{ number: 2, title: 'Add a dark-mode toggle', assignees: [], labels: [{ name: 'needs-input' }] },
{ number: 3, title: 'Document the export API', assignees: [], labels: [{ name: 'needs-input' }] },
{ number: 4, title: 'Record the onboarding walkthrough', assignees: [], labels: [{ name: 'needs-input' }] },
{ number: 5, title: 'Wire up the metrics pipeline', assignees: [], labels: [{ name: 'blocked' }] },
{ number: 6, title: 'Calibrate the ranking weights', assignees: [], labels: [{ name: 'needs-input' }] },
{ number: 7, title: 'Cache the aggregate query', assignees: [], labels: [{ name: 'needs-input' }] }
]) },
'git branch': { stdout: 'main\n' },
'gh pr': { stdout: '' }
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'any' });
expect(out).toMatchObject({ actionable: false, count: 0, reason: 'no-actionable-issues' });
expect(out.total).toBe(7);
expect(out.inFlightCount).toBe(0);
expect(out.filteredCount).toBe(7); // the epic (#1) + 6 needs-input/blocked
// Per-cause attribution: the park breakdown must say WHY each of the 7 was
// filtered, not just how many — "0 of 7 open" alone reads as a broken task.
expect(out.skipCauses).toEqual({ 'needs-input': 5, blocked: 1, 'decomposed-epic': 1 });
});
it('carries an empty skipCauses map when issues remain actionable (attribution is park-only)', async () => {
routeSpawn({
'gh issue': { stdout: JSON.stringify([
{ number: 1, title: 'plain', assignees: [], labels: [] },
{ number: 2, title: 'taken', assignees: [{ login: 'x' }], labels: [] },
{ number: 3, title: 'in flight', assignees: [], labels: [] },
{ number: 4, title: 'reserved', assignees: [], labels: [{ name: 'good first issue' }] }
]) },
'git branch': { stdout: 'main\norigin/claim/issue-3\n' },
'gh pr': { stdout: '' }
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'any', issueExcludeLabels: ['good first issue'] });
expect(out.actionable).toBe(true);
// Attribution is only computed for a park (0 actionable) — an actionable
// detection carries an empty map, not a partial one.
expect(out.skipCauses).toEqual({});
});
it('attributes every skip cause on a park, including in-flight and configured exclude labels', async () => {
routeSpawn({
'gh issue': { stdout: JSON.stringify([
{ number: 2, title: 'taken', assignees: [{ login: 'x' }], labels: [] },
{ number: 3, title: 'in flight', assignees: [], labels: [] },
{ number: 4, title: 'reserved', assignees: [], labels: [{ name: 'good first issue' }] },
{ number: 5, title: 'waiting on you', assignees: [], labels: [{ name: 'needs-input' }] }
]) },
'git branch': { stdout: 'main\norigin/claim/issue-3\n' },
'gh pr': { stdout: '' }
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'any', issueExcludeLabels: ['good first issue'] });
expect(out).toMatchObject({ actionable: false, count: 0, reason: 'no-actionable-issues' });
expect(out.inFlightCount).toBe(1);
expect(out.filteredCount).toBe(3);
expect(out.skipCauses).toEqual({ 'needs-input': 1, assigned: 1, 'in-flight': 1, 'good first issue': 1 });
});
it('counts a cause named after an Object.prototype key (a configured exclude label named "constructor")', async () => {
routeSpawn({
'gh issue': { stdout: JSON.stringify([
{ number: 1, title: 'reserved', assignees: [], labels: [{ name: 'constructor' }] }
]) },
'git branch': { stdout: 'main\n' },
'gh pr': { stdout: '' }
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'any', issueExcludeLabels: ['constructor'] });
expect(out).toMatchObject({ actionable: false, count: 0, reason: 'no-actionable-issues' });
// A plain-object counter would read the inherited `constructor` and
// produce a garbage string the formatter's Number.isFinite filter
// silently drops — the park would explain nothing.
expect(out.skipCauses).toEqual({ constructor: 1 });
});
it('disambiguates a configured exclude label that collides with a non-label structural cause', async () => {
routeSpawn({
'gh issue': { stdout: JSON.stringify([
{ number: 1, title: 'reserved', assignees: [], labels: [{ name: 'in-flight' }] }
]) },
'git branch': { stdout: 'main\n' },
'gh pr': { stdout: '' }
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'any', issueExcludeLabels: ['in-flight'] });
expect(out).toMatchObject({ actionable: false, count: 0, reason: 'no-actionable-issues' });
// A bare `in-flight` cause would be suppressed by both UI consumers
// (the toast and the picker exclude it because counts.inFlight carries
// the structural one) — the collision must stay distinguishable.
expect(out.skipCauses).toEqual({ 'excluded-label:in-flight': 1 });
});
it('preserves same-login assignment while querying the enterprise origin', async () => {
spawn.mockImplementation((cmd, args = []) => {
if (cmd === 'git' && args[0] === 'remote') return fakeChild('[email protected]:acme/widget.git\n');
if (cmd === 'gh' && args[0] === 'api' && args.includes('user')) return fakeChild('alice\n');
if (cmd === 'gh' && args[0] === 'issue') return fakeChild(JSON.stringify([{
number: 3, title: 'retry my claim', assignees: [{ login: 'alice' }], labels: []
}]));
if (cmd === 'git' && args[0] === 'branch') return fakeChild('main\n');
if (cmd === 'gh' && args[0] === 'api' && args.includes('graphql')) return fakePrChild([]);
if (cmd === 'glab' && args[0] === 'mr') return fakeChild('[]');
return fakeChild('');
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'any' });
expect(out).toMatchObject({ actionable: false, count: 0, skipCauses: { assigned: 1 } });
const query = spawn.mock.calls.find(([cmd, args]) => cmd === 'gh' && args.includes('graphql'));
expect(query[1]).toEqual(expect.arrayContaining(['--hostname', 'ghe.example.com']));
});
it('does not need an identity probe to park an assigned-only GitHub queue', async () => {
spawn.mockImplementation((cmd, args = []) => {
if (cmd === 'git' && args[0] === 'remote') return fakeChild('[email protected]:acme/widget.git\n');
if (cmd === 'gh' && args[0] === 'api' && args.includes('user')) return fakeChild('', 1);
if (cmd === 'gh' && args[0] === 'issue') return fakeChild(JSON.stringify([
{ number: 3, title: 'retry my claim', assignees: [{ login: 'alice' }], labels: [] }
]));
if (cmd === 'git' && args[0] === 'branch') return fakeChild('main\n');
if (cmd === 'gh' && args[0] === 'api' && args.includes('graphql')) return fakePrChild([]);
if (cmd === 'glab' && args[0] === 'mr') return fakeChild('[]');
return fakeChild('');
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'any' });
expect(out).toMatchObject({ actionable: false, reason: 'no-actionable-issues', skipCauses: { assigned: 1 } });
});
it('paginates open PRs and excludes PR-backed issues beyond the first 30', async () => {
const prRefs = Array.from({ length: 40 }, (_, i) => `claim/issue-${i + 100}`).join('\n');
routeSpawn({
'gh issue': { stdout: JSON.stringify([
{ number: 139, title: 'deep PR', assignees: [], labels: [] },
{ number: 500, title: 'free', assignees: [], labels: [] }
]) },
'git branch': { stdout: 'main\n' },
'gh pr': { stdout: prRefs }
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'any' });
expect(out.sample).toEqual([500]);
expect(out.inFlightCount).toBe(1);
const prCall = spawn.mock.calls.find(([cmd, args]) => cmd === 'gh' && args.includes('graphql'));
expect(prCall[1]).toEqual(expect.arrayContaining(['--paginate', '--slurp']));
expect(prCall[1].find(arg => arg.startsWith('query='))).not.toContain('authors');
});
it('excludes arbitrary PR branches by closing trailer and head commit references', async () => {
routeSpawn({
'gh issue': { stdout: JSON.stringify([7, 8, 9, 70].map(number => ({ number, title: 'work', labels: [], assignees: [] }))) },
'gh pr': { stdout: JSON.stringify([
{ headRefName: 'feature/interactive', body: 'Closes: #7', commits: [] },
{ headRefName: 'fix/combined', body: 'Refs #70', commits: [{ messageHeadline: 'fix: first [issue-8]', messageBody: 'Also fixes a regression (#9)' }] }
]) }
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'any' });
expect(out).toMatchObject({ sample: [70], inFlightCount: 3, count: 1 });
});
it('paginates a large PR without parking unrelated issue claims', async () => {
const pr = { number: 23, headRefName: 'large', body: '', commits: Array.from({ length: 100 }, () => ({ messageHeadline: 'other work' })) };
routeSpawn({
'gh issue': { stdout: JSON.stringify([7, 8].map(number => ({ number, title: 'work', labels: [], assignees: [] }))) },
'gh pr': { stdout: JSON.stringify([pr]) },
'gh api': { stdout: JSON.stringify([pr.commits.map(() => ({ commit: { message: 'other work' } })), [{ commit: { message: 'fix: work (#7)' } }]]) }
});
expect(await detectGithubIssues(app, { issueAuthorFilter: 'any' })).toMatchObject({ sample: [8], count: 1, inFlightCount: 1 });
expect(spawn.mock.calls.some(([cmd, args]) => cmd === 'gh' && args.includes('--paginate') && args.includes('repos/{owner}/{repo}/pulls/23/commits?per_page=100'))).toBe(true);
});
it.each(['{broken', JSON.stringify([{ headRefName: 'feature', body: '', commits: Array.from({ length: 100 }, () => ({ messageHeadline: 'change' })) }])])(
'keeps incomplete PR evidence transient', async stdout => {
routeSpawn({
'gh issue': { stdout: JSON.stringify([{ number: 7, title: 'work', labels: [], assignees: [] }]) },
'gh pr': { stdout }
});
expect(await detectGithubIssues(app, { issueAuthorFilter: 'any' })).toMatchObject({ actionable: false, transient: true, reason: 'gh-unavailable' });
}
);
it('refuses an incomplete paginated GraphQL response', async () => {
routeSpawn({ 'gh issue': { stdout: JSON.stringify([{ number: 7, title: 'work', labels: [], assignees: [] }]) } });
const routed = spawn.getMockImplementation();
spawn.mockImplementation((cmd, args, options) => cmd === 'gh' && args.includes('graphql')
? fakeChild(JSON.stringify([{ data: { repository: { pullRequests: { nodes: [], pageInfo: { hasNextPage: true } } } } }]))
: routed(cmd, args, options));
expect(await detectGithubIssues(app, { issueAuthorFilter: 'any' })).toMatchObject({ actionable: false, transient: true });
});
it('stays transient instead of under-counting in-flight work when gh pr list fails', async () => {
routeSpawn({
'gh issue': { stdout: JSON.stringify([{ number: 7, title: 'has a PR', assignees: [], labels: [] }]) },
'git branch': { stdout: 'main\n' },
'gh pr': { stdout: '', code: 1, stderr: 'API rate limit exceeded' }
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'any' });
expect(out).toMatchObject({ actionable: false, reason: 'gh-unavailable', transient: true });
expect(out.inFlightCount).toBeUndefined();
});
it('reports the open/in-flight breakdown when nothing is claimable (the "40 open but parked" case)', async () => {
routeSpawn({
'gh issue': { stdout: JSON.stringify([
{ number: 1, title: 'shipped, stale branch', assignees: [], labels: [] },
{ number: 2, title: 'shipped, stale branch', assignees: [], labels: [] },
{ number: 3, title: 'blocked', assignees: [], labels: [{ name: 'blocked' }] }
]) },
'git branch': { stdout: 'main\norigin/claim/issue-1\norigin/claim/issue-2\n' },
'gh pr': { stdout: '' }
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'any' });
expect(out).toMatchObject({ actionable: false, count: 0, reason: 'no-actionable-issues' });
expect(out.total).toBe(3);
expect(out.inFlightCount).toBe(2); // #1 + #2 held by stale claim branches
expect(out.filteredCount).toBe(1); // #3 blocked
});
it('parks (no-open-issues) on an empty list', async () => {
routeSpawn({ 'gh issue': { stdout: '[]' } });
const out = await detectGithubIssues(app, { issueAuthorFilter: 'any' });
expect(out).toMatchObject({ actionable: false, reason: 'no-open-issues', total: 0, inFlightCount: 0 });
});
it('reports no-authored-issues (not no-open-issues) when the author filter hides an otherwise non-empty queue', async () => {
// The author-filtered probe finds nothing (e.g. self/@me is the wrong forge
// identity); the unfiltered re-probe sees 3 open. Must NOT flatten to
// "no open issues" — surface the real count + the actionable reason.
spawn.mockImplementation((cmd, args = []) => {
if (cmd === 'gh' && args[0] === 'issue') {
const filtered = args.includes('--author');
return fakeChild(filtered ? '[]' : JSON.stringify([
{ number: 1, title: 'a', assignees: [], labels: [] },
{ number: 2, title: 'b', assignees: [], labels: [] },
{ number: 3, title: 'c', assignees: [], labels: [] }
]));
}
return fakeChild('');
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'self' });
expect(out).toMatchObject({
actionable: false, count: 0, total: 3, filteredCount: 0, inFlightCount: 0,
reason: 'no-authored-issues'
});
// Exactly two `gh issue` calls: the filtered probe + the unfiltered re-probe.
const issueCalls = spawn.mock.calls.filter(([cmd, a]) => cmd === 'gh' && a[0] === 'issue');
expect(issueCalls.some(([, a]) => a.includes('--author'))).toBe(true);
expect(issueCalls.some(([, a]) => !a.includes('--author'))).toBe(true);
});
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(JSON.stringify({ owner: { login: 'AcmeOrg' }, isInOrganization: true }));
}
if (cmd === 'gh' && args[0] === 'issue') {
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');
if (cmd === 'gh' && args[0] === 'api' && args.includes('graphql')) return fakePrChild([]);
if (cmd === 'glab' && args[0] === 'mr') return fakeChild('[]');
return fakeChild('');
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'owner' });
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 () => {
// Both the filtered probe AND the unfiltered re-probe are empty → truly nothing.
spawn.mockImplementation((cmd, args = []) => {
if (cmd === 'gh' && args[0] === 'issue') return fakeChild('[]');
return fakeChild('');
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'self' });
expect(out).toMatchObject({ actionable: false, reason: 'no-open-issues', total: 0 });
});
it('does not run a fallback re-probe under the "any" filter (no author was applied)', async () => {
let issueCalls = 0;
spawn.mockImplementation((cmd, args = []) => {
if (cmd === 'gh' && args[0] === 'issue') { issueCalls++; return fakeChild('[]'); }
return fakeChild('');
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'any' });
expect(out.reason).toBe('no-open-issues');
expect(issueCalls).toBe(1); // no second, unfiltered probe
});
it('falls back to no-open-issues when the unfiltered re-probe itself fails (safe, not a phantom count)', async () => {
spawn.mockImplementation((cmd, args = []) => {
if (cmd === 'gh' && args[0] === 'issue') {
if (args.includes('--author')) return fakeChild('[]', 0); // filtered: clean empty
return fakeChild('', 1); // unfiltered re-probe errors
}
return fakeChild('');
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'self' });
expect(out.reason).toBe('no-open-issues');
});
it('reports a transient failure when gh exits non-zero', async () => {
routeSpawn({ 'gh issue': { stdout: '', code: 1 } });
const out = await detectGithubIssues(app, { issueAuthorFilter: 'any' });
expect(out).toMatchObject({ actionable: false, reason: 'gh-list-failed', transient: true });
});
it('carries the CLI stderr into the transient reason as a redacted detail, instead of the bare literal alone', async () => {
routeSpawn({ 'gh issue': { stdout: '', code: 1, stderr: 'gh: authentication failed\n' } });
const out = await detectGithubIssues(app, { issueAuthorFilter: 'any' });
expect(out).toMatchObject({ reason: 'gh-list-failed', transient: true });
expect(out.detail).toBe('gh: authentication failed');
});
it('redacts a hostname and a token-shaped string out of the CLI stderr before it reaches the transient detail', async () => {
routeSpawn({
'gh issue': {
stdout: '', code: 1,
stderr: 'error talking to machine-abc123.tailnet-xyz.ts.net: token ghp_1234567890abcdef1234567890abcdef1234 rejected\n'
}
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'any' });
expect(out.detail).not.toContain('.ts.net');
expect(out.detail).not.toContain('ghp_1234567890abcdef1234567890abcdef1234');
expect(out.detail).not.toContain('machine-abc123');
});
it('runCli preserves accumulated stderr when the child process emits a spawn error, instead of blanking it', async () => {
spawn.mockImplementation((cmd, args = []) => {
if (cmd === 'gh' && args[0] === 'issue') return fakeErrorChild('gh: rate limit exceeded\n');
return fakeChild('');
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'any' });
expect(out).toMatchObject({ reason: 'gh-list-failed', transient: true });
expect(out.detail).toBe('gh: rate limit exceeded');
});
it('runCli preserves accumulated stderr on its CLI_TIMEOUT_MS timeout path, instead of blanking it', async () => {
vi.useFakeTimers();
try {
spawn.mockImplementation((cmd, args = []) => {
if (cmd === 'gh' && args[0] === 'issue') return fakeHangingChild('gh: request timed out\n');
return fakeChild('');
});
const pending = detectGithubIssues(app, { issueAuthorFilter: 'any' });
// Let the setImmediate stderr emission land before the timer fires.
await vi.advanceTimersByTimeAsync(0);
await vi.advanceTimersByTimeAsync(CLI_TIMEOUT_MS);
const out = await pending;
expect(out).toMatchObject({ reason: 'gh-list-failed', transient: true });
expect(out.detail).toBe('gh: request timed out');
} finally {
vi.useRealTimers();
}
});
it('self mode passes --author @me to the list (gh resolves @me natively, no extra lookup)', async () => {
routeSpawn({
'gh issue': { stdout: JSON.stringify([{ number: 1, title: 'mine', assignees: [], labels: [] }]) },
'git branch': { stdout: 'main\n' },
'gh pr': { stdout: '' }
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'self' });
expect(out.actionable).toBe(true);
const listCall = spawn.mock.calls.find(([cmd, args]) => cmd === 'gh' && args[0] === 'issue');
expect(listCall[1]).toContain('--author');
expect(listCall[1]).toContain('@me');
// No `gh repo view` owner lookup is needed in self mode.
expect(spawn.mock.calls.some(([cmd, args]) => cmd === 'gh' && args[0] === 'repo')).toBe(false);
});
it('an out-of-vocab filter value collapses to the @me self boundary (safe default)', async () => {
// Defense-in-depth: callers feed sanitizeTaskMetadata-constrained values,
// but if an unknown one ever reaches here it must fall to the @me security
// boundary (matching resolveIssueAuthorFilterBlock), never to owner/any.
routeSpawn({
'gh issue': { stdout: JSON.stringify([{ number: 1, title: 'mine', assignees: [], labels: [] }]) },
'git branch': { stdout: 'main\n' },
'gh pr': { stdout: '' }
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'bogus' });
expect(out.actionable).toBe(true);
const listCall = spawn.mock.calls.find(([cmd, args]) => cmd === 'gh' && args[0] === 'issue');
expect(listCall[1]).toContain('@me');
});
// `gh issue list --author` takes exactly ONE account, so the collaborators
// gate fans out into one server-side `--author <login>` query per trusted
// login and merges — post-filtering a single unfiltered page hid claimable
// issues past `--limit 100` on a busy repo. These cover that fan-out.
describe('collaborators filter', () => {
// gh api probes: `.login` (self) then the paginated collaborator logins.
// `issuesByAuthor` maps a lowercased login to the issues that author filed.
const routeCollaborators = ({ me = 'alice', collaborators = 'bob\ncarol\n', collabCode = 0, issuesByAuthor = {} } = {}) => {
spawn.mockImplementation((cmd, args = []) => {
if (cmd === 'gh' && args[0] === 'api' && args.includes('user')) return fakeChild(`${me}\n`);
if (cmd === 'gh' && args[0] === 'api' && args.includes('graphql')) return fakePrChild([]);
if (cmd === 'gh' && args[0] === 'api') return fakeChild(collabCode === 0 ? collaborators : '', collabCode);
if (cmd === 'gh' && args[0] === 'issue') {
const authorIdx = args.indexOf('--author');
if (authorIdx === -1) return fakeChild(JSON.stringify(Object.values(issuesByAuthor).flat()));
return fakeChild(JSON.stringify(issuesByAuthor[args[authorIdx + 1]] || []));
}
if (cmd === 'git' && args[0] === 'branch') return fakeChild('main\n');
if (cmd === 'gh' && args[0] === 'api' && args.includes('graphql')) return fakePrChild([]);
return fakeChild('');
});
};
const authorListCalls = () => spawn.mock.calls
.filter(([cmd, a]) => cmd === 'gh' && a[0] === 'issue' && a.includes('--author'))
.map(([, a]) => a[a.indexOf('--author') + 1]);
it('issues one --author query per trusted login and merges the results', async () => {
// The pre-fix shape (one unfiltered `--limit 100` page, filtered in
// memory) made a collaborator-filed issue past the first page invisible.
routeCollaborators({ issuesByAuthor: {
alice: [{ number: 1, title: 'mine', assignees: [], labels: [], author: { login: 'alice' } }],
bob: [{ number: 2, title: 'a teammate\'s', assignees: [], labels: [], author: { login: 'Bob' } }],
carol: []
} });
const out = await detectGithubIssues(app, { issueAuthorFilter: 'collaborators' });
expect(out.actionable).toBe(true);
// #2's login differs in case from the collaborator listing — the gate is
// case-insensitive, so a teammate isn't silently dropped.
expect(out.sample).toEqual([1, 2]);
expect(out.total).toBe(2);
expect(authorListCalls()).toEqual(['alice', 'bob', 'carol']);
const memberCall = spawn.mock.calls.find(([cmd, args]) => cmd === 'gh' && args[0] === 'api' && args.includes('--paginate'));
expect(memberCall[1]).toEqual(expect.arrayContaining(['--hostname', 'github.com']));
});
it('preloads only trusted authors and configured labels without applying claim-state skips', async () => {
routeCollaborators({ issuesByAuthor: {
alice: [
{ number: 1, title: 'Blocked context', labels: ['blocked'], author: { login: 'alice' } },
{ number: 2, title: 'Reserved', labels: [{ name: 'Human-Only' }], author: { login: 'alice' } },
{ number: 3, title: 'External', labels: [], author: { login: 'outsider' } },
{ number: 4, title: 'Unknown', labels: [] }
],
bob: [{ number: 5, title: 'Teammate', labels: [], author: { login: 'Bob' } }],
carol: []
} });
const out = await listConfiguredForgeIssues('gh', app, {
issueAuthorFilter: 'collaborators', issueExcludeLabels: ['human-only']
}, { PATH: '/bin' });
expect(out.ok).toBe(true);
expect(out.issues.map(issue => issue.number)).toEqual([1, 5]);
expect(spawn.mock.calls.filter(([cmd]) => cmd === 'gh').every(([, , options]) =>
options.env?.PATH === '/bin'
)).toBe(true);
expect(resolveForgeTokenEnv).not.toHaveBeenCalled();
expect(authorListCalls()).toEqual(['alice', 'bob', 'carol']);
});
it('does not preload a partial trusted set when collaborator lookup fails', async () => {
routeCollaborators({ collabCode: 1 });
const out = await listConfiguredForgeIssues('gh', app, { issueAuthorFilter: 'collaborators' });
expect(out).toMatchObject({ ok: false, issues: [] });
expect(authorListCalls()).toEqual([]);
});
it('de-duplicates an issue returned by more than one author query', async () => {
routeCollaborators({ issuesByAuthor: {
alice: [{ number: 7, title: 'shared', assignees: [], labels: [], author: { login: 'alice' } }],
bob: [{ number: 7, title: 'shared', assignees: [], labels: [], author: { login: 'alice' } }],
carol: []
} });
const out = await detectGithubIssues(app, { issueAuthorFilter: 'collaborators' });
expect(out.sample).toEqual([7]);
expect(out.total).toBe(1);
});
it('drops an issue whose author is unresolvable (unknown ⇒ untrusted)', async () => {
routeCollaborators({ issuesByAuthor: {
alice: [
{ number: 1, title: 'mine', assignees: [], labels: [], author: { login: 'alice' } },
{ number: 2, title: 'no author field', assignees: [], labels: [] }
],
bob: [], carol: []
} });
const out = await detectGithubIssues(app, { issueAuthorFilter: 'collaborators' });
expect(out.sample).toEqual([1]);
});
it('goes transient when one of the per-author list queries fails', async () => {
spawn.mockImplementation((cmd, args = []) => {
if (cmd === 'gh' && args[0] === 'api' && args.includes('user')) return fakeChild('alice\n');
if (cmd === 'gh' && args[0] === 'api') return fakeChild('bob\n');
if (cmd === 'gh' && args[0] === 'issue') {
return args[args.indexOf('--author') + 1] === 'bob' ? fakeChild('', 1) : fakeChild('[]');
}
return fakeChild('');
});
const out = await detectGithubIssues(app, { issueAuthorFilter: 'collaborators' });
expect(out).toMatchObject({ actionable: false, reason: 'gh-list-failed', transient: true });
});
it('caps the fan-out and logs the truncation rather than dropping logins silently', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const many = Array.from({ length: 40 }, (_, i) => `member${i}`).join('\n');
routeCollaborators({ collaborators: many, issuesByAuthor: {} });
await detectGithubIssues(app, { issueAuthorFilter: 'collaborators' });
// alice + 40 members = 41 trusted logins, capped at 25 queries.
expect(authorListCalls()).toHaveLength(25);
expect(warn).toHaveBeenCalledWith(expect.stringContaining('capped at 25 of 41'));
warn.mockRestore();
});
it('reports no-authored-issues with the real open count from an unfiltered re-probe', async () => {
routeCollaborators({ issuesByAuthor: {
mallory: [{ number: 1, title: 'x', assignees: [], labels: [], author: { login: 'mallory' } }],
eve: [{ number: 2, title: 'y', assignees: [], labels: [], author: { login: 'eve' } }]
} });
const out = await detectGithubIssues(app, { issueAuthorFilter: 'collaborators' });
expect(out).toMatchObject({ actionable: false, count: 0, total: 2, reason: 'no-authored-issues' });
// The author-filtered queries can't supply the unfiltered denominator, so
// exactly one extra list runs WITHOUT --author.
expect(spawn.mock.calls.filter(([cmd, a]) => cmd === 'gh' && a[0] === 'issue' && !a.includes('--author'))).toHaveLength(1);
});
it('goes transient with a remedy (never silently narrows to self) when the collaborators probe fails', async () => {
// A token without push access gets 403 here. Falling back to just `alice`
// would hide a teammate's claimable issue with no explanation — and since
// it fails identically forever, the result must name the way out rather
// than leaving the caller to say "try again shortly".
routeCollaborators({ collabCode: 1 });
const out = await detectGithubIssues(app, { issueAuthorFilter: 'collaborators' });
expect(out).toMatchObject({ actionable: false, reason: 'gh-collaborators-failed', transient: true, cli: 'gh' });
expect(out.remedy).toMatch(/push access/);
expect(spawn.mock.calls.some(([cmd, a]) => cmd === 'gh' && a[0] === 'issue')).toBe(false);
});
it('goes transient when the authenticated login can\'t be resolved', async () => {
routeCollaborators({ me: '' });
const out = await detectGithubIssues(app, { issueAuthorFilter: 'collaborators' });
expect(out).toMatchObject({ reason: 'gh-unavailable', transient: true });
});
});
it('runs every gh probe as the repo-pinned account, not the ambient credential', async () => {
// Ambient GH_TOKEN/GITHUB_TOKEN are the install's default account; a
// managed app under a different logged-in login must not inherit them.
vi.stubEnv('GH_TOKEN', 'ambient-owner-token');
vi.stubEnv('GITHUB_TOKEN', 'other-account-token');
vi.stubEnv('GH_ENTERPRISE_TOKEN', 'enterprise-token');
resolveForgeTokenEnv.mockResolvedValue({ GH_TOKEN: 'app-account-token' });
routeSpawn({
'gh issue': { stdout: '[]' },
'git branch': { stdout: 'main\n' },
'gh pr': { stdout: '' }
});
try {
await detectGithubIssues(app, { issueAuthorFilter: 'any' });
expect(resolveForgeTokenEnv).toHaveBeenCalledWith('/repo');
const ghCalls = spawn.mock.calls.filter(([cmd]) => cmd === 'gh');
expect(ghCalls.length).toBeGreaterThan(0);
for (const [, , options] of ghCalls) {
expect(options.env.GH_TOKEN).toBe('app-account-token');
expect(options.env).not.toHaveProperty('GITHUB_TOKEN');
expect(options.env).not.toHaveProperty('GH_ENTERPRISE_TOKEN');
}
} finally {
vi.unstubAllEnvs();
}
});
it('leaves gh on ambient auth when no account token can be minted', async () => {
routeSpawn({
'gh issue': { stdout: '[]' },
'git branch': { stdout: 'main\n' },
'gh pr': { stdout: '' }
});
await detectGithubIssues(app, { issueAuthorFilter: 'any' });
expect(resolveForgeTokenEnv).toHaveBeenCalledWith('/repo');
const ghCalls = spawn.mock.calls.filter(([cmd]) => cmd === 'gh');
expect(ghCalls.length).toBeGreaterThan(0);
expect(ghCalls.every(([, , options]) => options.env?.GH_TOKEN === process.env.GH_TOKEN)).toBe(true);
});
});
describe('detectGitlabIssues (spawn-mocked)', () => {
beforeEach(() => { spawn.mockReset(); });
const app = { id: 'a', repoPath: '/repo' };
it('does not overlay a GitHub token onto glab probes', async () => {
resolveForgeTokenEnv.mockResolvedValue({ GH_TOKEN: 'app-account-token' });
routeSpawn({
'glab issue': { stdout: '[]' },
'git branch': { stdout: 'main\n' },
'glab mr': { stdout: '[]' }
});
await detectGitlabIssues(app, { issueAuthorFilter: 'any' });
expect(resolveForgeTokenEnv).not.toHaveBeenCalled();
expect(spawn.mock.calls.filter(([cmd]) => cmd === 'glab').every(([, , options]) => options.env?.GH_TOKEN === process.env.GH_TOKEN)).toBe(true);
});
it('normalizes iid + string labels and excludes MR-in-flight issues', async () => {
routeSpawn({
'glab issue': { stdout: JSON.stringify([
{ iid: 10, title: 'plain', assignees: [], labels: [] },
{ iid: 11, title: 'blocked', assignees: [], labels: ['blocked'] },
{ iid: 12, title: 'in flight via MR', assignees: [], labels: [] }
]) },
'git branch': { stdout: 'main\n' },
'glab mr': { stdout: JSON.stringify([{ source_branch: 'claim/issue-12' }]) }
});
const out = await detectGitlabIssues(app, { issueAuthorFilter: 'any' });
expect(out.actionable).toBe(true);
expect(out.count).toBe(1); // only #10 (#11 blocked label, #12 in-flight MR)
expect(out.sample).toEqual([10]);
});
it('excludes an unassigned issue closed by an MR description on an arbitrary branch', async () => {
routeSpawn({
'glab issue': { stdout: JSON.stringify([{ iid: 10, title: 'work', labels: [], assignees: [] }]) },
'glab mr': { stdout: JSON.stringify([{ source_branch: 'interactive', description: 'Fixes: #10' }]) },
});
expect(await detectGitlabIssues(app, { issueAuthorFilter: 'any' })).toMatchObject({ actionable: false, inFlightCount: 1 });
});
it('does not reclaim an issue assigned to the authenticated account', async () => {
routeSpawn({
'glab api': { stdout: '{"username":"octo"}\n' }, // glab api user
'glab issue': { stdout: JSON.stringify([{ iid: 10, title: 'retry my claim', assignees: [{ username: 'octo' }], labels: [] }]) },
'git branch': { stdout: 'main\n' },
'glab mr': { stdout: '[]' }
});
const out = await detectGitlabIssues(app, { issueAuthorFilter: 'any' });
expect(out).toMatchObject({ actionable: false, count: 0, skipCauses: { assigned: 1 } });
});
it('does not need an identity probe to park an assigned-only GitLab queue', async () => {
routeSpawn({
'glab api': { stdout: '', code: 1 },
'glab issue': { stdout: JSON.stringify([{ iid: 10, title: 'retry my claim', assignees: [{ username: 'octo' }], labels: [] }]) },
'git branch': { stdout: 'main\n' },
'glab mr': { stdout: '[]' }
});
const out = await detectGitlabIssues(app, { issueAuthorFilter: 'any' });
expect(out).toMatchObject({ actionable: false, reason: 'no-actionable-issues', skipCauses: { assigned: 1 } });
});
it('stays transient instead of under-counting in-flight work when glab mr list fails', async () => {
routeSpawn({
'glab issue': { stdout: JSON.stringify([{ iid: 10, title: 'has an MR', assignees: [], labels: [] }]) },
'git branch': { stdout: 'main\n' },
'glab mr': { stdout: '', code: 1, stderr: 'timeout' }
});
const out = await detectGitlabIssues(app, { issueAuthorFilter: 'any' });
expect(out).toMatchObject({ actionable: false, reason: 'glab-unavailable', transient: true });
});
it('reports a transient failure when glab exits non-zero', async () => {
routeSpawn({ 'glab issue': { stdout: '', code: 1 } });
const out = await detectGitlabIssues(app, { issueAuthorFilter: 'any' });
expect(out).toMatchObject({ actionable: false, reason: 'glab-list-failed', transient: true });
});
it('self mode resolves the authenticated glab username and filters the list by it', async () => {
routeSpawn({
'glab api': { stdout: '{"username":"octo"}\n' }, // glab api user
'glab issue': { stdout: JSON.stringify([{ iid: 10, title: 'mine', assignees: [], labels: [] }]) },
'git branch': { stdout: 'main\n' },
'glab mr': { stdout: '[]' }
});
const out = await detectGitlabIssues(app, { issueAuthorFilter: 'self' });
expect(out.actionable).toBe(true);
const listCall = spawn.mock.calls.find(([cmd, args]) => cmd === 'glab' && args[0] === 'issue');
expect(listCall[1]).toContain('--author');
expect(listCall[1]).toContain('octo');
});
it('self mode reports a transient failure when glab api user fails (unauthenticated)', async () => {
routeSpawn({ 'glab api': { stdout: '', code: 1 } });
const out = await detectGitlabIssues(app, { issueAuthorFilter: 'self' });
expect(out).toMatchObject({ actionable: false, reason: 'glab-unavailable', transient: true });
});
it('self mode reports no-authored-issues when the author filter hides a non-empty queue', async () => {
spawn.mockImplementation((cmd, args = []) => {
if (cmd === 'glab' && args[0] === 'api') return fakeChild('{"username":"octo"}\n'); // glab api user
if (cmd === 'glab' && args[0] === 'issue') {
const filtered = args.includes('--author');
return fakeChild(filtered ? '[]' : JSON.stringify([{ iid: 10, title: 'x', assignees: [], labels: [] }]));
}
return fakeChild('');
});
const out = await detectGitlabIssues(app, { issueAuthorFilter: 'self' });
expect(out).toMatchObject({ actionable: false, reason: 'no-authored-issues', total: 1, filteredCount: 0 });
});
it('owner filter on a GROUP-owned project reports owner-is-group (probe 200) with the real open count', async () => {
// The GitLab twin of the GitHub org trap: the namespace is a group, which
// never authors issues. `glab api groups/<namespace>` returning 200 (code 0)
// marks it a group → the shared owner-filter short-circuit parks with the
// GitLab-flavored `owner-is-group` reason and never runs `--author <group>`.
spawn.mockImplementation((cmd, args = []) => {
if (cmd === 'git' && args[0] === 'remote') return fakeChild('[email protected]:acme-group/widget.git\n');
if (cmd === 'glab' && args[0] === 'api' && String(args[1]).startsWith('groups/')) return fakeChild('{"kind":"group"}');
if (cmd === 'glab' && args[0] === 'issue') return fakeChild(JSON.stringify([{ iid: 7, title: 'x', assignees: [], labels: [] }]));
return fakeChild('');
});
const out = await detectGitlabIssues(app, { issueAuthorFilter: 'owner' });
expect(out).toMatchObject({ reason: 'owner-is-group', total: 1, count: 0, filteredCount: 0 });
// The guaranteed-empty `--author <group>` query is never issued.
const issueCalls = spawn.mock.calls.filter(([cmd, a]) => cmd === 'glab' && a[0] === 'issue');
expect(issueCalls.every(([, a]) => !a.includes('--author'))).toBe(true);
});
it('owner filter on a nested SUBGROUP project resolves the full namespace and reports owner-is-group', async () => {
// Nested subgroups are the common GitLab layout: parseGitRemoteUrl rejects a
// >2-segment remote, so the namespace must be resolved from the raw path and
// URL-encoded (`parent/subgroup` → `parent%2Fsubgroup`) before the group probe.
spawn.mockImplementation((cmd, args = []) => {
if (cmd === 'git' && args[0] === 'remote') return fakeChild('[email protected]:parent/subgroup/widget.git\n');
if (cmd === 'glab' && args[0] === 'api' && String(args[1]).startsWith('groups/')) return fakeChild('{"kind":"group"}');
if (cmd === 'glab' && args[0] === 'issue') return fakeChild(JSON.stringify([{ iid: 9, title: 'x', assignees: [], labels: [] }]));
return fakeChild('');
});
const out = await detectGitlabIssues(app, { issueAuthorFilter: 'owner' });
expect(out).toMatchObject({ reason: 'owner-is-group', total: 1, count: 0 });
const probeCall = spawn.mock.calls.find(([cmd, a]) => cmd === 'glab' && a[0] === 'api' && String(a[1]).startsWith('groups/'));
expect(probeCall[1][1]).toBe('groups/parent%2Fsubgroup');
// Never issues the guaranteed-empty `--author <group>` query.
const issueCalls = spawn.mock.calls.filter(([cmd, a]) => cmd === 'glab' && a[0] === 'issue');
expect(issueCalls.every(([, a]) => !a.includes('--author'))).toBe(true);
});
it('preserves an all-numeric namespace but skips the ambiguous group-ID probe (uses --author)', async () => {
// Regression + guard: an all-numeric top-level namespace (`/1234/widget`) must
// NOT be stripped as if it were an SSH `:443/` port hop (it is preserved as
// `1234`), AND it must NOT be probed as `groups/1234` — GitLab reads a numeric
// groups/:id as a database group ID, not a path, which could falsely match an
// unrelated group. So the guard skips the probe and takes the safe --author path.
spawn.mockImplementation((cmd, args = []) => {
if (cmd === 'git' && args[0] === 'remote') return fakeChild('https://gitlab.example/1234/widget.git\n');
if (cmd === 'glab' && args[0] === 'issue') return fakeChild(JSON.stringify([{ iid: 3, title: 'x', assignees: [], labels: [] }]));
if (cmd === 'git' && args[0] === 'branch') return fakeChild('main\n');
if (cmd === 'glab' && args[0] === 'mr') return fakeChild('[]');
return fakeChild('');
});
const out = await detectGitlabIssues(app, { issueAuthorFilter: 'owner' });
expect(out.actionable).toBe(true);
// No ambiguous groups/ probe was issued for the numeric namespace.
const probeCall = spawn.mock.calls.find(([cmd, a]) => cmd === 'glab' && a[0] === 'api' && String(a[1]).startsWith('groups/'));
expect(probeCall).toBeUndefined();
// The preserved `1234` namespace is used as the author filter (not stripped).
const listCall = spawn.mock.calls.find(([cmd, a]) => cmd === 'glab' && a[0] === 'issue');
expect(listCall[1]).toContain('--author');
expect(listCall[1]).toContain('1234');
});
it('parses a bracketed IPv6 host without leaking the address into the namespace', async () => {
// Regression: the host/path split must not trip on the colons inside a
// bracketed IPv6 literal — the namespace is `group`, not part of the address.
spawn.mockImplementation((cmd, args = []) => {
if (cmd === 'git' && args[0] === 'remote') return fakeChild('https://[2001:db8::1]/group/widget.git\n');
if (cmd === 'glab' && args[0] === 'api' && String(args[1]).startsWith('groups/')) return fakeChild('{"kind":"group"}');
if (cmd === 'glab' && args[0] === 'issue') return fakeChild(JSON.stringify([{ iid: 4, title: 'x', assignees: [], labels: [] }]));
return fakeChild('');
});
const out = await detectGitlabIssues(app, { issueAuthorFilter: 'owner' });
expect(out).toMatchObject({ reason: 'owner-is-group', total: 1 });
const probeCall = spawn.mock.calls.find(([cmd, a]) => cmd === 'glab' && a[0] === 'api' && String(a[1]).startsWith('groups/'));
expect(probeCall[1][1]).toBe('groups/group');
});
it('collaborators filter keeps you + project members (via members/all) and drops outsiders', async () => {
// `members/all` (not `members`) so GROUP-inherited access counts — that's how
// most GitLab teams are granted, and `members` alone would drop them.
spawn.mockImplementation((cmd, args = []) => {
if (cmd === 'glab' && args[0] === 'api' && args.includes('user')) return fakeChild('{"username":"octo"}\n');
if (cmd === 'glab' && args[0] === 'api') return fakeChild('{"username":"teammate"}\n{"username":"octo"}\n');
if (cmd === 'glab' && args[0] === 'issue') {
const byAuthor = {
octo: [{ iid: 10, title: 'mine', assignees: [], labels: [], author: { username: 'octo' } }],
teammate: [{ iid: 11, title: 'a member\'s', assignees: [], labels: [], author: { username: 'teammate' } }],
'drive-by': [{ iid: 12, title: 'a stranger\'s', assignees: [], labels: [], author: { username: 'drive-by' } }]
};
const idx = args.indexOf('--author');
return fakeChild(JSON.stringify(idx === -1
? Object.values(byAuthor).flat()
: byAuthor[args[idx + 1]] || []));
}
if (cmd === 'git' && args[0] === 'branch') return fakeChild('main\n');
if (cmd === 'glab' && args[0] === 'mr') return fakeChild('[]');
return fakeChild('');
});
const out = await detectGitlabIssues(app, { issueAuthorFilter: 'collaborators' });
expect(out.sample).toEqual([10, 11]);
const membersCall = spawn.mock.calls.find(([cmd, a]) => cmd === 'glab' && a[0] === 'api' && String(a[2] || '').includes('members'));
expect(membersCall[1]).toContain('projects/:id/members/all');
expect(membersCall[1]).toContain('ndjson');
expect(membersCall[1]).not.toContain('-q');
// The trusted SET can't be one `--author` arg, so it fans out to one
// server-side query per login — the outsider's issue is never listed.
const authored = spawn.mock.calls
.filter(([cmd, a]) => cmd === 'glab' && a[0] === 'issue' && a.includes('--author'))
.map(([, a]) => a[a.indexOf('--author') + 1]);
expect(authored).toEqual(['octo', 'teammate']);
});
it.each(['not json', '{}', '{"username":42}'])('rejects malformed GitLab member data: %s', async (body) => {
spawn.mockImplementation((cmd, args = []) => {
if (cmd === 'glab' && args[0] === 'api' && args.includes('user')) return fakeChild('{"username":"octo"}');
if (cmd === 'glab' && args[0] === 'api') return fakeChild(body);
return fakeChild('');
});
const out = await detectGitlabIssues(app, { issueAuthorFilter: 'collaborators' });
expect(out).toMatchObject({ reason: 'glab-members-failed', transient: true });
expect(spawn.mock.calls.some(([cmd, args]) => cmd === 'glab' && args[0] === 'issue')).toBe(false);
});
it('collaborators filter goes transient when the members probe fails', async () => {
spawn.mockImplementation((cmd, args = []) => {
if (cmd === 'glab' && args[0] === 'api' && args.includes('user')) return fakeChild('{"username":"octo"}\n');
if (cmd === 'glab' && args[0] === 'api') return fakeChild('', 1);
return fakeChild('');
});
const out = await detectGitlabIssues(app, { issueAuthorFilter: 'collaborators' });
expect(out).toMatchObject({ reason: 'glab-members-failed', transient: true, cli: 'glab' });
expect(out.remedy).toMatch(/member list/);
});
it('owner filter on a USER-owned project passes --author <namespace> (groups probe 404)', async () => {
// A user namespace: `glab api groups/<namespace>` 404s (non-zero exit) → not
// a group, so owner-mode filters by the namespace login as before.
spawn.mockImplementation((cmd, args = []) => {
if (cmd === 'git' && args[0] === 'remote') return fakeChild('[email protected]:alice/widget.git\n');
if (cmd === 'git' && args[0] === 'branch') return fakeChild('main\n');
if (cmd === 'glab' && args[0] === 'api' && String(args[1]).startsWith('groups/')) return fakeChild('', 22); // glab 404 → non-zero
if (cmd === 'glab' && args[0] === 'issue') return fakeChild(JSON.stringify([{ iid: 7, title: 'x', assignees: [], labels: [] }]));
if (cmd === 'glab' && args[0] === 'mr') return fakeChild('[]');
return fakeChild('');
});
const out = await detectGitlabIssues(app, { issueAuthorFilter: 'owner' });
expect(out.actionable).toBe(true);
const listCall = spawn.mock.calls.find(([cmd, a]) => cmd === 'glab' && a[0] === 'issue');
expect(listCall[1]).toContain('--author');
expect(listCall[1]).toContain('alice');
});
});
});