Skip to content

Commit 181da6f

Browse files
authored
fix(cron): reject ambiguous multi-channel announce jobs (#118272)
* fix(cron): reject ambiguous announce delivery (#118236) * test(cron): move implicit announce ambiguity coverage to the service owner
1 parent 6c6e8fe commit 181da6f

11 files changed

Lines changed: 213 additions & 15 deletions

‎docs/automation/cron-jobs.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,8 @@ Agent-turn jobs default to the creating conversation when the create request car
326326

327327
Use `--announce --channel telegram --to "-1001234567890"` for channel delivery. For Telegram forum topics, use `-1001234567890:topic:123`; OpenClaw also accepts the Telegram-owned `-1001234567890:123` shorthand. Direct RPC/config callers may pass `delivery.threadId` as a string or number. Slack/Discord/Mattermost targets use explicit prefixes (`channel:<id>`, `user:<id>`). Matrix room IDs are case-sensitive; use the exact room ID or `room:!room:server` form from Matrix.
328328

329+
On hosts with multiple configured channels, isolated announce jobs created with `automations add|create` or changed with `automations edit` must set `--channel <id>` unless a provider-prefixed `--to` or a preserved session route selects the channel. Use `--best-effort-deliver` only when unresolved fallback delivery is acceptable; it does not choose a channel, and a delivery failure does not fail the job.
330+
329331
When announce delivery uses `channel: "last"` or omits `channel`, a provider-prefixed target such as `telegram:123` can select the channel before the scheduler falls back to session history or a single configured channel. Only prefixes advertised by the loaded plugin are provider selectors. If `delivery.channel` is explicit, the target prefix must name the same provider; `channel: "whatsapp"` with `to: "telegram:123"` is rejected instead of letting WhatsApp interpret the Telegram ID as a phone number. Target-kind and service prefixes (`channel:<id>`, `user:<id>`, `imessage:<handle>`, `sms:<number>`) stay channel-owned target syntax, not provider selectors.
330332

331333
For isolated jobs, chat delivery is shared: if a chat route is available, the agent can use the `message` tool even with `--no-deliver`. If the agent sends to the configured/current target, OpenClaw skips the fallback announce. Otherwise `announce`, `webhook`, and `none` only control what the runner does with the final reply after the agent turn.

‎src/cron/delivery-channel-validation.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,13 @@ async function assertConfiguredAnnounceChannel(params: {
3434
if (params.channel === "last") {
3535
return;
3636
}
37-
const configuredChannels = (await listConfiguredMessageChannels(params.cfg)).toSorted();
3837
const normalizedChannel = normalizeMessageChannel(params.channel);
38+
if (!normalizedChannel && params.field === "delivery.channel") {
39+
// Primary implicit routing is service-owned because session-backed and
40+
// best-effort jobs must remain valid even on multi-channel hosts.
41+
return;
42+
}
43+
const configuredChannels = (await listConfiguredMessageChannels(params.cfg)).toSorted();
3944
if (!normalizedChannel) {
4045
if (configuredChannels.length <= 1) {
4146
return;

‎src/cron/service.jobs.test.ts‎

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -558,6 +558,108 @@ function createMockState(
558558
} as unknown as CronServiceState;
559559
}
560560

561+
describe("announce delivery channel validation", () => {
562+
const now = Date.parse("2026-08-02T12:00:00.000Z");
563+
const configuredChannels = ["reef", "discord"];
564+
const input = (delivery: CronJob["delivery"], overrides?: { sessionKey?: string }) => ({
565+
name: "multi-channel announce",
566+
enabled: true,
567+
schedule: { kind: "every" as const, everyMs: 60_000 },
568+
sessionTarget: "isolated" as const,
569+
wakeMode: "now" as const,
570+
payload: { kind: "agentTurn" as const, message: "report" },
571+
delivery,
572+
...overrides,
573+
});
574+
575+
it("rejects creation when an isolated announce has no deterministic channel", () => {
576+
expect(() =>
577+
createJob(createMockState(now), input({ mode: "announce", channel: "last" }), {
578+
configuredChannels,
579+
}),
580+
).toThrow(
581+
"cron announce delivery requires an explicit channel when multiple channels are configured (discord, reef): set --channel <id> or use --best-effort-deliver",
582+
);
583+
});
584+
585+
it("accepts creation with an explicit channel", () => {
586+
expect(() =>
587+
createJob(createMockState(now), input({ mode: "announce", channel: "discord" }), {
588+
configuredChannels,
589+
}),
590+
).not.toThrow();
591+
});
592+
593+
it("accepts creation when best-effort delivery is explicit", () => {
594+
expect(() =>
595+
createJob(
596+
createMockState(now),
597+
input({ mode: "announce", channel: "last", bestEffort: true }),
598+
{ configuredChannels },
599+
),
600+
).not.toThrow();
601+
});
602+
603+
it("accepts creation when only one channel is configured", () => {
604+
expect(() =>
605+
createJob(createMockState(now), input({ mode: "announce", channel: "last" }), {
606+
configuredChannels: ["discord"],
607+
}),
608+
).not.toThrow();
609+
});
610+
611+
it.each([
612+
[
613+
"a preserved session route",
614+
input(
615+
{ mode: "announce", channel: "last" },
616+
{ sessionKey: "agent:main:discord:channel:ops" },
617+
),
618+
],
619+
[
620+
"a provider-prefixed target",
621+
input({ mode: "announce", channel: "last", to: "telegram:123" }),
622+
],
623+
])("accepts creation with %s", (_name, jobInput) => {
624+
expect(() => createJob(createMockState(now), jobInput, { configuredChannels })).not.toThrow();
625+
});
626+
627+
it("keeps enabled-only patches working for stored ambiguous jobs", () => {
628+
const job = createJob(createMockState(now), input({ mode: "announce", channel: "discord" }), {
629+
configuredChannels,
630+
});
631+
// Simulate a job persisted before service-level ambiguity validation shipped.
632+
job.delivery = { mode: "announce", channel: "last" };
633+
634+
expect(() => applyJobPatch(job, { enabled: false }, { configuredChannels })).not.toThrow();
635+
expect(job.enabled).toBe(false);
636+
});
637+
638+
it("revalidates patches that change delivery resolution", () => {
639+
const job = createJob(createMockState(now), input({ mode: "announce", channel: "discord" }), {
640+
configuredChannels,
641+
});
642+
643+
expect(() =>
644+
applyJobPatch(job, { delivery: { channel: "last" } }, { configuredChannels }),
645+
).toThrow("cron announce delivery requires an explicit channel");
646+
});
647+
648+
it("rejects ambiguous declarative convergence", () => {
649+
const job = createJob(createMockState(now), input({ mode: "announce", channel: "discord" }), {
650+
configuredChannels,
651+
});
652+
653+
expect(() =>
654+
applyDeclarativeJobSpec(job, input({ mode: "announce", channel: "last" }), {
655+
enabledExplicit: true,
656+
nowMs: now,
657+
configuredChannels,
658+
}),
659+
).toThrow("cron announce delivery requires an explicit channel");
660+
});
661+
});
662+
561663
describe("cron tool authority defaults", () => {
562664
const now = Date.parse("2026-07-21T12:00:00.000Z");
563665

‎src/cron/service/jobs-validation.ts‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,10 @@ import { resolveCronTriggerMinIntervalMs } from "../../config/cron-limits.js";
44
import type { CronConfig } from "../../config/types.cron.js";
55
import { normalizeAgentId } from "../../routing/session-key.js";
66
import { compileSafeRegexDetailed } from "../../security/safe-regex.js";
7+
import { resolveCronDeliveryPlan } from "../delivery-plan.js";
78
import { parseCronPacingBounds } from "../pacing.js";
89
import { assertSafeCronSessionTargetId } from "../session-target.js";
9-
import type { CronDelivery, CronJob } from "../types.js";
10+
import type { CronDelivery, CronJob, CronJobPatch } from "../types.js";
1011
import { normalizeHttpWebhookUrl } from "../webhook-url.js";
1112

1213
/** Validates that session target and payload kind form a supported cron job shape. */
@@ -239,6 +240,46 @@ export function assertDeliverySupport(job: Pick<CronJob, "sessionTarget" | "deli
239240
}
240241
}
241242

243+
export function assertAnnounceDeliveryChannelSupport(
244+
job: CronJob,
245+
configuredChannels?: readonly string[],
246+
patch?: CronJobPatch,
247+
) {
248+
if (patch && !cronPatchTouchesDeliveryResolution(patch)) {
249+
return;
250+
}
251+
const plan = resolveCronDeliveryPlan(job);
252+
const channels = [...new Set(configuredChannels ?? [])].toSorted();
253+
// Provider-prefix recognition is plugin-backed and may not be loaded at this
254+
// seam. A prefixed target can still select its channel at runtime, so accept.
255+
const targetMaySelectChannel = /^[a-z][a-z0-9_-]*:/i.test(plan.to ?? "");
256+
if (
257+
job.sessionTarget !== "isolated" ||
258+
job.sessionKey?.trim() ||
259+
plan.mode !== "announce" ||
260+
(plan.channel !== undefined && plan.channel !== "last") ||
261+
targetMaySelectChannel ||
262+
job.delivery?.bestEffort === true ||
263+
channels.length < 2
264+
) {
265+
return;
266+
}
267+
throw new Error(
268+
`cron announce delivery requires an explicit channel when multiple channels are configured (${channels.join(", ")}): set --channel <id> or use --best-effort-deliver`,
269+
);
270+
}
271+
272+
export function cronPatchTouchesDeliveryResolution(patch: CronJobPatch): boolean {
273+
// Legacy ambiguous jobs must remain disableable and renameable. Only fields
274+
// that can change the delivery identity opt a patch back into validation.
275+
return (
276+
patch.delivery !== undefined ||
277+
patch.sessionTarget !== undefined ||
278+
"agentId" in patch ||
279+
"sessionKey" in patch
280+
);
281+
}
282+
242283
export function hasConcreteFailureDestination(
243284
destination: CronDelivery["failureDestination"] | undefined,
244285
): boolean {

‎src/cron/service/jobs.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import {
3333
resolveEveryAnchorMs,
3434
} from "./jobs-scheduling.js";
3535
import {
36+
assertAnnounceDeliveryChannelSupport,
3637
assertCronExpressionSatisfiable,
3738
assertDeliverySupport,
3839
assertFailureDestinationSupport,
@@ -49,6 +50,7 @@ import { mergeCronPayload } from "./payload-merge.js";
4950
import type { CronServiceState } from "./state.js";
5051

5152
const CRON_DECLARATIVE_LABEL_MAX_LENGTH = 200;
53+
type DeliveryValidationOptions = { configuredChannels?: readonly string[] };
5254

5355
export { assertSupportedJobSpec };
5456

@@ -119,7 +121,7 @@ function reconcileScheduledToolPolicy(params: {
119121
export function createJob(
120122
state: CronServiceState,
121123
input: CronJobCreate,
122-
opts?: { scheduledToolPolicy?: CronScheduledToolPolicy },
124+
opts?: DeliveryValidationOptions & { scheduledToolPolicy?: CronScheduledToolPolicy },
123125
): CronJob {
124126
const now = state.deps.nowMs();
125127
const id = normalizeOptionalString(input.id) ?? crypto.randomUUID();
@@ -235,6 +237,7 @@ export function createJob(
235237
});
236238
assertMainSessionAgentId(job, state.deps.defaultAgentId);
237239
assertDeliverySupport(job);
240+
assertAnnounceDeliveryChannelSupport(job, opts?.configuredChannels);
238241
assertFailureDestinationSupport(job);
239242
assertCronExpressionSatisfiable(job, now, computeJobNextRunAtMs);
240243
job.state.nextRunAtMs = computeJobNextRunAtMs(job, now);
@@ -250,7 +253,7 @@ export function applyJobPatch(
250253
scheduleValidationNowMs?: number;
251254
cronConfig?: CronConfig;
252255
scheduledToolPolicy?: CronScheduledToolPolicy;
253-
},
256+
} & DeliveryValidationOptions,
254257
) {
255258
const previouslyUsedToolRuntime = cronJobUsesToolRuntime(job);
256259
const explicitlyClearsToolsAllow = patch.payload?.toolsAllow === null;
@@ -434,6 +437,7 @@ export function applyJobPatch(
434437
});
435438
assertMainSessionAgentId(job, opts?.defaultAgentId);
436439
assertDeliverySupport(job);
440+
assertAnnounceDeliveryChannelSupport(job, opts?.configuredChannels, patch);
437441
assertFailureDestinationSupport(job);
438442
if (
439443
opts?.scheduleValidationNowMs !== undefined &&
@@ -453,7 +457,7 @@ export function applyDeclarativeJobSpec(
453457
nowMs: number;
454458
cronConfig?: CronConfig;
455459
scheduledToolPolicy?: CronScheduledToolPolicy;
456-
},
460+
} & DeliveryValidationOptions,
457461
) {
458462
const previouslyUsedToolRuntime = cronJobUsesToolRuntime(job);
459463
const explicitlyDeclaresToolsAllow = input.payload.toolsAllow !== undefined;
@@ -558,6 +562,7 @@ export function applyDeclarativeJobSpec(
558562
assertPacingSupport(job);
559563
assertMainSessionAgentId(job, opts.defaultAgentId);
560564
assertDeliverySupport(job);
565+
assertAnnounceDeliveryChannelSupport(job, opts.configuredChannels);
561566
assertFailureDestinationSupport(job);
562567
assertCronExpressionSatisfiable(job, opts.nowMs, computeJobNextRunAtMs);
563568
}

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import { removeStaleCronJobFamilyRows } from "../store.js";
1616
import { createCronStreamSourceIdentity, cronStreamScheduleKey } from "../stream-schedule.js";
1717
import { normalizeCronTaskRunJobId } from "../task-run-history.js";
1818
import type { CronJob, CronJobCreate, CronJobPatch } from "../types.js";
19+
import { cronPatchTouchesDeliveryResolution } from "./jobs-validation.js";
1920
import {
2021
applyJobPatch,
2122
applyDeclarativeJobSpec,
@@ -48,6 +49,22 @@ import {
4849
} from "./store.js";
4950
import { armTimer } from "./timer.js";
5051

52+
async function resolveConfiguredChannelsForValidation(
53+
state: CronServiceState,
54+
): Promise<readonly string[] | undefined> {
55+
if (!state.deps.listConfiguredChannels) {
56+
return undefined;
57+
}
58+
try {
59+
return await state.deps.listConfiguredChannels();
60+
} catch {
61+
// Channel discovery is advisory at mutation time. Runtime delivery remains
62+
// authoritative, so discovery failures must not create false rejections.
63+
state.deps.log.debug({}, "cron: configured channel validation skipped");
64+
return undefined;
65+
}
66+
}
67+
5168
function reconcileStreamSourceIdentity(job: CronJob, nextJob: CronJob): void {
5269
if (nextJob.schedule.kind !== "stream") {
5370
nextJob.state.streamSourceIdentity = undefined;
@@ -229,6 +246,7 @@ export async function add(state: CronServiceState, input: CronJobCreate, opts?:
229246
throw new Error(`cron declarationKey is ambiguous within caller scope: ${declarationKey}`);
230247
}
231248
const existing = matches[0];
249+
const configuredChannels = await resolveConfiguredChannelsForValidation(state);
232250

233251
if (existing) {
234252
// A declarative upsert may not repurpose an existing heartbeat monitor
@@ -246,6 +264,7 @@ export async function add(state: CronServiceState, input: CronJobCreate, opts?:
246264
nowMs: now,
247265
cronConfig: state.deps.cronConfig,
248266
scheduledToolPolicy: opts?.scheduledToolPolicy,
267+
configuredChannels,
249268
});
250269
const includeEnabled = opts?.enabledExplicit === true;
251270
if (
@@ -274,6 +293,7 @@ export async function add(state: CronServiceState, input: CronJobCreate, opts?:
274293
const snapshot = snapshotStoreForRollback(state);
275294
const job = createJob(state, normalizedInput, {
276295
scheduledToolPolicy: opts?.scheduledToolPolicy,
296+
configuredChannels,
277297
});
278298
state.store?.jobs.push(job);
279299

@@ -352,11 +372,15 @@ export async function updateLoadedJob(params: {
352372
const now = state.deps.nowMs();
353373
await precondition?.(structuredClone(job), now);
354374
const nextJob = structuredClone(job);
375+
const configuredChannels = cronPatchTouchesDeliveryResolution(patch)
376+
? await resolveConfiguredChannelsForValidation(state)
377+
: undefined;
355378
applyJobPatch(nextJob, patch, {
356379
defaultAgentId: state.deps.defaultAgentId,
357380
scheduleValidationNowMs: now,
358381
cronConfig: state.deps.cronConfig,
359382
scheduledToolPolicy: opts?.scheduledToolPolicy,
383+
configuredChannels,
360384
});
361385
if (patch.agentId !== undefined) {
362386
const agentId = resolveEffectiveJobAgentId(nextJob, resolveCurrentDefaultAgentId(state));

‎src/cron/service/state.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,8 @@ export type CronServiceDeps = {
7777
cronEnabled: boolean;
7878
/** CronConfig for session retention settings. */
7979
cronConfig?: CronConfig;
80+
/** List enabled, configured channel ids without exposing channel machinery to cron core. */
81+
listConfiguredChannels?: () => readonly string[] | Promise<readonly string[]>;
8082
evaluateCronTrigger?: (params: {
8183
job: CronJob;
8284
script: string;

‎src/gateway/server-cron.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ import { formatErrorMessage } from "../infra/errors.js";
5353
import { resolveMainScopedEventSessionKey } from "../infra/event-session-routing.js";
5454
import { runHeartbeatOnce } from "../infra/heartbeat-runner.js";
5555
import { requestHeartbeat } from "../infra/heartbeat-wake.js";
56+
import { listConfiguredMessageChannels } from "../infra/outbound/channel-selection.js";
5657
import {
5758
consumeSelectedSystemEventEntries,
5859
enqueueSystemEventEntry,
@@ -608,6 +609,7 @@ export function buildGatewayCronService(params: {
608609
storePath,
609610
cronEnabled,
610611
cronConfig: params.cfg.cron,
612+
listConfiguredChannels: () => listConfiguredMessageChannels(getRuntimeConfig()),
611613
...(scriptRuntime
612614
? {
613615
evaluateCronTrigger: ({ job, script, state, streamBatch, abortSignal }) =>

‎src/gateway/server-methods/cron-error-classification.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,14 @@ describe("isCronInvalidRequestError", () => {
1414
it("does not classify unrelated script runtime failures", () => {
1515
expect(isCronInvalidRequestError(new Error("cron script payload runtime failed"))).toBe(false);
1616
});
17+
18+
it("classifies ambiguous announce delivery validation", () => {
19+
expect(
20+
isCronInvalidRequestError(
21+
new Error(
22+
"cron announce delivery requires an explicit channel when multiple channels are configured (discord, reef)",
23+
),
24+
),
25+
).toBe(true);
26+
});
1727
});

‎src/gateway/server-methods/cron-error-classification.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ export function isCronInvalidRequestError(err: unknown): boolean {
88
message.includes("cron job id must not be blank") ||
99
message.includes("cron declarationKey") ||
1010
message.includes("cron displayName") ||
11+
message.includes("cron announce delivery requires an explicit channel") ||
1112
message.includes("cron script payload has a syntax error") ||
1213
message.includes("cron script payload must not be empty") ||
1314
message.includes("cron script payloads cannot be combined") ||

0 commit comments

Comments
 (0)