Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 43 additions & 2 deletions packages/core/src/plan-gate/gateReviewAgents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@ import { createDebugLogger } from '../utils/debugLogger.js';

const debugLogger = createDebugLogger('GATE_REVIEW_AGENTS');

/**
* Timeout for the gate agent in milliseconds. The gate agent typically
* completes within 1–2 minutes; this 5-minute ceiling accounts for the
* runConfig.max_time_minutes limit and provides a safety net against hangs.
*/
const GATE_AGENT_TIMEOUT_MS = 5 * 60 * 1000;
Comment on lines +18 to +23

// ── Gate agent prompt ──────────────────────────────────────────────────

function buildReviewPrompt(evidence: string): string {
Expand Down Expand Up @@ -104,12 +111,21 @@ export function formatEvidence(bundle: EvidenceBundle): string {
* Runs the gate review agent via `createAgentHeadless`. The agent operates
* under a forced-PLAN config override and cannot spawn nested agents.
*
* Signal isolation: The gate agent creates its own independent AbortController
* with a timeout, rather than directly inheriting the parent's signal. This
* prevents transient parent-side issues (stream errors, round cleanup) from
* cascading into the gate agent. The parent signal is intentionally not
* checked or monitored — the gate agent's own 5-minute timeout (matching
* runConfig.max_time_minutes) is the sole cancellation mechanism.
*
Comment on lines +115 to +121

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Fix docstring: parent signal is pre-checked only, not monitored
    during execution. Matches the actual isolation behavior.
  • Remove signal.aborted check from retry loop. The gate agent is now
    fully signal-isolated with its own timeout, so parent-side aborts
    (typically transient) should not short-circuit retries. The caller
    discards the result if the parent is truly gone.
  • Replace plain setTimeout delay with abortableSleep() that returns
    early if the parent signal aborts during the 1s wait. Prevents
    wasted shutdown time on genuine cancellation.
  • Fix timeout comment: gate agent typically completes in 1-2 minutes;
    the 5-minute ceiling matches runConfig.max_time_minutes.

* Returns the parsed `GateAgentResult`, or throws on unrecoverable failure.
*/
export async function runGateAgent(
config: Config,
bundle: EvidenceBundle,
signal: AbortSignal,
// parentSignal is accepted for API consistency but intentionally unused:
// the gate agent is fully isolated from parent-side aborts.
_parentSignal: AbortSignal,
): Promise<GateAgentResult> {
Comment thread
CubeLander marked this conversation as resolved.
Resolved
Comment on lines 124 to 130
const evidence = formatEvidence(bundle);
const taskPrompt = buildReviewPrompt(evidence);
Expand All @@ -129,6 +145,27 @@ export async function runGateAgent(
ApprovalMode.PLAN,
);

// Create an independent AbortController for the gate agent.
// This isolates the gate agent from transient parent-side aborts
// (e.g., stream errors, round cleanup, NO_FINISH_REASON retries).
// The gate agent has its own timeout (GATE_AGENT_TIMEOUT_MS) to prevent
// indefinite hangs. We deliberately do NOT propagate parent aborts here
// because:
// 1. The gate agent is a critical review step that should complete if possible
// 2. Parent aborts are often transient (stream retries, round cleanup)
// 3. The gate agent's own timeout provides a safety net

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] _parentSignal is accepted but never observed. If the parent aborts during gate agent execution, there's zero log output connecting the parent abort to the gate agent's continued execution. For debugging "I cancelled but it kept going" reports, oncall needs a breadcrumb.

Consider adding a one-time listener before the AbortController:

Suggested change
// 3. The gate agent's own timeout provides a safety net
_parentSignal.addEventListener(
'abort',
() => {
debugLogger.warn(
'[runGateAgent] Parent signal aborted — gate agent continuing independently (own timeout is sole cancellation)',
);
},
{ once: true },
);
const gateAbortController = new AbortController();

— qwen3.7-max via Qwen Code /review

// If the parent is genuinely cancelled (user closes session), the timeout
// will eventually clean up, or the parent's cleanup logic will handle it.
const gateAbortController = new AbortController();

// Add a timeout so the gate agent doesn't hang indefinitely
const timeoutId = setTimeout(() => {
debugLogger.warn(
`[runGateAgent] Gate agent timed out after ${GATE_AGENT_TIMEOUT_MS}ms`,
);
gateAbortController.abort(new Error('Gate agent timeout'));
}, GATE_AGENT_TIMEOUT_MS);
Comment on lines +160 to +168
Comment on lines +160 to +168

let disposeSubagent: (() => Promise<void>) | undefined;

try {
Expand All @@ -142,7 +179,8 @@ export async function runGateAgent(
const contextState = new ContextState();
contextState.set('task_prompt', taskPrompt);

await subagent.execute(contextState, signal);
// Pass the isolated gate signal instead of the parent signal
await subagent.execute(contextState, gateAbortController.signal);
Comment on lines +183 to +184
Comment on lines +183 to +184

const terminateMode = subagent.getTerminateMode();
const rawText = subagent.getFinalText();
Expand All @@ -159,6 +197,7 @@ export async function runGateAgent(

return parseGateAgentResult(rawText);
} finally {
clearTimeout(timeoutId);
// Dispose the subagent (stops its per-spawn ToolRegistry and
// unregisters per-agent hooks, preventing listener leaks).
if (disposeSubagent) {
Expand All @@ -171,6 +210,8 @@ export async function runGateAgent(
}
}
cleanup();
// Abort the gate controller to clean up any remaining listeners
gateAbortController.abort();
Comment thread
CubeLander marked this conversation as resolved.
Resolved
}
}

Expand Down
41 changes: 37 additions & 4 deletions packages/core/src/plan-gate/planApprovalGate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,10 +142,11 @@ async function runAgentWithRetry(
signal: AbortSignal,
): Promise<GateAgentResult | null> {
for (let attempt = 1; attempt <= MAX_AGENT_RETRIES; attempt++) {
if (signal.aborted) {
debugLogger.warn('Gate agent skipped: signal already aborted');
return null;
}
// Note: We deliberately do NOT check signal.aborted here.
// The gate agent is signal-isolated (see runGateAgent), so parent-side
// aborts are typically transient (stream errors, round cleanup). The
// gate agent has its own 5-minute timeout as the safety net. If the
// parent is truly gone, the caller will discard the result anyway.
try {
return await runGateAgent(config, bundle, signal);
} catch (error) {
Comment on lines 157 to 160
Comment on lines 157 to 160

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] Timeout errors are retried identically to transient errors. When the gate agent's 5-minute timeout fires (gateReviewAgents.ts:165), the error propagates here and the retry loop launches another 5-minute attempt. With MAX_AGENT_RETRIES=3, worst case = ~15 minutes of blocked waiting.

A timeout signals the operation is too expensive — retrying it at the same budget defeats the safety net. Consider distinguishing timeout errors:

Suggested change
} catch (error) {
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
if (msg.includes('Gate agent timeout')) {
debugLogger.error(
`[runAgentWithRetry] Gate agent timed out; not retrying (attempt ${attempt}/${MAX_AGENT_RETRIES})`,
);
return null;
}

— qwen3.7-max via Qwen Code /review

Expand All @@ -159,11 +160,43 @@ async function runAgentWithRetry(
);
return null;
}
// Abort-aware delay: wait 1s between retries, but bail out early
// if the parent signal is aborted during the wait.
await abortableSleep(1000, signal);
}
}
Comment on lines +171 to 185
return null;
}

/**
* Sleep for `ms` milliseconds, but return early if `signal` is aborted.
* Attaches the abort listener first, then re-checks `signal.aborted` to
* eliminate the race window between the initial check and listener setup.
*/
function abortableSleep(ms: number, signal: AbortSignal): Promise<void> {
return new Promise<void>((resolve) => {
if (signal.aborted) {
resolve();
return;
}
const onAbort = () => {
clearTimeout(timer);
resolve();
};
const timer = setTimeout(() => {
signal.removeEventListener('abort', onAbort);
resolve();
}, ms);
signal.addEventListener('abort', onAbort, { once: true });
// Re-check after attaching listener to close the race window
if (signal.aborted) {
clearTimeout(timer);
signal.removeEventListener('abort', onAbort);
resolve();
}
});
}

// ── Finding id assignment ──────────────────────────────────────────────

/**
Expand Down