audit-zcode-agent-remnants.mjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. #!/usr/bin/env node
  2. import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
  3. import { relative, resolve, sep } from "node:path";
  4. import process from "node:process";
  5. const repoRoot = resolve(import.meta.dirname, "..");
  6. const keywordPattern = /\b(?:acp|Acp[A-Za-z0-9_]*|ACP|claude|codex|gemini|opencode)\b/u;
  7. const textExtensions = new Set([
  8. ".cjs",
  9. ".css",
  10. ".js",
  11. ".json",
  12. ".jsonc",
  13. ".jsx",
  14. ".mjs",
  15. ".ps1",
  16. ".sh",
  17. ".toml",
  18. ".ts",
  19. ".tsx",
  20. ".yaml",
  21. ".yml",
  22. ]);
  23. const defaultRoots = [
  24. "packages",
  25. "apps/zcode-cli/packages",
  26. "scripts",
  27. ];
  28. const alwaysIgnoredSegments = new Set([
  29. ".git",
  30. "node_modules",
  31. "out",
  32. "dist",
  33. "build",
  34. "coverage",
  35. ".turbo",
  36. ".vite",
  37. "bundled-agents",
  38. "bundled-resources",
  39. "mock-cdn",
  40. "locales",
  41. "assets",
  42. "material-icons",
  43. ".e2e-home",
  44. ]);
  45. const categoryRules = [
  46. {
  47. category: "runtime-blocker",
  48. patterns: [
  49. /^packages\/shared\/src\/zcode-agent-runtime\.ts$/u,
  50. /^packages\/desktop\/scripts\/ensure-local-runtime-assets\.mjs$/u,
  51. /^packages\/desktop\/electron-builder\.config\.js$/u,
  52. /^packages\/desktop\/wdio\.conf\.ts$/u,
  53. /^packages\/server\/src\/remote\/zcodeAgentDeploy\.ts$/u,
  54. /^scripts\/(?:download-glm|prepare-prebuilds|sign-macos-runtime-binaries)\.(?:mjs|sh)$/u,
  55. /^packages\/services\/src\/providers\/(?:claude|codex|gemini)/u,
  56. /^packages\/services\/src\/model-provider\/modelProviderServiceApply\.ts$/u,
  57. /^packages\/services\/src\/model-selection\//u,
  58. /^packages\/services\/src\/runtime-tools\/providerRuntimeResolver\.ts$/u,
  59. /^packages\/services\/src\/process\/runtimeProcessLifecycle\.ts$/u,
  60. /^packages\/services\/src\/runtime-tools\/runtimeCommandEnv\.ts$/u,
  61. ],
  62. },
  63. {
  64. category: "protocol-bridge",
  65. patterns: [
  66. /^packages\/services\/src\/session\/legacyTaskService\.ts$/u,
  67. /^packages\/services\/src\/zcode-agent\/zcodeLegacyTaskCompatService\.ts$/u,
  68. /^packages\/services\/src\/bots\/botRemoteWorkspaceBridge\.ts$/u,
  69. /^packages\/services\/src\/bots\//u,
  70. /^packages\/client\/src\/remoteServiceAccess\.ts$/u,
  71. /^packages\/desktop\/src\/host\/index\.ts$/u,
  72. /^packages\/desktop\/src\/(?:host|main)\/(?:desktopHostProcess|desktopRemoteSessions|externalProcessMetrics|processMonitorWindow|taskRealtimeBus|remoteWorkspaceServiceCollection)\.ts$/u,
  73. /^packages\/server\/src\/remote\/(?:connect|remoteAssetCdn|remoteAssetInstaller)\.ts$/u,
  74. /^packages\/ui\/src\/hooks\/useLegacyTaskService\.ts$/u,
  75. ],
  76. },
  77. {
  78. category: "compat-type",
  79. patterns: [
  80. /^packages\/shared\/src\/acp-types\.ts$/u,
  81. /^packages\/shared\/src\/task-realtime\.ts$/u,
  82. /^packages\/shared\/src\/tool-plan-adapter\.ts$/u,
  83. /^packages\/shared\/src\/(?:assistant-message-parts|assistant-presentation|channels|errors|index|mcp|model-selection-key|model-selection-types|permission-request-preview|protocol|subagents-types|test-ids|web-remote-control|zcode-agent-model-state|zcode-agent-policy)\.ts$/u,
  84. /^packages\/services\/src\/session\//u,
  85. /^packages\/services\/src\/usage-stats\//u,
  86. /^packages\/services\/src\/git\/repo\/gitCheckpointRepo\.ts$/u,
  87. /^packages\/services\/src\/logger\/serviceLogger\.ts$/u,
  88. /^packages\/ui\/src\//u,
  89. /^packages\/web\/src\//u,
  90. /^packages\/ui\/src\/hooks\/useAcp/u,
  91. /^packages\/ui\/src\/lib\/zcodeSessionProjection\.ts$/u,
  92. /^packages\/ui\/src\/store\/zcodeSessionStore/u,
  93. ],
  94. },
  95. {
  96. category: "legacy-data-parser",
  97. patterns: [
  98. /^packages\/shared\/src\/remoteResourcePackages\.ts$/u,
  99. /^packages\/shared\/src\/validation/u,
  100. /^packages\/shared\/src\/bots\.ts$/u,
  101. /^packages\/server\/src\/remote\/remoteAssetCache\.ts$/u,
  102. /^packages\/services\/src\/paths/u,
  103. ],
  104. },
  105. {
  106. category: "product-decision",
  107. patterns: [
  108. /^packages\/services\/src\/(?:commands|memory|plugins|skills)\//u,
  109. /^packages\/desktop\/src\/main\/(?:exportLogs|mcpUserDirectory\/.+)\.ts$/u,
  110. /^packages\/services\/src\/(?:feedback|hooks|model-provider|output-style|providers|settings-sync|subagents|workflow)\//u,
  111. /^packages\/services\/src\/(?:index|node)\.ts$/u,
  112. /^packages\/ui\/src\/settings\/(?:commands|mcp|model-provider|Skills)/u,
  113. /^packages\/ui\/src\/lib\/skillSourceFilter\.ts$/u,
  114. /^apps\/zcode-cli\/packages\/(?:adapters|bootstrap|cli|contracts|core)\/src\//u,
  115. /^apps\/zcode-cli\/packages\/cli\/scripts\//u,
  116. /^packages\/shared\/src\/(?:command-types|model-provider-types|plugin-marketplaces|settings-sync|zcode-protocol\/index)\.ts$/u,
  117. ],
  118. },
  119. ];
  120. function parseArgs(argv) {
  121. const options = {
  122. includeDocs: false,
  123. includeTests: false,
  124. json: false,
  125. roots: [...defaultRoots],
  126. maxUnclassified: null,
  127. maxRuntimeBlocker: null,
  128. };
  129. for (const arg of argv) {
  130. if (arg === "--") {
  131. continue;
  132. }
  133. if (arg === "--include-docs") {
  134. options.includeDocs = true;
  135. continue;
  136. }
  137. if (arg === "--include-tests") {
  138. options.includeTests = true;
  139. continue;
  140. }
  141. if (arg === "--json") {
  142. options.json = true;
  143. continue;
  144. }
  145. if (arg.startsWith("--root=")) {
  146. options.roots = arg.slice("--root=".length).split(",").filter(Boolean);
  147. continue;
  148. }
  149. if (arg.startsWith("--max-unclassified=")) {
  150. options.maxUnclassified = parseLimit(arg, "--max-unclassified=");
  151. continue;
  152. }
  153. if (arg.startsWith("--max-runtime-blocker=")) {
  154. options.maxRuntimeBlocker = parseLimit(arg, "--max-runtime-blocker=");
  155. continue;
  156. }
  157. if (arg === "--help" || arg === "-h") {
  158. printHelp();
  159. process.exit(0);
  160. }
  161. throw new Error(`Unknown option: ${arg}`);
  162. }
  163. return options;
  164. }
  165. function parseLimit(arg, prefix) {
  166. const raw = arg.slice(prefix.length);
  167. const value = Number(raw);
  168. if (!Number.isInteger(value) || value < 0) {
  169. throw new Error(`Invalid numeric limit: ${arg}`);
  170. }
  171. return value;
  172. }
  173. function printHelp() {
  174. console.log(`Usage: node scripts/audit-zcode-agent-remnants.mjs [options]
  175. Options:
  176. --json Print machine-readable JSON
  177. --include-docs Include docs and markdown files
  178. --include-tests Include test files
  179. --root=a,b Override scanned roots
  180. --max-unclassified=N Fail when unclassified production hits exceed N
  181. --max-runtime-blocker=N Fail when runtime-blocker hits exceed N
  182. `);
  183. }
  184. function toPosixPath(path) {
  185. return path.split(sep).join("/");
  186. }
  187. function isTestPath(relativePath) {
  188. return /(^|\/)(test|tests|__tests__)(\/|$)/u.test(relativePath) ||
  189. /\.(?:test|spec)\.[cm]?[jt]sx?$/u.test(relativePath);
  190. }
  191. function shouldSkipPath(relativePath, options) {
  192. if (relativePath === "scripts/audit-zcode-agent-remnants.mjs") {
  193. return true;
  194. }
  195. const segments = relativePath.split("/");
  196. if (segments.some((segment) => alwaysIgnoredSegments.has(segment))) {
  197. return true;
  198. }
  199. if (!options.includeDocs && (segments.includes("docs") || relativePath.endsWith(".md"))) {
  200. return true;
  201. }
  202. if (!options.includeTests && isTestPath(relativePath)) {
  203. return true;
  204. }
  205. return false;
  206. }
  207. function isTextFile(relativePath, options) {
  208. if (options.includeDocs && relativePath.endsWith(".md")) {
  209. return true;
  210. }
  211. const extensionMatch = /\.[^.]+$/u.exec(relativePath);
  212. return extensionMatch ? textExtensions.has(extensionMatch[0]) : false;
  213. }
  214. function* walk(root, options) {
  215. if (!existsSync(root)) {
  216. return;
  217. }
  218. const stat = statSync(root);
  219. const relativePath = toPosixPath(relative(repoRoot, root));
  220. if (relativePath && shouldSkipPath(relativePath, options)) {
  221. return;
  222. }
  223. if (stat.isDirectory()) {
  224. for (const entry of readdirSync(root, { withFileTypes: true })) {
  225. yield* walk(resolve(root, entry.name), options);
  226. }
  227. return;
  228. }
  229. if (stat.isFile() && isTextFile(relativePath, options)) {
  230. yield {
  231. absolutePath: root,
  232. relativePath,
  233. };
  234. }
  235. }
  236. function classifyFile(relativePath) {
  237. for (const rule of categoryRules) {
  238. if (rule.patterns.some((pattern) => pattern.test(relativePath))) {
  239. return rule.category;
  240. }
  241. }
  242. return "unclassified";
  243. }
  244. function scanFile(file) {
  245. const content = readFileSync(file.absolutePath, "utf8");
  246. const matches = [];
  247. const lines = content.split(/\r?\n/u);
  248. for (const [index, line] of lines.entries()) {
  249. const match = keywordPattern.exec(line);
  250. if (!match) {
  251. continue;
  252. }
  253. matches.push({
  254. line: index + 1,
  255. keyword: match[0],
  256. preview: line.trim().slice(0, 180),
  257. });
  258. }
  259. return matches;
  260. }
  261. function buildReport(options) {
  262. const hits = [];
  263. for (const root of options.roots) {
  264. const absoluteRoot = resolve(repoRoot, root);
  265. for (const file of walk(absoluteRoot, options)) {
  266. const matches = scanFile(file);
  267. if (matches.length === 0) {
  268. continue;
  269. }
  270. hits.push({
  271. path: file.relativePath,
  272. category: classifyFile(file.relativePath),
  273. matches,
  274. });
  275. }
  276. }
  277. const categories = new Map();
  278. for (const hit of hits) {
  279. const current = categories.get(hit.category) ?? { files: 0, matches: 0 };
  280. current.files += 1;
  281. current.matches += hit.matches.length;
  282. categories.set(hit.category, current);
  283. }
  284. return {
  285. roots: options.roots,
  286. includeDocs: options.includeDocs,
  287. includeTests: options.includeTests,
  288. totalFiles: hits.length,
  289. totalMatches: hits.reduce((sum, hit) => sum + hit.matches.length, 0),
  290. categories: Object.fromEntries([...categories.entries()].sort()),
  291. hits: hits.sort((left, right) =>
  292. left.category.localeCompare(right.category) || left.path.localeCompare(right.path),
  293. ),
  294. };
  295. }
  296. function assertLimits(report, options) {
  297. const failures = [];
  298. const unclassifiedFiles = report.categories.unclassified?.files ?? 0;
  299. const runtimeBlockerFiles = report.categories["runtime-blocker"]?.files ?? 0;
  300. if (options.maxUnclassified !== null && unclassifiedFiles > options.maxUnclassified) {
  301. failures.push(
  302. `unclassified files ${unclassifiedFiles} > ${options.maxUnclassified}`,
  303. );
  304. }
  305. if (options.maxRuntimeBlocker !== null && runtimeBlockerFiles > options.maxRuntimeBlocker) {
  306. failures.push(
  307. `runtime-blocker files ${runtimeBlockerFiles} > ${options.maxRuntimeBlocker}`,
  308. );
  309. }
  310. return failures;
  311. }
  312. function printTextReport(report, failures) {
  313. console.log("ZCode Agent remnant audit");
  314. console.log(`roots: ${report.roots.join(", ")}`);
  315. console.log(`files: ${report.totalFiles}, matches: ${report.totalMatches}`);
  316. console.log("");
  317. console.log("category summary:");
  318. for (const [category, counts] of Object.entries(report.categories)) {
  319. console.log(` ${category.padEnd(18)} files=${counts.files} matches=${counts.matches}`);
  320. }
  321. if (report.hits.length > 0) {
  322. console.log("");
  323. console.log("top files:");
  324. for (const hit of report.hits.slice(0, 80)) {
  325. const firstMatch = hit.matches[0];
  326. console.log(
  327. ` [${hit.category}] ${hit.path}:${firstMatch.line} ${firstMatch.keyword} (${hit.matches.length})`,
  328. );
  329. }
  330. }
  331. if (failures.length > 0) {
  332. console.log("");
  333. console.error(`ratchet failed: ${failures.join("; ")}`);
  334. }
  335. }
  336. try {
  337. const options = parseArgs(process.argv.slice(2));
  338. const report = buildReport(options);
  339. const failures = assertLimits(report, options);
  340. if (options.json) {
  341. console.log(JSON.stringify({ ...report, failures }, null, 2));
  342. } else {
  343. printTextReport(report, failures);
  344. }
  345. if (failures.length > 0) {
  346. process.exitCode = 1;
  347. }
  348. } catch (error) {
  349. console.error(error instanceof Error ? error.message : String(error));
  350. process.exitCode = 1;
  351. }