Skip to content

Commit 0bc877e

Browse files
authored
fix(cron): deliver main reminders in the main session (#125198)
* fix(cron): route main reminders through main session * refactor(cron): finish main reminder cleanup * test(cron): align main reminder expectations
1 parent daf7cae commit 0bc877e

28 files changed

Lines changed: 179 additions & 490 deletions

‎docs/automation/cron-jobs.md‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -301,18 +301,18 @@ envelope continue their ordinary non-app behavior; recreate or reauthorize one
301301
only when it needs Codex app access. See
302302
[Native Codex plugins](/plugins/codex-native-plugins#scheduled-automations).
303303

304-
| Style | `--session` value | Runs in | Best for |
305-
| --------------- | ------------------- | ------------------------- | ------------------------------- |
306-
| Main session | `main` | Dedicated automation lane | Reminders, system events |
307-
| Isolated | `isolated` | Dedicated `cron:<jobId>` | Reports, background chores |
308-
| Current session | `current` | Bound at creation time | Context-aware recurring work |
309-
| Custom session | `session:custom-id` | Persistent named session | Workflows that build on history |
304+
| Style | `--session` value | Runs in | Best for |
305+
| --------------- | ------------------- | --------------------------- | ------------------------------- |
306+
| Main session | `main` | Owning agent's main session | Reminders, system events |
307+
| Isolated | `isolated` | Dedicated `cron:<jobId>` | Reports, background chores |
308+
| Current session | `current` | Bound at creation time | Context-aware recurring work |
309+
| Custom session | `session:custom-id` | Persistent named session | Workflows that build on history |
310310

311311
Agent-turn jobs default to the creating conversation when the create request carries session context. Callers without a session key, including CLI and API callers that do not supply one, fall back to `isolated`. System events and heartbeats still default to `main`; command and script payloads still default to `isolated`.
312312

313313
<AccordionGroup>
314314
<Accordion title="Main session vs isolated vs custom">
315-
**Main session** jobs enqueue a system event into a scheduler-owned run lane and optionally wake the heartbeat (`--wake now` or `--wake next-heartbeat`). They can use the target main session's last delivery context for replies, but do not append routine automation turns to the human chat lane and do not extend daily/idle reset freshness for the target session. **Isolated** jobs run a dedicated agent turn with a fresh session. **Custom sessions** (`session:xxx`) persist context across runs, enabling workflows like daily standups that build on previous summaries.
315+
**Main session** jobs enqueue a system event into the owning agent's main session and optionally wake the heartbeat (`--wake now` or `--wake next-heartbeat`). The event is processed with that session's existing context and last delivery context. Internal automation turns do not extend daily or idle reset freshness; only visible user activity updates session freshness. **Isolated** jobs run a dedicated agent turn with a fresh session. **Custom sessions** (`session:xxx`) persist context across runs, enabling workflows like daily standups that build on previous summaries.
316316

317317
Main-session automation events are self-contained system-event reminders. They do not automatically include the default heartbeat prompt or the heartbeat monitor scratch; say it explicitly in the automation event text if a reminder should consult that context.
318318

‎src/cli/cron-cli/register.cron-add.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ export function registerCronAddCommand(cron: Command) {
9595
.option("--delete-after-run", "Delete one-shot job after it succeeds", false)
9696
.option("--keep-after-run", "Keep one-shot job after it succeeds", false)
9797
.option("--agent <id>", "Agent id for this job")
98-
.option("--session <target>", "Session target (main|isolated)")
98+
.option("--session <target>", "Session target (main|isolated|current|session:<id>)")
9999
.option("--session-key <key>", "Session key for job routing (e.g. agent:my-agent:my-session)")
100100
.option("--wake <mode>", "Wake mode (now|next-heartbeat)", "now")
101101
.option(

‎src/commands/tasks-session-registry-maintenance.ts‎

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import {
55
resolveAllAgentSessionStoreTargetsSync,
66
runSessionRegistryMaintenanceForStore,
77
} from "../config/sessions.js";
8-
import { normalizeCronLaneSegment } from "../cron/service/task-runs.js";
98
import { loadCronJobsStoreSync, resolveCronJobsStorePath } from "../cron/store.js";
109
import { formatErrorMessage } from "../infra/errors.js";
1110

@@ -44,22 +43,22 @@ function readRunningCronJobIds(): RunningCronJobIds {
4443
const runningJobs = loadCronJobsStoreSync(cronStorePath).jobs.filter(
4544
(job) => typeof job.state?.runningAtMs === "number",
4645
);
46+
// A running detached job may have been retargeted after its session was created. Keep its
47+
// explicit session segment because the registry has no producer metadata for the transcript.
48+
const ids = new Set<string>();
49+
for (const job of runningJobs) {
50+
ids.add(job.id.toLowerCase());
51+
if (job.sessionTarget === "main") {
52+
continue;
53+
}
54+
const explicitSessionSegment = resolveExplicitCronSessionSegment(job.sessionKey);
55+
if (explicitSessionSegment) {
56+
ids.add(explicitSessionSegment);
57+
}
58+
}
4759
return {
4860
ok: true,
49-
// A running job may have been retargeted after its session was created. Keep both historical
50-
// shapes; the registry has no producer metadata, so retaining an ambiguous alias is safer
51-
// than pruning a live transcript.
52-
ids: new Set(
53-
runningJobs.flatMap((job) => [
54-
job.id.toLowerCase(),
55-
normalizeCronLaneSegment(job.id, "job"),
56-
...(job.sessionTarget !== "main" && job.sessionKey
57-
? [resolveExplicitCronSessionSegment(job.sessionKey)].filter(
58-
(segment): segment is string => segment !== undefined,
59-
)
60-
: []),
61-
]),
62-
),
61+
ids,
6362
count: runningJobs.length,
6463
};
6564
} catch (err) {

‎src/cron/service.every-jobs-fire.test.ts‎

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,6 @@ const noopLogger = createNoopLogger();
2222
const { makeStorePath } = createCronStoreHarness();
2323
installCronTestHooks({ logger: noopLogger });
2424

25-
function expectCronRunSessionKey(value: unknown, jobId: string) {
26-
expect(value).toMatch(new RegExp(`^agent:main:cron:${jobId}:run:\\d+$`));
27-
}
28-
2925
describe("CronService interval/cron jobs fire on time", () => {
3026
const runLateTimerAndLoadJob = async ({
3127
cron,
@@ -49,15 +45,14 @@ describe("CronService interval/cron jobs fire on time", () => {
4945
const expectMainSystemEvent = (
5046
enqueueSystemEvent: ReturnType<typeof vi.fn>,
5147
expectedText: string,
52-
jobId: string,
5348
) => {
5449
const matchingCall = enqueueSystemEvent.mock.calls.find(([text]) => text === expectedText);
5550
if (!matchingCall) {
5651
throw new Error(`missing system event ${expectedText}`);
5752
}
5853
const options = matchingCall[1] as Record<string, unknown>;
59-
expect(options.agentId).toBeUndefined();
60-
expectCronRunSessionKey(options.sessionKey, jobId);
54+
expect(options.agentId).toBe("main");
55+
expect(options.sessionKey).toBeUndefined();
6156
expect(typeof options.contextKey).toBe("string");
6257
expect(String(options.contextKey).startsWith("cron:")).toBe(true);
6358
};
@@ -101,7 +96,7 @@ describe("CronService interval/cron jobs fire on time", () => {
10196
jobId: job.id,
10297
firstDueAt,
10398
});
104-
expectMainSystemEvent(enqueueSystemEvent, "tick", job.id);
99+
expectMainSystemEvent(enqueueSystemEvent, "tick");
105100
expect(updated?.state.lastStatus).toBe("ok");
106101
// nextRunAtMs must advance by at least one full interval past the due time.
107102
expect(updated?.state.nextRunAtMs).toBeGreaterThanOrEqual(firstDueAt + 10_000);
@@ -135,7 +130,7 @@ describe("CronService interval/cron jobs fire on time", () => {
135130
cron.resumeScheduling();
136131
await vi.runOnlyPendingTimersAsync();
137132
await finishedRun;
138-
expectMainSystemEvent(enqueueSystemEvent, "resumed-tick", job.id);
133+
expectMainSystemEvent(enqueueSystemEvent, "resumed-tick");
139134

140135
cron.stop();
141136
await store.cleanup();
@@ -216,7 +211,7 @@ describe("CronService interval/cron jobs fire on time", () => {
216211
const finishedRun = finished.waitForOk(job.id);
217212
await vi.advanceTimersByTimeAsync(9_005);
218213
await finishedRun;
219-
expectMainSystemEvent(enqueueSystemEvent, "recovered-tick", job.id);
214+
expectMainSystemEvent(enqueueSystemEvent, "recovered-tick");
220215
} finally {
221216
cron.stop();
222217
resetGatewayWorkAdmission();
@@ -251,7 +246,7 @@ describe("CronService interval/cron jobs fire on time", () => {
251246

252247
expect(pendingSignal?.rollback()).toBe(true);
253248
await finishedRun;
254-
expectMainSystemEvent(enqueueSystemEvent, "rollback-tick", job.id);
249+
expectMainSystemEvent(enqueueSystemEvent, "rollback-tick");
255250
} finally {
256251
cron.stop();
257252
resetGatewayWorkAdmission();
@@ -287,7 +282,7 @@ describe("CronService interval/cron jobs fire on time", () => {
287282
jobId: job.id,
288283
firstDueAt,
289284
});
290-
expectMainSystemEvent(enqueueSystemEvent, "cron-tick", job.id);
285+
expectMainSystemEvent(enqueueSystemEvent, "cron-tick");
291286
expect(updated?.state.lastStatus).toBe("ok");
292287
// nextRunAtMs should be the next whole-minute boundary (60s later).
293288
expect(updated?.state.nextRunAtMs).toBe(firstDueAt + 60_000);

‎src/cron/service.list-past-due.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ describe("#16156: cron.list() must not silently advance past-due recurring jobs"
8686
// Job must have actually executed.
8787
const [text, options] = requireEnqueueSystemEventCall(enqueueSystemEvent);
8888
expect(text).toBe("cron-tick");
89-
expect(options?.agentId).toBeUndefined();
89+
expect(options?.agentId).toBe("main");
9090
expect(updated?.state.lastStatus).toBe("ok");
9191
// nextRunAtMs must advance to a future minute boundary after execution.
9292
expect(updated?.state.nextRunAtMs).toBeGreaterThan(firstDueAt);
@@ -130,7 +130,7 @@ describe("#16156: cron.list() must not silently advance past-due recurring jobs"
130130

131131
const [text, options] = requireEnqueueSystemEventCall(enqueueSystemEvent);
132132
expect(text).toBe("tick-5");
133-
expect(options?.agentId).toBeUndefined();
133+
expect(options?.agentId).toBe("main");
134134
expect(updated?.state.lastStatus).toBe("ok");
135135

136136
cron.stop();

‎src/cron/service.main-job-passes-heartbeat-target-last.test.ts‎

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ describe("cron main job passes heartbeat target=last", () => {
6767
source?: string;
6868
intent?: string;
6969
reason?: string;
70+
agentId?: string;
7071
sessionKey?: string;
7172
heartbeat?: unknown;
7273
};
@@ -111,8 +112,8 @@ describe("cron main job passes heartbeat target=last", () => {
111112
// heartbeat runner delivers the response to the last active channel.
112113
const callArgs = requireRunHeartbeatOnceCall(runHeartbeatOnce);
113114
expect(callArgs.heartbeat.target).toBe("last");
114-
expect(callArgs.sessionKey).toMatch(/^agent:main:cron:test-main-delivery:run:\d+$/);
115-
expect(callArgs.sessionKey).not.toBe("agent:main:main");
115+
expect(callArgs.agentId).toBe("main");
116+
expect(callArgs.sessionKey).toBeUndefined();
116117
});
117118

118119
it("should preserve heartbeat.target=last when wakeMode=now falls back to requestHeartbeat", async () => {
@@ -144,10 +145,8 @@ describe("cron main job passes heartbeat target=last", () => {
144145
expect(heartbeatRequest.source).toBe("cron");
145146
expect(heartbeatRequest.intent).toBe("immediate");
146147
expect(heartbeatRequest.reason).toBe("cron:test-main-delivery-busy");
147-
expect(heartbeatRequest.sessionKey).toMatch(
148-
/^agent:main:cron:test-main-delivery-busy:run:\d+$/,
149-
);
150-
expect(heartbeatRequest.sessionKey).not.toBe("agent:main:main");
148+
expect(heartbeatRequest.agentId).toBe("main");
149+
expect(heartbeatRequest.sessionKey).toBeUndefined();
151150
expect(heartbeatRequest.heartbeat).toEqual({ target: "last" });
152151
});
153152

@@ -180,11 +179,15 @@ describe("cron main job passes heartbeat target=last", () => {
180179
expect(heartbeatRequest.source).toBe("cron");
181180
expect(heartbeatRequest.intent).toBe("event");
182181
expect(heartbeatRequest.reason).toBe("cron:test-next-heartbeat");
183-
expect(heartbeatRequest.sessionKey).toMatch(/^agent:main:cron:test-next-heartbeat:run:\d+$/);
184-
expect(heartbeatRequest.sessionKey).not.toBe("agent:main:main");
182+
expect(heartbeatRequest.agentId).toBe("main");
183+
expect(heartbeatRequest.sessionKey).toBeUndefined();
185184
expect(heartbeatRequest.heartbeat).toEqual({ target: "last" });
186185
expect(runHeartbeatOnce).not.toHaveBeenCalled();
187-
const enqueueOptions = enqueueSystemEvent.mock.calls[0]?.[1] as { sessionKey?: string };
188-
expect(enqueueOptions.sessionKey).toBe(heartbeatRequest.sessionKey);
186+
const enqueueOptions = enqueueSystemEvent.mock.calls[0]?.[1] as {
187+
agentId?: string;
188+
sessionKey?: string;
189+
};
190+
expect(enqueueOptions.agentId).toBe("main");
191+
expect(enqueueOptions.sessionKey).toBeUndefined();
189192
});
190193
});

‎src/cron/service.restart-catchup.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ describe("CronService restart catch-up", () => {
113113
expect(enqueueSystemEvent).toHaveBeenCalledTimes(1);
114114
const [text, options] = enqueueSystemEvent.mock.calls[0] ?? [];
115115
expect(text).toBe(expectedText);
116-
expect((options as { agentId?: string } | undefined)?.agentId).toBeUndefined();
116+
expect((options as { agentId?: string } | undefined)?.agentId).toBe("main");
117117
}
118118

119119
function expectInterruptedJobEvent(

‎src/cron/service.runs-one-shot-main-job-disables-it.test.ts‎

Lines changed: 24 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
// One-shot main job tests cover disabling cron jobs after a single run.
22
import { describe, expect, it, vi } from "vitest";
33
import { createDeferred } from "../../test/helpers/promise.js";
4+
import { resolveAgentMainSessionKey } from "../config/sessions.js";
45
import {
56
HEARTBEAT_SKIP_CRON_IN_PROGRESS,
67
HEARTBEAT_SKIP_REQUESTS_IN_FLIGHT,
78
type HeartbeatRunResult,
89
} from "../infra/heartbeat-wake.js";
910
import {
10-
consumeSelectedSystemEventEntries,
1111
drainSystemEventEntries,
12-
enqueueSystemEventEntry,
12+
enqueueSystemEventWithReceipt,
1313
peekSystemEventEntries,
1414
resetSystemEventsForTest,
1515
} from "../infra/system-events.js";
@@ -28,10 +28,6 @@ const { makeStorePath } = createCronStoreHarness({
2828
prefix: "openclaw-cron-runs-one-shot-",
2929
});
3030

31-
function expectCronRunSessionKey(value: unknown, jobId: string) {
32-
expect(value).toMatch(new RegExp(`^agent:main:cron:${jobId}:run:\\d+$`));
33-
}
34-
3531
function createCronEventHarness() {
3632
const events: CronEvent[] = [];
3733
const waiters: Array<{
@@ -75,25 +71,24 @@ type CronHarnessOptions = {
7571
withEvents?: boolean;
7672
};
7773

74+
function resolveHarnessSessionKey(target?: { agentId?: string; sessionKey?: string }): string {
75+
return (
76+
target?.sessionKey ??
77+
resolveAgentMainSessionKey({ cfg: {}, agentId: target?.agentId ?? "main" })
78+
);
79+
}
80+
7881
async function createCronHarness(options: CronHarnessOptions = {}) {
7982
const store = await makeStorePath();
8083
const enqueueSystemEvent = options.useRemovableSystemEventQueue
8184
? vi.fn((text: string, opts?: Parameters<CronServiceDeps["enqueueSystemEvent"]>[1]) => {
82-
if (!opts?.sessionKey) {
83-
throw new Error("test removable queue requires a sessionKey");
84-
}
85-
const event = enqueueSystemEventEntry(text, {
86-
sessionKey: opts.sessionKey,
87-
contextKey: opts.contextKey,
88-
deliveryContext: opts.deliveryContext,
85+
const sessionKey = resolveHarnessSessionKey(opts);
86+
const remove = enqueueSystemEventWithReceipt(text, {
87+
sessionKey,
88+
contextKey: opts?.contextKey,
89+
deliveryContext: opts?.deliveryContext,
8990
});
90-
return event
91-
? {
92-
accepted: true,
93-
remove: () =>
94-
consumeSelectedSystemEventEntries(opts.sessionKey as string, [event]).length > 0,
95-
}
96-
: { accepted: false };
91+
return remove ? { accepted: true, remove } : { accepted: false };
9792
})
9893
: vi.fn();
9994
const requestHeartbeat = vi.fn();
@@ -244,10 +239,10 @@ function expectMainSystemEventPosted(
244239
}
245240
const options = matchingCall[1] as Record<string, unknown>;
246241
expect(options).toMatchObject({
247-
agentId: undefined,
242+
agentId: "main",
248243
contextKey: `cron:${params.jobId}`,
249244
});
250-
expectCronRunSessionKey(options.sessionKey, params.jobId);
245+
expect(options.sessionKey).toBeUndefined();
251246
}
252247

253248
function expectQueuedCronHeartbeat(
@@ -259,16 +254,16 @@ function expectQueuedCronHeartbeat(
259254
source: "cron",
260255
intent: "immediate",
261256
reason: `cron:${params.jobId}`,
262-
agentId: undefined,
257+
agentId: "main",
263258
heartbeat: { target: "last" },
264259
});
265-
expectCronRunSessionKey(request?.sessionKey, params.jobId);
260+
expect(request?.sessionKey).toBeUndefined();
266261
}
267262

268263
function getPostedSystemEventSessionKeys(enqueueSystemEvent: ReturnType<typeof vi.fn>) {
269-
return enqueueSystemEvent.mock.calls
270-
.map(([, options]) => (options as { sessionKey?: string } | undefined)?.sessionKey)
271-
.filter((sessionKey): sessionKey is string => Boolean(sessionKey));
264+
return enqueueSystemEvent.mock.calls.map(([, options]) =>
265+
resolveHarnessSessionKey(options as { agentId?: string; sessionKey?: string } | undefined),
266+
);
272267
}
273268

274269
function expectNoQueuedEvents(sessionKeys: readonly string[]) {
@@ -579,10 +574,8 @@ describe("CronService", () => {
579574
if (runHeartbeatOnce.mock.calls.length < 3) {
580575
return { status: "skipped" as const, reason: "disabled" };
581576
}
582-
const sessionKey = opts?.sessionKey;
583-
if (sessionKey) {
584-
consumedTexts.push(...drainSystemEventEntries(sessionKey).map((event) => event.text));
585-
}
577+
const sessionKey = resolveHarnessSessionKey(opts);
578+
consumedTexts.push(...drainSystemEventEntries(sessionKey).map((event) => event.text));
586579
return { status: "ran" as const, durationMs: 1 };
587580
},
588581
);

‎src/cron/service.test-harness.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,6 @@ export function createMockCronStateForJobs(params: {
252252
stopped: false,
253253
schedulingPaused: false,
254254
schedulerStarted: false,
255-
restartRecoveryPending: false,
256255
activeManualRunJobIds: new Set<string>(),
257256
manualSetupTimeoutNotified: false,
258257
runAdmission: { active: 0, waiters: [] },

0 commit comments

Comments
 (0)