Skip to content

Commit 629a47e

Browse files
authored
fix(config): preserve indexed and whole-list agent edits (#131369)
* fix(config): preserve agent roster mutations * fix(config): reset indexes when replacing agent rosters * fix(config): replace rosters before converting discarded state * docs(config): keep roster release notes in PR
1 parent 099fc6b commit 629a47e

13 files changed

Lines changed: 1017 additions & 508 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2369,7 +2369,7 @@ src/cli/completion-runtime.ts 4
23692369
src/cli/config-cli-input.ts 3
23702370
src/cli/config-cli-path.ts 6
23712371
src/cli/config-cli-runner.ts 7
2372-
src/cli/config-cli.ts 11
2372+
src/cli/config-cli.ts 8
23732373
src/cli/config-model-validation.ts 7
23742374
src/cli/config-set-input.ts 2
23752375
src/cli/connect-cli.ts 1
@@ -2661,11 +2661,11 @@ src/config/io.snapshot.ts 1
26612661
src/config/io.warnings.ts 2
26622662
src/config/io.write-prepare.ts 16
26632663
src/config/io.write-safety.ts 4
2664-
src/config/io.write.ts 13
2664+
src/config/io.write.ts 10
26652665
src/config/issue-location.ts 2
26662666
src/config/legacy-private-network-migration.ts 1
26672667
src/config/legacy.default-agent-roles.ts 1
2668-
src/config/legacy.roster.ts 15
2668+
src/config/legacy.roster.ts 13
26692669
src/config/legacy.ts 3
26702670
src/config/markdown-tables.ts 3
26712671
src/config/materialize.ts 2

‎docs/cli/config.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,13 @@ openclaw config get agents.entries
5656
openclaw config set 'agents.entries.work.tools.exec.node' "node-id-or-name"
5757
```
5858

59+
Prefer `agents.entries.<id>` paths for agent edits. The legacy `agents.list[0]`
60+
syntax and whole-list inputs still work with `set`, `patch`, and `unset`; writes
61+
persist the canonical keyed roster. Indexed edits use the current roster order.
62+
Within a batch, a submitted list keeps its order across subsequent keyed edits,
63+
including when agent IDs are numeric strings. Existing roster-deletion and
64+
`$include` ownership protections still apply.
65+
5966
### `config get`
6067

6168
Reads a value from the redacted config snapshot (secrets never print). `--json` prints the same redacted value as JSON; otherwise strings/numbers/booleans print bare and objects/arrays print as formatted JSON.

‎src/cli/config-cli-roster.ts‎

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
2+
import { readAgentRosterProperty } from "../agents/agent-scope-config.js";
3+
import { parseLegacyAgentRoster } from "../config/legacy.roster.js";
4+
import type { ConfigSetOperation } from "./config-cli-input.js";
5+
import { getAtPath, type PathSegment } from "./config-cli-path.js";
6+
7+
/** Keeps the documented list input and keyed input on one mutable roster. */
8+
export class ConfigMutationAgentRoster {
9+
private legacyOrder: string[] | undefined;
10+
11+
constructor(
12+
private readonly root: Record<string, unknown>,
13+
sourceConfigBeforeMigrations: unknown,
14+
) {
15+
const sourceRoster = readAgentRosterProperty(sourceConfigBeforeMigrations);
16+
this.legacyOrder =
17+
sourceRoster?.kind === "list" ? parseLegacyAgentRoster(sourceRoster.value)?.order : undefined;
18+
}
19+
20+
prepare(operation: ConfigSetOperation, merge: boolean): void {
21+
const path = operation.setPath;
22+
if (path[0] !== "agents") {
23+
return;
24+
}
25+
if (
26+
path.length === 1 &&
27+
isRecord(operation.value) &&
28+
Object.hasOwn(operation.value, "list") &&
29+
Object.hasOwn(operation.value, "entries")
30+
) {
31+
throw new Error("Set either agents.list or agents.entries in one value, not both.");
32+
}
33+
const submittedRoster =
34+
path.length === 1 ? readAgentRosterProperty({ agents: operation.value }) : undefined;
35+
const kind = path.length === 1 ? submittedRoster?.kind : path[1];
36+
const roster = readAgentRosterProperty(this.root);
37+
// A removed roster's indexes cannot select entries in its replacement.
38+
if (!roster) {
39+
this.legacyOrder = undefined;
40+
}
41+
const agents = this.root.agents;
42+
if ((kind !== "list" && kind !== "entries") || !isRecord(agents)) {
43+
return;
44+
}
45+
// Whole replacements discard the old representation without validating it.
46+
// A list deletion still needs projection so unset can find its keyed target.
47+
if (path.length <= 2 && !merge && (kind === "entries" || operation.mutation !== "delete")) {
48+
delete agents[kind === "entries" ? "list" : "entries"];
49+
this.legacyOrder = undefined;
50+
return;
51+
}
52+
if (kind === "entries") {
53+
if (roster?.kind === "list") {
54+
this.canonicalize(true);
55+
}
56+
return;
57+
}
58+
if (roster?.kind !== "entries") {
59+
return;
60+
}
61+
if (
62+
!isRecord(roster.value) ||
63+
Object.values(roster.value).some((entry) => !isRecord(entry) || Object.hasOwn(entry, "id"))
64+
) {
65+
throw new Error(
66+
"Cannot address agents.list while agents.entries contains invalid entries; correct the keyed roster first.",
67+
);
68+
}
69+
const entries = roster.value;
70+
// Integer-like ids enumerate numerically in objects. A keyed leaf edit must not
71+
// change the index selected by a later operation in the same submitted list.
72+
const order = [...new Set([...(this.legacyOrder ?? []), ...Object.keys(entries)])].filter(
73+
(id) => Object.hasOwn(entries, id),
74+
);
75+
const list = [];
76+
for (const id of order) {
77+
// SAFETY: The roster check above rejects non-record entries and conflicting in-entry ids.
78+
list.push({ ...(entries[id] as Record<string, unknown>), id });
79+
}
80+
agents.list = list;
81+
delete agents.entries;
82+
}
83+
84+
writePath(path: PathSegment[]): PathSegment[] {
85+
if (path[0] !== "agents" || path[1] !== "list") {
86+
return path;
87+
}
88+
if (path.length === 2) {
89+
const roster = readAgentRosterProperty(this.root);
90+
return roster?.kind === "list" && parseLegacyAgentRoster(roster.value)
91+
? ["agents", "entries"]
92+
: path;
93+
}
94+
const entry = getAtPath(this.root, path.slice(0, 3));
95+
const roster = entry.found ? parseLegacyAgentRoster([entry.value]) : undefined;
96+
const id = roster?.order[0];
97+
return id === undefined ? path : ["agents", "entries", id, ...path.slice(3)];
98+
}
99+
100+
finish(): void {
101+
this.canonicalize(false);
102+
}
103+
104+
private canonicalize(required: boolean): void {
105+
const agents = this.root.agents;
106+
const roster = readAgentRosterProperty(this.root);
107+
if (!isRecord(agents) || roster?.kind !== "list") {
108+
return;
109+
}
110+
const parsed = parseLegacyAgentRoster(roster.value);
111+
if (!parsed) {
112+
if (required) {
113+
throw new Error(
114+
"Cannot address agents.entries while agents.list contains invalid or duplicate ids; correct the list first.",
115+
);
116+
}
117+
return;
118+
}
119+
this.legacyOrder = parsed.order;
120+
agents.entries = parsed.entries;
121+
delete agents.list;
122+
}
123+
}

‎src/cli/config-cli-runner.ts‎

Lines changed: 87 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import { isDeepStrictEqual } from "node:util";
22
import { uniqueValues } from "@openclaw/normalization-core/string-normalization";
3+
import { resolveManagedUnsetPathsForWrite } from "../config/config-path-mutation.js";
34
import { replaceConfigFile } from "../config/config.js";
45
import { AUTO_MANAGED_CONFIG_META_PATHS } from "../config/io.meta.js";
6+
import { prepareConfigWriteTopology } from "../config/io.write-topology.js";
57
import { formatConfigIssueLines } from "../config/issue-format.js";
68
import { ConfigMutationConflictError } from "../config/mutation-conflict.js";
79
import { resolveConfigPath } from "../config/paths.js";
@@ -30,13 +32,16 @@ import {
3032
import {
3133
assertNonDestructiveReplacement,
3234
formatConfigSetPath,
35+
formatConfigUnsetMissingPathMessage,
3336
getAtPath,
3437
mergeAtPath,
38+
parseConfigSetPath,
3539
setAtPath,
3640
type JsonSchemaRecord,
3741
type PathSegment,
3842
unsetAtPath,
3943
} from "./config-cli-path.js";
44+
import { ConfigMutationAgentRoster } from "./config-cli-roster.js";
4045
import {
4146
assertStrictConfigForMutation,
4247
collectDryRunRefs,
@@ -138,15 +143,6 @@ function formatAutoManagedMetaError(paths: readonly PathSegment[][]): string {
138143
].join("\n");
139144
}
140145

141-
export function assertConfigPathIsNotAutoManaged(path: PathSegment[]): void {
142-
const targets = findAutoManagedMetaTargets([
143-
{ inputMode: "json", requestedPath: path, setPath: path, value: undefined, mutation: "delete" },
144-
]);
145-
if (targets.length > 0) {
146-
throw new Error(formatAutoManagedMetaError(targets));
147-
}
148-
}
149-
150146
function pruneInactiveGatewayAuthCredentials(params: {
151147
root: Record<string, unknown>;
152148
operations: ConfigSetOperation[];
@@ -222,7 +218,7 @@ function expandActualChangedPaths(
222218
return [...expanded];
223219
}
224220

225-
export function configApplyHintForOperations(
221+
function configApplyHintForOperations(
226222
operations: ReadonlyArray<{ requestedPath?: PathSegment[] }>,
227223
beforeConfig: OpenClawConfig,
228224
afterConfig: OpenClawConfig,
@@ -303,18 +299,73 @@ export async function runConfigOperations(params: {
303299
structuredClone(snapshot.resolved) as OpenClawConfig,
304300
);
305301
const mutationSchema = await loadMutationSchema();
306-
const unsetPaths: PathSegment[][] = [];
302+
const roster = new ConfigMutationAgentRoster(next, snapshot.sourceConfigBeforeMigrations);
303+
let unsetPaths: PathSegment[][] = [];
307304
const explicitSetPaths: PathSegment[][] = [];
305+
const appliedOperations: ConfigSetOperation[] = [];
306+
const recordOperation = (operation: ConfigSetOperation): PathSegment[] => {
307+
const setPath = roster.writePath(operation.setPath);
308+
let touchedSecretTargetPath = operation.touchedSecretTargetPath;
309+
if (touchedSecretTargetPath) {
310+
const path = parseConfigSetPath(touchedSecretTargetPath);
311+
const writePath = roster.writePath(path);
312+
if (writePath !== path) {
313+
touchedSecretTargetPath = toDotPath(writePath);
314+
}
315+
}
316+
appliedOperations.push({
317+
...operation,
318+
setPath,
319+
...(touchedSecretTargetPath ? { touchedSecretTargetPath } : {}),
320+
});
321+
return setPath;
322+
};
308323
for (const operation of operations) {
324+
const merge =
325+
operation.mutation === "merge" || (options.merge && operation.mutation !== "replace");
326+
roster.prepare(operation, Boolean(merge));
309327
if (operation.mutation === "delete") {
328+
const writePath = recordOperation(operation);
310329
const unsetResult = unsetAtPath(next, operation.setPath);
330+
if (!unsetResult.removed && operation.inputMode === "unset") {
331+
const runtimeOnly = getAtPath(snapshot.runtimeConfig, operation.setPath).found;
332+
const message = formatConfigUnsetMissingPathMessage({
333+
path: formatConfigSetPath(operation.requestedPath, operation.pathTokens),
334+
runtimeOnly,
335+
});
336+
if (options.dryRun && options.json) {
337+
throw new ConfigSetDryRunValidationError({
338+
ok: false,
339+
operations: 1,
340+
configPath: snapshot.path,
341+
inputModes: ["unset"],
342+
checks: { schema: false, resolvability: false, resolvabilityComplete: false },
343+
refsChecked: 0,
344+
skippedExecRefs: 0,
345+
errors: [
346+
{
347+
kind: "missing-path",
348+
message: runtimeOnly
349+
? message
350+
: `Config path not found: ${formatConfigSetPath(operation.requestedPath, operation.pathTokens)}. Nothing was changed.`,
351+
},
352+
],
353+
});
354+
}
355+
if (!options.dryRun) {
356+
assertStrictConfigForMutation(
357+
currentConfig,
358+
mutationStart.writeOptions.basePluginMetadataSnapshot,
359+
);
360+
}
361+
throw new Error(message);
362+
}
311363
if (!unsetResult.removed || unsetResult.leafContainer !== "array") {
312-
unsetPaths.push(operation.setPath);
364+
unsetPaths.push(writePath);
313365
}
314366
continue;
315367
}
316-
explicitSetPaths.push(operation.setPath);
317-
if (operation.mutation === "merge" || (options.merge && operation.mutation !== "replace")) {
368+
if (merge) {
318369
mergeAtPath(next, operation.setPath, operation.value, {
319370
numericObjectKeys: params.successMode === "patch",
320371
...(operation.pathTokens ? { pathTokens: operation.pathTokens } : {}),
@@ -339,18 +390,33 @@ export async function runConfigOperations(params: {
339390
schema: mutationSchema,
340391
});
341392
}
393+
explicitSetPaths.push(recordOperation(operation));
342394
}
395+
roster.finish();
396+
// A later operation can recreate a deleted path, including through a roster alias.
397+
// Only final deletions may be replayed by the persistence owner.
398+
unsetPaths = unsetPaths.filter((path) => !getAtPath(next, path).found);
343399
const removedGatewayAuthPaths = pruneInactiveGatewayAuthCredentials({ root: next, operations });
344-
const nextConfig = normalizeConfigMutationModelRefs(next as OpenClawConfig);
400+
let nextConfig = normalizeConfigMutationModelRefs(next as OpenClawConfig);
345401
const normalizedExplicitSetPaths = explicitSetPaths.map(normalizeConfigMutationExplicitSetPath);
402+
if (options.dryRun) {
403+
nextConfig = prepareConfigWriteTopology({
404+
snapshot,
405+
pluginMetadataSnapshot: mutationStart.writeOptions.basePluginMetadataSnapshot,
406+
nextConfig,
407+
options: { explicitSetPaths: normalizedExplicitSetPaths },
408+
unsetPaths: resolveManagedUnsetPathsForWrite(unsetPaths),
409+
env: process.env,
410+
}).nextConfig;
411+
}
346412
const policyIssueLines = formatConfigIssueLines(
347413
collectUnsupportedSecretRefPolicyIssues(nextConfig),
348414
"",
349415
{ normalizeRoot: true },
350416
).map((line) => line.trim());
351417
const pluginIntegrationErrors = collectPluginIntegrationProviderErrors({
352418
config: nextConfig,
353-
operations,
419+
operations: appliedOperations,
354420
});
355421
if (options.dryRun) {
356422
const hasJsonMode = operations.some(({ inputMode }) => inputMode === "json");
@@ -362,7 +428,9 @@ export async function runConfigOperations(params: {
362428
(operation.inputMode === "json" && operation.schemaValidated !== true),
363429
);
364430
const checksRefs = hasJsonMode || hasBuilderMode || hasUnsetMode;
365-
const refs = checksRefs ? collectDryRunRefs({ config: nextConfig, operations }) : [];
431+
const refs = checksRefs
432+
? collectDryRunRefs({ config: nextConfig, operations: appliedOperations })
433+
: [];
366434
const selectedRefs = selectDryRunRefsForResolution({
367435
refs,
368436
allowExecInDryRun: Boolean(options.allowExec),
@@ -371,7 +439,7 @@ export async function runConfigOperations(params: {
371439
const modelRefCheck = await checkTouchedTextModelRefs({
372440
config: nextConfig,
373441
previousConfig: currentConfig,
374-
touchedPaths: operations.map(({ setPath }) => setPath),
442+
touchedPaths: appliedOperations.map(({ setPath }) => setPath),
375443
redactDependencyValues: true,
376444
});
377445
errors.push(...modelRefCheck.errors.map((message) => ({ kind: "model" as const, message })));
@@ -479,7 +547,7 @@ export async function runConfigOperations(params: {
479547
const modelRefCheck = await checkTouchedTextModelRefs({
480548
config: nextConfig,
481549
previousConfig: currentConfig,
482-
touchedPaths: operations.map(({ setPath }) => setPath),
550+
touchedPaths: appliedOperations.map(({ setPath }) => setPath),
483551
redactDependencyValues: true,
484552
});
485553
if (modelRefCheck.errors[0]) {

‎src/cli/config-cli-validation.ts‎

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { isRecord as isPlainRecord } from "@openclaw/normalization-core/record-coerce";
22
import type { ConfigFileSnapshot } from "../config/config.js";
3-
import { readConfigFileSnapshot, readConfigFileSnapshotForWrite } from "../config/config.js";
3+
import { readConfigFileSnapshotForWrite } from "../config/config.js";
44
import { formatConfigIssueLines, normalizeConfigIssues } from "../config/issue-format.js";
55
import { renderConfigValidationIssueLines } from "../config/issue-location.js";
66
import { isPluginPackagingRuntimeOutputInvalidConfigSnapshot } from "../config/recovery-policy.js";
@@ -68,18 +68,6 @@ export function ensureValidConfigSnapshotForCli(
6868
return false;
6969
}
7070

71-
export async function loadValidConfig(
72-
runtime: RuntimeEnv = defaultRuntime,
73-
options: { observe?: boolean; json?: boolean } = {},
74-
) {
75-
const snapshot =
76-
options.observe === false
77-
? await readConfigFileSnapshot({ observe: false })
78-
: await readConfigFileSnapshot();
79-
ensureValidConfigSnapshotForCli(snapshot, runtime, options);
80-
return snapshot;
81-
}
82-
8371
export async function loadValidConfigForWrite(runtime: RuntimeEnv = defaultRuntime) {
8472
const prepared = await readConfigFileSnapshotForWrite();
8573
ensureValidConfigSnapshotForCli(prepared.snapshot, runtime);

0 commit comments

Comments
 (0)