Skip to content

Commit 36171a3

Browse files
committed
refactor(config): split write preparation primitives
1 parent 3ba0d95 commit 36171a3

19 files changed

Lines changed: 385 additions & 374 deletions

‎src/cli/plugins-update-command.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
formatInvalidConfigDetails,
1313
} from "../config/io.invalid-config.js";
1414
import type { ConfigWriteOptions } from "../config/io.js";
15-
import { createMergePatch } from "../config/io.write-prepare.js";
15+
import { createMergePatch } from "../config/merge-patch.js";
1616
import { applyMergePatch } from "../config/merge-patch.js";
1717
import { ConfigMutationConflictError } from "../config/mutate.js";
1818
import type { OpenClawConfig } from "../config/types.openclaw.js";

‎src/commands/onboard-agent.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import {
66
toAgentEntriesRecord,
77
} from "../agents/agent-scope-config.js";
88
import { readConfigFileSnapshot } from "../config/config.js";
9-
import { createMergePatch } from "../config/io.write-prepare.js";
9+
import { createMergePatch } from "../config/merge-patch.js";
1010
import { applyMergePatch } from "../config/merge-patch.js";
1111
import type { OpenClawConfig } from "../config/types.openclaw.js";
1212

‎src/config/config-change-paths.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Reports config paths whose values differ between two snapshots.
2+
import { isDeepStrictEqual } from "node:util";
3+
import { isRecord } from "../utils.js";
4+
5+
export function collectChangedPaths(
6+
base: unknown,
7+
target: unknown,
8+
path: string,
9+
output: Set<string>,
10+
): void {
11+
if (Array.isArray(base) && Array.isArray(target)) {
12+
const max = Math.max(base.length, target.length);
13+
for (let index = 0; index < max; index += 1) {
14+
const childPath = path ? `${path}[${index}]` : `[${index}]`;
15+
if (index >= base.length || index >= target.length) {
16+
output.add(childPath);
17+
continue;
18+
}
19+
collectChangedPaths(base[index], target[index], childPath, output);
20+
}
21+
return;
22+
}
23+
if (isRecord(base) && isRecord(target)) {
24+
const keys = new Set([...Object.keys(base), ...Object.keys(target)]);
25+
for (const key of keys) {
26+
const childPath = path ? `${path}.${key}` : key;
27+
const hasBase = Object.hasOwn(base, key);
28+
const hasTarget = Object.hasOwn(target, key);
29+
if (!hasTarget || !hasBase) {
30+
output.add(childPath);
31+
continue;
32+
}
33+
collectChangedPaths(base[key], target[key], childPath, output);
34+
}
35+
return;
36+
}
37+
if (!isDeepStrictEqual(base, target)) {
38+
output.add(path);
39+
}
40+
}

