Skip to content

Commit 969efda

Browse files
committed
fix(agents): make run liveness evidence-based
1 parent 953f1c7 commit 969efda

10 files changed

Lines changed: 334 additions & 45 deletions

File tree

‎TRACK_B1_BRIEF.md‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# Track B1+B4+B5: truthful run liveness — delete fake evidence, honest recovery attribution, evidence-aged steer capture
2+
3+
Design issue: https://github.com/openclaw/openclaw/issues/101863 (Track B design comment). This branch is stacked on `fix/reply-run-terminal-release` (PR #101910, Track A) and uses its primitives: `ReplyOperation.lastActivityAtMs`, `recordActivity()`, `expireStaleReplyOperation()`, failure code `"run_stalled"`, constant `REPLY_RUN_STALE_TAKEOVER_MS` — all in `src/auto-reply/reply/reply-run-registry.ts`. This brief is authoritative for scope.
4+
5+
## B1 — delete the CLI timer heartbeat; phase-aware tool-stall floor
6+
7+
Problem (verified): `startClaudeLiveActiveToolHeartbeat` (`src/agents/cli-runner/claude-live-session.ts:551-566`) emits `cli_live:tool_running` on a 10s `setInterval` while a tool is merely _marked_ active (`turn.activeTools.size > 0`). That flows via `emitClaudeLiveProgress` → `run.progress` → `touchSessionActivity` (`src/logging/diagnostic-run-activity.ts:185`), resetting `lastProgressAt` with zero evidence the CLI child is alive. Consequence (#96168): the `blocked_tool_call` classifier branch (`src/logging/diagnostic-session-attention.ts:55-67`) — which correctly requires BOTH `activeToolAgeMs > staleMs` AND `lastProgressAgeMs > staleMs` — can never fire for a wedged CLI tool, and neither can any stuck-recovery abort gate keyed on `lastProgressAgeMs`.
8+
9+
Fix:
10+
11+
1. Delete the heartbeat entirely: `startClaudeLiveActiveToolHeartbeat`, `CLAUDE_LIVE_ACTIVE_TOOL_PROGRESS_MS` (`claude-live-session.ts:112`), the start call (~`:598`), the stop calls (~`:568`, `:654`), turn-cleanup clearing (~`:390`), and the `cli_live:tool_running` reason string. Real frames already stamp progress: tool start (`:597`), tool result (`:612`, `:653`), terminal result (`:711`), and any stdout frame via `noteClaudeLiveProgress` (`:705`, `:717`). Do NOT touch the byte-level no-output watchdog (`resetNoOutputTimer` `:720-738`) — it is evidence-based and correct.
12+
2. Deleting the fake stamp re-exposes the #88870 hazard: a legitimately quiet long tool would become abort-eligible at the default `stuckSessionAbortMs` (~6 min). Add a tool-phase abort floor in `src/logging/diagnostic.ts`:
13+
- New constant next to the other thresholds (`diagnostic.ts:80-85`): `BLOCKED_TOOL_CALL_ABORT_FLOOR_MS = 15 * 60_000`, with a 2-3 line contract comment: quiet-but-alive tools are normal agent behavior; the CLI byte watchdog kills truly-silent children at ≤600s; this floor only governs diagnostic recovery aborts for chatty-but-stuck turns; too low re-creates #88870, removal re-creates #96168's motivation for fake heartbeats.
14+
- Apply in `isBlockedToolCallRecoveryEligible` (`diagnostic.ts:514`): eligibility requires `lastProgressAgeMs >= Math.max(stuckSessionAbortMs, BLOCKED_TOOL_CALL_ABORT_FLOOR_MS)` (only for the tool_call kind — do not change model_call or embedded_run gates).
15+
- The warn-level classification (`classifySessionAttention` blocked_tool_call branch) keeps current thresholds — early warning naming the tool is good UX and cheap.
16+
3. Delete tests asserting the removed heartbeat behavior (they protect a removed path); update wedged-tool tests so a stuck tool with no frames becomes stale → classified → recovery-eligible after the floor.
17+
18+
## B4 — honest recovery attribution + stall-proof heartbeat math
19+
20+
Problem 1 (verified): a diagnostic stuck-recovery abort of a reply-backed run routes `abortAndDrainEmbeddedAgentRun` → `abortReplyRunBySessionId` (`reply-run-registry.ts:856`) → `operation.abortByUser()` (`:664`) which stamps `abortedCode: "aborted_by_user"` (`:671`). Watchdog kills surface to the user as their own abort (#88870's misattribution).
21+
22+
Fix: recovery is a staleness expiry, and Track A already built the primitive. In `src/logging/diagnostic-stuck-session-recovery.runtime.ts` (and the runs.ts abort leg it calls), when recovery decides to abort/force-clear a **reply-registry-owned** operation, route it through `expireStaleReplyOperation(operation, ...)` instead of `abortByUser()`/plain `fail("run_failed")`, so the terminal result is `{kind:"failed", code:"run_stalled"}` and the takeover log names the reason. Extend the `ReplyOperationStaleReason` union with `"stuck_recovery"` (closed union — check every consumer). For embedded (non-reply) runs, keep `abortAndDrainEmbeddedAgentRun` but ensure the abort reason threading does not produce a user-abort-shaped terminal outcome: check `resolveAgentRunAbortLifecycleFields` / terminal-outcome normalization (`src/agents/agent-run-terminal-outcome.ts`) and make the stuck-recovery abort distinguishable (a recovery-tagged abort error is acceptable; do not invent new lifecycle phases). Do not change the recovery module's detection logic beyond this routing.
23+
24+
Problem 2 (verified, #101670): all staleness ages are raw `Date.now()` deltas; the 30s heartbeat (`diagnostic.ts:1211`) computes `ageMs = now - state.lastActivity` (`:1281`) after an event-loop stall and reads the stall as session staleness.
25+
26+
Fix: the heartbeat records its own last tick timestamp. When a tick arrives later than ~3× the interval (>90s), that tick logs a warn (`liveness heartbeat delayed <n>ms; deferring recovery decisions`) and performs NO recovery/abort scheduling — classification/warn logging may still run. The next on-time tick proceeds normally. One module-local variable, one guard, one contract comment (a delayed tick means the process stalled, not the sessions; acting on inflated ages aborts healthy runs). Test with fake timers.
27+
28+
## B5 — steer capture refuses evidence-stale runs
29+
30+
Problem (proven live in PR #101910's E2E): steer acceptance checks only streaming/stopped state, so a wedged run swallows its own rescue messages before reply admission can evaluate Track A's stale takeover.
31+
32+
Fix, two gates:
33+
34+
1. `queueReplyRunMessage` (`reply-run-registry.ts:839-854`): refuse (return false) when `Date.now() - operation.lastActivityAtMs > REPLY_RUN_STALE_TAKEOVER_MS`. A refused caller already falls back to normal followup queueing → admission → Track A reclaim. Contract comment: steering into an evidence-dead run swallows the human message that would otherwise trigger stale takeover.
35+
2. `prepareEmbeddedAgentQueueMessage` (`src/agents/embedded-agent-runner/runs.ts:437-499`): after the injectable check, refuse when the session's diagnostic activity evidence is stale: use `getDiagnosticSessionActivitySnapshot` (`src/logging/diagnostic-run-activity.ts:572`) `lastProgressAgeMs` (when available) `>` a local `EMBEDDED_STEER_STALE_CAPTURE_MS = 10 * 60_000` constant (src/agents must not import src/auto-reply; duplicate the value with a comment naming `REPLY_RUN_STALE_TAKEOVER_MS` as the paired constant). New closed failure reason `"stale_run"` added to `EmbeddedAgentQueueFailureReason` (`runs.ts:56-62`) — check every consumer of that union handles it (sessions-send-tool.ts, subagent-announce-delivery.ts, etc.; they should treat it like `no_active_run`/`not_streaming` fall-through). If no diagnostic snapshot exists (diagnostics disabled), skip the gate (status quo).
36+
37+
- Non-goal: draining already-captured steer entries from a dead handle (Track C durability).
38+
39+
## Non-goals (do not touch)
40+
41+
- Codex app-server watches (`extensions/codex`) — separate Track B2 PR.
42+
- `llm-idle-timeout.ts` / `timeout.ts` semantics — separate Track B3 PR.
43+
- No new config keys or env vars; constants only. `stuckSessionWarnMs`/`stuckSessionAbortMs` keep their meaning.
44+
- No changes to the CLI byte-level no-output watchdog or supervisor.
45+
- No user-visible message wording work beyond what attribution requires (Track D owns messaging).
46+
47+
## Repo conventions
48+
49+
- TS ESM strict, no `any`, closed unions/codes. Comments: 1-3 lines, contract + bad outcome if removed, at lifecycle/threshold/ownership points only.
50+
- Tests colocated, Vitest, fake timers cleaned up, `--isolate=false` safe. Delete tests of removed paths rather than porting them.
51+
- Keep LOC tight; B1 should be clearly net-negative (a whole heartbeat mechanism disappears).
52+
53+
## Required tests
54+
55+
1. CLI wedged-tool: tool started, no further frames → `lastProgressAgeMs` grows (no timer stamps exist anymore), `blocked_tool_call` classification fires, recovery becomes eligible only after `max(stuckSessionAbortMs, BLOCKED_TOOL_CALL_ABORT_FLOOR_MS)`.
56+
2. CLI active-tool with real frames (tool result / stream frames arriving) → never classified stalled.
57+
3. Recovery abort of a reply-owned stale run → operation result `{failed, run_stalled}`, NOT `aborted_by_user`; user-abort path still yields `aborted_by_user`.
58+
4. Delayed heartbeat tick (fake timers, simulate >90s gap) → no recovery scheduled that tick, warn logged, next tick recovers normally.
59+
5. `queueReplyRunMessage` refuses when `lastActivityAtMs` stale, accepts when fresh (recordActivity just called).
60+
6. `prepareEmbeddedAgentQueueMessage` returns `"stale_run"` when diagnostic evidence stale; accepts when fresh; skips gate when no snapshot.
61+
7. Consumers of `EmbeddedAgentQueueFailureReason` handle `"stale_run"` (compile-time exhaustiveness + behavior fall-through where tested).
62+
63+
## Validation before you commit
64+
65+
- `node scripts/run-vitest.mjs src/logging src/agents/cli-runner src/auto-reply/reply src/agents/embedded-agent-runner` relevant test files (start with the directly touched test files, then the import sweep below). Never bare `pnpm test`/`vitest`.
66+
- Import sweep: `rg -l 'claude-live-session|diagnostic-run-activity|diagnostic-session-attention|stuck-session-recovery|queueEmbeddedAgentMessage|queueReplyRunMessage|EmbeddedAgentQueueFailureReason' --glob '*.test.ts' src test` and run those files.
67+
- Typecheck: `node scripts/run-tsgo.mjs -p tsconfig.core.json --incremental --tsBuildInfoFile .artifacts/tsgo-cache/core.tsbuildinfo` and the core-test lane; check exit codes directly, no pipes.
68+
- Format touched files with `node_modules/.bin/oxfmt`; lint with `node scripts/run-oxlint.mjs <files>`.
69+
70+
Commit on this branch with a conventional message (e.g. `fix(agents): replace fake CLI liveness with evidence-based stall detection`). Do not push. Do not open a PR. Write design decisions + test results to `TRACK_B1_NOTES.md` at the worktree root.

‎src/agents/cli-runner.spawn.test.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import { onAgentEvent, resetAgentEventsForTest } from "../infra/agent-events.js"
1717
import {
1818
onInternalDiagnosticEvent,
1919
onTrustedToolExecutionEvent,
20+
setDiagnosticsEnabledForProcess,
2021
waitForDiagnosticEventsDrained,
2122
} from "../infra/diagnostic-events.js";
2223
import {
@@ -66,6 +67,7 @@ type ProcessSupervisor = ReturnType<typeof getProcessSupervisor>;
6667
type SupervisorSpawnFn = ProcessSupervisor["spawn"];
6768

6869
beforeEach(() => {
70+
setDiagnosticsEnabledForProcess(true);
6971
resetAgentEventsForTest();
7072
resetDiagnosticRunActivityForTest();
7173
resetClaudeLiveSessionsForTest();
@@ -2142,7 +2144,7 @@ ${JSON.stringify({
21422144
expect(parsed.response.response.updatedInput).toEqual({ command: "ls" });
21432145
});
21442146

2145-
it("reports Claude live stream progress and keeps native tools fresh while they are running", async () => {
2147+
it("reports Claude live stream progress without timer heartbeats", async () => {
21462148
vi.useFakeTimers({
21472149
toFake: ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval"],
21482150
});
@@ -2250,11 +2252,11 @@ ${JSON.stringify({
22502252
expect(
22512253
getDiagnosticSessionActivitySnapshot({ sessionKey: "agent:main:diagnostics" })
22522254
.lastProgressReason,
2253-
).toBe("cli_live:tool_running");
2255+
).toBe("cli_live:tool_started");
22542256
expect(
22552257
getDiagnosticSessionActivitySnapshot({ sessionKey: "agent:main:diagnostics" })
22562258
.lastProgressAgeMs,
2257-
).toBeLessThan(100);
2259+
).toBeGreaterThanOrEqual(10_000);
22582260

22592261
stdoutListener?.(
22602262
[

‎src/agents/cli-runner/claude-live-session.ts‎

Lines changed: 0 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,6 @@ type ClaudeLiveTurn = {
5858
sessionId?: string;
5959
noOutputTimer: NodeJS.Timeout | null;
6060
timeoutTimer: NodeJS.Timeout | null;
61-
activeToolTimer: NodeJS.Timeout | null;
6261
activeTools: Map<string, ClaudeLiveActiveTool>;
6362
observedStdout: boolean;
6463
completedToolCallIds: Set<string>;
@@ -109,7 +108,6 @@ type ClaudeLiveToolTerminalOutcome =
109108
| { outcome: "blocked"; deniedReason: string; reason?: string }
110109
| { outcome: "cancelled" | "failed" | "timed_out" | "unknown" };
111110
const CLAUDE_LIVE_IDLE_TIMEOUT_MS = 10 * 60 * 1_000;
112-
const CLAUDE_LIVE_ACTIVE_TOOL_PROGRESS_MS = 10_000;
113111
const CLAUDE_LIVE_MAX_SESSIONS = 16;
114112
const CLAUDE_LIVE_MAX_STDERR_CHARS = 64 * 1024;
115113
const CLAUDE_LIVE_CLOSE_WAIT_TIMEOUT_MS = 5_000;
@@ -386,10 +384,6 @@ function clearTurnTimers(turn: ClaudeLiveTurn): void {
386384
clearTimeout(turn.timeoutTimer);
387385
turn.timeoutTimer = null;
388386
}
389-
if (turn.activeToolTimer) {
390-
clearInterval(turn.activeToolTimer);
391-
turn.activeToolTimer = null;
392-
}
393387
}
394388

395389
function finishTurn(session: ClaudeLiveSession, output: CliOutput): void {
@@ -548,31 +542,6 @@ function summarizeClaudeLiveToolInput(input: unknown): DiagnosticToolParamsSumma
548542
}
549543
}
550544

551-
function startClaudeLiveActiveToolHeartbeat(turn: ClaudeLiveTurn): void {
552-
if (turn.activeToolTimer || turn.activeTools.size === 0) {
553-
return;
554-
}
555-
turn.activeToolTimer = setInterval(() => {
556-
if (turn.activeTools.size === 0) {
557-
if (turn.activeToolTimer) {
558-
clearInterval(turn.activeToolTimer);
559-
turn.activeToolTimer = null;
560-
}
561-
return;
562-
}
563-
emitClaudeLiveProgress(turn, "cli_live:tool_running");
564-
}, CLAUDE_LIVE_ACTIVE_TOOL_PROGRESS_MS);
565-
turn.activeToolTimer.unref?.();
566-
}
567-
568-
function stopClaudeLiveActiveToolHeartbeatIfIdle(turn: ClaudeLiveTurn): void {
569-
if (turn.activeTools.size > 0 || !turn.activeToolTimer) {
570-
return;
571-
}
572-
clearInterval(turn.activeToolTimer);
573-
turn.activeToolTimer = null;
574-
}
575-
576545
function markClaudeLiveToolStarted(turn: ClaudeLiveTurn, tool: CliToolUseStartDelta): void {
577546
if (turn.completedToolCallIds.has(tool.toolCallId) || turn.activeTools.has(tool.toolCallId)) {
578547
return;
@@ -595,7 +564,6 @@ function markClaudeLiveToolStarted(turn: ClaudeLiveTurn, tool: CliToolUseStartDe
595564
paramsSummary: summarizeClaudeLiveToolInput(tool.args),
596565
});
597566
emitClaudeLiveProgress(turn, "cli_live:tool_started");
598-
startClaudeLiveActiveToolHeartbeat(turn);
599567
}
600568

601569
function markClaudeLiveToolCompleted(
@@ -651,7 +619,6 @@ function markClaudeLiveToolCompleted(
651619
});
652620
}
653621
emitClaudeLiveProgress(turn, "cli_live:tool_result");
654-
stopClaudeLiveActiveToolHeartbeatIfIdle(turn);
655622
}
656623

657624
function markClaudeLiveToolDenied(turn: ClaudeLiveTurn, tool: CliToolUseStartDelta): void {
@@ -1170,7 +1137,6 @@ function createTurn(params: {
11701137
rawChars: 0,
11711138
noOutputTimer: null,
11721139
timeoutTimer: null,
1173-
activeToolTimer: null,
11741140
activeTools: new Map(),
11751141
observedStdout: false,
11761142
completedToolCallIds: new Set(),

‎src/agents/embedded-agent-runner/runs.test.ts‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
isReplyRunActiveForSessionId,
1212
} from "../../auto-reply/reply/reply-run-registry.js";
1313
import { setDiagnosticsEnabledForProcess } from "../../infra/diagnostic-events.js";
14+
import { resetDiagnosticRunActivityForTest } from "../../logging/diagnostic-run-activity.js";
1415
import {
1516
getDiagnosticSessionState,
1617
resetDiagnosticSessionStateForTest,
@@ -236,6 +237,32 @@ describe("embedded-agent runner run registry", () => {
236237
expect(abort).toHaveBeenCalledWith("restart");
237238
});
238239

240+
it("expires reply-owned stuck recovery as run_stalled instead of user abort", async () => {
241+
const cancel = vi.fn();
242+
const operation = createReplyOperation({
243+
sessionKey: "agent:main:reply-stuck",
244+
sessionId: "session-reply-stuck",
245+
resetTriggered: false,
246+
});
247+
operation.attachBackend({
248+
kind: "embedded",
249+
cancel,
250+
isStreaming: () => true,
251+
});
252+
operation.setPhase("running");
253+
254+
const result = await abortAndDrainEmbeddedAgentRun({
255+
sessionId: "session-reply-stuck",
256+
sessionKey: "agent:main:reply-stuck",
257+
reason: "stuck_recovery",
258+
forceClear: true,
259+
});
260+
261+
expect(result).toEqual({ aborted: true, drained: true, forceCleared: false });
262+
expect(operation.result).toEqual({ kind: "failed", code: "run_stalled" });
263+
expect(cancel).toHaveBeenCalledWith("superseded");
264+
});
265+
239266
it("claims shared restart ownership before invoking an attached handle", () => {
240267
const abort = vi.fn();
241268
const handle = createRunHandle({ abort });
@@ -458,6 +485,53 @@ describe("embedded-agent runner run registry", () => {
458485
expect(queueMessage).toHaveBeenCalledWith("continue", { steeringMode: "all" });
459486
});
460487

488+
it("refuses embedded steering when diagnostic evidence is stale", () => {
489+
vi.useFakeTimers();
490+
try {
491+
const queueMessage = vi.fn(async () => {});
492+
setActiveEmbeddedRun("session-stale-steer", createRunHandle({ queueMessage }));
493+
494+
vi.advanceTimersByTime(10 * 60_000 + 1);
495+
496+
const outcome = queueEmbeddedAgentMessageWithOutcome("session-stale-steer", "continue");
497+
498+
expect(outcome).toEqual({
499+
queued: false,
500+
sessionId: "session-stale-steer",
501+
reason: "stale_run",
502+
gatewayHealth: "live",
503+
});
504+
expect(queueMessage).not.toHaveBeenCalled();
505+
} finally {
506+
vi.useRealTimers();
507+
}
508+
});
509+
510+
it("accepts embedded steering with fresh or missing diagnostic evidence", () => {
511+
const freshQueueMessage = vi.fn(async () => {});
512+
setActiveEmbeddedRun(
513+
"session-fresh-steer",
514+
createRunHandle({ queueMessage: freshQueueMessage }),
515+
);
516+
517+
expect(queueEmbeddedAgentMessageWithOutcome("session-fresh-steer", "continue").queued).toBe(
518+
true,
519+
);
520+
expect(freshQueueMessage).toHaveBeenCalledWith("continue", { steeringMode: "all" });
521+
522+
const missingSnapshotQueueMessage = vi.fn(async () => {});
523+
setActiveEmbeddedRun(
524+
"session-no-diagnostic-snapshot",
525+
createRunHandle({ queueMessage: missingSnapshotQueueMessage }),
526+
);
527+
resetDiagnosticRunActivityForTest();
528+
529+
expect(
530+
queueEmbeddedAgentMessageWithOutcome("session-no-diagnostic-snapshot", "continue").queued,
531+
).toBe(true);
532+
expect(missingSnapshotQueueMessage).toHaveBeenCalledWith("continue", { steeringMode: "all" });
533+
});
534+
461535
it("does not queue into stopped handles", () => {
462536
const queueMessage = vi.fn(async () => {});
463537
setActiveEmbeddedRun(

0 commit comments

Comments
 (0)