Skip to content

Commit 2f85e5e

Browse files
authored
fix(config): allow agents add while the local Gateway is running (#123490)
* fix(config): allow agent topology writes with healthy gateway * fix(config): preserve dynamic cron ownership
1 parent c500ab7 commit 2f85e5e

7 files changed

Lines changed: 205 additions & 41 deletions

File tree

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import fs from "node:fs/promises";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { afterEach, expect, it } from "vitest";
5+
import type { OpenClawConfig } from "../../../config/types.openclaw.js";
6+
import { saveCronStore } from "../../../cron/store.js";
7+
import { loadLegacyCronRepairState } from "./legacy-repair.js";
8+
9+
let tempRoot: string | undefined;
10+
11+
afterEach(async () => {
12+
if (tempRoot) {
13+
await fs.rm(tempRoot, { recursive: true, force: true });
14+
tempRoot = undefined;
15+
}
16+
});
17+
18+
it("projects a canonical agent-less row through the runtime default", async () => {
19+
tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-cron-owner-projection-"));
20+
const storePath = path.join(tempRoot, "cron", "jobs.json");
21+
await saveCronStore(storePath, {
22+
version: 1,
23+
jobs: [
24+
{
25+
id: "dynamic-default",
26+
name: "Dynamic default",
27+
enabled: true,
28+
createdAtMs: 1,
29+
updatedAtMs: 1,
30+
schedule: { kind: "every", everyMs: 60_000 },
31+
sessionTarget: "isolated",
32+
wakeMode: "now",
33+
payload: { kind: "agentTurn", message: "run" },
34+
state: {},
35+
},
36+
],
37+
});
38+
39+
const cfg = {
40+
cron: { store: storePath },
41+
agents: { entries: { ops: {} } },
42+
} as OpenClawConfig;
43+
const state = await loadLegacyCronRepairState({ cfg, storePath, readOnly: true });
44+
45+
expect(state?.projectedOwnersByJobId.get("dynamic-default")).toEqual({
46+
kind: "runtime-default",
47+
agentId: "ops",
48+
});
49+
expect(state?.rawJobs[0]?.agentId).toBeUndefined();
50+
});

‎src/commands/doctor/cron/legacy-repair.ts‎

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Doctor cron storage repair mechanics for legacy stores, run logs, payloads, and Codex refs.
22
import { normalizeOptionalString } from "../../../../packages/normalization-core/src/string-coerce.js";
3+
import { tryResolveLegacyCompatibilityAgentId } from "../../../agents/agent-scope-config.js";
34
import { formatCliCommand } from "../../../cli/command-format.js";
45
import type { OpenClawConfig } from "../../../config/types.openclaw.js";
56
import { getInvalidPersistedCronJobReason } from "../../../cron/persisted-shape.js";
@@ -15,6 +16,7 @@ import {
1516
} from "../../../cron/store.js";
1617
import type { CronJob } from "../../../cron/types.js";
1718
import { formatErrorMessage as errorMessage } from "../../../infra/errors.js";
19+
import { parseAgentSessionKey } from "../../../routing/session-key.js";
1820
import { shortenHomePath } from "../../../utils.js";
1921
import type { LegacyCodexModelIdentity } from "../shared/codex-route-model-ref.js";
2022
import { migrateLegacyDreamingPayloadShape } from "./dreaming-payload-migration.js";
@@ -54,6 +56,11 @@ import {
5456
type CronCodexRuntimePolicyTarget,
5557
} from "./store-migration.js";
5658

59+
export type CronOwnerProjection =
60+
| { kind: "explicit"; agentId: string }
61+
| { kind: "runtime-default"; agentId: string }
62+
| { kind: "unresolved" };
63+
5764
export type LegacyCronRepairState = {
5865
storePath: string;
5966
legacyStoreDetected: boolean;
@@ -64,7 +71,7 @@ export type LegacyCronRepairState = {
6471
legacyImportCount: number;
6572
sqliteProjectionBackfillCount: number;
6673
invalidConfigRows: QuarantinedCronConfigJob[];
67-
projectedOwnersByJobId: ReadonlyMap<string, { agentId?: unknown; sessionKey?: unknown }>;
74+
projectedOwnersByJobId: ReadonlyMap<string, CronOwnerProjection>;
6875
rawJobs: Array<Record<string, unknown>>;
6976
};
7077

@@ -89,6 +96,21 @@ function readLegacyCronStorePath(cfg: OpenClawConfig): string | undefined {
8996
?.store;
9097
}
9198

99+
function projectCronOwner(
100+
job: { agentId?: unknown; sessionKey?: unknown },
101+
runtimeDefaultAgentId: string | undefined,
102+
): CronOwnerProjection {
103+
const explicitAgentId =
104+
normalizeOptionalString(job.agentId) ??
105+
parseAgentSessionKey(normalizeOptionalString(job.sessionKey))?.agentId;
106+
if (explicitAgentId) {
107+
return { kind: "explicit", agentId: explicitAgentId };
108+
}
109+
return runtimeDefaultAgentId
110+
? { kind: "runtime-default", agentId: runtimeDefaultAgentId }
111+
: { kind: "unresolved" };
112+
}
113+
92114
export async function loadLegacyCronRepairState(params: {
93115
cfg: OpenClawConfig;
94116
storePath?: string;
@@ -113,14 +135,9 @@ export async function loadLegacyCronRepairState(params: {
113135
const loaded = params.readOnly
114136
? await loadCronJobsStoreWithConfigJobsReadOnly(storePath, params.env)
115137
: await loadCronJobsStoreWithConfigJobs(storePath);
138+
const runtimeDefaultAgentId = tryResolveLegacyCompatibilityAgentId(params.cfg);
116139
const projectedOwnersByJobId = new Map(
117-
loaded.store.jobs.map((job) => [
118-
job.id,
119-
{
120-
...(Object.hasOwn(job, "agentId") ? { agentId: job.agentId } : {}),
121-
...(Object.hasOwn(job, "sessionKey") ? { sessionKey: job.sessionKey } : {}),
122-
},
123-
]),
140+
loaded.store.jobs.map((job) => [job.id, projectCronOwner(job, runtimeDefaultAgentId)]),
124141
);
125142
const currentEntries = loaded.configJobs.map((job, index) => ({
126143
sourceIndex: loaded.configJobIndexes[index] ?? index,

‎src/config/io.cron-owner-refusal.test.ts‎

Lines changed: 86 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,100 @@
11
import { expect, it, vi } from "vitest";
2-
import type { LegacyCronRepairState } from "../commands/doctor/cron/legacy-repair.js";
2+
import type {
3+
CronOwnerProjection,
4+
LegacyCronRepairState,
5+
} from "../commands/doctor/cron/legacy-repair.js";
36
import {
47
isCronOwnerWriteRefusalError,
58
prepareCronOwnerWriteRefusal,
69
} from "./io.cron-owner-refusal.js";
710
import { assertAutomaticBindingsWriteAllowed } from "./io.ownership-write-guard.js";
811

9-
const state = (rawJobs: Array<Record<string, unknown>>) =>
10-
({ rawJobs, projectedOwnersByJobId: new Map() }) as unknown as LegacyCronRepairState;
11-
const deps = (activeGateway?: { pid: number; port: number }, jobs?: Record<string, unknown>[]) => ({
12+
const state = (
13+
rawJobs: Array<Record<string, unknown>>,
14+
invalidConfigRows: Array<Record<string, unknown>> = [],
15+
projectedOwnersByJobId: ReadonlyMap<string, CronOwnerProjection> = new Map(),
16+
) =>
17+
({
18+
rawJobs,
19+
invalidConfigRows,
20+
projectedOwnersByJobId,
21+
}) as unknown as LegacyCronRepairState;
22+
const deps = (
23+
activeGateway?: {
24+
pid: number;
25+
port: number;
26+
cronOwnerProjection?: "dynamic-default-v1";
27+
},
28+
jobs?: Record<string, unknown>[],
29+
) => ({
1230
readActiveGatewayLockIdentity: vi.fn(async () =>
1331
activeGateway ? { ...activeGateway, createdAt: new Date(0).toISOString() } : undefined,
1432
),
1533
loadLegacyCronRepairState: vi.fn(async () => (jobs ? state(jobs) : null)),
1634
materializeLegacyDefaultCronJobOwners: vi.fn(() => 0),
1735
});
36+
const cfg = { agents: { entries: { ops: {} } } };
1837

19-
it("refuses unsafe ownership writes and rechecks at commit", async () => {
38+
it("allows an ownership-safe live Gateway with a projected dynamic row and rechecks at commit", async () => {
39+
const injected = deps(
40+
{
41+
pid: process.pid + 1,
42+
port: 18_789,
43+
cronOwnerProjection: "dynamic-default-v1",
44+
},
45+
[{ id: "dynamic" }],
46+
);
47+
injected.loadLegacyCronRepairState.mockResolvedValueOnce(
48+
state(
49+
[{ id: "dynamic" }],
50+
[],
51+
new Map([["dynamic", { kind: "runtime-default" as const, agentId: "ops" }]]),
52+
),
53+
);
54+
const plan = await prepareCronOwnerWriteRefusal(cfg, { storePath: "/tmp/cron.json" }, injected);
55+
injected.loadLegacyCronRepairState.mockResolvedValueOnce(state([{ id: "ownerless" }]));
56+
await expect(plan.recheck()).rejects.toThrow("ownerless legacy cron job");
57+
});
58+
59+
it("refuses an unproven live Gateway without suggesting doctor", async () => {
2060
const injected = deps({ pid: process.pid + 1, port: 18_789 });
21-
await expect(
22-
prepareCronOwnerWriteRefusal({ storePath: "/tmp/cron.json" }, injected),
23-
).rejects.toThrow("live external Gateway");
24-
expect(injected.loadLegacyCronRepairState).not.toHaveBeenCalled();
61+
const refusal = prepareCronOwnerWriteRefusal(cfg, { storePath: "/tmp/cron.json" }, injected);
62+
await expect(refusal).rejects.toThrow("live external Gateway");
63+
await expect(refusal).rejects.not.toThrow("doctor --fix");
64+
});
2565

66+
it.each([
67+
["without a live Gateway", undefined],
68+
[
69+
"with an ownership-safe live Gateway",
70+
{
71+
pid: process.pid + 1,
72+
port: 18_789,
73+
cronOwnerProjection: "dynamic-default-v1" as const,
74+
},
75+
],
76+
])("refuses ownerless and corrupt cron rows %s", async (_name, activeGateway) => {
2677
await expect(
2778
prepareCronOwnerWriteRefusal(
79+
cfg,
2880
{ storePath: "/tmp/cron.json" },
29-
deps(undefined, [
81+
deps(activeGateway, [
3082
{ id: "null", agentId: null },
3183
{ id: "blank", agentId: " " },
3284
]),
3385
),
3486
).rejects.toThrow("contains 2 ownerless legacy cron job");
3587

36-
const commitDeps = deps(undefined, [{ id: "owned", agentId: "ops" }]);
37-
const plan = await prepareCronOwnerWriteRefusal({ storePath: "/tmp/cron.json" }, commitDeps);
38-
commitDeps.loadLegacyCronRepairState.mockResolvedValueOnce(state([{ id: "ownerless" }]));
39-
await expect(plan.recheck()).rejects.toThrow("ownerless legacy cron job");
88+
const corrupt = deps(activeGateway);
89+
corrupt.loadLegacyCronRepairState.mockResolvedValueOnce(
90+
state([], [{ id: "corrupt", reason: "invalid config" }]),
91+
);
92+
await expect(
93+
prepareCronOwnerWriteRefusal(cfg, { storePath: "/tmp/cron.json" }, corrupt),
94+
).rejects.toThrow("contains 1 corrupt row");
95+
});
4096

97+
it("keeps include-owned binding writes fail closed", () => {
4198
expect(() =>
4299
assertAutomaticBindingsWriteAllowed({
43100
bindingsIncludeOwned: true,
@@ -49,13 +106,24 @@ it("refuses unsafe ownership writes and rechecks at commit", async () => {
49106
it("materializes a proven retained owner before the commit recheck", async () => {
50107
for (const safe of [deps(), deps(undefined, [{ id: "owned", agentId: "research" }])]) {
51108
await prepareCronOwnerWriteRefusal(
109+
cfg,
52110
{ storePath: "/tmp/cron.json", provenOwnerAgentId: "ops" },
53111
safe,
54112
);
55113
expect(safe.materializeLegacyDefaultCronJobOwners).not.toHaveBeenCalled();
56114
}
57115

58116
const injected = deps(undefined, [{ id: "ownerless" }, { id: "owned", agentId: "research" }]);
117+
injected.loadLegacyCronRepairState.mockResolvedValueOnce(
118+
state(
119+
[{ id: "ownerless" }, { id: "owned", agentId: "research" }],
120+
[],
121+
new Map([
122+
["ownerless", { kind: "runtime-default" as const, agentId: "ops" }],
123+
["owned", { kind: "explicit" as const, agentId: "research" }],
124+
]),
125+
),
126+
);
59127
injected.materializeLegacyDefaultCronJobOwners.mockImplementationOnce(() => {
60128
injected.loadLegacyCronRepairState.mockResolvedValue(
61129
state([
@@ -67,6 +135,7 @@ it("materializes a proven retained owner before the commit recheck", async () =>
67135
});
68136

69137
const plan = await prepareCronOwnerWriteRefusal(
138+
cfg,
70139
{
71140
storePath: "/tmp/custom-cron.json",
72141
provenOwnerAgentId: "ops",
@@ -87,7 +156,7 @@ it("materializes a proven retained owner before the commit recheck", async () =>
87156
it("keeps ambiguous and failed owner handoffs as typed refusals", async () => {
88157
const ambiguous = deps(undefined, [{ id: "ownerless" }]);
89158
await expect(
90-
prepareCronOwnerWriteRefusal({ storePath: "/tmp/cron.json" }, ambiguous),
159+
prepareCronOwnerWriteRefusal(cfg, { storePath: "/tmp/cron.json" }, ambiguous),
91160
).rejects.toSatisfy(isCronOwnerWriteRefusalError);
92161
expect(ambiguous.materializeLegacyDefaultCronJobOwners).not.toHaveBeenCalled();
93162

@@ -96,6 +165,7 @@ it("keeps ambiguous and failed owner handoffs as typed refusals", async () => {
96165
throw new Error("database is temporarily read-only");
97166
});
98167
const failure = prepareCronOwnerWriteRefusal(
168+
cfg,
99169
{ storePath: "/tmp/cron.json", provenOwnerAgentId: "ops" },
100170
failed,
101171
);
@@ -107,6 +177,7 @@ it("keeps ambiguous and failed owner handoffs as typed refusals", async () => {
107177
new Error("database disk image is malformed"),
108178
);
109179
const unreadable = prepareCronOwnerWriteRefusal(
180+
cfg,
110181
{ storePath: "/tmp/corrupt-cron.json", provenOwnerAgentId: "ops" },
111182
corrupt,
112183
);

‎src/config/io.cron-owner-refusal.ts‎

Lines changed: 31 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
22
import { formatErrorMessage } from "../infra/errors.js";
33
import { parseAgentSessionKey } from "../routing/session-key.js";
4+
import type { OpenClawConfig } from "./types.js";
45

56
type CronOwnerRefusalDeps = Pick<
67
typeof import("../infra/gateway-lock.js"),
@@ -53,6 +54,7 @@ async function loadDefaultDeps(): Promise<CronOwnerRefusalDeps> {
5354
}
5455

5556
async function assertSafe(
57+
cfg: OpenClawConfig,
5658
storePath: string,
5759
env: NodeJS.ProcessEnv,
5860
deps: CronOwnerRefusalDeps,
@@ -64,31 +66,43 @@ async function assertSafe(
6466
error,
6567
);
6668
});
67-
if (active && active.pid !== process.pid) {
68-
throw refused(
69-
`Config write refused: live external Gateway pid ${active.pid} may write ownerless cron jobs. Stop it.${RETRY}`,
70-
);
71-
}
7269
const state = await deps
73-
.loadLegacyCronRepairState({ cfg: {}, storePath, env, readOnly: true })
70+
.loadLegacyCronRepairState({ cfg, storePath, env, readOnly: true })
7471
.catch((error: unknown) => {
7572
throw refused(
7673
`Config write refused: cannot inspect cron ownership at ${storePath} (${formatErrorMessage(error)}).${RETRY}`,
7774
error,
7875
);
7976
});
80-
const ownerless =
77+
const unresolved =
78+
state?.rawJobs.filter((job) => {
79+
const id = normalizeOptionalString(job.id) ?? normalizeOptionalString(job.jobId);
80+
const projection = id ? state.projectedOwnersByJobId.get(id) : undefined;
81+
return !hasOwner(job) && (!projection || projection.kind === "unresolved");
82+
}).length ?? 0;
83+
const projectedDynamicDefaults =
8184
state?.rawJobs.filter((job) => {
8285
const id = normalizeOptionalString(job.id) ?? normalizeOptionalString(job.jobId);
83-
return !hasOwner(job) && !hasOwner(id ? state.projectedOwnersByJobId.get(id) : undefined);
86+
const projection = id ? state.projectedOwnersByJobId.get(id) : undefined;
87+
return !hasOwner(job) && projection?.kind === "runtime-default";
8488
}).length ?? 0;
8589
const unverifiable = state?.invalidConfigRows?.length ?? 0;
8690
if (unverifiable > 0) {
8791
throw refused(
8892
`Config write refused: cron store ${storePath} contains ${unverifiable} corrupt row(s) whose ownership cannot be verified.${RETRY}`,
8993
);
9094
}
91-
if (ownerless > 0 && provenOwnerAgentId) {
95+
if (unresolved > 0 && !provenOwnerAgentId) {
96+
throw refused(
97+
`Config write refused: cron store ${storePath} contains ${unresolved} ownerless legacy cron job(s).${RETRY}`,
98+
);
99+
}
100+
if (active && active.pid !== process.pid && active.cronOwnerProjection !== "dynamic-default-v1") {
101+
throw refused(
102+
`Config write refused: live external Gateway pid ${active.pid} does not prove compatibility with the current cron ownership projection. Restart it with this OpenClaw version, or stop it, then retry.`,
103+
);
104+
}
105+
if ((unresolved > 0 || projectedDynamicDefaults > 0) && provenOwnerAgentId) {
92106
try {
93107
deps.materializeLegacyDefaultCronJobOwners({
94108
storePath,
@@ -101,22 +115,22 @@ async function assertSafe(
101115
error,
102116
);
103117
}
104-
return await assertSafe(storePath, env, deps);
105-
}
106-
if (ownerless > 0) {
107-
throw refused(
108-
`Config write refused: cron store ${storePath} contains ${ownerless} ownerless legacy cron job(s).${RETRY}`,
109-
);
118+
return await assertSafe(cfg, storePath, env, deps);
110119
}
111120
}
112121

113122
export async function prepareCronOwnerWriteRefusal(
114-
params: { storePath: string; provenOwnerAgentId?: string; env?: NodeJS.ProcessEnv },
123+
cfg: OpenClawConfig,
124+
params: {
125+
storePath: string;
126+
provenOwnerAgentId?: string;
127+
env?: NodeJS.ProcessEnv;
128+
},
115129
injectedDeps?: CronOwnerRefusalDeps,
116130
): Promise<{ recheck: () => Promise<void> }> {
117131
const env = params.env ?? process.env;
118132
const deps = injectedDeps ?? (await loadDefaultDeps());
119-
const recheck = () => assertSafe(params.storePath, env, deps, params.provenOwnerAgentId);
133+
const recheck = () => assertSafe(cfg, params.storePath, env, deps, params.provenOwnerAgentId);
120134
await recheck();
121135
return { recheck };
122136
}

0 commit comments

Comments
 (0)