Skip to content

Commit 103e1a4

Browse files
fix(claws): recover lifecycle state safely (#123254)
* fix(claws): preserve runtime lifecycle state Co-authored-by: Copilot <[email protected]> Copilot-Session: 34377cd6-beac-4e49-8ab0-22cfaf8b54a5 * fix(claws): harden lifecycle reconciliation Co-authored-by: Copilot <[email protected]> Copilot-Session: 34377cd6-beac-4e49-8ab0-22cfaf8b54a5 * fix(mcp): serialize ownership mutations Co-authored-by: Copilot <[email protected]> Copilot-Session: 34377cd6-beac-4e49-8ab0-22cfaf8b54a5 * test(mcp): prove lifecycle lease ordering * fix(claws): page cron recovery inventory * fix(claws): fail closed on missing cron ownership * refactor(claws): keep pending cron recovery unchanged --------- Co-authored-by: Copilot <[email protected]> Co-authored-by: Gio Della-Libera <[email protected]> Copilot-Session: 34377cd6-beac-4e49-8ab0-22cfaf8b54a5
1 parent 53074ae commit 103e1a4

19 files changed

Lines changed: 1147 additions & 248 deletions

‎docs/cli/claws.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@ Enable the command surface explicitly:
2121
export OPENCLAW_EXPERIMENTAL_CLAWS=1
2222
```
2323

24+
For human-readable `claws add`, OpenClaw prints the experimental warning before
25+
changing state. JSON mode keeps stdout machine-readable and identifies the
26+
contract with `"stability": "experimental"`.
27+
2428
The current CLI reads a local package directory, `CLAW.md`, or grouped JSON manifest.
2529
Publishing, searching, and installing whole Claws through ClawHub are a
2630
separate registry track and are not part of this command surface yet.
@@ -468,6 +472,10 @@ credentials, sessions, and unowned local state are excluded.
468472

469473
| Command | Purpose |
470474
| ----------------------------------- | --------------------------------------------------- |
475+
| `claws create [path]` | Create a minimal local Claw project. |
476+
| `claws validate [path]` | Validate project inputs and package contents. |
477+
| `claws dev [path]` | Build and preview locally without mutation. |
478+
| `claws build [path] --out <tgz>` | Build a deterministic package artifact. |
471479
| `claws inspect <source>` | Validate a package directory or grouped manifest. |
472480
| `claws add <source>` | Preview or create one new agent and workspace. |
473481
| `claws status [claw-or-agent]` | Report installed state, ownership, and drift. |
@@ -477,6 +485,12 @@ credentials, sessions, and unowned local state are excluded.
477485

478486
Use `--json` for experimental machine-readable output.
479487

488+
Successful commands exit `0`. Validation errors, blocked plans, missing
489+
targets, and both `failed` and `partial` mutation results exit `1`. Inspect the
490+
JSON `status` and `error.code` fields to distinguish a failure that made no
491+
change from a partial result that requires `claws status`, `openclaw doctor`,
492+
and a new preview before retrying.
493+
480494
## See also
481495

482496
- [Agents](/cli/agents)

‎docs/plugins/manage-plugins.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,12 @@ that will be removed. The managed install directory is removed once unless you
228228
pass `--keep-files`. A running managed Gateway restarts automatically when the
229229
uninstall changes plugin source.
230230

231+
If an installed Claw references the plugin, preview and uninstall print the
232+
affected Claw package names. Ordinary plugin uninstall can still proceed and
233+
may break those Claws; use `openclaw claws status` to review ownership first.
234+
Removing a Claw releases its plugin reference but retains the process-wide
235+
plugin by default.
236+
231237
In Nix mode (`OPENCLAW_NIX_MODE=1`), plugin install, update, uninstall,
232238
enable, and disable are all disabled; manage those choices in the Nix source
233239
for the install instead.

‎src/agents/mcp-config-mutation.test.ts‎

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,16 @@
11
import path from "node:path";
22
import { withTempHome } from "openclaw/plugin-sdk/test-env";
3-
import { afterEach, describe, expect, it } from "vitest";
3+
import { afterEach, describe, expect, it, vi } from "vitest";
4+
import { createDeferred } from "../../test/helpers/promise.js";
5+
import { mcpConfigInternal } from "../config/mcp-config.js";
46
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
57
import {
68
setConfiguredMcpServer,
79
unsetConfiguredMcpServer,
810
updateConfiguredMcpServer,
911
updateConfiguredMcpServerTools,
1012
} from "./mcp-config-mutation.js";
13+
import { withMcpLifecycleLease } from "./mcp-lifecycle-lease.js";
1114
import { operatorMcpOAuthIdentity, requesterMcpOAuthIdentity } from "./mcp-oauth-identity.js";
1215
import {
1316
readMcpOAuthPendingAuthorization,
@@ -41,6 +44,7 @@ function seedOAuthState(name: string) {
4144
}
4245

4346
afterEach(() => {
47+
vi.restoreAllMocks();
4448
closeOpenClawStateDatabaseForTest();
4549
});
4650

@@ -123,3 +127,59 @@ describe("configured MCP OAuth cleanup", () => {
123127
});
124128
});
125129
});
130+
131+
describe("configured MCP ownership coordination", () => {
132+
it("waits for active Claw ownership reconciliation before an ordinary mutation", async () => {
133+
await withMcpConfigHome(async () => {
134+
const leaseEntered = createDeferred();
135+
const releaseLease = createDeferred();
136+
const order: string[] = [];
137+
const set = vi.spyOn(mcpConfigInternal, "set").mockImplementation(async () => ({
138+
ok: true,
139+
path: "config",
140+
config: {},
141+
mcpServers: {},
142+
}));
143+
const lifecycle = withMcpLifecycleLease("fixture", {}, async () => {
144+
order.push("lifecycle");
145+
leaseEntered.resolve();
146+
await releaseLease.promise;
147+
});
148+
await leaseEntered.promise;
149+
150+
const mutation = setConfiguredMcpServer({
151+
name: " fixture ",
152+
server: { command: "uvx", args: ["operator-mcp"] },
153+
}).then((result) => {
154+
order.push("operator");
155+
return result;
156+
});
157+
await Promise.resolve();
158+
expect(set).not.toHaveBeenCalled();
159+
expect(order).toEqual(["lifecycle"]);
160+
161+
releaseLease.resolve();
162+
await lifecycle;
163+
const result = await mutation;
164+
165+
expect(result.ok).toBe(true);
166+
expect(set).toHaveBeenCalledOnce();
167+
expect(order).toEqual(["lifecycle", "operator"]);
168+
});
169+
});
170+
171+
it("preserves the canonical validation result for an empty server name", async () => {
172+
await withMcpConfigHome(async () => {
173+
const result = await setConfiguredMcpServer({
174+
name: " ",
175+
server: { command: "uvx", args: ["operator-mcp"] },
176+
});
177+
178+
expect(result).toEqual({
179+
ok: false,
180+
path: "",
181+
error: "MCP server name is required.",
182+
});
183+
});
184+
});
185+
});

‎src/agents/mcp-config-mutation.ts‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
/** Canonical configured-MCP mutations with OAuth credential lifecycle cleanup. */
22
import { asNullableRecord } from "@openclaw/normalization-core/record-coerce";
33
import { mcpConfigInternal } from "../config/mcp-config.js";
4+
import { withMcpLifecycleLease } from "./mcp-lifecycle-lease.js";
45
import { operatorMcpOAuthIdentity } from "./mcp-oauth-identity.js";
56
import { clearMcpOAuthRequesters, clearMcpOAuthServer } from "./mcp-oauth.js";
67
import { resolveMcpTransportConfig } from "./mcp-transport-config.js";
@@ -46,26 +47,46 @@ async function clearReplacedMcpOAuth(mutation: {
4647
await clearMcpOAuthServer(operatorMcpOAuthIdentity(mutation.name, previous.url));
4748
}
4849

50+
async function withMcpOwnershipCoordination<T>(
51+
params: { name: string; recordIndependentOwner?: boolean },
52+
run: () => Promise<T>,
53+
): Promise<T> {
54+
// Claw lifecycle callers already hold this non-reentrant lease.
55+
const name = params.name.trim();
56+
if (!name || params.recordIndependentOwner === false) {
57+
return run();
58+
}
59+
return withMcpLifecycleLease(name, {}, run);
60+
}
61+
4962
export function setConfiguredMcpServer(
5063
params: Parameters<typeof mcpConfigInternal.set>[0],
5164
): ReturnType<typeof mcpConfigInternal.set> {
52-
return mcpConfigInternal.set(params, clearReplacedMcpOAuth);
65+
return withMcpOwnershipCoordination(params, () =>
66+
mcpConfigInternal.set(params, clearReplacedMcpOAuth),
67+
);
5368
}
5469

5570
export function unsetConfiguredMcpServer(
56-
params: Parameters<typeof mcpConfigInternal.unset>[0],
71+
params: Parameters<typeof mcpConfigInternal.unset>[0] & { recordIndependentOwner?: boolean },
5772
): ReturnType<typeof mcpConfigInternal.unset> {
58-
return mcpConfigInternal.unset(params, clearReplacedMcpOAuth);
73+
return withMcpOwnershipCoordination(params, () =>
74+
mcpConfigInternal.unset(params, clearReplacedMcpOAuth),
75+
);
5976
}
6077

6178
export function updateConfiguredMcpServer(
6279
params: Parameters<typeof mcpConfigInternal.update>[0],
6380
): ReturnType<typeof mcpConfigInternal.update> {
64-
return mcpConfigInternal.update(params, clearReplacedMcpOAuth);
81+
return withMcpOwnershipCoordination(params, () =>
82+
mcpConfigInternal.update(params, clearReplacedMcpOAuth),
83+
);
6584
}
6685

6786
export function updateConfiguredMcpServerTools(
6887
params: Parameters<typeof mcpConfigInternal.updateTools>[0],
6988
): ReturnType<typeof mcpConfigInternal.updateTools> {
70-
return mcpConfigInternal.updateTools(params, clearReplacedMcpOAuth);
89+
return withMcpOwnershipCoordination(params, () =>
90+
mcpConfigInternal.updateTools(params, clearReplacedMcpOAuth),
91+
);
7192
}

‎src/agents/mcp-lifecycle-lease.ts‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import type { OpenClawStateDatabaseOptions } from "../state/openclaw-state-db.js";
2+
import { withOpenClawStateLease } from "../state/openclaw-state-lease.js";
3+
4+
const MCP_LIFECYCLE_LEASE_SCOPE = "core:claw-mcp-lifecycle";
5+
const MCP_LIFECYCLE_LEASE_MS = 5 * 60_000;
6+
const MCP_LIFECYCLE_WAIT_MS = 10 * 60_000;
7+
8+
type McpLifecycleLeaseOptions = Pick<OpenClawStateDatabaseOptions, "env" | "path" | "database"> & {
9+
signal?: AbortSignal;
10+
};
11+
12+
/** Serialize ownership decisions and global config mutations for one MCP server. */
13+
export async function withMcpLifecycleLease<T>(
14+
name: string,
15+
options: McpLifecycleLeaseOptions,
16+
run: () => Promise<T>,
17+
): Promise<T> {
18+
return await withOpenClawStateLease(
19+
{
20+
scope: MCP_LIFECYCLE_LEASE_SCOPE,
21+
key: name.trim(),
22+
database: {
23+
scope: "shared",
24+
options: {
25+
...(options.env ? { env: options.env } : {}),
26+
...(options.path ? { path: options.path } : {}),
27+
...(options.database ? { database: options.database } : {}),
28+
},
29+
},
30+
leaseMs: MCP_LIFECYCLE_LEASE_MS,
31+
waitMs: MCP_LIFECYCLE_WAIT_MS,
32+
...(options.signal ? { signal: options.signal } : {}),
33+
leaseLabel: "Claw MCP lifecycle lease",
34+
operationLabel: "claws.mcp.lifecycle.lease",
35+
},
36+
async (lease) => {
37+
lease.assertOwned();
38+
const result = await run();
39+
lease.assertOwned();
40+
return result;
41+
},
42+
);
43+
}
44+
45+
export const withClawMcpLifecycleLease = withMcpLifecycleLease;

‎src/claws/cron.test.ts‎

Lines changed: 89 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,15 @@ import { join } from "node:path";
22
import { afterEach, describe, expect, it, vi } from "vitest";
33
import { validateCronAddParams } from "../../packages/gateway-protocol/src/index.js";
44
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
5+
import { normalizeCronJobCreate } from "../cron/normalize.js";
56
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
6-
import { installClawCronJobs, readClawCronRefs } from "./cron.js";
7+
import { clawCronGatewayInput, installClawCronJobs, readClawCronRefs } from "./cron.js";
78
import { buildClawAddPlan } from "./lifecycle.js";
89
import { parseClawManifest } from "./schema.js";
910
import type { ClawSourceIdentity } from "./types.js";
1011

11-
afterEach(() => closeOpenClawStateDatabaseForTest());
1212
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
13+
afterEach(() => closeOpenClawStateDatabaseForTest());
1314

1415
async function fixture() {
1516
const root = tempDirs.make("openclaw-claw-cron-");
@@ -30,6 +31,7 @@ async function fixture() {
3031
if (!parsed.ok) {
3132
throw new Error(JSON.stringify(parsed.diagnostics));
3233
}
34+
3335
const source: ClawSourceIdentity = {
3436
kind: "package",
3537
name: "@acme/worker",
@@ -48,6 +50,24 @@ async function fixture() {
4850
return { root, plan, env: { OPENCLAW_STATE_DIR: join(root, "state") } };
4951
}
5052

53+
function listedCronJob(
54+
agentId: string,
55+
ref: ReturnType<typeof readClawCronRefs>[number],
56+
id: string,
57+
) {
58+
const normalized = normalizeCronJobCreate(clawCronGatewayInput(agentId, ref));
59+
if (!normalized) {
60+
throw new Error("expected normalized cron job");
61+
}
62+
return {
63+
...normalized,
64+
id,
65+
createdAtMs: 1,
66+
updatedAtMs: 1,
67+
state: {},
68+
};
69+
}
70+
5171
describe("installClawCronJobs", () => {
5272
it("pins declarations and execution to the final agent id", async () => {
5373
const current = await fixture();
@@ -124,6 +144,73 @@ describe("installClawCronJobs", () => {
124144
expect(add).not.toHaveBeenCalled();
125145
});
126146

147+
it("fails closed when a complete scheduler job disappeared", async () => {
148+
const current = await fixture();
149+
await installClawCronJobs(current.plan, {
150+
env: current.env,
151+
gateway: { add: vi.fn().mockResolvedValue({ id: "scheduler-123" }) },
152+
});
153+
const list = vi.fn().mockResolvedValue({ jobs: [] });
154+
const add = vi.fn();
155+
156+
await expect(
157+
installClawCronJobs(current.plan, {
158+
env: current.env,
159+
gateway: { add, list },
160+
}),
161+
).rejects.toMatchObject({ code: "cron_reconcile_conflict" });
162+
163+
expect(list).toHaveBeenCalledOnce();
164+
expect(add).not.toHaveBeenCalled();
165+
expect(readClawCronRefs("worker-two", { env: current.env })).toMatchObject([
166+
{ schedulerJobId: "scheduler-123", status: "complete" },
167+
]);
168+
});
169+
170+
it("rejects a same-key scheduler job whose declaration drifted", async () => {
171+
const current = await fixture();
172+
await installClawCronJobs(current.plan, {
173+
env: current.env,
174+
gateway: { add: vi.fn().mockResolvedValue({ id: "scheduler-123" }) },
175+
});
176+
const [ref] = readClawCronRefs("worker-two", { env: current.env });
177+
const drifted = listedCronJob("worker-two", ref!, "scheduler-123");
178+
drifted.payload = { kind: "agentTurn", message: "Different declaration" };
179+
const add = vi.fn();
180+
181+
await expect(
182+
installClawCronJobs(current.plan, {
183+
env: current.env,
184+
gateway: { add, list: vi.fn().mockResolvedValue({ jobs: [drifted] }) },
185+
}),
186+
).rejects.toMatchObject({ code: "cron_reconcile_conflict" });
187+
expect(add).not.toHaveBeenCalled();
188+
});
189+
190+
it("rejects a drifted complete job beyond the first gateway page", async () => {
191+
const current = await fixture();
192+
await installClawCronJobs(current.plan, {
193+
env: current.env,
194+
gateway: { add: vi.fn().mockResolvedValue({ id: "scheduler-123" }) },
195+
});
196+
const [ref] = readClawCronRefs("worker-two", { env: current.env });
197+
const drifted = listedCronJob("worker-two", ref!, "scheduler-123");
198+
drifted.payload = { kind: "agentTurn", message: "Different declaration" };
199+
const fillers = Array.from({ length: 200 }, (_, index) => ({ id: `filler-${index}` }));
200+
const add = vi.fn();
201+
202+
await expect(
203+
installClawCronJobs(current.plan, {
204+
env: current.env,
205+
gateway: {
206+
add,
207+
list: vi.fn().mockResolvedValue({ jobs: [...fillers, drifted] }),
208+
},
209+
}),
210+
).rejects.toMatchObject({ code: "cron_reconcile_conflict" });
211+
expect(add).not.toHaveBeenCalled();
212+
});
213+
127214
it("preserves an ambiguous pending reference when cron.add fails", async () => {
128215
const current = await fixture();
129216

0 commit comments

Comments
 (0)