File size: 12,323 Bytes
fb4d8fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
import path from "node:path";
import { describe, expect, it } from "vitest";
import {
  CircularIncludeError,
  ConfigIncludeError,
  type IncludeResolver,
  resolveConfigIncludes,
} from "./includes.js";

const ROOT_DIR = path.parse(process.cwd()).root;
const CONFIG_DIR = path.join(ROOT_DIR, "config");
const ETC_OPENCLAW_DIR = path.join(ROOT_DIR, "etc", "openclaw");
const SHARED_DIR = path.join(ROOT_DIR, "shared");

const DEFAULT_BASE_PATH = path.join(CONFIG_DIR, "openclaw.json");

function configPath(...parts: string[]) {
  return path.join(CONFIG_DIR, ...parts);
}

function etcOpenClawPath(...parts: string[]) {
  return path.join(ETC_OPENCLAW_DIR, ...parts);
}

function sharedPath(...parts: string[]) {
  return path.join(SHARED_DIR, ...parts);
}

function createMockResolver(files: Record<string, unknown>): IncludeResolver {
  return {
    readFile: (filePath: string) => {
      if (filePath in files) {
        return JSON.stringify(files[filePath]);
      }
      throw new Error(`ENOENT: no such file: ${filePath}`);
    },
    parseJson: JSON.parse,
  };
}

function resolve(obj: unknown, files: Record<string, unknown> = {}, basePath = DEFAULT_BASE_PATH) {
  return resolveConfigIncludes(obj, basePath, createMockResolver(files));
}

