Skip to content

Commit ed37774

Browse files
AyitLabsobviyus
andauthored
fix(cron): retain best-effort context after restart (#130551)
Best-effort isolated Cron delivery mirrors now remain available as bounded fallback context after a Gateway restart removes the live chat window. Normal transcript artifacts stay filtered, strict delivery awareness remains separate, and the fallback activates only when no live window survives. Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent cfddfc2 commit ed37774

11 files changed

Lines changed: 144 additions & 26 deletions

‎.agents/skills/telegram-e2e-userbot/scripts/run-mock-sut-user-e2e.mjs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -691,6 +691,7 @@ async function runCronScenarioAction({
691691
gatewayEnv,
692692
cronDeliveryTarget,
693693
message,
694+
bestEffort,
694695
isStopped,
695696
}) {
696697
let jobId;
@@ -717,6 +718,7 @@ async function runCronScenarioAction({
717718
"telegram",
718719
"--to",
719720
cronDeliveryTarget,
721+
...(bestEffort ? ["--best-effort-deliver"] : []),
720722
"--json",
721723
"--keep-after-run",
722724
],
@@ -1324,6 +1326,7 @@ async function driveWithTelegramProxy(args, repoRoot, creds) {
13241326
gatewayEnv: controlEnv,
13251327
cronDeliveryTarget: selectedChatTarget.cronDeliveryTarget,
13261328
message: action.message,
1329+
bestEffort: action.bestEffort,
13271330
isStopped: () => controlsStopped,
13281331
}).then(
13291332
(result) => {

‎.agents/skills/telegram-e2e-userbot/scripts/scenario.mjs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ const ACTION_KEYS = {
99
restartGateway: new Set(["type", "atMs", "graceMs"]),
1010
patchConfig: new Set(["type", "atMs", "patch"]),
1111
systemEvent: new Set(["type", "atMs", "text"]),
12-
cron: new Set(["type", "atMs", "message"]),
12+
cron: new Set(["type", "atMs", "message", "bestEffort"]),
1313
command: new Set(["type", "atMs", "argv", "cwd", "timeoutMs"]),
1414
telegramApiHold: new Set(["type", "atMs", "method", "skip"]),
1515
telegramApiWaitHeld: new Set(["type", "atMs", "method", "timeoutMs"]),
@@ -77,10 +77,14 @@ export function parseScenario(value) {
7777
return { type: action.type, atMs, text: nonEmptyString(action.text, `${label}.text`) };
7878
}
7979
if (action.type === "cron") {
80+
if (action.bestEffort !== undefined && typeof action.bestEffort !== "boolean") {
81+
throw new Error(`${label}.bestEffort must be a boolean.`);
82+
}
8083
return {
8184
type: action.type,
8285
atMs,
8386
message: nonEmptyString(action.message, `${label}.message`),
87+
...(action.bestEffort === true ? { bestEffort: true } : {}),
8488
};
8589
}
8690
if (action.type === "command") {

‎.agents/skills/telegram-e2e-userbot/scripts/scenario.test.mjs‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ test("normalizes Telegram and gateway actions", () => {
2020
},
2121
{ type: "patchConfig", atMs: 750, patch: { channels: { telegram: { historyLimit: 9 } } } },
2222
{ type: "systemEvent", atMs: 900, text: "heartbeat proof" },
23-
{ type: "cron", atMs: 950, message: "deliver the schedule" },
23+
{ type: "cron", atMs: 950, message: "deliver the schedule", bestEffort: true },
2424
{ type: "command", atMs: 975, argv: ["node", "--version"], cwd: "repo" },
2525
{ type: "telegramApiHold", atMs: 980, method: "sendMessage", skip: 1 },
2626
{ type: "telegramApiWaitHeld", atMs: 990, method: "sendMessage" },
@@ -48,7 +48,7 @@ test("normalizes Telegram and gateway actions", () => {
4848
patch: { channels: { telegram: { historyLimit: 9 } } },
4949
},
5050
{ type: "systemEvent", atMs: 900, text: "heartbeat proof" },
51-
{ type: "cron", atMs: 950, message: "deliver the schedule" },
51+
{ type: "cron", atMs: 950, message: "deliver the schedule", bestEffort: true },
5252
{
5353
type: "command",
5454
atMs: 975,
@@ -113,6 +113,10 @@ test("rejects fields and action types outside the closed schema", () => {
113113
() => parseScenario({ actions: [{ type: "restartGateway", atMs: -1 }] }),
114114
/atMs must be a non-negative integer/u,
115115
);
116+
assert.throws(
117+
() => parseScenario({ actions: [{ type: "cron", message: "deliver", bestEffort: "yes" }] }),
118+
/bestEffort must be a boolean/u,
119+
);
116120
});
117121

118122
test("validates the recorder-ready artifact as a closed shape", () => {

‎src/channels/inbound-event/session-transcript-context.runtime.test.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,34 @@ describe("session transcript inbound context", () => {
6363
]);
6464
});
6565

66+
it("restores marked Cron delivery context when no live chat window survives", async () => {
67+
readRecent.mockImplementation(async (params) =>
68+
params.includeCronDirectDeliveryContext
69+
? [{ id: "cron-1", role: "assistant", text: "scheduled payload", timestamp: 2_000 }]
70+
: [],
71+
);
72+
const ctx = context({
73+
SessionTranscriptContext: { chatWindow: true, historyLimit: 3 },
74+
});
75+
76+
await mergeSessionTranscriptContext({
77+
agentId: "main",
78+
ctx,
79+
sessionKey: ctx.SessionKey!,
80+
storePath: "/tmp/sessions.json",
81+
});
82+
83+
expect(ctx.ChannelStructuredContext).toEqual([
84+
expect.objectContaining({
85+
source: "session",
86+
type: "chat_window",
87+
payload: expect.objectContaining({
88+
messages: [expect.objectContaining({ body: "scheduled payload" })],
89+
}),
90+
}),
91+
]);
92+
});
93+
6694
it("dedupes the canonical turn against the live window and merges chronologically", async () => {
6795
readRecent.mockResolvedValue([
6896
{ id: "u1", role: "user", text: "cached user turn", timestamp: 1_000 },
@@ -136,6 +164,7 @@ describe("session transcript inbound context", () => {
136164
storePath: "/tmp/sessions.json",
137165
});
138166

167+
expect(readRecent.mock.calls[0]?.[0]).not.toHaveProperty("includeCronDirectDeliveryContext");
139168
expect(ctx.ChannelStructuredContext?.[0]).toMatchObject({
140169
source: "session",
141170
payload: {

‎src/channels/inbound-event/session-transcript-context.runtime.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,11 +119,15 @@ export async function mergeSessionTranscriptContext(params: {
119119
if (!agentId) {
120120
throw new Error("Session transcript context requires an agent owner.");
121121
}
122+
const windows = chatWindowEntries(params.ctx);
122123
const turns = await readRecentUserAssistantTextForSession({
123124
agentId,
124125
sessionKey: params.sessionKey,
125126
storePath: params.storePath,
126127
limit,
128+
...(windows.length === 0 && options?.chatWindow === true
129+
? { includeCronDirectDeliveryContext: true }
130+
: {}),
127131
...((options?.beforeTimestampMs ?? params.ctx.Timestamp) !== undefined
128132
? { beforeTimestampMs: options?.beforeTimestampMs ?? params.ctx.Timestamp }
129133
: {}),
@@ -154,7 +158,6 @@ export async function mergeSessionTranscriptContext(params: {
154158
if (transcript.length === 0) {
155159
return;
156160
}
157-
const windows = chatWindowEntries(params.ctx);
158161
if (windows.length === 0 && options?.chatWindow) {
159162
params.ctx.ChannelStructuredContext = [
160163
...(params.ctx.ChannelStructuredContext ?? []),

‎src/config/sessions/transcript.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { normalizeLegacySessionEntryDelivery } from "../../infra/state-migration
99
import * as transcriptEvents from "../../sessions/transcript-events.js";
1010
import type { InternalSessionTranscriptUpdate } from "../../sessions/transcript-events.js";
1111
import {
12+
CRON_DIRECT_DELIVERY_CONTEXT_KIND,
1213
OPENCLAW_DELIVERY_MIRROR_MODEL,
1314
OPENCLAW_TRANSCRIPT_ARTIFACT_API,
1415
OPENCLAW_TRANSCRIPT_ARTIFACT_PROVIDER,
@@ -1015,6 +1016,52 @@ describe("appendAssistantMessageToSessionTranscript", () => {
10151016
]);
10161017
});
10171018

1019+
it("admits only marked Cron delivery context when explicitly requested", async () => {
1020+
await writeTranscriptStore();
1021+
await persistSessionTranscriptTurn(createFixtureTranscriptScope(), {
1022+
updateMode: "none",
1023+
messages: [
1024+
{ eventId: "user", message: { role: "user", content: "ordinary user" } },
1025+
{ eventId: "assistant", message: { role: "assistant", content: "ordinary assistant" } },
1026+
],
1027+
});
1028+
await appendAssistantMessageToSessionTranscript({
1029+
sessionKey,
1030+
storePath: fixture.storePath(),
1031+
text: "scheduled result",
1032+
idempotencyKey: "cron-delivery",
1033+
deliveryMirror: { kind: CRON_DIRECT_DELIVERY_CONTEXT_KIND },
1034+
});
1035+
await appendAssistantMessageToSessionTranscript({
1036+
sessionKey,
1037+
storePath: fixture.storePath(),
1038+
text: "ordinary delivery mirror",
1039+
idempotencyKey: "channel-delivery",
1040+
deliveryMirror: { kind: "channel-final" },
1041+
});
1042+
const params = {
1043+
agentId: "main",
1044+
sessionKey,
1045+
storePath: fixture.storePath(),
1046+
limit: 10,
1047+
};
1048+
1049+
await expect(readRecentUserAssistantTextForSession(params)).resolves.toEqual([
1050+
expect.objectContaining({ role: "user", text: "ordinary user" }),
1051+
expect.objectContaining({ role: "assistant", text: "ordinary assistant" }),
1052+
]);
1053+
await expect(
1054+
readRecentUserAssistantTextForSession({
1055+
...params,
1056+
includeCronDirectDeliveryContext: true,
1057+
}),
1058+
).resolves.toEqual([
1059+
expect.objectContaining({ role: "user", text: "ordinary user" }),
1060+
expect.objectContaining({ role: "assistant", text: "ordinary assistant" }),
1061+
expect.objectContaining({ role: "assistant", text: "scheduled result" }),
1062+
]);
1063+
});
1064+
10181065
it("reads recent context only from the active transcript branch", async () => {
10191066
await writeTranscriptStore();
10201067
await persistSessionTranscriptTurn(

‎src/config/sessions/transcript.ts‎

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,11 @@ import {
1515
extractFirstTextBlock,
1616
} from "../../shared/chat-message-content.js";
1717
import {
18+
CRON_DIRECT_DELIVERY_CONTEXT_KIND,
1819
OPENCLAW_DELIVERY_MIRROR_MODEL,
1920
OPENCLAW_TRANSCRIPT_ARTIFACT_API,
2021
OPENCLAW_TRANSCRIPT_ARTIFACT_PROVIDER,
21-
isTranscriptOnlyOpenClawAssistantModel,
22+
isTranscriptOnlyOpenClawAssistantMessage,
2223
} from "../../shared/transcript-only-openclaw-assistant.js";
2324
import type { OpenClawConfig } from "../types.openclaw.js";
2425
import {
@@ -101,6 +102,9 @@ type InternalSessionTranscriptDeliveryMirror =
101102
final: boolean;
102103
sourceTurnId?: string;
103104
toolCallId?: string;
105+
}
106+
| {
107+
kind: typeof CRON_DIRECT_DELIVERY_CONTEXT_KIND;
104108
};
105109

106110
export type SessionTranscriptAssistantMessage = Parameters<SessionManager["appendMessage"]>[0] & {
@@ -123,6 +127,7 @@ export type SessionRecentConversationText = {
123127

124128
type ReadRecentSessionConversationTextOptions = {
125129
beforeTimestampMs?: number;
130+
includeCronDirectDeliveryContext?: boolean;
126131
limit?: number;
127132
minTimestampMs?: number;
128133
role?: "user" | "assistant";
@@ -186,13 +191,6 @@ function parseAssistantTranscriptText(
186191
};
187192
}
188193

189-
function isTranscriptOnlyOpenClawAssistantMessage(message: {
190-
provider?: unknown;
191-
model?: unknown;
192-
}): boolean {
193-
return isTranscriptOnlyOpenClawAssistantModel(message.provider, message.model);
194-
}
195-
196194
type SessionConversationTranscriptTarget = {
197195
sqliteScope?: SqliteSessionFileMarker;
198196
};
@@ -212,6 +210,7 @@ function parseRecentConversationText(
212210
provenance?: unknown;
213211
provider?: unknown;
214212
model?: unknown;
213+
openclawDeliveryMirror?: unknown;
215214
__openclaw?: unknown;
216215
}
217216
| undefined;
@@ -222,7 +221,19 @@ function parseRecentConversationText(
222221
) {
223222
return undefined;
224223
}
225-
if (message.role === "assistant" && isTranscriptOnlyOpenClawAssistantMessage(message)) {
224+
const deliveryMirror = message.openclawDeliveryMirror;
225+
const includeCronDirectDeliveryContext =
226+
options.includeCronDirectDeliveryContext === true &&
227+
deliveryMirror !== null &&
228+
typeof deliveryMirror === "object" &&
229+
!Array.isArray(deliveryMirror) &&
230+
"kind" in deliveryMirror &&
231+
deliveryMirror.kind === CRON_DIRECT_DELIVERY_CONTEXT_KIND;
232+
if (
233+
message.role === "assistant" &&
234+
isTranscriptOnlyOpenClawAssistantMessage(message) &&
235+
!includeCronDirectDeliveryContext
236+
) {
226237
return undefined;
227238
}
228239
const upstreamUserText =
@@ -752,7 +763,8 @@ function isIdentifiedDeliveryMirror(message: SessionTranscriptAssistantMessage):
752763
isRedundantDeliveryMirror(message) &&
753764
(marker?.kind === "channel-final" ||
754765
marker?.kind === "channel-final-suppressed" ||
755-
marker?.kind === "message-tool-source-reply")
766+
marker?.kind === "message-tool-source-reply" ||
767+
marker?.kind === CRON_DIRECT_DELIVERY_CONTEXT_KIND)
756768
);
757769
}
758770

‎src/cron/isolated-agent/delivery-dispatch-awareness.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import { hasReplyPayloadContent } from "../../interactive/payload.js";
2121
import { parseThreadSessionSuffix } from "../../routing/session-key.js";
2222
import { beginSessionWorkAdmission } from "../../sessions/session-lifecycle-admission.js";
2323
import { createLazyImportLoader } from "../../shared/lazy-promise.js";
24+
import { CRON_DIRECT_DELIVERY_CONTEXT_KIND } from "../../shared/transcript-only-openclaw-assistant.js";
2425
import type { CronJob } from "../types.js";
2526
import {
2627
buildDirectCronDeliveryIdempotencyKey,
@@ -44,6 +45,7 @@ export type DirectCronTranscriptMirror = {
4445
mediaUrls?: string[];
4546
storePath?: string;
4647
idempotencyKey: string;
48+
deliveryMirror?: { kind: typeof CRON_DIRECT_DELIVERY_CONTEXT_KIND };
4749
config: OpenClawConfig;
4850
};
4951

‎src/cron/isolated-agent/delivery-dispatch.double-announce.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1751,6 +1751,9 @@ describe("dispatchCronDelivery — double-announce guard", () => {
17511751
mediaUrls: undefined,
17521752
}),
17531753
);
1754+
expect(
1755+
vi.mocked(appendAssistantMessageToSessionTranscript).mock.calls[0]?.[0],
1756+
).not.toHaveProperty("deliveryMirror");
17541757
expect(enqueueSystemEvent).toHaveBeenCalledWith("Redacted cron update.", {
17551758
sessionKey: "agent:main:main",
17561759
contextKey: "cron-direct-delivery:v1:cron:test-job:1000:telegram::123456:",
@@ -2113,6 +2116,7 @@ describe("dispatchCronDelivery — double-announce guard", () => {
21132116
});
21142117

21152118
it("skips main-session awareness for best-effort deliveries", async () => {
2119+
mockResolvedOutboundRoute();
21162120
const params = makeBaseParams({
21172121
synthesizedText: "Best-effort cron update.",
21182122
deliveryBestEffort: true,
@@ -2124,6 +2128,12 @@ describe("dispatchCronDelivery — double-announce guard", () => {
21242128
expect(state.deliveryAttempted).toBe(true);
21252129
expect(deliverOutboundPayloads).toHaveBeenCalledTimes(1);
21262130
expect(enqueueSystemEvent).not.toHaveBeenCalled();
2131+
expect(appendAssistantMessageToSessionTranscript).toHaveBeenCalledWith(
2132+
expect.objectContaining({
2133+
sessionKey: "agent:main:telegram:direct:123456",
2134+
deliveryMirror: { kind: "cron-direct-delivery-context" },
2135+
}),
2136+
);
21272137
});
21282138

21292139
it("skips stale cron deliveries while still suppressing fallback main summary", async () => {

‎src/cron/isolated-agent/delivery-dispatch.ts‎

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import { hasReplyPayloadContent } from "../../interactive/payload.js";
1616
import { stringifyRouteThreadId } from "../../plugin-sdk/channel-route.js";
1717
import { isCronSessionKey } from "../../routing/session-key.js";
1818
import { createLazyImportLoader } from "../../shared/lazy-promise.js";
19+
import { CRON_DIRECT_DELIVERY_CONTEXT_KIND } from "../../shared/transcript-only-openclaw-assistant.js";
1920
import { resolveAdmittedCronCompletionStatus } from "../completion-status.js";
2021
import { normalizeCronRunErrorText } from "../service/execution-errors.js";
2122
import type { CronResolvedDeliveryState } from "../types.js";
@@ -505,14 +506,17 @@ export async function dispatchCronDelivery(
505506
delivery,
506507
deliveryBestEffort: params.deliveryBestEffort,
507508
});
509+
const targetSessionAwarenessText =
510+
!params.deliveryBestEffort &&
511+
(shouldQueueAwarenessForDelivery ||
512+
!isSameSessionKey(deliverySessionKey, awarenessMainSessionKey))
513+
? deliveryAwarenessText
514+
: undefined;
508515
// For explicit isolated deliveries that resolve to the main session, the
509516
// awareness queue is the intentional main-session record on the next turn;
510517
// adding an immediate assistant mirror would make the cron text appear twice.
511-
const awarenessText = shouldQueueAwarenessForDelivery ? deliveryAwarenessText : undefined;
512518
const deliveryWillReachAwarenessMainSession =
513-
mirrorTargetsAwarenessMainSession &&
514-
shouldQueueAwarenessForDelivery &&
515-
Boolean(awarenessText);
519+
mirrorTargetsAwarenessMainSession && Boolean(targetSessionAwarenessText);
516520
// Implicit/default isolated delivery must not create main-session awareness.
517521
const mirrorWouldBypassIsolatedAwarenessPolicy =
518522
mirrorTargetsAwarenessMainSession &&
@@ -557,6 +561,10 @@ export async function dispatchCronDelivery(
557561
agentId: params.agentId,
558562
}),
559563
idempotencyKey: deliveryIdempotencyKey,
564+
// The durable marker is a fallback only when target awareness is absent.
565+
...(targetSessionAwarenessText === undefined
566+
? { deliveryMirror: { kind: CRON_DIRECT_DELIVERY_CONTEXT_KIND } }
567+
: {}),
560568
config: params.cfgWithAgentDefaults,
561569
};
562570
if (mirrorTargetsDeletingRunSession) {
@@ -569,20 +577,14 @@ export async function dispatchCronDelivery(
569577
});
570578
}
571579
}
572-
if (
573-
deliveryState.delivered &&
574-
!params.deliveryBestEffort &&
575-
deliveryAwarenessText &&
576-
(shouldQueueAwarenessForDelivery ||
577-
!isSameSessionKey(deliverySessionKey, awarenessMainSessionKey))
578-
) {
580+
if (deliveryState.delivered && targetSessionAwarenessText) {
579581
await queueCronAwarenessSystemEvent({
580582
cfg: params.cfgWithAgentDefaults,
581583
jobId: params.job.id,
582584
agentId: params.agentId,
583585
deliveryIdempotencyKey,
584586
queueMainSession: shouldQueueAwarenessForDelivery,
585-
text: deliveryAwarenessText,
587+
text: targetSessionAwarenessText,
586588
targetSessionKey: deliverySessionKey,
587589
});
588590
}

0 commit comments

Comments
 (0)