Skip to content

Commit 63e6869

Browse files
authored
fix(cron): persist delivery suppression reason and log strict failures (#130811)
1 parent 2a41b4e commit 63e6869

24 files changed

Lines changed: 173 additions & 4 deletions

‎apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16582,6 +16582,7 @@ public struct CronJob: Codable, Sendable {
1658216582
public let lastdelivered: Bool?
1658316583
public let lastdeliverystatus: AnyCodable?
1658416584
public let lastdeliveryerror: String?
16585+
public let deliverysuppressionreason: String?
1658516586
public let lastfailurenotificationdelivered: Bool?
1658616587
public let lastfailurenotificationdeliverystatus: AnyCodable?
1658716588
public let lastfailurenotificationdeliveryerror: String?
@@ -16617,6 +16618,7 @@ public struct CronJob: Codable, Sendable {
1661716618
lastdelivered: Bool? = nil,
1661816619
lastdeliverystatus: AnyCodable? = nil,
1661916620
lastdeliveryerror: String? = nil,
16621+
deliverysuppressionreason: String? = nil,
1662016622
lastfailurenotificationdelivered: Bool? = nil,
1662116623
lastfailurenotificationdeliverystatus: AnyCodable? = nil,
1662216624
lastfailurenotificationdeliveryerror: String? = nil)
@@ -16651,6 +16653,7 @@ public struct CronJob: Codable, Sendable {
1665116653
self.lastdelivered = lastdelivered
1665216654
self.lastdeliverystatus = lastdeliverystatus
1665316655
self.lastdeliveryerror = lastdeliveryerror
16656+
self.deliverysuppressionreason = deliverysuppressionreason
1665416657
self.lastfailurenotificationdelivered = lastfailurenotificationdelivered
1665516658
self.lastfailurenotificationdeliverystatus = lastfailurenotificationdeliverystatus
1665616659
self.lastfailurenotificationdeliveryerror = lastfailurenotificationdeliveryerror
@@ -16687,6 +16690,7 @@ public struct CronJob: Codable, Sendable {
1668716690
case lastdelivered = "lastDelivered"
1668816691
case lastdeliverystatus = "lastDeliveryStatus"
1668916692
case lastdeliveryerror = "lastDeliveryError"
16693+
case deliverysuppressionreason = "deliverySuppressionReason"
1669016694
case lastfailurenotificationdelivered = "lastFailureNotificationDelivered"
1669116695
case lastfailurenotificationdeliverystatus = "lastFailureNotificationDeliveryStatus"
1669216696
case lastfailurenotificationdeliveryerror = "lastFailureNotificationDeliveryError"
@@ -16948,6 +16952,7 @@ public struct CronRunLogEntry: Codable, Sendable {
1694816952
public let delivered: Bool?
1694916953
public let deliverystatus: AnyCodable?
1695016954
public let deliveryerror: String?
16955+
public let deliverysuppressionreason: String?
1695116956
public let failurenotificationdelivery: [String: AnyCodable]?
1695216957
public let delivery: [String: AnyCodable]?
1695316958
public let sessionid: String?
@@ -16975,6 +16980,7 @@ public struct CronRunLogEntry: Codable, Sendable {
1697516980
delivered: Bool? = nil,
1697616981
deliverystatus: AnyCodable? = nil,
1697716982
deliveryerror: String? = nil,
16983+
deliverysuppressionreason: String? = nil,
1697816984
failurenotificationdelivery: [String: AnyCodable]? = nil,
1697916985
delivery: [String: AnyCodable]? = nil,
1698016986
sessionid: String? = nil,
@@ -17001,6 +17007,7 @@ public struct CronRunLogEntry: Codable, Sendable {
1700117007
self.delivered = delivered
1700217008
self.deliverystatus = deliverystatus
1700317009
self.deliveryerror = deliveryerror
17010+
self.deliverysuppressionreason = deliverysuppressionreason
1700417011
self.failurenotificationdelivery = failurenotificationdelivery
1700517012
self.delivery = delivery
1700617013
self.sessionid = sessionid
@@ -17029,6 +17036,7 @@ public struct CronRunLogEntry: Codable, Sendable {
1702917036
case delivered
1703017037
case deliverystatus = "deliveryStatus"
1703117038
case deliveryerror = "deliveryError"
17039+
case deliverysuppressionreason = "deliverySuppressionReason"
1703217040
case failurenotificationdelivery = "failureNotificationDelivery"
1703317041
case delivery
1703417042
case sessionid = "sessionId"

‎docs/automation/cron-jobs.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1017,6 +1017,7 @@ openclaw doctor
10171017
- Delivery target missing/invalid (`channel`/`to`) means outbound was skipped.
10181018
- For Matrix, copied or legacy jobs with lowercased `delivery.to` room IDs can fail because Matrix room IDs are case-sensitive. Edit the job to the exact `!room:server` or `room:!room:server` value from Matrix.
10191019
- Channel auth errors (`unauthorized`, `Forbidden`) mean delivery was blocked by credentials.
1020+
- When the dispatcher records intentional suppression, job state, run history, and finished events include `deliverySuppressionReason` (`empty`, `silent`, `heartbeat`, or `channel_transform`). This is separate from `lastDeliveryError` / `deliveryError`; required delivery failures also log an error when they happen.
10201021
- If the isolated run returns only the silent token (`NO_REPLY` / `no_reply`), OpenClaw suppresses direct outbound delivery and the fallback queued-summary path, so nothing is posted back to chat.
10211022
- If the agent should message the user itself, check that the job has a usable route (`channel: "last"` with a previous chat, or an explicit channel/target).
10221023

‎packages/gateway-protocol/src/schema/cron.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -509,6 +509,7 @@ export const CronJobStateSchema = closedObject({
509509
lastDelivered: Type.Optional(Type.Boolean()),
510510
lastDeliveryStatus: Type.Optional(CronDeliveryStatusSchema),
511511
lastDeliveryError: Type.Optional(Type.String()),
512+
deliverySuppressionReason: Type.Optional(Type.String()),
512513
lastFailureNotificationDelivered: Type.Optional(Type.Boolean()),
513514
lastFailureNotificationDeliveryStatus: Type.Optional(CronDeliveryStatusSchema),
514515
lastFailureNotificationDeliveryError: Type.Optional(Type.String()),
@@ -614,6 +615,7 @@ export const CronJobSchema = closedObject({
614615
lastDelivered: Type.Optional(Type.Boolean()),
615616
lastDeliveryStatus: Type.Optional(CronDeliveryStatusSchema),
616617
lastDeliveryError: Type.Optional(Type.String()),
618+
deliverySuppressionReason: Type.Optional(Type.String()),
617619
lastFailureNotificationDelivered: Type.Optional(Type.Boolean()),
618620
lastFailureNotificationDeliveryStatus: Type.Optional(CronDeliveryStatusSchema),
619621
lastFailureNotificationDeliveryError: Type.Optional(Type.String()),
@@ -773,6 +775,7 @@ export const CronRunLogEntrySchema = closedObject({
773775
delivered: Type.Optional(Type.Boolean()),
774776
deliveryStatus: Type.Optional(CronDeliveryStatusSchema),
775777
deliveryError: Type.Optional(Type.String()),
778+
deliverySuppressionReason: Type.Optional(Type.String()),
776779
failureNotificationDelivery: Type.Optional(CronFailureNotificationDeliverySchema),
777780
delivery: Type.Optional(CronDeliveryTraceSchema),
778781
sessionId: Type.Optional(NonEmptyString),

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,7 @@ import {
188188
} from "../../infra/outbound/outbound-session.js";
189189
import { buildOutboundSessionContext } from "../../infra/outbound/session-context.js";
190190
import { enqueueSystemEvent } from "../../infra/system-events.js";
191+
import { logError } from "../../logger.js";
191192
import {
192193
dispatchCronDelivery,
193194
queueCronMessageToolDeliveryAwareness,
@@ -3147,6 +3148,9 @@ describe("dispatchCronDelivery — double-announce guard", () => {
31473148
error: "boom",
31483149
deliveryAttempted: true,
31493150
});
3151+
expect(logError).toHaveBeenCalledExactlyOnceWith(
3152+
"[cron:test-job] delivery failed (required): boom",
3153+
);
31503154
});
31513155

31523156
it("records structured direct delivery failures when best-effort is enabled", async () => {
@@ -3165,6 +3169,9 @@ describe("dispatchCronDelivery — double-announce guard", () => {
31653169
expect(state.delivered).toBe(false);
31663170
expect(state.deliveryAttempted).toBe(true);
31673171
expect(state.deliveryError).toBe("boom");
3172+
expect(logError).toHaveBeenCalledExactlyOnceWith(
3173+
"[cron:test-job] delivery failed (bestEffort): boom",
3174+
);
31683175
});
31693176

31703177
it("no delivery requested means deliveryAttempted stays false and no delivery is sent", async () => {

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -577,6 +577,9 @@ export async function dispatchCronDelivery(
577577
}
578578
return null;
579579
} catch (err) {
580+
await logCronDeliveryError(
581+
`[cron:${params.job.id}] delivery failed (${params.deliveryBestEffort ? "bestEffort" : "required"}): ${formatErrorMessage(err)}`,
582+
);
580583
if (!params.deliveryBestEffort) {
581584
return params.withRunSession({
582585
status: "error",
@@ -587,9 +590,6 @@ export async function dispatchCronDelivery(
587590
...params.telemetry,
588591
});
589592
}
590-
await logCronDeliveryError(
591-
`[cron:${params.job.id}] delivery failed (bestEffort): ${formatErrorMessage(err)}`,
592-
);
593593
deliveryError = formatErrorMessage(err);
594594
return null;
595595
}

‎src/cron/isolated-agent/run-finalize.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,7 @@ export async function finalizeCronRun(params: {
366366
delivered?: boolean;
367367
deliveryAttempted?: boolean;
368368
deliveryError?: string;
369+
deliverySuppressionReason?: RunCronAgentTurnResult["deliverySuppressionReason"];
369370
delivery?: CronDeliveryTrace;
370371
}) =>
371372
prepared.withRunSession({
@@ -378,6 +379,7 @@ export async function finalizeCronRun(params: {
378379
delivered: result?.delivered,
379380
deliveryAttempted: result?.deliveryAttempted,
380381
deliveryError: result?.deliveryError,
382+
deliverySuppressionReason: result?.deliverySuppressionReason,
381383
delivery: result?.delivery,
382384
diagnostics: mergeCronRunDiagnostics(
383385
runDiagnostics,
@@ -602,6 +604,7 @@ export async function finalizeCronRun(params: {
602604
return resolveRunOutcome({
603605
delivered: deliveryResult.result.delivered,
604606
deliveryAttempted: resultWithDeliveryMeta.deliveryAttempted,
607+
deliverySuppressionReason: resultWithDeliveryMeta.deliverySuppressionReason,
605608
delivery: deliveryTrace,
606609
});
607610
}
@@ -612,6 +615,7 @@ export async function finalizeCronRun(params: {
612615
delivered: deliveryResult.delivered,
613616
deliveryAttempted: deliveryResult.deliveryAttempted,
614617
deliveryError: deliveryResult.deliveryError,
618+
deliverySuppressionReason: deliveryResult.deliverySuppressionReason,
615619
delivery: deliveryTrace,
616620
});
617621
}

‎src/cron/run-log-types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
/** Stable cron run-history wire shape and legacy JSONL migration input. */
22
import type { FailoverReason } from "../agents/failover/signal.js";
3+
import type { NormalizeReplySkipReason } from "../auto-reply/reply/normalize-reply.js";
34
import type {
45
CronCompletionStatus,
56
CronDeliveryStatus,
@@ -24,6 +25,7 @@ export type CronRunLogEntry = {
2425
delivered?: boolean;
2526
deliveryStatus?: CronDeliveryStatus;
2627
deliveryError?: string;
28+
deliverySuppressionReason?: NormalizeReplySkipReason;
2729
failureNotificationDelivery?: CronFailureNotificationDelivery;
2830
delivery?: CronDeliveryTrace;
2931
sessionId?: string;
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
import { CronService, type CronEvent } from "./service.js";
3+
import { createFinishedBarrier, setupCronServiceSuite } from "./service.test-harness.js";
4+
import type { CronServiceDeps } from "./service/state.js";
5+
import { loadCronStore } from "./store.js";
6+
import { cronStoreKey } from "./store/key.js";
7+
import { readCronTaskRunHistoryPage } from "./task-run-history.js";
8+
9+
const { logger, makeStorePath } = setupCronServiceSuite();
10+
11+
describe("CronService persists delivery suppression", () => {
12+
it.each(["scheduled", "manual"] as const)(
13+
"persists %s delivery suppression in job state, history, and the finished event",
14+
async (mode) => {
15+
const { storePath } = await makeStorePath();
16+
const events: CronEvent[] = [];
17+
const finished = createFinishedBarrier();
18+
const runIsolatedAgentJob = vi.fn<CronServiceDeps["runIsolatedAgentJob"]>();
19+
runIsolatedAgentJob.mockResolvedValue({
20+
status: "ok",
21+
delivered: false,
22+
deliveryAttempted: true,
23+
deliverySuppressionReason: "channel_transform",
24+
});
25+
const cron = new CronService({
26+
storePath,
27+
cronEnabled: true,
28+
log: logger,
29+
enqueueSystemEvent: vi.fn(),
30+
requestHeartbeat: vi.fn(),
31+
runIsolatedAgentJob,
32+
onEvent: (event) => {
33+
if (event.action === "finished") {
34+
events.push(event);
35+
}
36+
finished.onEvent(event);
37+
},
38+
});
39+
await cron.start();
40+
try {
41+
const job = await cron.add({
42+
name: "suppression-readback",
43+
enabled: true,
44+
schedule: { kind: "every", everyMs: 60_000 },
45+
sessionTarget: "isolated",
46+
wakeMode: "next-heartbeat",
47+
payload: { kind: "agentTurn", message: "test" },
48+
delivery: { mode: "announce", channel: "forum", to: "123" },
49+
});
50+
if (mode === "scheduled") {
51+
const done = finished.waitForOk(job.id);
52+
await vi.advanceTimersByTimeAsync(job.state.nextRunAtMs! - Date.now());
53+
await done;
54+
} else {
55+
await cron.run(job.id, "force");
56+
}
57+
const persisted = (await loadCronStore(storePath)).jobs.find(
58+
(entry) => entry.id === job.id,
59+
);
60+
expect.soft(persisted?.state).toMatchObject({
61+
lastRunStatus: "ok",
62+
lastDelivered: false,
63+
lastDeliveryStatus: "not-delivered",
64+
deliverySuppressionReason: "channel_transform",
65+
});
66+
expect.soft(persisted?.state.lastDeliveryError).toBeUndefined();
67+
expect
68+
.soft(events)
69+
.toEqual([expect.objectContaining({ deliverySuppressionReason: "channel_transform" })]);
70+
const history = readCronTaskRunHistoryPage({
71+
storeKey: cronStoreKey(storePath),
72+
jobId: job.id,
73+
});
74+
expect
75+
.soft(history.entries)
76+
.toEqual([expect.objectContaining({ deliverySuppressionReason: "channel_transform" })]);
77+
78+
runIsolatedAgentJob.mockResolvedValue({ status: "ok", delivered: true });
79+
vi.setSystemTime(Date.now() + 1);
80+
await cron.run(job.id, "force");
81+
expect(
82+
(await loadCronStore(storePath)).jobs[0]?.state.deliverySuppressionReason,
83+
).toBeUndefined();
84+
expect(events.at(-1)?.deliverySuppressionReason).toBeUndefined();
85+
expect(
86+
readCronTaskRunHistoryPage({ storeKey: cronStoreKey(storePath), jobId: job.id })
87+
.entries[0]?.deliverySuppressionReason,
88+
).toBeUndefined();
89+
} finally {
90+
cron.stop();
91+
}
92+
},
93+
);
94+
});

‎src/cron/service/ops-run.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,7 @@ async function finishPreparedManualRun(
220220
? "queued manual run skipped: trigger condition not met"
221221
: coreResult.error,
222222
deliveryError: coreResult.deliveryError,
223+
deliverySuppressionReason: coreResult.deliverySuppressionReason,
223224
summary: triggerSkipped ? undefined : coreResult.summary,
224225
diagnostics: coreResult.diagnostics,
225226
delivered: coreResult.delivered,
@@ -382,6 +383,7 @@ async function finishPreparedManualRun(
382383
delivered: committed.job.state.lastDelivered,
383384
deliveryStatus: committed.job.state.lastDeliveryStatus,
384385
deliveryError: committed.job.state.lastDeliveryError,
386+
deliverySuppressionReason: committed.job.state.deliverySuppressionReason,
385387
failureNotificationDelivery: failureNotificationDeliveryFromJobState(committed.job),
386388
delivery: coreResult.delivery,
387389
sessionId: coreResult.sessionId,

‎src/cron/service/startup-run-repair.auto-disable.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ describe("startup run repair auto-disable", () => {
5252
runningAtMs,
5353
consecutiveErrors: 9,
5454
lastErrorReason: "timeout",
55+
deliverySuppressionReason: "silent",
5556
},
5657
};
5758
const deferredNotifications: Array<() => void> = [];
@@ -76,6 +77,7 @@ describe("startup run repair auto-disable", () => {
7677
},
7778
});
7879
expect(enqueueSystemEvent).not.toHaveBeenCalled();
80+
expect(job.state.deliverySuppressionReason).toBeUndefined();
7981
expect(requestHeartbeat).not.toHaveBeenCalled();
8082
expect(deferredNotifications).toHaveLength(1);
8183

0 commit comments

Comments
 (0)