describe("resolveConfigIncludes", () => {
  it("passes through primitives unchanged", () => {
    expect(resolve("hello")).toBe("hello");
    expect(resolve(42)).toBe(42);
    expect(resolve(true)).toBe(true);
    expect(resolve(null)).toBe(null);
  });

  it("passes through arrays with recursion", () => {
    expect(resolve([1, 2, { a: 1 }])).toEqual([1, 2, { a: 1 }]);
  });

  it("passes through objects without $include", () => {
    const obj = { foo: "bar", nested: { x: 1 } };
    expect(resolve(obj)).toEqual(obj);
  });

  it("resolves single file $include", () => {
    const files = { [configPath("agents.json")]: { list: [{ id: "main" }] } };
    const obj = { agents: { $include: "./agents.json" } };
    expect(resolve(obj, files)).toEqual({
      agents: { list: [{ id: "main" }] },
    });
  });

  it("resolves absolute path $include", () => {
    const absolute = etcOpenClawPath("agents.json");
    const files = { [absolute]: { list: [{ id: "main" }] } };
    const obj = { agents: { $include: absolute } };
    expect(resolve(obj, files)).toEqual({
      agents: { list: [{ id: "main" }] },
    });
  });

  it("resolves array $include with deep merge", () => {
    const files = {
      [configPath("a.json")]: { "group-a": ["agent1"] },
      [configPath("b.json")]: { "group-b": ["agent2"] },
    };
    const obj = { broadcast: { $include: ["./a.json", "./b.json"] } };
    expect(resolve(obj, files)).toEqual({
      broadcast: {
        "group-a": ["agent1"],
        "group-b": ["agent2"],
      },
    });
  });

  it("deep merges overlapping keys in array $include", () => {
    const files = {
      [configPath("a.json")]: { agents: { defaults: { workspace: "~/a" } } },
      [configPath("b.json")]: { agents: { list: [{ id: "main" }] } },
    };
    const obj = { $include: ["./a.json", "./b.json"] };
    expect(resolve(obj, files)).toEqual({
      agents: {
        defaults: { workspace: "~/a" },
        list: [{ id: "main" }],
      },
    });
  });

  it("merges $include with sibling keys", () => {
    const files = { [configPath("base.json")]: { a: 1, b: 2 } };
    const obj = { $include: "./base.json", c: 3 };
    expect(resolve(obj, files)).toEqual({ a: 1, b: 2, c: 3 });
  });

  it("sibling keys override included values", () => {
    const files = { [configPath("base.json")]: { a: 1, b: 2 } };
    const obj = { $include: "./base.json", b: 99 };
    expect(resolve(obj, files)).toEqual({ a: 1, b: 99 });
  });

  it("throws when sibling keys are used with non-object includes", () => {
    const files = { [configPath("list.json")]: ["a", "b"] };
    const obj = { $include: "./list.json", extra: true };
    expect(() => resolve(obj, files)).toThrow(ConfigIncludeError);
    expect(() => resolve(obj, files)).toThrow(
      /Sibling keys require included content to be an object/,
    );
  });

  it("throws when sibling keys are used with primitive includes", () => {
    const files = { [configPath("value.json")]: "hello" };
    const obj = { $include: "./value.json", extra: true };
    expect(() => resolve(obj, files)).toThrow(ConfigIncludeError);
    expect(() => resolve(obj, files)).toThrow(
      /Sibling keys require included content to be an object/,
    );
  });

  it("resolves nested includes", () => {
    const files = {
      [configPath("level1.json")]: { nested: { $include: "./level2.json" } },
      [configPath("level2.json")]: { deep: "value" },
    };
    const obj = { $include: "./level1.json" };
    expect(resolve(obj, files)).toEqual({
      nested: { deep: "value" },
    });
  });

  it("throws ConfigIncludeError for missing file", () => {
    const obj = { $include: "./missing.json" };
    expect(() => resolve(obj)).toThrow(ConfigIncludeError);
    expect(() => resolve(obj)).toThrow(/Failed to read include file/);
  });

  it("throws ConfigIncludeError for invalid JSON", () => {
    const resolver: IncludeResolver = {
      readFile: () => "{ invalid json }",
      parseJson: JSON.parse,
    };
    const obj = { $include: "./bad.json" };
    expect(() => resolveConfigIncludes(obj, DEFAULT_BASE_PATH, resolver)).toThrow(
      ConfigIncludeError,
    );
    expect(() => resolveConfigIncludes(obj, DEFAULT_BASE_PATH, resolver)).toThrow(
      /Failed to parse include file/,
    );
  });

  it("throws CircularIncludeError for circular includes", () => {
    const aPath = configPath("a.json");
    const bPath = configPath("b.json");
    const resolver: IncludeResolver = {
      readFile: (filePath: string) => {
        if (filePath === aPath) {
          return JSON.stringify({ $include: "./b.json" });
        }
        if (filePath === bPath) {
          return JSON.stringify({ $include: "./a.json" });
        }
        throw new Error(`Unknown file: ${filePath}`);
      },
      parseJson: JSON.parse,
    };
    const obj = { $include: "./a.json" };
    try {
      resolveConfigIncludes(obj, DEFAULT_BASE_PATH, resolver);
      throw new Error("expected circular include error");
    } catch (err) {
      expect(err).toBeInstanceOf(CircularIncludeError);
      const circular = err as CircularIncludeError;
      expect(circular.chain).toEqual(expect.arrayContaining([DEFAULT_BASE_PATH, aPath, bPath]));
      expect(circular.message).toMatch(/Circular include detected/);
      expect(circular.message).toContain("a.json");
      expect(circular.message).toContain("b.json");
    }
  });

  it("throws ConfigIncludeError for invalid $include value type", () => {
    const obj = { $include: 123 };
    expect(() => resolve(obj)).toThrow(ConfigIncludeError);
    expect(() => resolve(obj)).toThrow(/expected string or array/);
  });

  it("throws ConfigIncludeError for invalid array item type", () => {
    const files = { [configPath("valid.json")]: { valid: true } };
    const obj = { $include: ["./valid.json", 123] };
    expect(() => resolve(obj, files)).toThrow(ConfigIncludeError);
    expect(() => resolve(obj, files)).toThrow(/expected string, got number/);
  });

  it("throws ConfigIncludeError for null/boolean include items", () => {
    const files = { [configPath("valid.json")]: { valid: true } };
    const cases = [
      { value: null, expected: "object" },
      { value: false, expected: "boolean" },
    ];
    for (const item of cases) {
      const obj = { $include: ["./valid.json", item.value] };
      expect(() => resolve(obj, files)).toThrow(ConfigIncludeError);
      expect(() => resolve(obj, files)).toThrow(
        new RegExp(`expected string, got ${item.expected}`),
      );
    }
  });

  it("respects max depth limit", () => {
    const files: Record<string, unknown> = {};
    for (let i = 0; i < 15; i++) {
      files[configPath(`level${i}.json`)] = {
        $include: `./level${i + 1}.json`,
      };
    }
    files[configPath("level15.json")] = { done: true };

    const obj = { $include: "./level0.json" };
    expect(() => resolve(obj, files)).toThrow(ConfigIncludeError);
    expect(() => resolve(obj, files)).toThrow(/Maximum include depth/);
  });

  it("allows depth 10 but rejects depth 11", () => {
    const okFiles: Record<string, unknown> = {};
    for (let i = 0; i < 9; i++) {
      okFiles[configPath(`ok${i}.json`)] = { $include: `./ok${i + 1}.json` };
    }
    okFiles[configPath("ok9.json")] = { done: true };
    expect(resolve({ $include: "./ok0.json" }, okFiles)).toEqual({
      done: true,
    });

    const failFiles: Record<string, unknown> = {};
    for (let i = 0; i < 10; i++) {
      failFiles[configPath(`fail${i}.json`)] = {
        $include: `./fail${i + 1}.json`,
      };
    }
    failFiles[configPath("fail10.json")] = { done: true };
    expect(() => resolve({ $include: "./fail0.json" }, failFiles)).toThrow(ConfigIncludeError);
    expect(() => resolve({ $include: "./fail0.json" }, failFiles)).toThrow(/Maximum include depth/);
  });

  it("handles relative paths correctly", () => {
    const files = {
      [configPath("clients", "mueller", "agents.json")]: { id: "mueller" },
    };
    const obj = { agent: { $include: "./clients/mueller/agents.json" } };
    expect(resolve(obj, files)).toEqual({
      agent: { id: "mueller" },
    });
  });

  it("applies nested includes before sibling overrides", () => {
    const files = {
      [configPath("base.json")]: { nested: { $include: "./nested.json" } },
      [configPath("nested.json")]: { a: 1, b: 2 },
    };
    const obj = { $include: "./base.json", nested: { b: 9 } };
    expect(resolve(obj, files)).toEqual({
      nested: { a: 1, b: 9 },
    });
  });

  it("resolves parent directory references", () => {
    const files = { [sharedPath("common.json")]: { shared: true } };
    const obj = { $include: "../../shared/common.json" };
    expect(resolve(obj, files, configPath("sub", "openclaw.json"))).toEqual({
      shared: true,
    });
  });
});

