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

refactor: resolve finalizeAgent's outcome through one pure verdict resolver (#9645)

Adam Eivyf11300b37442
diff --git a/server/lib/README.md b/server/lib/README.md
index 45e2195582..6d0732ad38 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -56,6 +56,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `spriteChromaKey.js` | Chroma-key selection color math (`CHROMA_KEYS`, `CHROMA_KEY_HEXES`, `DEFAULT_CHROMA_KEY`, hue-distance picking). Pure color math, no image I/O — that lives in `services/sprites/normalize.js`. |
| `spriteAnimationTracks.js` | The animation-track registry (`ANIMATION_TRACKS`, `WALK_TRACK`, `TRACK_BOUND_TRIPLES`, `AUTHORED_TRACK_FIELDS`) — a zero-import table of per-track frame/fps bounds. |
| `spriteAnimationTrackStore.js` | The EFFECTIVE track table — compiled built-ins plus the user-defined store read from one small JSON config, so sprite schemas stay module-load constants rather than lazily-built. |
+| `agentFinalVerdict.js` | `resolveAgentFinalVerdict` — the completion outcome `finalizeAgent` persists, as one pure function of its evidence: the drift > PR > goal-fidelity > output-hook > reported precedence ladder, returned as a frozen `{ source, success, errorAnalysis, error, completionReason }`. A permanent hook rejection escalates an already-failed run only through the caller's pure `failureIsTerminal` predicate, so the side-effecting retry resolution runs once. |
| `agentOutcome.js` | Is a completed CoS agent record an OUTCOME, or a HANDOFF to its own continuation? `isAgentHandoff(agent)` — `result.resumed === true`, what `resumeAgent`/`relaunchAgent` stamps when it retires a record and requeues the SAME task, typically because the user swapped providers after a usage limit. Every consumer that read `result.success` as the verdict booked a phantom failure per swap — a red history card, a failed task in the daily report and weekly digest, a dented success rate, a quota-burn denial recorded against "Relaunched by user", a feature agent flipped to `error` — so the rule task-learning already applied lives here once. Reads only `result`, so `completeAgent`'s stats writer can ask it before the record exists. Keyed on a field `resumeAgent` has always written, so archived relaunches reclassify retroactively with no migration. Also carries `agentHandoffReason(agent)` — `metadata.pauseReason` when a continuation was queued, else `result.error`, so an abandoned run is not captioned as a deliberate provider swap — and `isQueuedContinuation(agent)`, the narrower check for a caller about to SKIP its own completion handling because it expects a continuation run to fire it instead: `isAgentHandoff` alone is not proof a continuation exists (a stranded pause retirement also stamps `resumed: true` with nothing requeued), so use this one there. `client/src/lib/agentOutcome.js` re-exports this file rather than copying it. |
| `cosAgentCompletionOrder.js` | Wire format + projection rule for the CoS archive completion-order sidecar (`data/cos/agents/index.order.json`). `projectArchivedAgent` reduces an archived record to its completion timestamp plus a completed / still-needs-feedback bitfield; `encodeCompletionOrder` / `decodeCompletionOrder` round-trip the versioned document, decoding anything unrecognized as empty so the readers repair it by re-reading the day. Shared by the runtime index and the one-shot backfill migration so the two cannot drift. |
| `cosAgentFeedback.js` | Pure shared eligibility, rating, update-target, and archive-locator predicates for durable CoS feedback actions; mirrored to the client so the queue and Agents tab use the server contract. |
diff --git a/server/lib/agentFinalVerdict.js b/server/lib/agentFinalVerdict.js
new file mode 100644
index 0000000000..f6594e21ee
--- /dev/null
+++ b/server/lib/agentFinalVerdict.js
@@ -0,0 +1,182 @@
+/**
+ * Agent final verdict (#9645)
+ *
+ * The completion outcome `finalizeAgent` (services/agentFinalization.js)
+ * persists, as one pure function of the evidence it gathered: the agent's
+ * reported result, primary-checkout drift, the PR claim check, the goal-fidelity
+ * review, and the programmatic-I/O output hook. Kept out of the finalization
+ * module so the precedence ladder can be read — and tested — without the
+ * agent-state graph that module drags in.
+ */
+
+import { PR_MISSING_CATEGORY } from './prDisposition.js';
+import { PRIMARY_CHECKOUT_MUTATED_ESCALATION, PRIMARY_CHECKOUT_MUTATED_REASON } from './primaryCheckoutGuard.js';
+import { GOAL_FIDELITY_CATEGORY, formatGoalFidelitySummary, goalFidelityHoldsRun } from './goalFidelity.js';
+
+/**
+ * The `errorAnalysis` shape for a detected branch-jack. `actionable` because a
+ * human has to decide whether to discard the primary's commits — a retry cannot
+ * repair this, and silently retrying would leave the mutated checkout in place.
+ */
+function primaryCheckoutDriftAnalysis(drift) {
+ return {
+ category: drift.category,
+ // Observed by the spawner from the checkout's own git state, not scraped out
+ // of the transcript — the same provenance rule the structural analyses use.
+ origin: 'runner',
+ completionReason: PRIMARY_CHECKOUT_MUTATED_REASON,
+ actionable: true,
+ escalation: PRIMARY_CHECKOUT_MUTATED_ESCALATION,
+ message: drift.message,
+ suggestedFix: drift.suggestedFix
+ };
+}
+
+/**
+ * The `errorAnalysis` shape for a failed PR verification. Non-actionable so the
+ * task RETRIES (a re-run can open the missing PR, or find the forge back) rather
+ * than blocking on a first miss — `resolveFailedTaskDecision` still blocks it
+ * once it has burned its retry budget.
+ */
+function prVerificationAnalysis(verdict) {
+ return {
+ category: verdict.category,
+ message: verdict.message,
+ actionable: false,
+ suggestedFix: verdict.category === PR_MISSING_CATEGORY
+ ? `The branch ${verdict.branch} holds ${verdict.commitsAhead ?? 'unreviewed'} commit(s) but has no open change request. Re-run the task, or open it by hand (\`gh pr create --head ${verdict.branch}\` / \`glab mr create --source-branch ${verdict.branch}\`).`
+ : 'Check the forge probe on the System Health page — the forge CLI could not reach the forge, so the run\'s change request could not be confirmed.'
+ };
+}
+
+/** `errorAnalysis` for a run held by the goal-fidelity gate. */
+function goalFidelityAnalysis(review) {
+ const named = [...(review.missing || []), ...(review.unrequested || [])];
+ return {
+ category: GOAL_FIDELITY_CATEGORY,
+ message: `${formatGoalFidelitySummary(review)} — the diff does not deliver the task's stated objective`,
+ actionable: false,
+ origin: 'goal-fidelity-review',
+ suggestedFix: named.length
+ ? `Re-read the task against the change and reconcile: ${named.slice(0, 3).join('; ')}.`
+ : 'Re-read the task against the change: the review found the work does something other than what was asked.',
+ };
+}
+
+/**
+ * The run's outcome as one pure function of the evidence finalize gathered.
+ * Diagnoses apply in a fixed priority — drift > PR > fidelity > hook > the
+ * originally reported error — and each later layer can only replace a verdict
+ * it is eligible to replace:
+ *
+ * - DRIFT overrides only a run that would otherwise have been a success. On a
+ * run that already failed, the original analysis is the better diagnosis;
+ * the branch-jack is on the record via finalize's warn log either way.
+ * - PR replaces any non-drift verdict when the forge could not confirm the
+ * promised change request — a concrete delivery failure.
+ * - FIDELITY can only hold a run that is still a success; re-judging a failed
+ * run against its objective would trade a real cause for a symptom.
+ * - HOOK rejection fails a successful run outright. On an already-failed run
+ * it takes over only when the rejection is PERMANENT (#6124), the run named
+ * no other cause (an `unknown` category), and the prior failure would not
+ * already block the task — a terminal decision keeps its own diagnosis
+ * rather than being re-resolved into a second investigation task. A
+ * non-escalating rejection of an otherwise-undowngraded failure surfaces the
+ * original analysis on the card.
+ *
+ * Callers gate evidence gathering on an earlier layer's answer (fidelity runs
+ * only on a delivered success; the hook is told the judged outcome), so they
+ * call this with the evidence collected so far and omit the rest — an omitted
+ * layer simply does not apply. Returns a frozen verdict; nothing downstream may
+ * amend it.
+ *
+ * @param {object} p
+ * @param {(errorAnalysis: object) => boolean} [p.failureIsTerminal] whether a
+ * failure with this analysis would block the task. Consulted only when a
+ * permanent hook rejection lands on an already-failed run; must be pure.
+ * @returns {Readonly<{source: 'reported'|'drift'|'pr'|'fidelity'|'hook', success: boolean, errorAnalysis: object|null|undefined, error: string|undefined, completionReason: string|undefined}>}
+ */
+export function resolveAgentFinalVerdict({
+ reportedSuccess,
+ errorAnalysis,
+ error,
+ completionReason,
+ terminatedByUser = false,
+ drift = null,
+ prEvidence,
+ fidelityReview = null,
+ hookResult = null,
+ failureIsTerminal = () => false,
+}) {
+ const driftDowngrade = Boolean(drift?.drifted) && reportedSuccess && !terminatedByUser;
+ const prVerdict = prEvidence.completionVerdict;
+ const delivered = driftDowngrade
+ ? {
+ source: 'drift',
+ success: false,
+ errorAnalysis: primaryCheckoutDriftAnalysis(drift),
+ error: drift.message,
+ completionReason: PRIMARY_CHECKOUT_MUTATED_REASON,
+ }
+ : !prEvidence.completionOk
+ ? {
+ source: 'pr',
+ success: false,
+ errorAnalysis: prVerificationAnalysis(prVerdict),
+ error: prVerdict.message,
+ completionReason: prVerdict.category,
+ }
+ : { source: 'reported', success: Boolean(reportedSuccess), errorAnalysis, error, completionReason };
+
+ const fidelityAnalysis = delivered.success && goalFidelityHoldsRun(fidelityReview)
+ ? goalFidelityAnalysis(fidelityReview)
+ : null;
+ const judged = fidelityAnalysis
+ ? {
+ source: 'fidelity',
+ success: false,
+ errorAnalysis: fidelityAnalysis,
+ error: fidelityAnalysis.message,
+ completionReason: GOAL_FIDELITY_CATEGORY,
+ }
+ : delivered;
+
+ const hookOutcome = hookResult?.outcome;
+ const hookRejected = !terminatedByUser && Boolean(hookResult?.ran) && hookOutcome?.accepted === false;
+ if (!hookRejected) return Object.freeze(judged);
+
+ // A PERMANENT rejection — the stage produced no parseable output at all —
+ // re-fails identically on every retry, so it blocks instead of burning
+ // MAX_TASK_RETRIES spawns. Honoured only when the run named no other cause:
+ // a run that failed for a NAMED reason (rate-limit, auth-error, a killed
+ // provider) is missing its output because the environment misbehaved, and
+ // keeps its ordinary retries.
+ const causeNamed = !judged.success && Boolean(judged.errorAnalysis?.category) && judged.errorAnalysis.category !== 'unknown';
+ const hookPermanent = hookOutcome.permanent === true && !causeNamed;
+ if (judged.success || (hookPermanent && !failureIsTerminal(judged.errorAnalysis))) {
+ const analysis = {
+ 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',
+ };
+ return Object.freeze({
+ source: 'hook',
+ success: false,
+ errorAnalysis: analysis,
+ error: analysis.message,
+ completionReason: analysis.category,
+ });
+ }
+ // A rejection on an already-failed run keeps its original diagnosis. Surface
+ // that analysis on the card too, without replacing a prior downgrade.
+ if (judged.source === 'reported') {
+ return Object.freeze({
+ ...judged,
+ error: judged.errorAnalysis?.message || error,
+ completionReason: judged.errorAnalysis?.category || completionReason,
+ });
+ }
+ return Object.freeze(judged);
+}
diff --git a/server/lib/agentFinalVerdict.test.js b/server/lib/agentFinalVerdict.test.js
new file mode 100644
index 0000000000..e6c2aed312
--- /dev/null
+++ b/server/lib/agentFinalVerdict.test.js
@@ -0,0 +1,58 @@
+import { describe, expect, it, vi } from 'vitest';
+import { resolveAgentFinalVerdict } from './agentFinalVerdict.js';
+import { GOAL_FIDELITY_HOLD_VERDICT } from './goalFidelity.js';
+
+// The precedence ladder finalize persists, as a pure function (#9645). Each
+// case is a layer the next one must NOT be able to override, or vice versa.
+describe('resolveAgentFinalVerdict', () => {
+ const PR_OK = { completionOk: true, completionVerdict: { ok: true } };
+ const PR_MISSING = { completionOk: false, completionVerdict: { ok: false, category: 'pr-missing', message: 'No PR', branch: 'b' } };
+ const DRIFT = { drifted: true, category: 'primary-checkout-mutated', message: 'Primary moved' };
+ const HOLD = { verdict: GOAL_FIDELITY_HOLD_VERDICT, missing: ['x'], unrequested: [] };
+ const rejected = (extra = {}) => ({ ran: true, outcome: { accepted: false, reason: 'output-missing', message: 'No output', ...extra } });
+ const resolve = (overrides) => resolveAgentFinalVerdict({
+ reportedSuccess: true, errorAnalysis: null, error: undefined, completionReason: undefined, prEvidence: PR_OK, ...overrides,
+ });
+
+ it('applies drift ahead of a missing PR, and only to an otherwise-successful run', () => {
+ expect(resolve({ drift: DRIFT, prEvidence: PR_MISSING })).toMatchObject({ source: 'drift', success: false, error: 'Primary moved' });
+ expect(resolve({ reportedSuccess: false, errorAnalysis: { category: 'unknown' }, drift: DRIFT }).source).toBe('reported');
+ expect(resolve({ reportedSuccess: false, drift: DRIFT, prEvidence: PR_MISSING })).toMatchObject({ source: 'pr', completionReason: 'pr-missing' });
+ });
+
+ it('lets fidelity hold only a delivered success', () => {
+ expect(resolve({ fidelityReview: HOLD })).toMatchObject({ source: 'fidelity', success: false });
+ expect(resolve({ prEvidence: PR_MISSING, fidelityReview: HOLD }).source).toBe('pr');
+ });
+
+ it('fails a successful run on any hook rejection and returns a frozen verdict', () => {
+ const verdict = resolve({ hookResult: rejected() });
+ expect(verdict).toMatchObject({ source: 'hook', success: false, completionReason: 'output-missing', error: 'No output' });
+ expect(verdict.errorAnalysis.permanent).toBeUndefined();
+ expect(Object.isFrozen(verdict)).toBe(true);
+ });
+
+ it('escalates a permanent rejection of an unnamed failure only while that failure would retry', () => {
+ const failed = { reportedSuccess: false, errorAnalysis: { category: 'unknown', message: 'Exited 1' }, hookResult: rejected({ permanent: true }) };
+ expect(resolve({ ...failed, failureIsTerminal: () => false })).toMatchObject({
+ source: 'hook', errorAnalysis: expect.objectContaining({ permanent: true }),
+ });
+ expect(resolve({ ...failed, failureIsTerminal: () => true })).toMatchObject({
+ source: 'reported', error: 'Exited 1', completionReason: 'unknown',
+ });
+ });
+
+ it('keeps a named cause or a prior downgrade when the hook rejects a failed run', () => {
+ const terminal = vi.fn(() => false);
+ expect(resolve({
+ reportedSuccess: false, errorAnalysis: { category: 'rate-limit', message: 'Later' }, hookResult: rejected({ permanent: true }), failureIsTerminal: terminal,
+ })).toMatchObject({ source: 'reported', completionReason: 'rate-limit', error: 'Later' });
+ expect(terminal).not.toHaveBeenCalled();
+ expect(resolve({ reportedSuccess: false, prEvidence: PR_MISSING, hookResult: rejected() })).toMatchObject({ source: 'pr', error: 'No PR' });
+ });
+
+ it('ignores a hook rejection on a user-terminated run', () => {
+ expect(resolve({ reportedSuccess: false, terminatedByUser: true, error: 'stopped', hookResult: rejected({ permanent: true }) }))
+ .toMatchObject({ source: 'reported', error: 'stopped' });
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index 8c2b395cd0..ee6c5d921e 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -343,6 +343,7 @@ export * from './zipWriter.js';
// === Process execution ===
export * from './agentGuard/index.js';
+export * from './agentFinalVerdict.js';
export * from './agentOutcome.js';
export * from './cosAgentCompletionOrder.js';
export * from './cosAgentFeedback.js';
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index e9860d3833..967ba9626d 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -35,12 +35,12 @@ import { markProviderUsageLimit, markProviderUnavailable } from './providerStatu
import { resolveProviderBench } from '../lib/providerCooldown.js';
import { release } from './executionLanes.js';
import { completeExecution, errorExecution } from './toolStateMachine.js';
-import { resolveFailedTaskUpdate, resolveTypeFailureSignal } from './agentErrorAnalysis.js';
+import { resolveFailedTaskDecision, resolveFailedTaskUpdate, resolveTypeFailureSignal } from './agentErrorAnalysis.js';
+import { resolveAgentFinalVerdict } from '../lib/agentFinalVerdict.js';
import { completeAgentRun } from './agentRunTracking.js';
import { appendRunEvent } from './agentRunEventLog.js';
import { committedDuringRun, runWindowDiff } from '../lib/gitCommitProbe.js';
import {
- GOAL_FIDELITY_CATEGORY,
GOAL_FIDELITY_HOLD_EVENT,
MAX_FIDELITY_DIFF_CHARS,
MAX_OBJECTIVE_CHARS,
@@ -55,7 +55,7 @@ import {
import { formatGoalFidelityFollowUpSummary, goalFidelityFollowUpApplies } from '../lib/goalFidelityFollowUp.js';
import { getGoalFidelityConfig, runLocalGoalFidelityReview } from './codeReview.js';
import { SKIP_LEARNING_VERDICT } from '../lib/learningVerdict.js';
-import { detectPrimaryCheckoutDrift, PRIMARY_CHECKOUT_MUTATED_ESCALATION, PRIMARY_CHECKOUT_MUTATED_REASON } from '../lib/primaryCheckoutGuard.js';
+import { detectPrimaryCheckoutDrift } from '../lib/primaryCheckoutGuard.js';
import { canRunTaskOutputHookWithoutPayload, getTaskOutputPayloadPredicate, isProgrammaticIoTaskType, resolveTaskHookType, declaresNoCommitCriterion, isClaimFlowDispatch } from './taskTypeHooks.js';
import { processAgentCompletion } from './agentCompletion.js';
import { extractFinalSummary, extractSimplifySummaries } from './agentSummaryExtraction.js';
@@ -714,42 +714,6 @@ export async function checkPrimaryCheckoutDrift(agentId) {
return await detectPrimaryCheckoutDrift(baseline, { agentBranch: agent?.metadata?.worktreeBranch || null });
}
-/**
- * The `errorAnalysis` shape for a detected branch-jack. `actionable` because a
- * human has to decide whether to discard the primary's commits — a retry cannot
- * repair this, and silently retrying would leave the mutated checkout in place.
- */
-function primaryCheckoutDriftAnalysis(drift) {
- return {
- category: drift.category,
- // Observed by the spawner from the checkout's own git state, not scraped out
- // of the transcript — the same provenance rule the structural analyses use.
- origin: 'runner',
- completionReason: PRIMARY_CHECKOUT_MUTATED_REASON,
- actionable: true,
- escalation: PRIMARY_CHECKOUT_MUTATED_ESCALATION,
- message: drift.message,
- suggestedFix: drift.suggestedFix
- };
-}
-
-/**
- * The `errorAnalysis` shape for a failed PR verification. Non-actionable so the
- * task RETRIES (a re-run can open the missing PR, or find the forge back) rather
- * than blocking on a first miss — `resolveFailedTaskDecision` still blocks it
- * once it has burned its retry budget.
- */
-function prVerificationAnalysis(verdict) {
- return {
- category: verdict.category,
- message: verdict.message,
- actionable: false,
- suggestedFix: verdict.category === PR_MISSING_CATEGORY
- ? `The branch ${verdict.branch} holds ${verdict.commitsAhead ?? 'unreviewed'} commit(s) but has no open change request. Re-run the task, or open it by hand (\`gh pr create --head ${verdict.branch}\` / \`glab mr create --source-branch ${verdict.branch}\`).`
- : 'Check the forge probe on the System Health page — the forge CLI could not reach the forge, so the run\'s change request could not be confirmed.'
- };
-}
-
/** Resolve requirements independently of the agent's transcript or PR prose. */
async function claimedIssueObjective(workspacePath) {
const branch = await resolveWorkspaceBranch(workspacePath);
@@ -966,20 +930,6 @@ async function evaluateGoalFidelity({ task, workspacePath, startedAt }) {
};
}
-/** `errorAnalysis` for a run held by the goal-fidelity gate. */
-function goalFidelityAnalysis(review) {
- const named = [...(review.missing || []), ...(review.unrequested || [])];
- return {
- category: GOAL_FIDELITY_CATEGORY,
- message: `${formatGoalFidelitySummary(review)} — the diff does not deliver the task's stated objective`,
- actionable: false,
- origin: 'goal-fidelity-review',
- suggestedFix: named.length
- ? `Re-read the task against the change and reconcile: ${named.slice(0, 3).join('; ')}.`
- : 'Re-read the task against the change: the review found the work does something other than what was asked.',
- };
-}
-
/**
* Hard bound on output-hook dispatch (#2727). The hook is only awaited BEFORE
* `completeAgent` so its verdict can be recorded — but `status: 'running'` is what
@@ -1447,42 +1397,22 @@ export async function finalizeAgent({
agentId, taskId: task?.id
});
}
- // A drift downgrade only OVERRIDES a run that would otherwise have been
- // recorded a success. On a run that already failed, the original analysis is
- // the better diagnosis of why it failed, and the branch-jack is already on the
- // record via the warn above — replacing it would trade a real cause for a
- // side effect. Same reason `terminatedByUser` keeps its own verdict.
- const driftDowngrade = drift.drifted && reportedSuccess && !terminatedByUser;
-
- // One accumulator owns every completion write and the caller's cleanup
- // decision. Apply diagnoses in priority order: drift > PR > fidelity > hook
- // > original error. Fidelity and hooks can only replace an eligible verdict.
- // Drift demands repair of the primary checkout even if a PR exists; a
- // missing PR is a concrete delivery failure, ahead of fidelity's judgement
- // about what was built. Keep each diagnosis's card text and reason together.
- const prCompletionVerdict = prEvidence.completionVerdict;
- const verdict = {
- source: 'reported',
- success: reportedSuccess && prEvidence.completionOk && !driftDowngrade,
+ // The run's outcome is one pure resolution over the evidence (see
+ // resolveAgentFinalVerdict for the drift > PR > fidelity > hook > reported
+ // ladder). Fidelity and the output hook are themselves gated on an earlier
+ // layer's answer, so each stage below re-resolves with the evidence gathered
+ // so far rather than amending a shared accumulator.
+ const verdictEvidence = {
+ reportedSuccess,
errorAnalysis: reportedErrorAnalysis,
error,
completionReason,
+ terminatedByUser,
+ drift,
+ prEvidence,
};
- if (driftDowngrade) {
- Object.assign(verdict, {
- source: 'drift',
- errorAnalysis: primaryCheckoutDriftAnalysis(drift),
- error: drift.message,
- completionReason: PRIMARY_CHECKOUT_MUTATED_REASON,
- });
- } else if (!prEvidence.completionOk) {
- Object.assign(verdict, {
- source: 'pr',
- errorAnalysis: prVerificationAnalysis(prCompletionVerdict),
- error: prCompletionVerdict.message,
- completionReason: prCompletionVerdict.category,
- });
- }
+ const deliveredVerdict = resolveAgentFinalVerdict(verdictEvidence);
+ const prCompletionVerdict = prEvidence.completionVerdict;
if (!prEvidence.completionOk) {
emitLog('warn', `⚠️ ${prCompletionVerdict.message} — recording ${agentId} as needs-attention (${prCompletionVerdict.category}) rather than complete`, {
agentId, taskId: task?.id, branch: prCompletionVerdict.branch, category: prCompletionVerdict.category
@@ -1511,7 +1441,7 @@ export async function finalizeAgent({
// the diff probe's git timeouts — it holds the agent's CoS concurrency slot for
// its duration, which is why it is skipped entirely unless the user configured
// a local backend for it.
- const fidelity = verdict.success && !isPrivateSecurityTask(task)
+ const fidelity = deliveredVerdict.success && !isPrivateSecurityTask(task)
? await evaluateGoalFidelity({ task, workspacePath, startedAt: runStartedAt })
.catch(err => {
emitLog('warn', `Goal-fidelity review failed for ${agentId}: ${err.message}`, { agentId });
@@ -1526,16 +1456,7 @@ export async function finalizeAgent({
} else if (fidelity.error) {
emitLog('warn', `Goal-fidelity review returned no verdict for ${agentId}: ${fidelity.error}`, { agentId, taskId: task?.id });
}
- if (fidelityDowngrade) {
- const analysis = goalFidelityAnalysis(fidelity.review);
- Object.assign(verdict, {
- source: 'fidelity',
- success: false,
- errorAnalysis: analysis,
- error: analysis.message,
- completionReason: GOAL_FIDELITY_CATEGORY,
- });
- }
+ const judgedVerdict = resolveAgentFinalVerdict({ ...verdictEvidence, fidelityReview: fidelity.review });
// A finding that lives only in this run's record dies with the agent card
// nobody opened. When the user has configured it, the follow-up files the
// finding on the project's own tracker and/or queues the run that fixes it.
@@ -1579,25 +1500,10 @@ export async function finalizeAgent({
cosEvents.emit(GOAL_FIDELITY_HOLD_EVENT, { agentId, taskId: task?.id, review: fidelity.review });
}
- if (verdict.success) {
+ if (judgedVerdict.success) {
await persistSimplifySummaries(agentId, task, outputBuffer);
}
- const taskType = task?.taskType || 'user';
- let taskUpdate = terminatedByUser
- ? {
- status: 'blocked',
- metadata: {
- ...task.metadata,
- blockedReason: 'Terminated by user',
- blockedCategory: 'user-terminated',
- blockedAt: new Date().toISOString(),
- },
- }
- : verdict.success
- ? { status: 'completed' }
- : await resolveFailedTaskUpdate(task, verdict.errorAnalysis, agentId);
-
// Programmatic-I/O task types (e.g. layered-intelligence) run a deterministic
// post-agent step on the agent's STRUCTURED output — the parsed `.agent-done`
// payload — rather than only handling the completion sentinel. Read + dispatch
@@ -1620,7 +1526,7 @@ export async function finalizeAgent({
// of awaiting here is that the agent still counts against the CoS concurrency
// gate for the hook's duration, so the dispatch is hard-bounded — see
// withOutputHookTimeout.
- let hookResult = await dispatchTaskOutputHookOnce({ agentId, task, success: verdict.success, workspacePath });
+ let hookResult = await dispatchTaskOutputHookOnce({ agentId, task, success: judgedVerdict.success, workspacePath });
// A private assessment's deliverable is the validated, persisted report.
// A skipped, thrown or timed-out hook cannot establish that deliverable,
// even when the CLI exited zero. Keep other task types' existing semantics.
@@ -1643,54 +1549,46 @@ export async function finalizeAgent({
// sees the narrowed input set. An explicit `accepted: false` is a real
// programmatic-output failure even when the agent exited zero; this is the
// fail-closed path for incomplete or contradictory eligibility envelopes.
+ // The patch only travels with a run the hook itself failed or one that
+ // succeeded — any other failure or a user termination is resolved against the
+ // task as it stood before the hook ran, so a retry does not inherit a stage
+ // advance its own run never earned.
const hookOutcome = hookResult?.outcome;
const hookMetadata = hookOutcome?.taskMetadata && typeof hookOutcome.taskMetadata === 'object'
&& !Array.isArray(hookOutcome.taskMetadata)
? hookOutcome.taskMetadata
: null;
+ const preHookTask = hookMetadata ? { ...task } : task;
if (hookMetadata) {
task.metadata = { ...task.metadata, ...hookMetadata };
}
- const hookRejected = !terminatedByUser && hookResult?.ran && hookOutcome?.accepted === false;
- // 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 = !verdict.success && verdict.errorAnalysis?.category && verdict.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 && !verdict.success && taskUpdate?.status !== 'blocked';
- if (hookRejected && (verdict.success || escalatePermanent)) {
- const analysis = {
- 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',
- };
- Object.assign(verdict, {
- source: 'hook',
- success: false,
- errorAnalysis: analysis,
- error: analysis.message || error,
- completionReason: analysis.category || completionReason,
- });
- taskUpdate = await resolveFailedTaskUpdate(task, verdict.errorAnalysis, agentId);
- } else if (hookRejected && verdict.source === 'reported') {
- // A rejection on an already-failed run keeps its original diagnosis.
- // Surface that analysis on the card too, without replacing a prior downgrade.
- verdict.error = verdict.errorAnalysis?.message || error;
- verdict.completionReason = verdict.errorAnalysis?.category || completionReason;
- } else if (hookMetadata && verdict.success && !terminatedByUser) {
- taskUpdate = { ...taskUpdate, metadata: task.metadata };
- }
+
+ // A permanent hook rejection on an already-failed run escalates only while
+ // that failure would still be retried; a task the prior failure would block
+ // is terminal and keeps its own diagnosis. Asked of the PURE retry decision
+ // so the side-effecting resolveFailedTaskUpdate below runs exactly once.
+ const verdict = resolveAgentFinalVerdict({
+ ...verdictEvidence,
+ fidelityReview: fidelity.review,
+ hookResult,
+ failureIsTerminal: (analysis) => isPrivateSecurityTask(task)
+ || resolveFailedTaskDecision(preHookTask, analysis, { agentId }).status === 'blocked',
+ });
+
+ const taskType = task?.taskType || 'user';
+ const taskUpdate = terminatedByUser
+ ? {
+ status: 'blocked',
+ metadata: {
+ ...preHookTask.metadata,
+ blockedReason: 'Terminated by user',
+ blockedCategory: 'user-terminated',
+ blockedAt: new Date().toISOString(),
+ },
+ }
+ : verdict.success
+ ? (hookMetadata ? { status: 'completed', metadata: task.metadata } : { status: 'completed' })
+ : await resolveFailedTaskUpdate(verdict.source === 'hook' ? task : preHookTask, verdict.errorAnalysis, agentId);
// Success-criteria validation (issue #2344): stamp an explicit pass/fail (or
// null-when-undeclared) verdict onto the completion result, distinct from the
diff --git a/server/services/agentFinalization.outputHooks.test.js b/server/services/agentFinalization.outputHooks.test.js
index 8da2d7ab9c..f544793908 100644
--- a/server/services/agentFinalization.outputHooks.test.js
+++ b/server/services/agentFinalization.outputHooks.test.js
@@ -363,6 +363,9 @@ describe('permanent output-hook rejection (#6124)', () => {
expect(completeAgentRun).toHaveBeenCalledWith('run-rejected', '', 1, 1000,
expect.objectContaining({ category: 'output-missing', permanent: true }), false);
expect(addTask).not.toHaveBeenCalled();
+ // The task's retry decision is resolved once, against the final verdict —
+ // not once for the run's own failure and again for the escalation (#9645).
+ expect(resolveFailedTaskUpdate).toHaveBeenCalledTimes(1);
});
it('leaves a named failure on its ordinary retry path', async () => {