‎src/config/config-path-mutation.ts‎

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
// Applies immutable path removals to config-like objects.
2+
import { isDeepStrictEqual } from "node:util";
3+
import { expectDefined } from "@openclaw/normalization-core";
4+
import { isBlockedObjectKey } from "../infra/prototype-keys.js";
5+
import { parseConfigPathArrayIndex } from "../shared/path-array-index.js";
6+
import type { OpenClawConfig } from "./types.js";
7+
8+
const MANAGED_CONFIG_UNSET_PATHS = [["plugins", "installs"]] as const;
9+
const WRITE_PRUNED_OBJECT = Symbol("write-pruned-object");
10+
11+
function isWritePlainObject(value: unknown): value is Record<string, unknown> {
12+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
13+
}
14+
15+
function coerceConfig(value: unknown): OpenClawConfig {
16+
if (!value || typeof value !== "object" || Array.isArray(value)) {
17+
return {};
18+
}
19+
return value as OpenClawConfig;
20+
}
21+
22+
function unsetPathForWriteAt(
23+
value: unknown,
24+
pathSegments: string[],
25+
depth: number,
26+
): { changed: boolean; value: unknown } {
27+
if (depth >= pathSegments.length) {
28+
return { changed: false, value };
29+
}
30+
const segment = expectDefined(pathSegments[depth], "path segments entry at depth");
31+
const isLeaf = depth === pathSegments.length - 1;
32+
33+
if (Array.isArray(value)) {
34+
const index = parseConfigPathArrayIndex(segment);
35+
if (index === undefined || index >= value.length) {
36+
return { changed: false, value };
37+
}
38+
if (isLeaf) {
39+
const next = value.slice();
40+
next.splice(index, 1);
41+
return { changed: true, value: next };
42+
}
43+
const child = unsetPathForWriteAt(value[index], pathSegments, depth + 1);
44+
if (!child.changed) {
45+
return { changed: false, value };
46+
}
47+
const next = value.slice();
48+
if (child.value === WRITE_PRUNED_OBJECT) {
49+
next.splice(index, 1);
50+
} else {
51+
next[index] = child.value;
52+
}
53+
return { changed: true, value: next };
54+
}
55+
56+
if (isBlockedObjectKey(segment) || !isWritePlainObject(value) || !Object.hasOwn(value, segment)) {
57+
return { changed: false, value };
58+
}
59+
if (isLeaf) {
60+
const next: Record<string, unknown> = { ...value };
61+
delete next[segment];
62+
return {
63+
changed: true,
64+
value: Object.keys(next).length === 0 ? WRITE_PRUNED_OBJECT : next,
65+
};
66+
}
67+
68+
const child = unsetPathForWriteAt(value[segment], pathSegments, depth + 1);
69+
if (!child.changed) {
70+
return { changed: false, value };
71+
}
72+
const next: Record<string, unknown> = { ...value };
73+
if (child.value === WRITE_PRUNED_OBJECT) {
74+
delete next[segment];
75+
} else {
76+
next[segment] = child.value;
77+
}
78+
return {
79+
changed: true,
80+
value: Object.keys(next).length === 0 ? WRITE_PRUNED_OBJECT : next,
81+
};
82+
}
83+
84+
function unsetPathForWrite(
85+
root: OpenClawConfig,
86+
pathSegments: string[],
87+
): { changed: boolean; next: OpenClawConfig } {
88+
if (pathSegments.length === 0) {
89+
return { changed: false, next: root };
90+
}
91+
const result = unsetPathForWriteAt(root, pathSegments, 0);
92+
if (!result.changed) {
93+
return { changed: false, next: root };
94+
}
95+
if (result.value === WRITE_PRUNED_OBJECT) {
96+
return { changed: true, next: {} };
97+
}
98+
if (isWritePlainObject(result.value)) {
99+
return { changed: true, next: coerceConfig(result.value) };
100+
}
101+
return { changed: false, next: root };
102+
}
103+
104+
export function applyUnsetPathsForWrite(
105+
root: OpenClawConfig,
106+
unsetPaths: readonly string[][] | undefined,
107+
): OpenClawConfig {
108+
let next = root;
109+
for (const unsetPath of unsetPaths ?? []) {
110+
if (!Array.isArray(unsetPath) || unsetPath.length === 0) {
111+
continue;
112+
}
113+
const unsetResult = unsetPathForWrite(next, unsetPath);
114+
if (unsetResult.changed) {
115+
next = unsetResult.next;
116+
}
117+
}
118+
return next;
119+
}
120+
121+
export function resolveManagedUnsetPathsForWrite(
122+
unsetPaths: readonly string[][] | undefined,
123+
): string[][] {
124+
const next: string[][] = [];
125+
for (const managedPath of MANAGED_CONFIG_UNSET_PATHS) {
126+
next.push(Array.from(managedPath));
127+
}
128+
for (const unsetPath of unsetPaths ?? []) {
129+
if (!Array.isArray(unsetPath) || unsetPath.length === 0) {
130+
continue;
131+
}
132+
if (next.some((existing) => isDeepStrictEqual(existing, unsetPath))) {
133+
continue;
134+
}
135+
next.push([...unsetPath]);
136+
}
137+
return next;
138+
}

‎src/config/env-preserve.ts‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import { isDeepStrictEqual } from "node:util";
33
import { expectDefined } from "@openclaw/normalization-core";
44
import { isPlainObject } from "../infra/plain-object.js";
5+
import { isRecord } from "../utils.js";
56