describe("real-world config patterns", () => {
  it("supports per-client agent includes", () => {
    const files = {
      [configPath("clients", "mueller.json")]: {
        agents: [
          {
            id: "mueller-screenshot",
            workspace: "~/clients/mueller/screenshot",
          },
          {
            id: "mueller-transcribe",
            workspace: "~/clients/mueller/transcribe",
          },
        ],
        broadcast: {
          "group-mueller": ["mueller-screenshot", "mueller-transcribe"],
        },
      },
      [configPath("clients", "schmidt.json")]: {
        agents: [
          {
            id: "schmidt-screenshot",
            workspace: "~/clients/schmidt/screenshot",
          },
        ],
        broadcast: { "group-schmidt": ["schmidt-screenshot"] },
      },
    };

    const obj = {
      gateway: { port: 18789 },
      $include: ["./clients/mueller.json", "./clients/schmidt.json"],
    };

    expect(resolve(obj, files)).toEqual({
      gateway: { port: 18789 },
      agents: [
        { id: "mueller-screenshot", workspace: "~/clients/mueller/screenshot" },
        { id: "mueller-transcribe", workspace: "~/clients/mueller/transcribe" },
        { id: "schmidt-screenshot", workspace: "~/clients/schmidt/screenshot" },
      ],
      broadcast: {
        "group-mueller": ["mueller-screenshot", "mueller-transcribe"],
        "group-schmidt": ["schmidt-screenshot"],
      },
    });
  });

  it("supports modular config structure", () => {
    const files = {
      [configPath("gateway.json")]: {
        gateway: { port: 18789, bind: "loopback" },
      },
      [configPath("channels", "whatsapp.json")]: {
        channels: { whatsapp: { dmPolicy: "pairing", allowFrom: ["+49123"] } },
      },
      [configPath("agents", "defaults.json")]: {
        agents: { defaults: { sandbox: { mode: "all" } } },
      },
    };

    const obj = {
      $include: ["./gateway.json", "./channels/whatsapp.json", "./agents/defaults.json"],
    };

    expect(resolve(obj, files)).toEqual({
      gateway: { port: 18789, bind: "loopback" },
      channels: { whatsapp: { dmPolicy: "pairing", allowFrom: ["+49123"] } },
      agents: { defaults: { sandbox: { mode: "all" } } },
    });
  });
});