Skip to content

Commit 42500d1

Browse files
licheer-ztesallyom
andauthored
fix(hooks): target hook-triggered heartbeat wakes at the hook agent/session (#119808) (#119817)
* fix(hooks): allow scoped hook wakes for unscheduled targets; keep announce wake aligned with queued session - heartbeat-wake-policy: add isTargetedImmediateHookWake so a scoped hook wake (source=hook, reason=hook:*) counts as an immediate targeted wake; a known agent without a recurring heartbeat schedule can now be woken once so its queued hook event gets consumed instead of sitting unread. - scheduler + execution: accept the hook wake in the allowsUnscheduledTarget gate alongside notifications-event wakes; unconfigured agents stay rejected. - hooks announce path: only pass agentId when the hook explicitly named an agent; an unnamed hook resolves its event session from fresh config at announce time, so pairing the dispatch-time default agent with that session could wake a stale agent after a default-agent reload. - regression tests: targeted hook wake for an unscheduled agent runs once; unconfigured hook targets rejected; announce wake omits default agentId for unnamed hooks. * test(infra): split hook-wake heartbeat tests out of scheduler test file Keep heartbeat-runner.scheduler.test.ts inside the oxlint max-lines budget (1045 -> 995 effective lines) by moving the two hook-source wake targeting tests into heartbeat-runner.hook-wake.test.ts. No production code changes. * fix(gateway): target global-scope hook wakes at the fresh default agent Global session scope resolves hook event keys to the unscoped "global" sentinel, which carries no agent identity. The scheduler refuses to resolve a target from it, so announce and failure wakes for unnamed hooks left the queued event unread. Carry the fresh default agent alongside the global key on both paths (announce and failure), mirroring the enqueue-wake path. Non-global unnamed-hook wakes are unchanged: their session key embeds the agent, and pairing a frozen default agent could wake a stale agent after a default-agent reload. * fix(gateway): target recovered global failure wakes at the explicit or fresh default agent The failure-wake agent selection gated both branches on hookEventSessionKey. When initial event-key resolution fails (early config failure), that key is absent even though recovery still yields the unscoped "global" sentinel; the wake then carried no agentId and the queued failure event sat unread. Use the recovered session key for the sentinel check and attach the explicit agent, or the fresh default agent, so the global failure event is consumed. Non-global unnamed-hook wakes are unchanged: their session key embeds the agent, and pairing a frozen default agent could wake a stale agent after a default-agent reload. * fix(gateway): preserve agent identity for global hook wakes Signed-off-by: sallyom <[email protected]> * test(infra): allow seeding a heartbeat session without delivery fields The new hook-wake test seeds an empty session for the hooks agent, which has no real delivery context. Relax seedSessionStore's seed type to Partial so empty seeds typecheck. * fix(gateway): keep global hook wakes on the dispatch-time agent The announce and failure wake paths resolved the default agent from fresh config at queue-execution time. If a default-agent reload happened between dispatch and execution, a global-scope wake retargeted at the new default while the isolated run used the accepted agent, so the event produced under one agent was consumed by another. Freeze the accepted agent at dispatch (acceptedHookAgentId) and prefer it in both wake paths; fresh resolution remains the fallback for pre-acceptance failures. Adds announce + failure reload regressions (default main -> work mid-queue). * test(hooks): annotate reload fixtures as OpenClawConfig The default-agent reload fixtures widened session.scope to string and fixed agents.entries to the first assignment's shape, breaking check-test-types. Annotate both fixtures so each reload conforms to the config contract. * fix(hooks): partition global-scope hook events by owning agent Global-scope hook announce and failure events all land in the shared literal `global` system-event queue while each wake targets a single agent, so concurrent hook completions can cross-consume each other's events: the first targeted wake drains every agent's queued result or failure into one prompt. Give transient system events an ownerAgentId set by the hook dispatch paths (announce, failure, and wake-only enqueues) whenever the event lands on the unscoped sentinel queue, and filter the heartbeat preflight peek to the running agent's owned events. The store's literal global session row stays shared; unowned events remain visible to every agent, so non-hook global events are unchanged. Add a two-agent concurrent regression proving the first targeted wake leaves the other agent's event queued for its owner. * fix(hooks): isolate global events by agent Signed-off-by: sallyom <[email protected]> * fix(infra): unexport internal targeted-wake helpers isTargetedImmediateSystemEventWake and isTargetedImmediateHookWake are only consumed by isTargetedImmediateUnscheduledWake within the same module; keep them module-private so knip deadcode stops flagging the unused exports. --------- Signed-off-by: sallyom <[email protected]> Co-authored-by: sallyom <[email protected]>
1 parent 25ddd42 commit 42500d1

24 files changed

Lines changed: 1185 additions & 50 deletions

‎src/agents/bash-tools.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -461,6 +461,7 @@ async function expectNotifyOnExitWake(tool: ExecToolInstance, expected: Record<s
461461
async function drainNotifyEvents(sessionKey = DEFAULT_NOTIFY_SESSION_KEY) {
462462
return await drainFormattedSystemEvents({
463463
cfg: notifyCfg,
464+
agentId: "main",
464465
sessionKey,
465466
isMainSession: false,
466467
isNewSession: false,

‎src/auto-reply/reply/get-reply-run-admission.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,7 @@ export async function prepareReplyRunAdmission(context: PreparedReplyRunContext)
135135
if (!useFastReplyRuntime && heartbeatRunScope !== "commitment-only") {
136136
const eventsBlock = await drainFormattedSystemEvents({
137137
cfg,
138+
agentId,
138139
sessionKey,
139140
isMainSession,
140141
isNewSession,

‎src/auto-reply/reply/get-reply-run.media-only.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,12 @@ import {
1010
} from "../../agents/embedded-agent-runner/runs.js";
1111
import type { SessionEntry } from "../../config/sessions.js";
1212
import { HEARTBEAT_RUN_SCOPE } from "../../infra/heartbeat-run-scope.js";
13+
import { withSystemEventOwner } from "../../infra/system-event-ownership.js";
14+
import {
15+
enqueueSystemEvent,
16+
peekSystemEventEntries,
17+
resetSystemEventsForTest,
18+
} from "../../infra/system-events.js";
1319
import { MESSAGE_TOOL_ONLY_DELIVERY_HINT } from "../../plugin-sdk/message-tool-delivery-hints.js";
1420
import { normalizeSessionDeliveryState } from "../../utils/delivery-context.shared.js";
1521
import { hasControlCommand } from "../command-detection.js";
@@ -352,6 +358,7 @@ describe("runPreparedReply media-only handling", () => {
352358

353359
afterEach(() => {
354360
vi.useRealTimers();
361+
resetSystemEventsForTest();
355362
const paths = cleanupPaths.splice(0);
356363
return Promise.all(paths.map((entry) => rm(entry, { recursive: true, force: true })));
357364
});
@@ -3704,6 +3711,40 @@ describe("runPreparedReply media-only handling", () => {
37043711
expect(call.followupRun.prompt).toContain("System: [t] Node connected.");
37053712
});
37063713

3714+
it("admits only system events visible to the prepared agent", async () => {
3715+
const actualSystemEvents = await vi.importActual<typeof import("./session-system-events.js")>(
3716+
"./session-system-events.js",
3717+
);
3718+
vi.mocked(drainFormattedSystemEvents).mockImplementationOnce(
3719+
actualSystemEvents.drainFormattedSystemEvents,
3720+
);
3721+
enqueueSystemEvent(
3722+
"Alpha hook finished",
3723+
withSystemEventOwner({ sessionKey: "global" }, "alpha"),
3724+
);
3725+
enqueueSystemEvent(
3726+
"Beta hook finished",
3727+
withSystemEventOwner({ sessionKey: "global" }, "beta"),
3728+
);
3729+
enqueueSystemEvent("Legacy unowned event", { sessionKey: "global" });
3730+
3731+
await runPreparedReply(
3732+
baseParams({
3733+
agentId: "alpha",
3734+
sessionKey: "global",
3735+
opts: { isHeartbeat: true },
3736+
}),
3737+
);
3738+
3739+
const call = requireRunReplyAgentCall();
3740+
expect(call.followupRun.prompt).toContain("Alpha hook finished");
3741+
expect(call.followupRun.prompt).toContain("Legacy unowned event");
3742+
expect(call.followupRun.prompt).not.toContain("Beta hook finished");
3743+
expect(peekSystemEventEntries("global").map((event) => event.text)).toEqual([
3744+
"Beta hook finished",
3745+
]);
3746+
});
3747+
37073748
it("does not strip think-hint token from deferred queue body", async () => {
37083749
// In steer mode the inferred thinkLevel is never consumed, so the first token
37093750
// must not be stripped from the queue/steer body (followupRun.prompt).

‎src/auto-reply/reply/session-reset-cleanup.test.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
clearEmbeddedSessionPromptStates,
55
getEmbeddedSessionPromptState,
66
} from "../../agents/embedded-agent-runner/session-prompt-state.js";
7+
import { withSystemEventOwner } from "../../infra/system-event-ownership.js";
78
import {
89
enqueueSystemEvent,
910
peekSystemEvents,
@@ -26,7 +27,7 @@ describe("clearSessionResetRuntimeState", () => {
2627
const state = getEmbeddedSessionPromptState("old-session");
2728
state.sentUserTurnIds.add("sent-user-turn");
2829

29-
clearSessionResetRuntimeState(["old-session"]);
30+
clearSessionResetRuntimeState(["old-session"], { agentId: "main" });
3031

3132
expect(getEmbeddedSessionPromptState("old-session")).not.toBe(state);
3233
});
@@ -36,7 +37,9 @@ describe("clearSessionResetRuntimeState", () => {
3637
enqueueSystemEvent("stale beta", { sessionKey: "beta" });
3738
enqueueSystemEvent("fresh gamma", { sessionKey: "gamma" });
3839

39-
const result = clearSessionResetRuntimeState([" alpha ", undefined, " ", "alpha", "beta"]);
40+
const result = clearSessionResetRuntimeState([" alpha ", undefined, " ", "alpha", "beta"], {
41+
agentId: "main",
42+
});
4043

4144
expect(result.keys).toEqual(["alpha", "beta"]);
4245
expect(result.systemEventsCleared).toBe(2);
@@ -45,6 +48,17 @@ describe("clearSessionResetRuntimeState", () => {
4548
expect(peekSystemEvents("gamma")).toEqual(["fresh gamma"]);
4649
});
4750

51+
it("preserves events owned by other agents during an agent-scoped reset", () => {
52+
enqueueSystemEvent("unowned", { sessionKey: "global" });
53+
enqueueSystemEvent("alpha", withSystemEventOwner({ sessionKey: "global" }, "alpha"));
54+
enqueueSystemEvent("beta", withSystemEventOwner({ sessionKey: "global" }, "beta"));
55+
56+
const result = clearSessionResetRuntimeState(["global"], { agentId: " Alpha " });
57+
58+
expect(result.systemEventsCleared).toBe(2);
59+
expect(peekSystemEvents("global")).toEqual(["beta"]);
60+
});
61+
4862
it("releases active reply work owned by the archived reset session id", () => {
4963
const cancel = vi.fn();
5064
const operation = createReplyOperation({
@@ -60,6 +74,7 @@ describe("clearSessionResetRuntimeState", () => {
6074
operation.setPhase("running");
6175

6276
clearSessionResetRuntimeState(["agent:main:slack:room:1", "old-session"], {
77+
agentId: "main",
6378
activeReplySessionId: "old-session",
6479
});
6580

@@ -82,6 +97,7 @@ describe("clearSessionResetRuntimeState", () => {
8297
operation.setPhase("running");
8398

8499
clearSessionResetRuntimeState(["agent:main:slack:room:1", "old-session"], {
100+
agentId: "main",
85101
activeReplySessionId: "old-session",
86102
});
87103

@@ -111,6 +127,7 @@ describe("clearSessionResetRuntimeState", () => {
111127
operation.setPhase("running");
112128

113129
clearSessionResetRuntimeState(["agent:main:slack:room:1", "old-session"], {
130+
agentId: "main",
114131
activeReplySessionId: "old-session",
115132
});
116133

@@ -126,6 +143,7 @@ describe("clearSessionResetRuntimeState", () => {
126143
});
127144

128145
clearSessionResetRuntimeState(["agent:main:slack:room:1", "old-session"], {
146+
agentId: "main",
129147
activeReplySessionId: "old-session",
130148
});
131149

‎src/auto-reply/reply/session-reset-cleanup.ts‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
/** Clears reset-related queues and system events for session keys. */
22
import { clearEmbeddedSessionPromptStates } from "../../agents/embedded-agent-runner/session-prompt-state.js";
3-
import { drainSystemEventEntries } from "../../infra/system-events.js";
3+
import { selectAgentSystemEvents } from "../../infra/system-event-ownership.js";
4+
import {
5+
consumeSelectedSystemEventEntries,
6+
peekSystemEventEntries,
7+
} from "../../infra/system-events.js";
48
import { clearSessionQueues, type ClearSessionQueueResult } from "./queue/cleanup.js";
59
import { clearReplyRunForResetBySessionId } from "./reply-run-registry.js";
610

@@ -9,20 +13,26 @@ type ClearSessionResetRuntimeStateResult = ClearSessionQueueResult & {
913
systemEventsCleared: number;
1014
};
1115

12-
/** Clears queued follow-ups and pending system events for reset session keys. */
16+
/** Clears queued follow-ups and pending system events visible to the resetting agent. */
1317
export function clearSessionResetRuntimeState(
1418
keys: Array<string | undefined>,
15-
opts?: { activeReplySessionId?: string },
19+
opts: { agentId: string; activeReplySessionId?: string },
1620
): ClearSessionResetRuntimeStateResult {
1721
clearEmbeddedSessionPromptStates(keys);
1822
const cleared = clearSessionQueues(keys);
1923
let systemEventsCleared = 0;
2024

2125
for (const key of cleared.keys) {
22-
systemEventsCleared += drainSystemEventEntries(key).length;
26+
// Global session rows may share one transient queue across agents. An
27+
// agent-scoped reset must not discard another agent's pending work.
28+
const removed = consumeSelectedSystemEventEntries(
29+
key,
30+
selectAgentSystemEvents(peekSystemEventEntries(key), opts.agentId),
31+
);
32+
systemEventsCleared += removed.length;
2333
}
2434

25-
if (opts?.activeReplySessionId) {
35+
if (opts.activeReplySessionId) {
2636
clearReplyRunForResetBySessionId(opts.activeReplySessionId);
2737
}
2838

‎src/auto-reply/reply/session-system-events.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
// Records system-level session events for restarts, forks, and resets.
21
import {
32
normalizeLowercaseStringOrEmpty,
43
normalizeOptionalString,
@@ -12,6 +11,8 @@ import {
1211
resolveTimezone,
1312
} from "../../infra/format-time/format-datetime.ts";
1413
import { isExecCompletionEvent } from "../../infra/heartbeat-events-filter.js";
14+
// Records system-level session events for restarts, forks, and resets.
15+
import { selectAgentSystemEvents } from "../../infra/system-event-ownership.js";
1516
import {
1617
consumeSelectedSystemEventEntries,
1718
peekSystemEventEntries,
@@ -104,6 +105,7 @@ function formatSystemEventTimestamp(ts: number, cfg: OpenClawConfig) {
104105
/** Drain queued system events, format as `System:` lines, return the block text (or undefined). */
105106
export async function drainFormattedSystemEvents(params: {
106107
cfg: OpenClawConfig;
108+
agentId: string;
107109
sessionKey: string;
108110
isMainSession: boolean;
109111
isNewSession: boolean;
@@ -115,9 +117,10 @@ export async function drainFormattedSystemEvents(params: {
115117
// so the heartbeat path can consume and deliver them.
116118
const queued = consumeSelectedSystemEventEntries(
117119
params.sessionKey,
118-
selectGenericSystemEvents(peekSystemEventEntries(params.sessionKey), {
119-
suppressHeartbeatOwnedEvents: params.suppressHeartbeatOwnedEvents,
120-
}),
120+
selectGenericSystemEvents(
121+
selectAgentSystemEvents(peekSystemEventEntries(params.sessionKey), params.agentId),
122+
{ suppressHeartbeatOwnedEvents: params.suppressHeartbeatOwnedEvents },
123+
),
121124
);
122125
const sessionStateTargets = queued
123126
.map((event) =>

‎src/auto-reply/reply/session.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1291,6 +1291,7 @@ describe("initSessionState RawBody", () => {
12911291
await expect(
12921292
drainFormattedSystemEvents({
12931293
cfg,
1294+
agentId: "main",
12941295
sessionKey,
12951296
isMainSession: false,
12961297
isNewSession: true,
@@ -2141,6 +2142,7 @@ describe("initSessionState reset policy", () => {
21412142
await expect(
21422143
drainFormattedSystemEvents({
21432144
cfg,
2145+
agentId: "main",
21442146
sessionKey,
21452147
isMainSession: false,
21462148
isNewSession: true,
@@ -4326,6 +4328,7 @@ describe("drainFormattedSystemEvents", () => {
43264328

43274329
const result = await drainFormattedSystemEvents({
43284330
cfg: {} as OpenClawConfig,
4331+
agentId: "main",
43294332
sessionKey: "agent:main:main",
43304333
isMainSession: true,
43314334
isNewSession: false,
@@ -4346,6 +4349,7 @@ describe("drainFormattedSystemEvents", () => {
43464349

43474350
const result = await drainFormattedSystemEvents({
43484351
cfg: { channels: {} } as OpenClawConfig,
4352+
agentId: "main",
43494353
sessionKey: "agent:main:main",
43504354
isMainSession: true,
43514355
isNewSession: true,
@@ -4371,6 +4375,7 @@ describe("drainFormattedSystemEvents", () => {
43714375

43724376
const result = await drainFormattedSystemEvents({
43734377
cfg: {} as OpenClawConfig,
4378+
agentId: "main",
43744379
sessionKey: "agent:main:main",
43754380
isMainSession: true,
43764381
isNewSession: false,
@@ -4395,6 +4400,7 @@ describe("drainFormattedSystemEvents", () => {
43954400

43964401
const result = await drainFormattedSystemEvents({
43974402
cfg: {} as OpenClawConfig,
4403+
agentId: "main",
43984404
sessionKey: "agent:main:main",
43994405
isMainSession: true,
44004406
isNewSession: false,

‎src/auto-reply/reply/session.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -741,6 +741,7 @@ async function initSessionStateAttemptLocked(
741741
if (previousSessionEntry) {
742742
clearSessionResetRuntimeState([sessionKey, previousSessionEntry.sessionId], {
743743
activeReplySessionId: previousSessionEntry.sessionId,
744+
agentId,
744745
});
745746
}
746747

0 commit comments

Comments
 (0)