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: block a pr-reviewer stage that produces no output instead of re-spawning it (#6124)

Adam Eivyecb28302dfd6
diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.js
index 5c7cbb648b..a7dcf43343 100644
--- a/server/services/agentErrorAnalysis.js
+++ b/server/services/agentErrorAnalysis.js
@@ -1386,6 +1386,24 @@ export async function maybeCreateInvestigationTask(agentId, task, analysis) {
* }}
*/
export function resolveFailedTaskDecision(task, errorAnalysis, { agentId = null, now = Date.now() } = {}) {
+ // A PERMANENT failure (#6124) re-fails identically on every re-dispatch — a
+ // pipeline stage whose agent finished with no parseable output has nothing a
+ // retry could read differently. Block on the FIRST occurrence, ahead of the
+ // actionable branch, and file NO investigation task: an investigation agent
+ // is another unbounded spawn against a cause the block already names.
+ if (errorAnalysis?.permanent) {
+ return {
+ status: 'blocked',
+ investigationAnalysis: null,
+ metadataUpdates: {
+ failureCount: (Number(task.metadata?.failureCount) || 0) + 1,
+ lastErrorCategory: errorAnalysis.category || 'unknown',
+ blockedReason: errorAnalysis.message || 'The run failed permanently and will not be retried',
+ blockedCategory: errorAnalysis.category || 'permanent-failure'
+ }
+ };
+ }
+
// Actionable errors get blocked immediately. The investigation task (created
// by the wrapper unless the failure is an API-access error) gets the original
// analysis verbatim.
@@ -1517,7 +1535,10 @@ export async function resolveFailedTaskUpdate(task, errorAnalysis, agentId, now
emitLog('warn', `🚫 Task ${task.id} blocked after ${failureCount} failures (${lastErrorCategory})`, {
taskId: task.id, failureCount, category: lastErrorCategory
});
- await maybeCreateInvestigationTask(agentId, task, decision.investigationAnalysis);
+ // A null analysis is the permanent-failure branch's explicit "do not
+ // investigate" — see resolveFailedTaskDecision. Every other blocked path
+ // supplies one.
+ if (decision.investigationAnalysis) await maybeCreateInvestigationTask(agentId, task, decision.investigationAnalysis);
const at = new Date(now).toISOString();
return {
status: 'blocked',
diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.js
index 8c1594ccfd..054a7a1739 100644
--- a/server/services/agentErrorAnalysis.test.js
+++ b/server/services/agentErrorAnalysis.test.js
@@ -473,6 +473,35 @@ describe('resolveFailedTaskDecision', () => {
});
+ // #6124: an empty pr-reviewer stage burned MAX_TASK_RETRIES spawns and then
+ // regenerated, because "the agent wrote nothing" was classified as an ordinary
+ // retryable failure. A permanent failure re-fails identically, so it blocks now.
+ describe('permanent failures', () => {
+ const noOutput = {
+ actionable: false,
+ permanent: true,
+ category: 'stage-produced-no-output',
+ message: 'The pr-reviewer eligibility stage agent finished without writing any parseable output',
+ };
+
+ it('blocks on the FIRST failure and files no investigation task', () => {
+ const decision = resolveFailedTaskDecision(task(), noOutput, { agentId: 'agent-z', now: HOLD_NOW });
+ expect(decision.status).toBe('blocked');
+ expect(decision.investigationAnalysis).toBeNull();
+ expect(decision.metadataUpdates.failureCount).toBe(1);
+ expect(decision.metadataUpdates.blockedCategory).toBe('stage-produced-no-output');
+ expect(decision.metadataUpdates.blockedReason).toBe(noOutput.message);
+ // No retry hold: there is no retry to release.
+ expect(decision.metadataUpdates.retryPendingCleanup).toBeUndefined();
+ });
+
+ it('outranks the actionable branch so no investigation agent is spawned either', () => {
+ const decision = resolveFailedTaskDecision(task(), { ...noOutput, actionable: true });
+ expect(decision.status).toBe('blocked');
+ expect(decision.investigationAnalysis).toBeNull();
+ });
+ });
+
describe('non-actionable errors with retry tracking', () => {
// NOT `pending` (#3373): the retry is HELD non-spawnable — `in_progress` plus
// the hold marker — until `releaseRetryHold` writes its resume pointer.
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index d05d5ade93..529fd48b2c 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -1006,12 +1006,28 @@ export async function finalizeAgent({
task.metadata = { ...task.metadata, ...hookMetadata };
}
const hookRejected = !terminatedByUser && hookResult?.ran && hookOutcome?.accepted === false;
- if (hookRejected && success) {
+ // A PERMANENT hook rejection (#6124) — the stage produced no parseable output
+ // at all — re-fails identically on every retry, so it blocks instead of
+ // burning MAX_TASK_RETRIES spawns and (for a pipeline whose generator keys its
+ // dedup on a live task) re-generating behind them. Honoured only when the run
+ // named no other cause: an exit-0 run, or a failure whose category is the
+ // `unknown` that an empty run produces. A run that failed for a NAMED reason
+ // (rate-limit, auth-error, a killed provider) keeps its ordinary retries —
+ // that output is missing because the environment misbehaved, not because the
+ // stage can never produce one.
+ const causeNamed = !success && errorAnalysis?.category && errorAnalysis.category !== 'unknown';
+ const hookPermanent = hookRejected && hookOutcome?.permanent === true && !causeNamed;
+ // When the run had already failed, `taskUpdate` holds its retry decision. Only
+ // escalate a decision that is still retrying — a task this run already blocked
+ // is terminal, and re-resolving it would file a second investigation task.
+ const escalatePermanent = hookPermanent && !success && taskUpdate?.status !== 'blocked';
+ if (hookRejected && (success || escalatePermanent)) {
success = false;
errorAnalysis = {
category: hookOutcome.reason || 'output-hook-rejected',
message: hookOutcome.message || 'The scheduled task output was rejected by its validation hook',
actionable: false,
+ ...(hookPermanent && { permanent: true }),
origin: 'task-output-hook',
};
taskUpdate = await resolveFailedTaskUpdate(task, errorAnalysis, agentId);
diff --git a/server/services/agentFinalization.outputHooks.test.js b/server/services/agentFinalization.outputHooks.test.js
index 621af91af1..1a73f08e5c 100644
--- a/server/services/agentFinalization.outputHooks.test.js
+++ b/server/services/agentFinalization.outputHooks.test.js
@@ -38,6 +38,7 @@ import {
const __dirname = dirname(fileURLToPath(import.meta.url));
const MANAGEMENT_SOURCE = readFileSync(join(__dirname, 'agentManagement.js'), 'utf8');
const LIFECYCLE_SOURCE = readFileSync(join(__dirname, 'agentLifecycle.js'), 'utf8');
+const FINALIZATION_SOURCE = readFileSync(join(__dirname, 'agentFinalization.js'), 'utf8');
const TASK = {
id: 'sys-example',
taskType: 'internal',
@@ -222,3 +223,31 @@ describe('recovery path wiring (#3182)', () => {
expect(body.indexOf('dispatchRecoveredTaskOutputHook({')).toBeLessThan(body.indexOf('await completeAgent(agentId'));
});
});
+
+// #6124: the escalation the old `hookRejected && success` guard could not reach.
+// The pr-reviewer stage that produced no output exited NON-zero with no captured
+// error, so the run was already `success === false` and the permanent verdict
+// never applied — the task consumed its retries and the pipeline re-spawned.
+describe('permanent output-hook rejection (#6124)', () => {
+ const block = (() => {
+ const start = FINALIZATION_SOURCE.indexOf('const hookRejected = !terminatedByUser');
+ return FINALIZATION_SOURCE.slice(start, FINALIZATION_SOURCE.indexOf('const validationPassed = await evaluateSuccessCriteria', start));
+ })();
+
+ it('escalates a permanent rejection on a run that had ALREADY failed', () => {
+ expect(block).toContain("hookOutcome?.permanent === true");
+ expect(block).toContain('if (hookRejected && (success || escalatePermanent)) {');
+ expect(block).toContain('...(hookPermanent && { permanent: true })');
+ });
+
+ it('leaves a NAMED failure cause on its ordinary retry path', () => {
+ // A rate-limited or unauthenticated run also writes no output; blocking it
+ // permanently would strand work that a retry would have completed.
+ expect(block).toContain("errorAnalysis.category !== 'unknown'");
+ expect(block).toContain('&& !causeNamed');
+ });
+
+ it('never re-resolves a decision that already blocked (no duplicate investigation task)', () => {
+ expect(block).toContain("taskUpdate?.status !== 'blocked'");
+ });
+});
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 544df54f86..ce5b149e0f 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -2053,9 +2053,23 @@ async function findActiveSecurityScanTask(appId, scanKey) {
* hook's strict envelope check) is scoped to that one PR by construction rather
* than by a prompt asking the agent to ignore the rest.
*/
-async function runPrReviewerSecurityPreflight(taskType, app, metadata, targetPullRequest = null) {
+async function runPrReviewerSecurityPreflight(taskType, app, metadata, targetPullRequest = null, taskSchedule = null) {
if (taskType !== 'pr-reviewer') return { skipped: false };
+ // A churn park has to be a STOP, not just a log line (#6124). pr-reviewer runs
+ // on the ON_DEMAND cadence, and `shouldRunTask` only reads `parkedUntil` on a
+ // `perpetual` interval — so the park `observeAgentChurn` stamps when a stage
+ // loops ("parked ${type} so the loop stops burning quota") gated nothing, and
+ // the drain regenerated a fresh task seconds later. Ask here, the one place
+ // every pr-reviewer run is built, and ask BEFORE the security scan so a parked
+ // type does not keep paying for the preflight it is only going to discard.
+ // A human "Run" is unaffected: applyOnDemandRunResets clears the park for a
+ // USER-origin request before it reaches generation.
+ if (taskSchedule && await taskSchedule.isPerpetualParkActive(taskType, app.id)) {
+ emitLog('info', `Skipping pr-reviewer for ${app.name}: parked until its recheck cadence`, { appId: app.id, analysisType: taskType });
+ return { skipped: true, reason: 'parked' };
+ }
+
const stages = metadata.pipeline?.stages;
const securityStage = stages?.[0];
const nextStage = stages?.[1];
@@ -2811,7 +2825,7 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st
if (taskType === 'pr-reviewer') ensurePrReviewerPipeline(metadata);
initializePipelineMetadata(metadata);
- const securityPreflight = await runPrReviewerSecurityPreflight(taskType, app, metadata, targetPullRequest);
+ const securityPreflight = await runPrReviewerSecurityPreflight(taskType, app, metadata, targetPullRequest, taskSchedule);
if (securityPreflight.skipped) return null;
if (!skipPreconditions && shouldSkipForPrecondition(metadata, app, taskType)) return null;
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index 6ec29228e7..1d524cc9af 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -1571,7 +1571,7 @@ describe('pr-reviewer security preflight wiring', () => {
it('runs the direct preflight before stage gates and resolves the next-stage prompt', () => {
const start = GEN_SRC.indexOf('export async function generateManagedAppImprovementTaskForType');
const body = GEN_SRC.slice(start, GEN_SRC.indexOf('return task;', start));
- const preflightAt = body.indexOf('runPrReviewerSecurityPreflight(taskType, app, metadata, targetPullRequest)');
+ const preflightAt = body.indexOf('runPrReviewerSecurityPreflight(taskType, app, metadata, targetPullRequest, taskSchedule)');
const preconditionAt = body.indexOf('shouldSkipForPrecondition(metadata, app, taskType)');
const promptAt = body.indexOf('getStagePrompt(taskType, currentStageIndex)');
@@ -1587,6 +1587,21 @@ describe('pr-reviewer security preflight wiring', () => {
expect(GEN_SRC).toContain('securityScanFingerprint');
});
+ // #6124: observeAgentChurn parks pr-reviewer, but pr-reviewer runs ON_DEMAND
+ // and shouldRunTask only reads `parkedUntil` on a perpetual interval — so the
+ // park logged "the loop stops burning quota" while the drain regenerated a
+ // fresh task every ~15s. The preflight is the one place every run is built.
+ it('lets an active churn park stop the run before the scan is paid for', () => {
+ const start = GEN_SRC.indexOf('async function runPrReviewerSecurityPreflight');
+ const body = GEN_SRC.slice(start, GEN_SRC.indexOf('\n return { skipped: false, scan };', start));
+ const parkAt = body.indexOf('taskSchedule.isPerpetualParkActive(taskType, app.id)');
+ const scanAt = body.indexOf('runPrReviewerSecurityScan(');
+
+ expect(parkAt, 'a parked pr-reviewer must not regenerate').toBeGreaterThan(-1);
+ expect(parkAt).toBeLessThan(scanAt);
+ expect(body).toContain("return { skipped: true, reason: 'parked' };");
+ });
+
it('narrows a targeted run before the fingerprint, the scan, and the stage-2 allowlist', () => {
const start = GEN_SRC.indexOf('async function runPrReviewerSecurityPreflight');
const body = GEN_SRC.slice(start, GEN_SRC.indexOf('\n return { skipped: false, scan };', start));
diff --git a/server/services/prReviewerPipeline.js b/server/services/prReviewerPipeline.js
index 2726983449..b63171cb7b 100644
--- a/server/services/prReviewerPipeline.js
+++ b/server/services/prReviewerPipeline.js
@@ -138,6 +138,29 @@ function invalidEligibility(reason, message = 'The eligibility gate did not retu
return { action: 'no-op', accepted: false, reason, message };
}
+/**
+ * A stage agent that finished having written NO parseable deliverable at all
+ * (#6124). This is NOT the same as a payload the validator rejected: there is
+ * nothing to re-read, so the identical stage re-dispatches into the identical
+ * empty result — the shape that burned ~20 spawns in five minutes while the
+ * churn park logged that it had stopped the loop.
+ *
+ * `permanent: true` is the posture `resolvePublicReviewAgentProvider` already
+ * uses when no provider can enforce the stage's contract: surface a blocked
+ * task carrying the reason instead of retrying it. Finalization only honours
+ * the flag when the run named no other cause (see agentFinalization), so a
+ * rate-limited or unauthenticated run still gets its ordinary retries.
+ */
+function stageProducedNoOutput(role) {
+ return {
+ action: 'no-op',
+ accepted: false,
+ permanent: true,
+ reason: 'stage-produced-no-output',
+ message: `The pr-reviewer ${role || 'pipeline'} stage agent finished without writing any parseable output`,
+ };
+}
+
function processEligibilityTaskOutput({ appId, success, payload, task } = {}) {
if (!appId) return invalidEligibility('missing-app');
if (!success) return invalidEligibility('agent-failed', 'The eligibility gate agent failed before returning a decision');
@@ -226,6 +249,11 @@ export function isTaskOutputPayload(payload) {
export async function processTaskOutput(args = {}, deps) {
const role = prReviewerStageRole(args.task?.metadata?.pipeline?.stages?.[args.task?.metadata?.pipeline?.currentStage ?? 0]);
+ // Checked before the role switch: every stage of this pipeline delivers its
+ // result as a parsed sentinel payload, so "no payload at all" is the same
+ // permanent failure whichever stage produced it, and answering it here keeps
+ // the per-role validators about the CONTENT of a payload that exists.
+ if (args.payload == null) return stageProducedNoOutput(role);
if (role === 'eligibility') return processEligibilityTaskOutput(args);
if (role === 'actions') return processIssueWatcherOutput({ ...args, requireEligibilityFacts: true }, deps);
return invalidEligibility('unsupported-pr-review-stage');
diff --git a/server/services/prReviewerPipeline.test.js b/server/services/prReviewerPipeline.test.js
index b71b5d2354..fdf16306c9 100644
--- a/server/services/prReviewerPipeline.test.js
+++ b/server/services/prReviewerPipeline.test.js
@@ -279,6 +279,47 @@ describe('pr-reviewer output routing', () => {
}, { execGh: expect.any(Function) });
});
+ it('fails a stage PERMANENTLY when its agent wrote no parseable output', async () => {
+ // #6124: an empty run used to be retried through a fresh task id, so the
+ // stage re-spawned ~20 times in five minutes while the churn park only logged.
+ await expect(processTaskOutput({ appId: 'app-example', success: false, payload: null, task: eligibilityTask() }))
+ .resolves.toEqual({
+ action: 'no-op',
+ accepted: false,
+ permanent: true,
+ reason: 'stage-produced-no-output',
+ message: 'The pr-reviewer eligibility stage agent finished without writing any parseable output',
+ });
+ });
+
+ it('fails an exit-zero actions stage permanently too, without consulting issue-watcher', async () => {
+ const task = {
+ metadata: {
+ pipeline: {
+ currentStage: 2,
+ stages: [{ role: 'security' }, { role: 'eligibility' }, { role: 'actions' }],
+ },
+ },
+ };
+
+ issueWatcherMock.processTaskOutput.mockClear();
+ const outcome = await processTaskOutput({ appId: 'app-example', success: true, payload: null, task }, { execGh: vi.fn() });
+
+ expect(outcome).toMatchObject({ accepted: false, permanent: true, reason: 'stage-produced-no-output' });
+ expect(issueWatcherMock.processTaskOutput).not.toHaveBeenCalled();
+ });
+
+ it('keeps a RETRYABLE rejection for a payload that arrived but failed validation', async () => {
+ // Only "no payload at all" is permanent — a malformed envelope may parse on
+ // a re-run, so it must not block the task on its first failure.
+ const outcome = await processTaskOutput({
+ appId: 'app-example', success: true, payload: { eligible: true, decisions: 'nope' }, task: eligibilityTask(),
+ });
+
+ expect(outcome.accepted).toBe(false);
+ expect(outcome.permanent).toBeUndefined();
+ });
+
it('recognizes both the binary gate envelope and the action envelope', () => {
expect(isEligibilityPayload(decisionPayload())).toBe(true);
expect(isTaskOutputPayload(decisionPayload())).toBe(true);