File size: 9,777 Bytes
4c76b0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Plugin tool contract tests cover bundled plugin tool schemas and invocation contracts.
import fs from "node:fs";
import path from "node:path";
import { beforeAll, describe, expect, it } from "vitest";
import { expectNoReaddirSyncDuring } from "../../test-utils/fs-scan-assertions.js";
import {
  listGitTrackedFiles,
  toRepoPath,
  toRepoRelativePath,
} from "../../test-utils/repo-files.js";

type PluginManifestFile = {
  id?: unknown;
  contracts?: {
    tools?: unknown;
  };
};

function walkFiles(dir: string): string[] {
  const gitFiles = listGitFiles(dir);
  if (gitFiles) {
    return gitFiles;
  }

  const files: string[] = [];
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
    if (entry.name === "node_modules" || entry.name === "dist" || entry.name.startsWith(".")) {
      continue;
    }
    const entryPath = path.join(dir, entry.name);
    if (entry.isDirectory()) {
      files.push(...walkFiles(entryPath));
      continue;
    }
    files.push(entryPath);
  }
  return files;
}

function repoRelativePath(filePath: string): string {
  return toRepoRelativePath(process.cwd(), filePath);
}

function isSkippedRepoPath(relativePath: string): boolean {
  return relativePath
    .split("/")
    .some((part) => part === "node_modules" || part === "dist" || part.startsWith("."));
}

function listGitFiles(dir: string): string[] | null {
  const relativeDir = repoRelativePath(dir);
  if (!relativeDir || relativeDir.startsWith("..") || path.isAbsolute(relativeDir)) {
    return null;
  }
  const files = listGitTrackedFiles({ pathspecs: relativeDir });
  if (!files) {
    return null;
  }
  return files
    .filter((line) => !isSkippedRepoPath(line))
    .map((line) => path.join(process.cwd(), ...line.split("/")))
    .filter((filePath) => fs.existsSync(filePath))
    .toSorted();
}

function listGitPluginManifestPaths(extensionsDir: string): string[] | null {
  const relativeDir = repoRelativePath(extensionsDir);
  if (!relativeDir || relativeDir.startsWith("..") || path.isAbsolute(relativeDir)) {
    return null;
  }
  const files = listGitTrackedFiles({ pathspecs: relativeDir });
  if (!files) {
    return null;
  }
  return files
    .filter((line) => /^extensions\/[^/]+\/openclaw\.plugin\.json$/u.test(line))
    .map((line) => path.join(process.cwd(), ...line.split("/")))
    .filter((filePath) => fs.existsSync(filePath))
    .toSorted();
}

function listPluginManifestPaths(extensionsDir: string): string[] {
  const gitPaths = listGitPluginManifestPaths(extensionsDir);
  if (gitPaths) {
    return gitPaths;
  }

  return fs
    .readdirSync(extensionsDir, { withFileTypes: true })
    .filter((entry) => entry.isDirectory() && !entry.name.startsWith("."))
    .map((entry) => path.join(extensionsDir, entry.name, "openclaw.plugin.json"))
    .filter((manifestPath) => fs.existsSync(manifestPath));
}

function isProductionSource(filePath: string): boolean {
  if (!/\.(?:cjs|mjs|js|ts|tsx)$/.test(filePath)) {
    return false;
  }
  const normalized = toRepoPath(filePath);
  return !/(\.test\.|\.spec\.|\/__tests__\/|\/test-support\/)/.test(normalized);
}

function readBalancedCallArguments(source: string, openParenIndex: number): string | undefined {
  let depth = 0;
  let quote: '"' | "'" | "`" | undefined;
  let escaped = false;
  for (let index = openParenIndex; index < source.length; index += 1) {
    const char = source[index];
    if (!char) {
      continue;
    }
    if (quote) {
      if (escaped) {
        escaped = false;
        continue;
      }
      if (char === "\\") {
        escaped = true;
        continue;
      }
      if (char === quote) {
        quote = undefined;
      }
      continue;
    }
    if (char === '"' || char === "'" || char === "`") {
      quote = char;
      continue;
    }
    if (char === "(" || char === "{" || char === "[") {
      depth += 1;
      continue;
    }
    if (char === ")" || char === "}" || char === "]") {
      depth -= 1;
      if (depth === 0 && char === ")") {
        return source.slice(openParenIndex + 1, index);
      }
    }
  }
  return undefined;
}

