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: surface and escalate a stalled perpetual-drain forge probe (#7551)

[._.]/ Adam Eivy1128dbd25f0b
diff --git a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx
index 65e42e2721..3c55fef0ae 100644
--- a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx
+++ b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx
@@ -376,31 +376,58 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri
// (config.perpetualStatus) over the global status.reason — which always
// reads 'perpetual-drain' for app-scoped tasks even when every app is parked.
const p = config.perpetualStatus;
+ // A stall (the forge CLI has failed several evaluations in a row) can
+ // coexist with an apparently-healthy "Draining" line — the gate skips
+ // WITHOUT parking on purpose, so nothing else here would ever surface
+ // it. Render it ahead of the park/drain line rather than instead of it.
+ const stall = p?.stall;
+ const stallNote = stall ? (
+ <p className="text-xs text-port-warning mt-1">
+ Probe failing{stall.cli ? ` (${stall.cli})` : ''}: {stall.reason}{stall.detail ? ` — ${stall.detail}` : ''}
+ {' '}({stall.consecutive} consecutive)
+ </p>
+ ) : null;
if (p && (p.trackedAppCount > 0 || p.globalParked)) {
const allParked = p.globalParked || (p.trackedAppCount > 0 && p.parkedAppCount === p.trackedAppCount);
if (allParked) {
const scope = p.trackedAppCount > 0 ? `${p.trackedAppCount} app(s) parked` : 'Parked';
return (
- <p className="text-xs text-port-warning mt-1">
- {scope}{p.parkReason ? ` (${p.parkReason})` : ''}{p.nextRecheckAt ? ` — next recheck ${formatDateTime(p.nextRecheckAt)}` : ''}
- </p>
+ <>
+ {stallNote}
+ <p className="text-xs text-port-warning mt-1">
+ {scope}{p.parkReason ? ` (${p.parkReason})` : ''}{p.nextRecheckAt ? ` — next recheck ${formatDateTime(p.nextRecheckAt)}` : ''}
+ </p>
+ </>
);
}
const partial = p.parkedAppCount > 0 ? ` — ${p.parkedAppCount}/${p.trackedAppCount} app(s) parked` : '';
- return <p className="text-xs text-port-success mt-1">Draining — actionable work available{partial}</p>;
+ return (
+ <>
+ {stallNote}
+ <p className="text-xs text-port-success mt-1">Draining — actionable work available{partial}</p>
+ </>
+ );
}
// Global (non-app) perpetual task: the global status.reason is accurate.
if (status.reason === 'perpetual-parked') {
return (
- <p className="text-xs text-port-warning mt-1">
- Parked{status.parkReason ? ` (${status.parkReason})` : ''}{status.nextRunAt ? ` — rechecks ${formatDateTime(status.nextRunAt)}` : ''}
- </p>
+ <>
+ {stallNote}
+ <p className="text-xs text-port-warning mt-1">
+ Parked{status.parkReason ? ` (${status.parkReason})` : ''}{status.nextRunAt ? ` — rechecks ${formatDateTime(status.nextRunAt)}` : ''}
+ </p>
+ </>
);
}
if (status.reason === 'perpetual-drain' || status.reason === 'perpetual-recheck') {
- return <p className="text-xs text-port-success mt-1">Draining — actionable work available</p>;
+ return (
+ <>
+ {stallNote}
+ <p className="text-xs text-port-success mt-1">Draining — actionable work available</p>
+ </>
+ );
}
- return null;
+ return stallNote;
})()}
</div>
)}
diff --git a/client/src/components/cos/tabs/schedule/GlobalConfigControls.test.jsx b/client/src/components/cos/tabs/schedule/GlobalConfigControls.test.jsx
index e952bc6843..7fc0434f54 100644
--- a/client/src/components/cos/tabs/schedule/GlobalConfigControls.test.jsx
+++ b/client/src/components/cos/tabs/schedule/GlobalConfigControls.test.jsx
@@ -328,6 +328,49 @@ describe('GlobalConfigControls — cadence + perpetual', () => {
});
});
+// A stall (the forge CLI failing several evaluations in a row) can coexist
+// with an apparently-healthy "Draining" state — the gate skips without
+// parking on purpose (#7551) — so it must render regardless of park state.
+describe('GlobalConfigControls — perpetual probe-failure stall', () => {
+ it('renders the redacted probe-failure diagnostic alongside a still-draining status', () => {
+ renderControls({
+ config: {
+ type: 'on-demand',
+ cronExpression: null,
+ perpetual: true,
+ autoStart: true,
+ perpetualStatus: {
+ globalParked: false,
+ parkedAppCount: 0,
+ trackedAppCount: 1,
+ nextRecheckAt: null,
+ parkReason: null,
+ stall: { cli: 'gh', reason: 'gh-list-failed', detail: 'gh: authentication failed', consecutive: 3 }
+ }
+ }
+ });
+ expect(screen.getByText(/Probe failing/)).toBeInTheDocument();
+ expect(screen.getByText(/gh-list-failed/)).toBeInTheDocument();
+ expect(screen.getByText(/authentication failed/)).toBeInTheDocument();
+ expect(screen.getByText(/3 consecutive/)).toBeInTheDocument();
+ // Still reports the drain as healthy — a stall does not imply a park.
+ expect(screen.getByText(/Draining — actionable work available/)).toBeInTheDocument();
+ });
+
+ it('renders nothing extra when the probe is healthy (no stall)', () => {
+ renderControls({
+ config: {
+ type: 'on-demand',
+ cronExpression: null,
+ perpetual: true,
+ autoStart: true,
+ perpetualStatus: { globalParked: false, parkedAppCount: 0, trackedAppCount: 1, nextRecheckAt: null, parkReason: null, stall: null }
+ }
+ });
+ expect(screen.queryByText(/Probe failing/)).not.toBeInTheDocument();
+ });
+});
+
describe('GlobalConfigControls — external issue isolation', () => {
it('offers text API providers and explains the source policy while retaining an invalid saved pin', async () => {
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 241fc57b7b..c87a4e2980 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -2088,10 +2088,24 @@ const TRANSIENT_VERDICT_TTL_MS = 60_000;
const transientVerdicts = new Map();
const transientVerdictKey = (taskType, appId) => `${taskType}:${appId || 'global'}`;
+// How many CONSECUTIVE transient skips (across evaluations, not within any
+// single 60s window) applyPerpetualWorkGate tolerates at `debug` before
+// escalating to `warn` — see recordPerpetualTransient's return value.
+export const PERPETUAL_TRANSIENT_ESCALATION_THRESHOLD = 3;
+
+// Consecutive-transient-skip counters, keyed the same as transientVerdicts but
+// deliberately tracked SEPARATELY from it: this streak must survive across
+// evaluations more than 60s apart (it counts how many evaluations IN A ROW came
+// back transient, not how many landed inside one verdict's TTL window), and it
+// is reset — not just expired — the moment a probe stops being transient.
+const transientStreaks = new Map();
+
/**
* Record why a perpetual work gate skipped WITHOUT parking. `cli` is the forge
* CLI whose probe failed (`gh` / `glab`), or null when no forge was involved.
- * Passing a null verdict clears any stale entry (the actionable / park paths).
+ * Passing a null verdict clears any stale entry (the actionable / park paths)
+ * AND resets the consecutive-transient streak — a successful probe means
+ * whatever was stuck has cleared.
*
* Also doubles as pr-reviewer's idle-skip reason channel: pr-reviewer is
* on-demand, not perpetual, so its preflight skip (churn park, no external PRs,
@@ -2100,14 +2114,22 @@ const transientVerdictKey = (taskType, appId) => `${taskType}:${appId || 'global
* for WHY — the same gap this map already closes for 'transient'. The payload
* shape here is a free-form object (`{ ...verdict }`), so a `{ reason }` payload
* under the `taskType: 'pr-reviewer'` key needs no separate map or TTL logic.
+ * pr-reviewer shares the streak counter too — harmless, since it is keyed
+ * per-`taskType:appId` and nothing reads pr-reviewer's streak today.
+ *
+ * @returns {number} the new consecutive-transient count (0 once cleared).
*/
export function recordPerpetualTransient(taskType, appId, verdict) {
const key = transientVerdictKey(taskType, appId);
if (!verdict) {
transientVerdicts.delete(key);
- return;
+ transientStreaks.delete(key);
+ return 0;
}
transientVerdicts.set(key, { ...verdict, at: Date.now() });
+ const count = (transientStreaks.get(key) || 0) + 1;
+ transientStreaks.set(key, count);
+ return count;
}
/** Read-and-consume the recorded verdict; null when absent or past its TTL. */
@@ -2455,6 +2477,11 @@ async function applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, i
ignoreTaskId
});
if (detection.actionable) {
+ // A probe that reports actionable work is, by definition, not stuck — clear
+ // both the transient streak and any persisted stall diagnostic before
+ // deciding whether THIS evaluation dispatches or parks on no-progress.
+ recordPerpetualTransient(taskType, app.id, null);
+ await taskSchedule.recordPerpetualStall(taskType, app.id, null);
// A successful claim/plan agent can still return without changing forge or
// PLAN state (for example, it decides not to pick the advertised item). The
// completion refill would otherwise dispatch the same candidate forever.
@@ -2479,25 +2506,42 @@ async function applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, i
return { skip: true };
}
}
- recordPerpetualTransient(taskType, app.id, null);
metadata.perpetual = true;
// The dispatch is SPENT BY THE CALLER, once a task is certain — see the note
// on `spendDispatch` in the JSDoc above.
return { skip: false, spendDispatch: true, signature: drainSignature };
}
if (detection.transient) {
- emitLog('debug', `Perpetual ${taskType} skip for ${app.name} (transient: ${detection.reason})`, { appId: app.id });
- // The skip is silent by design (the next tick retries), but an explicit user
- // "Run" ends here too — record which CLI failed so emitOnDemandEmpty can tell
- // the difference between a blip and a forge that is broken for good, plus any
- // remedy the detector already named (a permission the token lacks, which no
- // amount of retrying fixes).
- recordPerpetualTransient(taskType, app.id, {
- cli: detection.cli || null, reason: detection.reason, remedy: detection.remedy || null
+ // Record BEFORE logging, so the log line (and the escalation decision) can
+ // report which consecutive occurrence this is. A single blip stays at
+ // `debug` (suppressed on a default install); once the SAME probe has failed
+ // PERPETUAL_TRANSIENT_ESCALATION_THRESHOLD evaluations in a row, escalate to
+ // `warn` (reaches the console and the cos:log stream) and persist the
+ // stalled verdict — otherwise a perpetual drain whose forge CLI is broken
+ // produces zero console output, zero persisted state, and zero UI signal,
+ // indefinitely (#7551).
+ const consecutive = recordPerpetualTransient(taskType, app.id, {
+ cli: detection.cli || null, reason: detection.reason, remedy: detection.remedy || null, detail: detection.detail || null
});
+ const detailSuffix = detection.detail ? ` — ${detection.detail}` : '';
+ const escalated = consecutive >= PERPETUAL_TRANSIENT_ESCALATION_THRESHOLD;
+ emitLog(escalated ? 'warn' : 'debug',
+ `Perpetual ${taskType} skip for ${app.name} (transient: ${detection.reason}${detailSuffix}, ${consecutive} consecutive)`,
+ { appId: app.id, consecutive });
+ // The skip is silent by design at low counts (the next tick retries), but an
+ // explicit user "Run" ends here too — record which CLI failed so
+ // emitOnDemandEmpty can tell the difference between a blip and a forge that
+ // is broken for good, plus any remedy the detector already named (a
+ // permission the token lacks, which no amount of retrying fixes).
+ if (escalated) {
+ await taskSchedule.recordPerpetualStall(taskType, app.id, {
+ cli: detection.cli || null, reason: detection.reason, detail: detection.detail || null, consecutive
+ });
+ }
return { skip: true };
}
recordPerpetualTransient(taskType, app.id, null);
+ await taskSchedule.recordPerpetualStall(taskType, app.id, null);
// Carry the detector's open/in-flight/filtered breakdown into the park so an
// explicit "Run" can explain WHY a non-empty queue yielded no work.
const counts = detection.total != null
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index 2cb1878f26..f061b2e8f0 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -77,6 +77,7 @@ import {
applyOnDemandConsent,
isConfiguredApprovalRequired,
recordPerpetualTransient,
+ PERPETUAL_TRANSIENT_ESCALATION_THRESHOLD,
buildJiraTicketTask,
buildClaimWorkTask,
resolveAppClaimReviewers,
@@ -1276,6 +1277,48 @@ describe('emitOnDemandEmpty', () => {
}
});
+ it('recordPerpetualTransient counts CONSECUTIVE transient verdicts for the same taskType+app', () => {
+ expect(recordPerpetualTransient('claim-issue', 'app-streak', { cli: 'gh', reason: 'gh-list-failed' })).toBe(1);
+ expect(recordPerpetualTransient('claim-issue', 'app-streak', { cli: 'gh', reason: 'gh-list-failed' })).toBe(2);
+ expect(recordPerpetualTransient('claim-issue', 'app-streak', { cli: 'gh', reason: 'gh-list-failed' })).toBe(3);
+ expect(recordPerpetualTransient('claim-issue', 'app-streak', { cli: 'gh', reason: 'gh-list-failed' })).toBe(4);
+ });
+
+ it('recordPerpetualTransient resets the streak to 0 on a null (actionable/idle) verdict', () => {
+ recordPerpetualTransient('claim-issue', 'app-streak-2', { cli: 'gh', reason: 'gh-list-failed' });
+ recordPerpetualTransient('claim-issue', 'app-streak-2', { cli: 'gh', reason: 'gh-list-failed' });
+ expect(recordPerpetualTransient('claim-issue', 'app-streak-2', null)).toBe(0);
+ // The next transient verdict after a reset starts the streak over at 1, not
+ // where it left off — a recovered probe means the escalation clock restarts.
+ expect(recordPerpetualTransient('claim-issue', 'app-streak-2', { cli: 'gh', reason: 'gh-list-failed' })).toBe(1);
+ });
+
+ it('recordPerpetualTransient keys the streak by taskType+app, so one app never inherits another\'s count', () => {
+ recordPerpetualTransient('claim-issue', 'app-streak-a', { cli: 'gh', reason: 'gh-list-failed' });
+ recordPerpetualTransient('claim-issue', 'app-streak-a', { cli: 'gh', reason: 'gh-list-failed' });
+ expect(recordPerpetualTransient('claim-issue', 'app-streak-b', { cli: 'gh', reason: 'gh-list-failed' })).toBe(1);
+ });
+
+ it('the escalation threshold is exported and applyPerpetualWorkGate levels its skip log against it, persisting a stall once escalated', () => {
+ const start = GEN_SRC.indexOf('async function applyPerpetualWorkGate');
+ const gate = GEN_SRC.slice(start, GEN_SRC.indexOf('\n}', start));
+ expect(PERPETUAL_TRANSIENT_ESCALATION_THRESHOLD).toBeGreaterThanOrEqual(1);
+ expect(gate).toMatch(/consecutive >= PERPETUAL_TRANSIENT_ESCALATION_THRESHOLD/);
+ expect(gate).toMatch(/emitLog\(escalated \? 'warn' : 'debug'/);
+ expect(gate).toContain('taskSchedule.recordPerpetualStall(taskType, app.id,');
+ });
+
+ it('the actionable path resets both the transient streak and the persisted stall before deciding to dispatch or no-progress-park', () => {
+ const start = GEN_SRC.indexOf('async function applyPerpetualWorkGate');
+ const gate = GEN_SRC.slice(start, GEN_SRC.indexOf('\n}', start));
+ const actionableIdx = gate.indexOf('if (detection.actionable) {');
+ const resetIdx = gate.indexOf('recordPerpetualTransient(taskType, app.id, null);');
+ const stallClearIdx = gate.indexOf('taskSchedule.recordPerpetualStall(taskType, app.id, null);');
+ expect(actionableIdx).toBeGreaterThan(-1);
+ expect(resetIdx).toBeGreaterThan(actionableIdx);
+ expect(stallClearIdx).toBeGreaterThan(actionableIdx);
+ });
+
it("surfaces the pr-reviewer preflight's recorded skip reason on an idle outcome", async () => {
const persist = vi.spyOn(taskStore, 'addTask').mockResolvedValue({ id: 'diagnostic' });
recordPerpetualTransient('pr-reviewer', 'app-1', { reason: 'security-guard-not-ready' });
diff --git a/server/services/perpetualWork.js b/server/services/perpetualWork.js
index 3c7b79c351..80c5dd5981 100644
--- a/server/services/perpetualWork.js
+++ b/server/services/perpetualWork.js
@@ -30,6 +30,8 @@ import { parsePlanItems, extractAllIds, findInProgressIds, pickFirstAvailable, e
import { readOriginRemoteUrl } from '../lib/gitRemote.js';
import { withGlabJson } from '../lib/glabArgs.js';
import { githubApiHost, hostFromOriginUrl } from '../lib/workTracker.js';
+import { scrubSecretTokens } from '../lib/secretText.js';
+import { redactPii } from '../lib/piiRedactionPatterns.js';
// The workflow markers live with the forge label vocabulary (name + color + the
// `label create` idiom the prompt bodies interpolate), so the detector and the
// live claim agent cannot drift on how "already decomposed" or "claimed and
@@ -54,7 +56,9 @@ export const NON_ACTIONABLE_ISSUE_LABELS = new Set([
IN_PROGRESS_LABEL, 'blocked', 'needs-input', 'future', 'wontfix', 'question', 'discussion'
]);
-const CLI_TIMEOUT_MS = 15000;
+// Exported so the timeout path is directly testable with fake timers rather
+// than a real 15s wait.
+export const CLI_TIMEOUT_MS = 15000;
// How many actionable work items a detector carries back in `items`. The
// detectors exist for the perpetual drain (which only needs `actionable`/`count`),
@@ -63,6 +67,29 @@ const CLI_TIMEOUT_MS = 15000;
// hundreds of open issues can't balloon the response the picker renders.
export const WORK_ITEM_LIMIT = 50;
+// Cap on the CLI stderr detail carried into a transient reason — long enough to
+// show the actual fault (an auth message, a rate-limit window, a DNS failure),
+// short enough that a verbose CLI dump never bloats a log line or a toast.
+const CLI_DETAIL_MAX_CHARS = 200;
+
+/**
+ * Redact a raw CLI stderr capture into a short, safe detail string for a
+ * transient reason. Per AGENTS.md "Sensitive Data & Privacy", a forge CLI's
+ * stderr can carry a hostname, tailnet name, or token, so it must be scrubbed
+ * before it can reach a log line or a UI toast — `scrubSecretTokens` for
+ * credential-shaped values, `redactPii` for hosts/paths/IPs/emails/etc. Keeps
+ * only the LAST non-empty line: the actual failure is almost always the tail of
+ * a gh/glab error, not its usage banner. Returns null for empty/blank stderr so
+ * callers can tell "no detail available" apart from a detail that redacted to
+ * an empty string.
+ */
+function redactCliDetail(stderr) {
+ const lines = String(stderr || '').split('\n').map((l) => l.trim()).filter(Boolean);
+ if (lines.length === 0) return null;
+ const detail = redactPii(scrubSecretTokens(lines[lines.length - 1]));
+ return detail.length > CLI_DETAIL_MAX_CHARS ? `${detail.slice(0, CLI_DETAIL_MAX_CHARS)}…` : detail;
+}
+
/**
* Best-effort CLI runner mirroring git.js#spawnCli (which isn't exported).
* Never rejects: a spawn error, non-zero exit, or timeout all resolve to a
@@ -75,9 +102,13 @@ function runCli(cmd, args, cwd, env) {
const done = (result) => { if (!settled) { settled = true; clearTimeout(timer); resolve(result); } };
child.stdout.on('data', (d) => { stdout += d.toString(); });
child.stderr.on('data', (d) => { stderr += d.toString(); });
- child.on('error', () => done({ code: -1, stdout: '', stderr: '' }));
+ // Preserve whatever stderr accumulated before the spawn error / timeout —
+ // the CLI's actual fault (expired token, rate limit, network refused, wrong
+ // repo) lives there, and blanking it left every transient reason a bare
+ // fixed literal with no diagnostic content (#7551).
+ child.on('error', () => done({ code: -1, stdout, stderr }));
child.on('close', (code) => done({ code, stdout, stderr }));
- const timer = setTimeout(() => { try { child.kill(); } catch { /* noop */ } done({ code: -1, stdout: '', stderr: '' }); }, CLI_TIMEOUT_MS);
+ const timer = setTimeout(() => { try { child.kill(); } catch { /* noop */ } done({ code: -1, stdout, stderr }); }, CLI_TIMEOUT_MS);
if (timer.unref) timer.unref();
});
}
@@ -273,7 +304,7 @@ async function resolveAuthenticatedLogin(cli, args, repoPath, env) {
? (await import('../lib/streamJsonParser.js')).safeParse(res.stdout)?.username
: res.stdout;
const login = typeof rawLogin === 'string' ? rawLogin.trim() : '';
- return (res.code !== 0 || !login) ? { error: `${cli}-unavailable` } : { login };
+ return (res.code !== 0 || !login) ? { error: `${cli}-unavailable`, detail: redactCliDetail(res.stderr) } : { login };
}
/**
@@ -286,13 +317,13 @@ async function resolveAuthenticatedLogin(cli, args, repoPath, env) {
* carries a `remedy` the caller can surface instead.
*/
async function resolveTrustedLogins(cfg, repoPath, env) {
- const { login, error } = await resolveAuthenticatedLogin(cfg.cli, cfg.selfLoginArgs, repoPath, env);
- if (error) return { error };
+ const { login, error, detail } = await resolveAuthenticatedLogin(cfg.cli, cfg.selfLoginArgs, repoPath, env);
+ if (error) return { error, detail };
const membersArgs = cfg.cli === 'gh'
? await withGithubHost(cfg.membersArgs, repoPath)
: cfg.membersArgs;
const res = await runCli(cfg.cli, membersArgs, repoPath, env);
- if (res.code !== 0) return { error: cfg.membersFail, remedy: cfg.membersRemedy };
+ if (res.code !== 0) return { error: cfg.membersFail, remedy: cfg.membersRemedy, detail: redactCliDetail(res.stderr) };
const lines = (res.stdout || '').split('\n').filter(line => line.trim());
// glab api emits raw NDJSON; unlike gh api it has no -q selector.
const parseMember = cfg.cli === 'glab' ? (await import('../lib/streamJsonParser.js')).safeParse : null;
@@ -403,7 +434,7 @@ const FORGE_ISSUE_CONFIG = {
// never an issue author, so `--author <org>` is guaranteed to match nothing.
resolveOwner: async (repoPath, env) => {
const r = await runCli('gh', ['repo', 'view', '--json', 'owner,isInOrganization'], repoPath, env);
- if (r.code !== 0) return { error: 'gh-unavailable' };
+ if (r.code !== 0) return { error: 'gh-unavailable', detail: redactCliDetail(r.stderr) };
let parsed;
try {
parsed = JSON.parse(r.stdout || '{}');
@@ -480,8 +511,8 @@ const FORGE_ISSUE_CONFIG = {
// the self-assignee retry check. It is transient if glab is unauthenticated
// or unreachable.
resolveSelf: async (repoPath, env) => {
- const { login, error } = await resolveAuthenticatedLogin('glab', GLAB_SELF_LOGIN_ARGS, repoPath, env);
- return error ? { error } : { author: login };
+ const { login, error, detail } = await resolveAuthenticatedLogin('glab', GLAB_SELF_LOGIN_ARGS, repoPath, env);
+ return error ? { error, detail } : { author: login };
},
// `collaborators` mode: you + every project member. `members/all` (not
// `members`) so members INHERITED from the parent group/subgroup count —
@@ -549,8 +580,8 @@ async function detectForgeIssues(forgeKey, app, { issueAuthorFilter = 'self', is
// `remedy` rides along when the probe named a fault that won't self-clear (a
// permission the token doesn't have), so the on-demand toast can print the way
// out instead of "try again shortly".
- const transient = (reason, remedy = null) => ({
- actionable: false, count: 0, cli: cfg.cli, reason, remedy, transient: true
+ const transient = (reason, remedy = null, detail = null) => ({
+ actionable: false, count: 0, cli: cfg.cli, reason, remedy, detail, transient: true
});
const args = [...cfg.listArgs];
@@ -572,13 +603,13 @@ async function detectForgeIssues(forgeKey, app, { issueAuthorFilter = 'self', is
if (issueAuthorFilter === 'any') {
// no --author filter
} else if (issueAuthorFilter === 'collaborators') {
- const { logins, error, remedy } = await resolveTrustedLogins(cfg, repoPath, env);
- if (error) return transient(error, remedy);
+ const { logins, error, remedy, detail } = await resolveTrustedLogins(cfg, repoPath, env);
+ if (error) return transient(error, remedy, detail);
trustedLogins = logins;
authorApplied = true;
} else if (issueAuthorFilter === 'owner') {
- const { owner, isOrg, error } = await cfg.resolveOwner(repoPath, env);
- if (error) return transient(error);
+ const { owner, isOrg, error, detail } = await cfg.resolveOwner(repoPath, env);
+ if (error) return transient(error, null, detail);
if (isOrg) {
// The owner filter resolved to a non-authoring owner (a GitHub ORG or a
// GitLab GROUP), which can never be an issue author — `--author <owner>` is
@@ -592,8 +623,8 @@ async function detectForgeIssues(forgeKey, app, { issueAuthorFilter = 'self', is
args.push('--author', owner);
authorApplied = true;
} else {
- const { author, error } = await cfg.resolveSelf(repoPath, env);
- if (error) return transient(error);
+ const { author, error, detail } = await cfg.resolveSelf(repoPath, env);
+ if (error) return transient(error, null, detail);
args.push('--author', author);
authorApplied = true;
}
@@ -604,7 +635,7 @@ async function detectForgeIssues(forgeKey, app, { issueAuthorFilter = 'self', is
let listingTruncated = false;
const listIssues = async (extraArgs = []) => {
const res = await runCli(cfg.cli, [...args, ...extraArgs], repoPath, env);
- if (res.code !== 0) return { error: cfg.listFail };
+ if (res.code !== 0) return { error: cfg.listFail, detail: redactCliDetail(res.stderr) };
let parsed;
try {
parsed = JSON.parse(res.stdout || '[]');
@@ -633,13 +664,13 @@ async function detectForgeIssues(forgeKey, app, { issueAuthorFilter = 'self', is
const merged = new Map();
for (const login of queried) {
const out = await listIssues(['--author', login]);
- if (out.error) return transient(out.error);
+ if (out.error) return transient(out.error, null, out.detail);
for (const issue of out.issues) merged.set(issue.number, issue);
}
issues = [...merged.values()];
} else {
const out = await listIssues();
- if (out.error) return transient(out.error);
+ if (out.error) return transient(out.error, null, out.detail);
issues = out.issues;
}
@@ -693,7 +724,7 @@ async function detectForgeIssues(forgeKey, app, { issueAuthorFilter = 'self', is
? resolveAuthenticatedLogin(cfg.cli, cfg.selfLoginArgs, repoPath, env)
: Promise.resolve({ login: null })
]);
- if (currentLoginResult.error) return transient(currentLoginResult.error);
+ if (currentLoginResult.error) return transient(currentLoginResult.error, null, currentLoginResult.detail);
const currentLogin = currentLoginResult.login || null;
const total = issues.length;
// How many of the OPEN issues were skipped only because a claim/PR is already
diff --git a/server/services/perpetualWork.test.js b/server/services/perpetualWork.test.js
index c74e1354f9..3176629674 100644
--- a/server/services/perpetualWork.test.js
+++ b/server/services/perpetualWork.test.js
@@ -29,29 +29,58 @@ import {
getWorkDetector,
hasWorkDetector,
NON_ACTIONABLE_ISSUE_LABELS,
- EPIC_DECOMPOSED_LABEL
+ EPIC_DECOMPOSED_LABEL,
+ CLI_TIMEOUT_MS
} from './perpetualWork.js';
-// A fake child process that emits canned stdout then closes — enough for the
-// best-effort runCli() in perpetualWork.js (stdout/close/error + kill).
-function fakeChild(stdout, code = 0) {
+// 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;
+}
+
// Route spawn calls to canned output by command + first arg.
function routeSpawn(routes) {
spawn.mockImplementation((cmd, args = []) => {
const key = `${cmd} ${args[0] || ''}`;
const r = routes[key] ?? (key === 'gh api' ? { stdout: 'alice\n' } : undefined);
- return fakeChild(r?.stdout ?? '', r?.code ?? 0);
+ return fakeChild(r?.stdout ?? '', r?.code ?? 0, r?.stderr ?? '');
});
}
@@ -481,6 +510,55 @@ describe('perpetualWork', () => {
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: [] }]) },
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 4a4e60fc56..1a5626f8b4 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -619,6 +619,51 @@ export async function getPerpetualParkInfo(taskType, appId = null) {
};
}
+/**
+ * Stamp (or clear) the perpetual work gate's escalated probe-failure diagnostic
+ * onto the task's schedule record — ALONGSIDE the park fields, never instead of
+ * them, because a stall means the gate is skipping WITHOUT parking (the drain
+ * keeps ticking; there is no park record to hang the reason on otherwise). This
+ * is what lets the Schedule tab render "probe failing — gh: <reason>" instead of
+ * an apparently-healthy armed schedule while a broken forge CLI silently skips
+ * every evaluation (#7551). Survives a process restart the same way a park does.
+ *
+ * `stall: null` clears it — a probe that stops being transient (recovers,
+ * dispatches, or reaches a definitive park) means whatever was stuck has
+ * cleared, so applyPerpetualWorkGate clears this on every non-escalated path.
+ */
+export async function recordPerpetualStall(taskType, appId = null, stall = null) {
+ return updateSchedule(async (schedule) => {
+ const record = ensureExecutionRecord(schedule, taskType, appId);
+ if (!stall) {
+ if (!('stall' in record)) return { result: null, changed: false };
+ delete record.stall;
+ return { result: null, changed: true };
+ }
+ record.stall = {
+ cli: stall.cli || null,
+ reason: stall.reason || null,
+ detail: stall.detail || null,
+ consecutive: Number.isFinite(stall.consecutive) ? stall.consecutive : 0,
+ at: new Date().toISOString()
+ };
+ return { result: null, changed: true };
+ });
+}
+
+/**
+ * First still-relevant stall diagnostic across a perpetual task's per-app (and
+ * global) execution records. Unlike a park, a stall can coexist with a
+ * currently-draining task (the gate skips without parking), so the UI needs its
+ * own signal independent of aggregatePerpetualParks — mirrors that function's
+ * per-app-then-global scan order.
+ */
+function aggregatePerpetualStall(execution) {
+ const appRecords = Object.values(execution?.perApp || {});
+ const stalledApp = appRecords.find((rec) => rec?.stall);
+ return stalledApp?.stall || execution?.stall || null;
+}
+
/**
* Is this type+app parked with an UNEXPIRED `parkedUntil`?
*
@@ -1453,7 +1498,12 @@ export async function getScheduleStatus() {
parkedAppCount: parks.parkedAppCount,
trackedAppCount: parks.trackedAppCount,
nextRecheckAt: parks.soonestParkAt === null ? null : new Date(parks.soonestParkAt).toISOString(),
- parkReason: parks.parkReason
+ parkReason: parks.parkReason,
+ // A stall means the probe (e.g. gh/glab) has failed several evaluations
+ // in a row WITHOUT parking — the drain keeps ticking, so it can be
+ // present at the same time `globalParked`/`parkedAppCount` read "not
+ // parked". Null when the probe is healthy.
+ stall: aggregatePerpetualStall(execution)
};
}
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index c2b4f0b286..96080e071e 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -136,6 +136,7 @@ import {
parkPerpetual,
resetPerpetualForManualRun,
getPerpetualParkInfo,
+ recordPerpetualStall,
isPerpetualParkActive,
getPerpetualDrainState,
recordPerpetualDispatch,
@@ -3378,6 +3379,49 @@ describe('taskSchedule', () => {
})
})
+ // The escalated-stall diagnostic (#7551): a perpetual gate that skips
+ // WITHOUT parking (a broken forge CLI) has no park record to hang its
+ // reason on, so it needs its own persisted channel — one that survives a
+ // process restart the same way a park does, and that coexists with a
+ // "draining" (not parked) status.
+ describe('recordPerpetualStall + getScheduleStatus stall surfacing', () => {
+ it('stamps a stall on the per-app record without touching the park fields', async () => {
+ mockSchedule({
+ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
+ executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0 } } } }
+ })
+ await recordPerpetualStall('claim-issue', 'app-1', { cli: 'gh', reason: 'gh-list-failed', detail: 'gh: authentication failed', consecutive: 3 })
+ const status = await getScheduleStatus()
+ const p = status.tasks['claim-issue'].perpetualStatus
+ expect(p.stall).toMatchObject({ cli: 'gh', reason: 'gh-list-failed', detail: 'gh: authentication failed', consecutive: 3 })
+ expect(p.globalParked).toBe(false)
+ expect(p.parkedAppCount).toBe(0)
+ })
+
+ it('clears the stall when recorded with a null verdict', async () => {
+ mockSchedule({
+ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
+ executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0 } } } }
+ })
+ await recordPerpetualStall('claim-issue', 'app-1', { cli: 'gh', reason: 'gh-list-failed', consecutive: 3 })
+ await recordPerpetualStall('claim-issue', 'app-1', null)
+ const status = await getScheduleStatus()
+ expect(status.tasks['claim-issue'].perpetualStatus.stall).toBeNull()
+ })
+
+ it('survives being re-read as if from a process restart (persisted, not in-memory)', async () => {
+ mockSchedule({
+ tasks: { 'claim-issue': { type: 'on-demand', perpetual: true, enabled: true } },
+ executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0 } } } }
+ })
+ await recordPerpetualStall('claim-issue', 'app-1', { cli: 'gh', reason: 'gh-list-failed', consecutive: 5 })
+ // A fresh getScheduleStatus() call re-reads the persisted schedule from
+ // scratch rather than any in-process cache, standing in for a restart.
+ const status = await getScheduleStatus()
+ expect(status.tasks['claim-issue'].perpetualStatus.stall).toMatchObject({ consecutive: 5 })
+ })
+ })
+
// getScheduleStatus (UI rollup) and getUpcomingTasks (daemon wake-up) both
// project the shared aggregatePerpetualParks rollup. These fixtures pin them
// to the SAME park semantics — including the global-record inclusion rule