67
/**
78
* Preserves `${VAR}` environment variable references during config write-back.
@@ -833,4 +834,102 @@ export function restoreEnvVarRefs(
833834
// Mismatched types or primitives — keep incoming
834835
return incoming;
835836
}
837+
838+
function parentPath(value: string): string {
839+
if (!value) {
840+
return "";
841+
}
842+
if (value.endsWith("]")) {
843+
const index = value.lastIndexOf("[");
844+
return index > 0 ? value.slice(0, index) : "";
845+
}
846+
const index = value.lastIndexOf(".");
847+
return index >= 0 ? value.slice(0, index) : "";
848+
}
849+
850+
function isPathChanged(path: string, changedPaths: Set<string>): boolean {
851+
if (changedPaths.has(path)) {
852+
return true;
853+
}
854+
let current = parentPath(path);
855+
while (current) {
856+
if (changedPaths.has(current)) {
857+
return true;
858+
}
859+
current = parentPath(current);
860+
}
861+
return changedPaths.has("");
862+
}
863+
864+
export function restoreEnvRefsFromMap(
865+
value: unknown,
866+
path: string,
867+
envRefMap: Map<string, string>,
868+
changedPaths: Set<string>,
869+
identityRestoredPaths: ReadonlySet<string> = new Set(),
870+
): unknown {
871+
if (typeof value === "string") {
872+
if (identityRestoredPaths.has(path)) {
873+
return value;
874+
}
875+
if (!isPathChanged(path, changedPaths)) {
876+
const original = envRefMap.get(path);
877+
if (original !== undefined) {
878+
return original;
879+
}
880+
}
881+
return value;
882+
}
883+
if (Array.isArray(value)) {
884+
let changed = false;
885+
const next = value.map((item, index) => {
886+
const updated = restoreEnvRefsFromMap(
887+
item,
888+
`${path}[${index}]`,
889+
envRefMap,
890+
changedPaths,
891+
identityRestoredPaths,
892+
);
893+
if (updated !== item) {
894+
changed = true;
895+
}
896+
return updated;
897+
});
898+
return changed ? next : value;
899+
}
900+
if (isRecord(value)) {
901+
let changed = false;
902+
const next: Record<string, unknown> = {};
903+
for (const [key, child] of Object.entries(value)) {
904+
const childPath = path ? `${path}.${key}` : key;
905+
const updated = restoreEnvRefsFromMap(
906+
child,
907+
childPath,
908+
envRefMap,
909+
changedPaths,
910+
identityRestoredPaths,
911+
);
912+
if (updated !== child) {
913+
changed = true;
914+
}
915+
next[key] = updated;
916+
}
917+
return changed ? next : value;
918+
}
919+
return value;
920+
}
921+
922+
export function resolveWriteEnvSnapshotForPath(params: {
923+
actualConfigPath: string;
924+
expectedConfigPath?: string;
925+
envSnapshotForRestore?: Record<string, string | undefined>;
926+
}): Record<string, string | undefined> | undefined {
927+
if (
928+
params.expectedConfigPath === undefined ||
929+
params.expectedConfigPath === params.actualConfigPath
930+
) {
931+
return params.envSnapshotForRestore;
932+
}
933+
return undefined;
934+
}
836935
/* oxlint-disable max-lines -- TODO: split this grandfathered oversized file. */