function listRegisterToolCalls(source: string): string[] {
  const calls: string[] = [];
  const pattern = /\bregisterTool\s*\(/g;
  let match: RegExpExecArray | null;
  while ((match = pattern.exec(source))) {
    const openParenIndex = source.indexOf("(", match.index);
    const args = readBalancedCallArguments(source, openParenIndex);
    if (args !== undefined) {
      calls.push(args);
    }
  }
  return calls;
}

function splitTopLevelArgs(args: string): string[] {
  const parts: string[] = [];
  let depth = 0;
  let quote: '"' | "'" | "`" | undefined;
  let escaped = false;
  let start = 0;
  for (let index = 0; index < args.length; index += 1) {
    const char = args[index];
    if (!char) {
      continue;
    }
    if (quote) {
      if (escaped) {
        escaped = false;
        continue;
      }
      if (char === "\\") {
        escaped = true;
        continue;
      }
      if (char === quote) {
        quote = undefined;
      }
      continue;
    }
    if (char === '"' || char === "'" || char === "`") {
      quote = char;
      continue;
    }
    if (char === "(" || char === "{" || char === "[") {
      depth += 1;
      continue;
    }
    if (char === ")" || char === "}" || char === "]") {
      depth -= 1;
      continue;
    }
    if (char === "," && depth === 0) {
      const part = args.slice(start, index).trim();
      if (part.length > 0) {
        parts.push(part);
      }
      start = index + 1;
    }
  }
  const part = args.slice(start).trim();
  if (part.length > 0) {
    parts.push(part);
  }
  return parts;
}

function extractStringLiterals(source: string): string[] {
  const names: string[] = [];
  const pattern = /["']([^"']+)["']/g;
  let match: RegExpExecArray | null;
  while ((match = pattern.exec(source))) {
    if (match[1]) {
      names.push(match[1]);
    }
  }
  return names;
}

function extractStaticRegisteredToolNamesFromObject(source: string): string[] {
  const names = new Set<string>();
  const namesPattern = /\bnames\s*:\s*\[([\s\S]*?)\]/g;
  let namesMatch: RegExpExecArray | null;
  while ((namesMatch = namesPattern.exec(source))) {
    for (const name of extractStringLiterals(namesMatch[1] ?? "")) {
      names.add(name);
    }
  }

  const namePattern = /\bname\s*:\s*["']([^"']+)["']/g;
  let nameMatch: RegExpExecArray | null;
  while ((nameMatch = namePattern.exec(source))) {
    if (nameMatch[1]) {
      names.add(nameMatch[1]);
    }
  }
  return [...names];
}

function extractStaticRegisteredToolNames(callArgs: string): string[] {
  const args = splitTopLevelArgs(callArgs);
  const names = new Set<string>();
  const firstArg = args[0]?.trim() ?? "";
  const optionsArg = args[1]?.trim() ?? "";
  if (firstArg.startsWith("{")) {
    for (const name of extractStaticRegisteredToolNamesFromObject(firstArg)) {
      names.add(name);
    }
  }
  if (optionsArg.startsWith("{")) {
    for (const name of extractStaticRegisteredToolNamesFromObject(optionsArg)) {
      names.add(name);
    }
  }
  return [...names];
}

function readManifest(manifestPath: string): PluginManifestFile {
  return JSON.parse(fs.readFileSync(manifestPath, "utf-8")) as PluginManifestFile;
}

function normalizeManifestTools(value: unknown): string[] {
  if (!Array.isArray(value)) {
    return [];
  }
  return value.filter((item): item is string => typeof item === "string" && item.trim() !== "");
}

describe("bundled plugin tool manifest contracts", () => {
  let toolContractFailures: string[] = [];

  beforeAll(() => {
    listGitTrackedFiles({ pathspecs: "extensions" });
    toolContractFailures = collectToolContractFailures(path.join(process.cwd(), "extensions"));
  });

  it("lists plugin tool contract inputs from git without walking extension roots", () => {
    const extensionsDir = path.join(process.cwd(), "extensions");
    expectNoReaddirSyncDuring(() => {
      const manifestPaths = listPluginManifestPaths(extensionsDir);
      const sourceFiles = manifestPaths[0]
        ? walkFiles(path.dirname(manifestPaths[0])).filter(isProductionSource)
        : [];

      expect(manifestPaths.length).toBeGreaterThan(0);
      expect(sourceFiles.length).toBeGreaterThan(0);
    });
  });

  it("declares every production registerTool owner in contracts.tools", () => {
    expect(toolContractFailures).toStrictEqual([]);
  });
});

function collectToolContractFailures(extensionsDir: string): string[] {
  const failures: string[] = [];

  for (const manifestPath of listPluginManifestPaths(extensionsDir)) {
    const pluginDir = path.dirname(manifestPath);
    const manifest = readManifest(manifestPath);
    const pluginId = typeof manifest.id === "string" ? manifest.id : path.basename(pluginDir);
    const declaredTools = new Set(normalizeManifestTools(manifest.contracts?.tools));
    const registeredNames = new Set<string>();
    let registerCallCount = 0;

    for (const filePath of walkFiles(pluginDir).filter(isProductionSource)) {
      const source = fs.readFileSync(filePath, "utf-8");
      for (const call of listRegisterToolCalls(source)) {
        registerCallCount += 1;
        for (const name of extractStaticRegisteredToolNames(call)) {
          registeredNames.add(name);
        }
      }
    }

    if (registerCallCount === 0) {
      continue;
    }
    if (declaredTools.size === 0) {
      failures.push(`${pluginId}: registers agent tools but has no contracts.tools`);
      continue;
    }

    const missing = [...registeredNames].filter((name) => !declaredTools.has(name)).toSorted();
    if (missing.length > 0) {
      failures.push(`${pluginId}: missing contracts.tools for ${missing.join(", ")}`);
    }
  }

  return failures;
}