‎src/config/io.runtime.ts‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import fs from "node:fs";
22
import { formatErrorMessage } from "../infra/errors.js";
33
import { cloneEnvWithPlatformSemantics, createConfigRuntimeEnvBase } from "./config-env-vars.js";
4+
import { resolveManagedUnsetPathsForWrite } from "./config-path-mutation.js";
5+
import { resolveWriteEnvSnapshotForPath } from "./env-preserve.js";
46
import { GATEWAY_CONFIG_SELECTION_ENV_KEYS } from "./gateway-env-selection.js";
57
import { createConfigIO } from "./io.factory.js";
68
import {
@@ -21,13 +23,8 @@ import type {
2123
ReadConfigFileSnapshotWithPluginMetadataResult,
2224
} from "./io.types.js";
2325
import { ConfigRuntimeRefreshError, configWritePostCommitRollback } from "./io.types.js";
24-
import {
25-
createMergePatch,
26-
resolveManagedUnsetPathsForWrite,
27-
resolveWriteEnvSnapshotForPath,
28-
} from "./io.write-prepare.js";
2926
import { rollbackConfigFileWriteIfUnchanged } from "./io.write-safety.js";
30-
import { applyMergePatch } from "./merge-patch.js";
27+
import { applyMergePatch, createMergePatch } from "./merge-patch.js";
3128
import { ConfigMutationConflictError } from "./mutation-conflict.js";
3229
import { assertConfigWriteAllowedInCurrentMode } from "./nix-mode-write-guard.js";
3330
import {

‎src/config/io.snapshot.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { includeContributionOwnsAgentRoster } from "./agent-roster-provenance.js";
2+
import { resolveManagedUnsetPathsForWrite } from "./config-path-mutation.js";
23
import { ConfigIncludeError } from "./includes.js";
34
import type { ConfigIoContext } from "./io.context.js";
45
import { maybeRecoverSuspiciousConfigRead } from "./io.observe-recovery.js";
@@ -27,7 +28,6 @@ import type {
2728
ReadConfigFileSnapshotWithPluginMetadataResult,
2829
} from "./io.types.js";
2930
import { warnIfConfigFromFuture } from "./io.warnings.js";
30-
import { resolveManagedUnsetPathsForWrite } from "./io.write-prepare.js";
3131
import { migratePersistedImplicitMainRoster } from "./legacy.js";
3232
import { materializeRuntimeConfig } from "./materialize.js";
3333
import { ConfigMutationConflictError } from "./mutation-conflict.js";

‎src/config/io.write-errors.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Formats stable user-facing config write failures.
2+
const OPEN_DM_POLICY_ALLOW_FROM_RE =
3+
/^(?<policyPath>[a-z0-9_.-]+)\s*=\s*"open"\s+requires\s+(?<allowPath>[a-z0-9_.-]+)(?:\s+\(or\s+[a-z0-9_.-]+\))?\s+to include "\*"$/i;
4+
5+
export function formatConfigValidationFailure(pathLabel: string, issueMessage: string): string {
6+
const match = issueMessage.match(OPEN_DM_POLICY_ALLOW_FROM_RE);
7+
const policyPath = match?.groups?.policyPath?.trim();
8+
const allowPath = match?.groups?.allowPath?.trim();
9+
if (!policyPath || !allowPath) {
10+
return `Config validation failed: ${pathLabel}: ${issueMessage}`;
11+
}
12+
13+
return [
14+
`Config validation failed: ${pathLabel}`,
15+
"",
16+
`Configuration mismatch: ${policyPath} is "open", but ${allowPath} does not include "*".`,
17+
"",
18+
"Fix with:",
19+
` openclaw config set ${allowPath} '["*"]'`,
20+
"",
21+
"Or switch policy:",
22+
` openclaw config set ${policyPath} "pairing"`,
23+
].join("\n");
24+
}

‎src/config/io.write-prepare.test.ts‎

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,11 @@
11
// Covers config write preparation diffs and metadata preservation.
22
import { describe, expect, it, vi } from "vitest";
3-
import {
4-
collectChangedPaths,
5-
applyUnsetPathsForWrite,
6-
createMergePatch,
7-
formatConfigValidationFailure,
8-
restoreEnvRefsFromMap,
9-
resolvePersistCandidateForWrite,
10-
resolveWriteEnvSnapshotForPath,
11-
} from "./io.write-prepare.js";
3+
import { collectChangedPaths } from "./config-change-paths.js";
4+
import { applyUnsetPathsForWrite } from "./config-path-mutation.js";
5+
import { restoreEnvRefsFromMap, resolveWriteEnvSnapshotForPath } from "./env-preserve.js";
6+
import { formatConfigValidationFailure } from "./io.write-errors.js";
7+
import { resolvePersistCandidateForWrite } from "./io.write-prepare.js";
8+
import { createMergePatch } from "./merge-patch.js";
129
import type { OpenClawConfig } from "./types.js";
1310

1411
vi.unmock("../agents/agent-scope-config.js");

0 commit comments

Comments
 (0)