@a-t-h-i/bot-lobby 0.6.61 → 0.6.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +3 -7
  2. package/package.json +2 -1
  3. package/prompts/designer.md +25 -15
  4. package/prompts/master.md +284 -491
  5. package/prompts/panel.md +7 -0
  6. package/prompts/planner.md +15 -4
  7. package/prompts/qa.md +5 -1
  8. package/prompts/worker.md +0 -7
  9. package/scripts/builtin/affected_packages.mjs +106 -0
  10. package/scripts/builtin/check_changed.mjs +51 -0
  11. package/scripts/builtin/check_contract_breakage.mjs +118 -0
  12. package/scripts/builtin/circular_dependency_check.mjs +79 -0
  13. package/scripts/builtin/code_duplication_check.mjs +86 -0
  14. package/scripts/builtin/diff_summary.mjs +62 -0
  15. package/scripts/builtin/failure_digest.mjs +107 -0
  16. package/scripts/builtin/find_generated_files.mjs +79 -0
  17. package/scripts/builtin/find_symbol.mjs +81 -0
  18. package/scripts/builtin/find_test_fixtures.mjs +73 -0
  19. package/scripts/builtin/find_tests_for.mjs +12 -0
  20. package/scripts/builtin/lib/common.mjs +267 -0
  21. package/scripts/builtin/outline_file.mjs +77 -0
  22. package/scripts/builtin/project_commands.mjs +49 -0
  23. package/scripts/builtin/recent_changes.mjs +14 -0
  24. package/scripts/builtin/repo_map.mjs +65 -0
  25. package/scripts/builtin/run_changed_tests.mjs +48 -0
  26. package/src/delivery/transport.ts +1 -1
  27. package/src/desk/client-extension.ts +1 -31
  28. package/src/desk/ipc.ts +1 -11
  29. package/src/desk/session.ts +4 -101
  30. package/src/execution/agent-runner.ts +50 -8
  31. package/src/execution/assigned-session.ts +263 -0
  32. package/src/execution/assignment-discovery.ts +128 -0
  33. package/src/execution/assignment-policy.ts +46 -0
  34. package/src/execution/assignment.ts +175 -0
  35. package/src/execution/delegation.ts +9 -94
  36. package/src/execution/pi-runner.ts +99 -9
  37. package/src/harness/instructions.ts +1 -1
  38. package/src/index.ts +3 -0
  39. package/src/knowledge/design-record.ts +394 -0
  40. package/src/knowledge/file-notes.ts +36 -8
  41. package/src/lobby/ask.ts +6 -0
  42. package/src/lobby/exec.ts +28 -0
  43. package/src/lobby/host.ts +1 -11
  44. package/src/lobby/planner.ts +50 -124
  45. package/src/lobby/prompts.ts +1 -7
  46. package/src/lobby/runtime.ts +2 -26
  47. package/src/lobby/service.ts +25 -23
  48. package/src/lobby/topics.ts +0 -2
  49. package/src/master/evidence-freshness.ts +96 -0
  50. package/src/master/master.ts +248 -74
  51. package/src/master/scout-cache.ts +1 -1
  52. package/src/master/scout-lock.ts +44 -0
  53. package/src/master/scout-prefetch.ts +78 -0
  54. package/src/pi/activity.ts +2 -0
  55. package/src/pi/assignment-guard.ts +157 -0
  56. package/src/pi/delegation.ts +2 -21
  57. package/src/pi/model-support.ts +0 -6
  58. package/src/pi/start-task.ts +18 -7
  59. package/src/pi/tools.ts +41 -8
  60. package/src/roles/scout.ts +3 -1
  61. package/src/roles/worker.ts +107 -5
  62. package/src/schemas/configuration.ts +11 -45
  63. package/src/schemas/findings.ts +3 -0
  64. package/src/schemas/task.ts +30 -12
  65. package/src/scripts/library.ts +31 -1
  66. package/src/scripts/pick.ts +31 -15
  67. package/src/state/archive.ts +10 -0
  68. package/src/state/checkpoint.ts +0 -1
  69. package/src/state/gitignore.ts +39 -0
  70. package/src/state/persistence.ts +56 -0
  71. package/src/state/recovery.ts +33 -1
  72. package/src/webui/api/index.ts +6 -35
  73. package/src/webui/api/retention.ts +44 -0
  74. package/src/webui/api/status.ts +4 -6
  75. package/src/webui/dev/fake-service.ts +0 -117
  76. package/src/webui/dev/fixtures.ts +2 -16
  77. package/src/webui/protocol.ts +2 -142
  78. package/src/workflow/draft-assignments.ts +118 -0
  79. package/src/workflow/workflow.ts +271 -214
  80. package/webui/dist/assets/{CodeSurface-BtzJOVyH.js → CodeSurface-D3c12DBE.js} +1 -1
  81. package/webui/dist/assets/{TerminalView-Cz-KNWsq.js → TerminalView-DG4X3Yyr.js} +1 -1
  82. package/webui/dist/assets/index-BDmgr1OS.js +112 -0
  83. package/webui/dist/assets/index-BTyu99rI.css +2 -0
  84. package/webui/dist/build.json +29 -65
  85. package/webui/dist/index.html +2 -2
  86. package/prompts/expert.md +0 -17
  87. package/prompts/goal-check.md +0 -44
  88. package/prompts/pr-review.md +0 -62
  89. package/prompts/splitter.md +0 -58
  90. package/src/execution/worker-trees.ts +0 -396
  91. package/src/lobby/issues.ts +0 -219
  92. package/src/lobby/pr-review.ts +0 -366
  93. package/src/lobby/pulls.ts +0 -250
  94. package/src/lobby/split.ts +0 -262
  95. package/src/master/goal-check.ts +0 -115
  96. package/src/webui/api/gh-error.ts +0 -17
  97. package/src/webui/api/git.ts +0 -98
  98. package/src/webui/api/issues.ts +0 -50
  99. package/webui/dist/assets/index-D5fvY8f8.js +0 -112
  100. package/webui/dist/assets/index-DFvk8ADr.css +0 -2
@@ -0,0 +1,107 @@
1
+ #!/usr/bin/env node
2
+ // purpose: boil a long build, test, typecheck or lint log down to its errors (file:line, message, failing tests) and show our own code at each stack frame; reads a file, stdin, or runs a command
3
+ // usage: node {script} [log file] | <command> | node {script} | node {script} --run "<command>" [--timeout <seconds>]
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import { isAbsolute, join, relative } from "node:path";
6
+ import { parseArgs, projectRoot, sh } from "./lib/common.mjs";
7
+
8
+ const { flags, rest } = parseArgs();
9
+ const root = projectRoot();
10
+ let log = "";
11
+ let exit;
12
+ if (typeof flags.run === "string") {
13
+ const result = sh("bash", ["-lc", flags.run], { cwd: root, timeout: Number(flags.timeout ?? 300) * 1000, env: { ...process.env, CI: "1", FORCE_COLOR: "0", NO_COLOR: "1" } });
14
+ log = `${result.out}\n${result.err}`;
15
+ exit = result.code;
16
+ console.log(`$ ${flags.run} (exit ${exit})`);
17
+ } else if (rest[0]) log = readFileSync(rest[0], "utf8");
18
+ else if (!process.stdin.isTTY) log = readFileSync(0, "utf8");
19
+ else {
20
+ console.error("Give a log file, pipe a log in, or --run a command.");
21
+ process.exit(2);
22
+ }
23
+ log = log.replace(/\x1b\[[0-9;]*m/g, "");
24
+ const rows = log.split("\n");
25
+
26
+ /** A path in the log, as a project file, or undefined when it is not ours. */
27
+ function ours(path) {
28
+ if (!path || /node_modules|site-packages|dist-packages|\/usr\/lib|internal\/|^node:|<anonymous>/.test(path)) return undefined;
29
+ const clean = path.replace(/^file:\/\//, "");
30
+ const rel = isAbsolute(clean) ? relative(root, clean) : clean;
31
+ return !rel.startsWith("..") && existsSync(join(root, rel)) ? rel : undefined;
32
+ }
33
+
34
+ const errors = [];
35
+ const seen = new Set();
36
+ const add = (file, line, message, kind = "error") => {
37
+ const key = `${file}:${line}:${message}`;
38
+ if (seen.has(key)) return;
39
+ seen.add(key);
40
+ errors.push({ file, line: Number(line) || 0, message: message.trim().slice(0, 220), kind });
41
+ };
42
+ const failing = new Set();
43
+ const frames = [];
44
+ let eslintFile;
45
+ for (let i = 0; i < rows.length; i++) {
46
+ const row = rows[i];
47
+ let m;
48
+ if ((m = /^(.+?)\((\d+),\d+\):\s*(error|warning)\s+(TS\d+:.*)$/.exec(row))) add(m[1], m[2], m[4], m[3]);
49
+ else if ((m = /^(\S+\.\w+):(\d+):(\d+)\s*-\s*(error|warning)\s+(TS\d+:.*)$/.exec(row))) add(m[1], m[2], m[5], m[4]);
50
+ else if ((m = /^\s*-->\s*(\S+):(\d+):\d+/.exec(row))) add(m[1], m[2], (rows[i - 1] ?? "").replace(/^(error|warning)(\[\w+\])?:\s*/, ""), /warning/.test(rows[i - 1] ?? "") ? "warning" : "error");
51
+ else if ((m = /^(\/\S+|[\w./-]+\.\w+)$/.exec(row.trim())) && ours(m[1]) && /^\s+\d+:\d+\s+(error|warning)/.test(rows[i + 1] ?? "")) eslintFile = ours(m[1]);
52
+ else if (eslintFile && (m = /^\s+(\d+):\d+\s+(error|warning)\s+(.+?)\s{2,}([\w@/-]+)?\s*$/.exec(row))) add(eslintFile, m[1], `${m[3]}${m[4] ? ` (${m[4]})` : ""}`, m[2]);
53
+ else if ((m = /^FAILED\s+(\S+?)::(\S+)(?:\s+-\s+(.*))?/.exec(row))) { failing.add(`${m[1]} › ${m[2]}`); if (m[3]) add(m[1], 0, m[3]); }
54
+ else if ((m = /^(?:✖|×|✕|not ok \d+ -)\s+(.+?)(?:\s+\(\d+(?:\.\d+)?m?s\))?$/.exec(row.trim())) && !/^\d+ (passing|failing)/.test(m[1])) failing.add(m[1]);
55
+ else if ((m = /^\s*●\s+(.+)$/.exec(row)) && !/Console/.test(m[1])) failing.add(m[1]);
56
+ else if ((m = /^\s*(?:FAIL)\s+(\S+)/.exec(row))) failing.add(m[1]);
57
+ else if ((m = /^--- FAIL: (\S+)/.exec(row))) failing.add(m[1]);
58
+ else if ((m = /^(?:\s*)([\w./-]+\.(?:go|py|rs|c|cpp|h|java|kt|swift|rb)):(\d+)(?::\d+)?:\s*(.+)$/.exec(row)) && ours(m[1])) add(ours(m[1]), m[2], m[3]);
59
+ else if ((m = /^\s*([\w./-]+\.[cm]?[jt]sx?):(\d+):\d+:?\s+(.+)$/.exec(row)) && ours(m[1])) add(ours(m[1]), m[2], m[3]);
60
+ // Assertion and error messages, kept with the test they belong to.
61
+ if ((m = /^\s*(AssertionError[^:]*|Error|TypeError|ReferenceError|SyntaxError|RangeError|E\s{2,})\s*:?\s*(.+)$/.exec(row)) && !/^\s+at /.test(row) && errors.length < 200) {
62
+ const text = `${m[1].trim()}: ${m[2]}`.replace(/^E:\s*/, "");
63
+ if (!seen.has(text)) { seen.add(text); errors.push({ file: "", line: 0, message: text.slice(0, 220), kind: "assert" }); }
64
+ }
65
+ // Stack frames: JS `at fn (path:line:col)`, Python `File "path", line N`, Go `path.go:N +0x`.
66
+ if ((m = /^\s+at (?:(.+?) \()?((?:file:\/\/)?[^():\s]+):(\d+):\d+\)?$/.exec(row)) && ours(m[2])) frames.push({ file: ours(m[2]), line: Number(m[3]), fn: m[1] ?? "" });
67
+ else if ((m = /^\s*File "(.+?)", line (\d+), in (\S+)/.exec(row)) && ours(m[1])) frames.push({ file: ours(m[1]), line: Number(m[2]), fn: m[3] });
68
+ else if ((m = /^\s+(\/\S+\.go):(\d+)/.exec(row)) && ours(m[1])) frames.push({ file: ours(m[1]), line: Number(m[2]), fn: (rows[i - 1] ?? "").trim().replace(/\(.*$/, "") });
69
+ }
70
+
71
+ const real = errors.filter((entry) => entry.kind !== "warning");
72
+ const warnings = errors.length - real.length;
73
+ console.log(`## Digest: ${real.length} error${real.length === 1 ? "" : "s"}${warnings ? `, ${warnings} warning${warnings === 1 ? "" : "s"}` : ""}, ${failing.size} failing test${failing.size === 1 ? "" : "s"}${exit !== undefined ? `, exit ${exit}` : ""} (from ${rows.length} log lines)`);
74
+ if (failing.size > 0) {
75
+ console.log("## Failing tests");
76
+ for (const name of [...failing].slice(0, 25)) console.log(`- ${name}`);
77
+ if (failing.size > 25) console.log(`… ${failing.size - 25} more`);
78
+ }
79
+ const located = real.filter((entry) => entry.file);
80
+ if (located.length > 0) {
81
+ console.log("## Errors by file");
82
+ const byFile = new Map();
83
+ for (const entry of located) byFile.set(entry.file, [...(byFile.get(entry.file) ?? []), entry]);
84
+ let shown = 0;
85
+ for (const [file, list] of byFile) {
86
+ console.log(`${file}`);
87
+ for (const entry of list.slice(0, 8)) { console.log(` ${entry.line ? `${entry.line}: ` : ""}${entry.message}`); shown += 1; }
88
+ if (list.length > 8) console.log(` … ${list.length - 8} more in this file`);
89
+ if (shown >= 40) { console.log(`… more errors cut; ${located.length - shown} not shown`); break; }
90
+ }
91
+ }
92
+ const asserts = real.filter((entry) => !entry.file);
93
+ if (asserts.length > 0) {
94
+ console.log("## Messages");
95
+ for (const entry of asserts.slice(0, 12)) console.log(`- ${entry.message}`);
96
+ }
97
+ const unique = [...new Map(frames.map((frame) => [`${frame.file}:${frame.line}`, frame])).values()].slice(0, 4);
98
+ if (unique.length > 0) {
99
+ console.log("## Where it broke (our frames, innermost first)");
100
+ for (const frame of unique) {
101
+ const code = readFileSync(join(root, frame.file), "utf8").split("\n");
102
+ console.log(`${frame.file}:${frame.line}${frame.fn ? ` in ${frame.fn}` : ""}`);
103
+ for (let n = Math.max(1, frame.line - 2); n <= Math.min(code.length, frame.line + 2); n++) console.log(` ${n === frame.line ? ">" : " "}${String(n).padStart(5)} ${code[n - 1]}`);
104
+ }
105
+ }
106
+ if (real.length === 0 && failing.size === 0) console.log(exit ? "No recognisable errors; the tail of the log:\n" + rows.filter(Boolean).slice(-25).join("\n") : "No errors found.");
107
+ process.exit(exit === undefined ? 0 : exit === 0 ? 0 : 1);
@@ -0,0 +1,79 @@
1
+ #!/usr/bin/env node
2
+ // purpose: list generated files (header markers, .gitattributes linguist-generated, codegen output folders) and where each comes from: the generator line in its header and the package scripts that make it, so the source is edited instead of the output
3
+ // usage: node {script} [file or folder…]
4
+ import { readFileSync } from "node:fs";
5
+ import { basename, dirname, join } from "node:path";
6
+ import { detect, isNoise, parseArgs, projectRoot, runScript, sh, tracked } from "./lib/common.mjs";
7
+
8
+ const { rest } = parseArgs();
9
+ const root = projectRoot();
10
+ const files = tracked(root, ...rest);
11
+ const MARK = /@generated|DO NOT EDIT|auto-?generated|generated (by|from|with)|This file (was|is) (automatically )?generated|Code generated .* DO NOT EDIT/i;
12
+
13
+ // Only a comment says it: code that merely mentions the words does not count.
14
+ const COMMENT = /^\s*(\/\/|#|\/?\*|<!--|--|;|%)/;
15
+
16
+ // .gitattributes `path linguist-generated` (or `-diff`/`binary` next to a generated hint).
17
+ const attributes = (() => {
18
+ try {
19
+ return readFileSync(join(root, ".gitattributes"), "utf8").split("\n").filter((row) => /linguist-generated(=true)?\b/.test(row) && !/linguist-generated=false/.test(row)).map((row) => row.trim().split(/\s+/)[0]);
20
+ } catch {
21
+ return [];
22
+ }
23
+ })();
24
+ const globRe = (pattern) => new RegExp(`(^|/)${pattern.replace(/^\//, "").replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*\/?/g, "\u0000").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]").replace(/\u0000/g, ".*")}($|/)`);
25
+ const marked = attributes.map(globRe);
26
+
27
+ const { pkg, pm } = detect(root);
28
+ const scripts = Object.entries(pkg?.scripts ?? {});
29
+ const GENERATOR = /codegen|generate|\bgen\b|prisma|protoc|buf\s|openapi|swagger|graphql-codegen|orval|sqlc|typechain|relay-compiler|tsc\s.*--declaration|wasm-bindgen|bindgen|i18n/i;
30
+
31
+ const found = [];
32
+ for (const file of files) {
33
+ if (isNoise(file) && !/\.(snap)$/.test(file)) continue;
34
+ let why;
35
+ let header = "";
36
+ if (marked.some((re) => re.test(file))) why = ".gitattributes";
37
+ try {
38
+ const head = readFileSync(join(root, file), "utf8").slice(0, 800);
39
+ const line = head.split("\n").find((row) => COMMENT.test(row) && MARK.test(row));
40
+ if (line) {
41
+ why ??= "header";
42
+ header = line.replace(/^[\s/#*<!-]+|[\s*/>-]+$/g, "").slice(0, 160);
43
+ }
44
+ } catch {}
45
+ if (why) found.push({ file, why, header });
46
+ }
47
+ // Build output checked into git is generated too, but one line each is enough.
48
+ const output = new Map();
49
+ for (const file of files) {
50
+ const m = /^(.*?(?:^|\/)(?:dist|build|out|\.next|coverage))\//.exec(file);
51
+ if (m) output.set(m[1], (output.get(m[1]) ?? 0) + 1);
52
+ }
53
+ if (output.size) console.log(`## Build output tracked in git: ${[...output].map(([dir, count]) => `${dir}/ (${count})`).join(", ")}; rebuild it, never edit it`);
54
+ if (found.length === 0) {
55
+ console.log(`No generated files found${rest.length ? ` in ${rest.join(", ")}` : ""} (looked for header markers and .gitattributes linguist-generated).`);
56
+ process.exit(0);
57
+ }
58
+ // Group by folder: a codegen output folder is one line, not hundreds.
59
+ const byDir = new Map();
60
+ for (const hit of found) byDir.set(dirname(hit.file), [...(byDir.get(dirname(hit.file)) ?? []), hit]);
61
+ console.log(`# ${found.length} generated file(s) in ${byDir.size} folder(s): edit the source, then rerun the generator`);
62
+ for (const [dir, hits] of [...byDir].sort((a, b) => b[1].length - a[1].length)) {
63
+ console.log(`## ${dir}/ (${hits.length})`);
64
+ for (const hit of hits.slice(0, 6)) console.log(` ${basename(hit.file)} [${hit.why}]${hit.header ? ` "${hit.header}"` : ""}`);
65
+ if (hits.length > 6) console.log(` … ${hits.length - 6} more`);
66
+ // Package scripts that name this folder or a file in it, or look like a generator.
67
+ const makers = scripts.filter(([, command]) => command.includes(dir) || hits.some((hit) => command.includes(basename(hit.file))));
68
+ for (const [name, command] of makers.length ? makers : []) console.log(` made by: ${runScript(pm, name)} (${command.slice(0, 120)})`);
69
+ // A file naming its own source: "generated from x.proto".
70
+ const sources = new Set(hits.map((hit) => /from\s+["'`]?([\w./-]+\.\w+)/i.exec(hit.header)?.[1]).filter(Boolean));
71
+ if (sources.size) console.log(` source: ${[...sources].slice(0, 4).join(", ")}`);
72
+ }
73
+ const generators = scripts.filter(([name, command]) => GENERATOR.test(name) || GENERATOR.test(command));
74
+ if (generators.length) {
75
+ console.log("## Generator scripts in package.json");
76
+ for (const [name, command] of generators) console.log(` ${runScript(pm, name)}: ${command.slice(0, 140)}`);
77
+ }
78
+ const config = sh("git", ["ls-files", "--", "*codegen*", "*.proto", "*.graphql", "schema.prisma", "*openapi*.y*ml", "*openapi*.json", "buf.gen.yaml", "sqlc.y*ml"], { cwd: root }).out.split("\n").filter(Boolean);
79
+ if (config.length) console.log(`## Likely sources and generator configs: ${config.slice(0, 12).join(", ")}${config.length > 12 ? ", …" : ""}`);
@@ -0,0 +1,81 @@
1
+ #!/usr/bin/env node
2
+ // purpose: find where a function, class, type, component or variable is defined and every place it is used, as file:line, in one call; with --config, where a setting or environment variable is set, overridden and read
3
+ // usage: node {script} <name> [--defs] [--max <lines>] | node {script} --config <KEY or dotted.key>
4
+ import { fail, lines, parseArgs, projectRoot, sh } from "./lib/common.mjs";
5
+
6
+ const { flags, rest } = parseArgs();
7
+ const name = typeof flags.config === "string" ? flags.config : rest[0];
8
+ if (!name || !/^[\w$.-]+$/.test(name)) fail("usage: find_symbol.mjs <name> [--defs] [--max <lines>]");
9
+ const root = projectRoot();
10
+ const max = Number(flags.max ?? 60);
11
+ if (flags.config) config();
12
+ const escaped = name.replace(/[.$]/g, "\\$&");
13
+ const hits = lines(sh("git", ["grep", "-n", "-I", "-w", "-E", escaped, "--", ".", ":!*.min.*", ":!*lock*", ":!dist/*", ":!build/*"], { cwd: root }).out);
14
+ if (hits.length === 0) {
15
+ console.log(`"${name}" not found in tracked files.`);
16
+ process.exit(1);
17
+ }
18
+ const DEFINES = new RegExp([
19
+ `(function\\*?|class|interface|type|enum|struct|trait|impl|def|fn|func|module|namespace)\\s+${escaped}\\b`,
20
+ `(const|let|var|val)\\s+${escaped}\\s*[:=]`,
21
+ `export\\s+(default\\s+)?(async\\s+)?(function|class|const)\\s+${escaped}\\b`,
22
+ `^\\s*(public|private|protected|static|async|\\s)*${escaped}\\s*\\([^)]*\\)\\s*[:{]`,
23
+ `^\\s*${escaped}\\s*[:=]\\s*(async\\s*)?(\\(|function)`,
24
+ `func\\s+\\([^)]*\\)\\s+${escaped}\\b`,
25
+ ].join("|"));
26
+ const defs = [];
27
+ const uses = [];
28
+ for (const hit of hits) {
29
+ const [file, line, ...text] = hit.split(":");
30
+ const body = text.join(":").trim();
31
+ (DEFINES.test(body) ? defs : uses).push({ file, line, body: body.length > 140 ? `${body.slice(0, 140)}…` : body });
32
+ }
33
+ console.log(`## Defined (${defs.length})`);
34
+ for (const hit of defs) console.log(`${hit.file}:${hit.line} ${hit.body}`);
35
+ if (flags.defs) process.exit(0);
36
+ const byFile = new Map();
37
+ for (const hit of uses) byFile.set(hit.file, [...(byFile.get(hit.file) ?? []), hit]);
38
+ console.log(`## Used (${uses.length} in ${byFile.size} files)`);
39
+ let shown = 0;
40
+ for (const [file, list] of byFile) {
41
+ if (shown >= max) {
42
+ console.log(`… ${uses.length - shown} more uses; narrow with git grep`);
43
+ break;
44
+ }
45
+ for (const hit of list.slice(0, 5)) {
46
+ console.log(`${file}:${hit.line} ${hit.body}`);
47
+ shown += 1;
48
+ }
49
+ if (list.length > 5) console.log(`${file} … ${list.length - 5} more in this file`);
50
+ }
51
+
52
+ /** Where a setting lives: config and env files that set it, code that reads it from the environment or a settings object. */
53
+ function config() {
54
+ const leaf = name.split(".").pop();
55
+ const hits = lines(sh("git", ["grep", "-n", "-I", "-w", "-E", leaf.replace(/[$]/g, "\\$&"), "--", ".", ":!*lock*", ":!*.min.*", ":!dist/*", ":!build/*", ":!**/dist/*"], { cwd: root }).out);
56
+ if (hits.length === 0) {
57
+ console.log(`"${name}" is not set or read in any tracked file.`);
58
+ process.exit(1);
59
+ }
60
+ const CONFIG_FILE = /(^|\/)(\.env[\w.-]*|[\w.-]+\.(ya?ml|toml|ini|cfg|conf|properties)|[\w.-]*config[\w.-]*\.json|settings[\w.-]*\.json|package\.json|Dockerfile[\w.-]*|docker-compose[\w.-]*|Makefile|\.github\/.*)$/i;
61
+ const e = leaf.replace(/[$]/g, "\\$&");
62
+ const SETS = new RegExp(`^\\s*(-\\s*)?(export\\s+|ENV\\s+|ARG\\s+|set\\s+)?["']?${e}["']?\\s*[:=]|^\\s*(ENV|ARG)\\s+${e}\\b`);
63
+ const ENV_READ = new RegExp(`process\\.env(\\.${e}\\b|\\[\\s*["'\`]${e}["'\`])|import\\.meta\\.env\\.${e}\\b|os\\.(environ(\\.get)?\\s*[\\[(]\\s*["']${e}["']|getenv\\(\\s*["']${e}["'])|os\\.(Getenv|LookupEnv)\\(\\s*"${e}"|env::var\\(\\s*"${e}"|ENV\\[["']${e}["']\\]|\\$\\{?${e}\\b`);
64
+ const groups = { set: [], env: [], code: [] };
65
+ for (const hit of hits) {
66
+ const [file, line, ...text] = hit.split(":");
67
+ const body = text.join(":").trim();
68
+ const row = `${file}:${line} ${body.length > 140 ? `${body.slice(0, 140)}…` : body}`;
69
+ if (CONFIG_FILE.test(file) && SETS.test(body)) groups.set.push(row);
70
+ else if (ENV_READ.test(body)) groups.env.push(row);
71
+ else if (name.includes(".") ? body.includes(name) || new RegExp(`[.\\["']${e}\\b`).test(body) : true) groups.code.push(row);
72
+ }
73
+ console.log(`## Set in config or env files (${groups.set.length})`);
74
+ for (const row of groups.set) console.log(row);
75
+ console.log(`## Read from the environment (${groups.env.length})`);
76
+ for (const row of groups.env.slice(0, max)) console.log(row);
77
+ console.log(`## Other mentions: defaults, schemas, settings reads (${groups.code.length})`);
78
+ for (const row of groups.code.slice(0, max)) console.log(row);
79
+ if (groups.code.length > max) console.log(`… ${groups.code.length - max} more`);
80
+ process.exit(0);
81
+ }
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env node
2
+ // purpose: list the test helpers already in the project (fixtures, mocks, fakes, factories, stubs, test utilities, pytest fixtures) with what each exports and how many tests use it, so a new test reuses them instead of writing its own
3
+ // usage: node {script} [word to filter by]
4
+ import { readFileSync } from "node:fs";
5
+ import { basename, dirname, extname, join } from "node:path";
6
+ import { isCode, isNoise, isTest, parseArgs, projectRoot, sh, tracked } from "./lib/common.mjs";
7
+
8
+ const { rest } = parseArgs();
9
+ const word = rest[0]?.toLowerCase();
10
+ const root = projectRoot();
11
+ const all = tracked(root).filter((file) => !isNoise(file));
12
+ const DIR = /(^|\/)(fixtures?|__fixtures__|__mocks__|mocks?|factories|stubs?|fakes?|test-?utils?|testing|testdata|test-helpers?|support)\//i;
13
+ const NAME = /(^|[-_.])(fixtures?|mocks?|factor(y|ies)|stubs?|fakes?|test-?utils?|testing|helpers?|conftest|setup-?tests?|test-?setup)([-_.]|$)/i;
14
+ const TEST_AREA = /(^|\/)(test|tests|__tests__|spec|e2e)\//;
15
+ const helpers = all.filter((file) => {
16
+ // A test itself is not a helper, though everything under test/ counts as "test" to isTest.
17
+ if (/\.(test|spec)\.[cm]?[jt]sx?$|(^|\/)test_[^/]+\.py$|_test\.(py|go)$/.test(file) && !DIR.test(file)) return false;
18
+ return DIR.test(file) || NAME.test(basename(file, extname(file))) || (TEST_AREA.test(file) && isCode(file));
19
+ });
20
+ const tests = all.filter((file) => isTest(file));
21
+ const read = (file) => { try { return readFileSync(join(root, file), "utf8"); } catch { return ""; } };
22
+
23
+ function exportsOf(file, text) {
24
+ if (file.endsWith(".py")) {
25
+ // pytest fixtures first: they are what a test asks for by name.
26
+ const fixtures = [...text.matchAll(/@pytest\.fixture[^\n]*\n(?:\s*@[^\n]*\n)*\s*(?:async\s+)?def\s+(\w+)/g)].map((m) => `${m[1]} (fixture)`);
27
+ return [...fixtures, ...[...text.matchAll(/^(?:def|class)\s+([A-Za-z]\w*)/gm)].map((m) => m[1]).filter((name) => !fixtures.some((f) => f.startsWith(`${name} `)))];
28
+ }
29
+ if (file.endsWith(".go")) return [...text.matchAll(/^func\s+(?:\([^)]*\)\s*)?([A-Z]\w*)/gm)].map((m) => m[1]);
30
+ return [...new Set([
31
+ ...[...text.matchAll(/^export\s+(?:default\s+)?(?:async\s+)?(?:function\*?|class|const|let|interface|type|enum)\s+([\w$]+)/gm)].map((m) => m[1]),
32
+ ...[...text.matchAll(/^export\s+\{([^}]*)\}/gm)].flatMap((m) => m[1].split(",").map((part) => part.trim().split(/\s+as\s+/).pop()).filter(Boolean)),
33
+ ...[...text.matchAll(/^\s*(?:jest|vi)\.mock\(\s*['"]([^'"]+)/gm)].map((m) => `mocks ${m[1]}`),
34
+ ])];
35
+ }
36
+
37
+ const testText = new Map(tests.map((file) => [file, read(file)]));
38
+ function users(file) {
39
+ const stem = basename(file, extname(file)).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
40
+ const re = file.endsWith(".py") && basename(file) === "conftest.py" ? undefined : new RegExp(`['"/]${stem}(\\.[a-z]+)?['"]|\\b${stem}\\.(json|ya?ml)\\b`);
41
+ if (!re) return [...testText.keys()].filter((test) => test.startsWith(dirname(file) === "." ? "" : `${dirname(file)}/`)).length;
42
+ return [...testText.values()].filter((text) => re.test(text)).length;
43
+ }
44
+
45
+ const code = [];
46
+ const data = new Map();
47
+ for (const file of helpers) {
48
+ if (isCode(file)) {
49
+ const text = read(file);
50
+ const names = exportsOf(file, text);
51
+ if (word && !file.toLowerCase().includes(word) && !names.some((name) => name.toLowerCase().includes(word))) continue;
52
+ const used = users(file);
53
+ // A helper-sounding name outside the tests that no test uses is not a test helper.
54
+ if (used === 0 && !TEST_AREA.test(file) && !DIR.test(file)) continue;
55
+ code.push({ file, names, used, lines: text.split("\n").length });
56
+ } else if (!word || file.toLowerCase().includes(word)) data.set(dirname(file), [...(data.get(dirname(file)) ?? []), file]);
57
+ }
58
+ if (code.length === 0 && data.size === 0) {
59
+ console.log(`No test helpers found${word ? ` matching "${word}"` : ""}.`);
60
+ process.exit(0);
61
+ }
62
+ code.sort((a, b) => b.used - a.used || a.file.localeCompare(b.file));
63
+ console.log(`# ${code.length} helper module(s)${data.size ? `, fixture data in ${data.size} folder(s)` : ""}${word ? ` matching "${word}"` : ""}`);
64
+ for (const hit of code) {
65
+ console.log(`${hit.file} (${hit.lines} lines, used by ${hit.used} test file(s))`);
66
+ if (hit.names.length) console.log(` ${hit.names.slice(0, 14).join(", ")}${hit.names.length > 14 ? `, +${hit.names.length - 14}` : ""}`);
67
+ }
68
+ for (const [dir, files] of data) {
69
+ console.log(`## data ${dir}/ (${files.length})`);
70
+ console.log(` ${files.slice(0, 10).map((file) => basename(file)).join(", ")}${files.length > 10 ? ", …" : ""}`);
71
+ }
72
+ const config = sh("git", ["ls-files", "--", "jest.config.*", "vitest.config.*", "playwright.config.*", "pytest.ini", "conftest.py", "**/setupTests.*", "karma.conf.*"], { cwd: root }).out.trim();
73
+ if (config) console.log(`## Test setup: ${config.split("\n").join(", ")}`);
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ // purpose: list the test files that cover the given source files (named after them or importing them), to know which tests to update and run
3
+ // usage: node {script} <file> [more files…]
4
+ import { fail, parseArgs, projectRoot, testsFor } from "./lib/common.mjs";
5
+
6
+ const { rest } = parseArgs();
7
+ if (rest.length === 0) fail("usage: find_tests_for.mjs <file> [more files…]");
8
+ const root = projectRoot();
9
+ for (const [file, tests] of testsFor(root, rest)) {
10
+ console.log(`${file}: ${tests.length > 0 ? "" : "no test found"}`);
11
+ for (const test of tests) console.log(` ${test}`);
12
+ }
@@ -0,0 +1,267 @@
1
+ // Shared helpers for bot-lobby's built-in scripts. Read-only: nothing here writes, commits or pushes.
2
+ import { spawnSync } from "node:child_process";
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import { basename, dirname, extname, join } from "node:path";
5
+
6
+ /** Run a command; never throws. */
7
+ export function sh(cmd, args = [], options = {}) {
8
+ const result = spawnSync(cmd, args, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024, ...options });
9
+ return { code: result.status ?? (result.error ? 127 : 1), out: result.stdout ?? "", err: result.stderr ?? (result.error ? String(result.error.message) : "") };
10
+ }
11
+
12
+ export function lines(text) {
13
+ return text.split("\n").map((line) => line.trimEnd()).filter(Boolean);
14
+ }
15
+
16
+ /** The project's root: the git top level, else where the script was run. */
17
+ export function projectRoot() {
18
+ const git = sh("git", ["rev-parse", "--show-toplevel"]);
19
+ return git.code === 0 ? git.out.trim() : process.cwd();
20
+ }
21
+
22
+ /** `--name value` / `--flag` options and the rest as positional arguments. */
23
+ export function parseArgs(argv = process.argv.slice(2)) {
24
+ if (argv.includes("--help") || argv.includes("-h")) {
25
+ // The script's own header says what it does and how to run it.
26
+ const head = readFileSync(process.argv[1], "utf8").split("\n").slice(0, 6);
27
+ for (const row of head) if (/^\/\/\s*(purpose|usage):/.test(row)) console.log(row.replace(/^\/\/\s*/, "").replace("{script}", process.argv[1]));
28
+ process.exit(0);
29
+ }
30
+ const flags = {};
31
+ const rest = [];
32
+ for (let i = 0; i < argv.length; i++) {
33
+ const arg = argv[i];
34
+ if (arg.startsWith("--")) {
35
+ const [key, inline] = arg.slice(2).split("=", 2);
36
+ if (inline !== undefined) flags[key] = inline;
37
+ else if (argv[i + 1] !== undefined && !argv[i + 1].startsWith("--")) flags[key] = argv[++i];
38
+ else flags[key] = true;
39
+ } else rest.push(arg);
40
+ }
41
+ return { flags, rest };
42
+ }
43
+
44
+ /** The ref the branch is compared with: `--base`, else the merge base with the default branch, else HEAD. */
45
+ export function baseRef(root, asked) {
46
+ if (typeof asked === "string") return asked;
47
+ for (const ref of ["origin/HEAD", "origin/main", "origin/master", "main", "master"]) {
48
+ const base = sh("git", ["merge-base", "HEAD", ref], { cwd: root });
49
+ if (base.code === 0 && base.out.trim()) {
50
+ const head = sh("git", ["rev-parse", "HEAD"], { cwd: root }).out.trim();
51
+ // On the default branch itself, compare with the working tree only.
52
+ return base.out.trim() === head ? "HEAD" : base.out.trim();
53
+ }
54
+ }
55
+ return "HEAD";
56
+ }
57
+
58
+ /** Files changed since `base`: committed on the branch, staged, unstaged and new (untracked, not ignored). */
59
+ export function changedFiles(root, base) {
60
+ const files = new Set();
61
+ const add = (text) => lines(text).forEach((file) => files.add(file));
62
+ if (base !== "HEAD") add(sh("git", ["diff", "--name-only", "--diff-filter=ACMR", `${base}...HEAD`], { cwd: root }).out);
63
+ add(sh("git", ["diff", "--name-only", "--diff-filter=ACMR", "HEAD"], { cwd: root }).out);
64
+ add(sh("git", ["ls-files", "--others", "--exclude-standard"], { cwd: root }).out);
65
+ return [...files].filter((file) => existsSync(join(root, file))).sort();
66
+ }
67
+
68
+ export function readJson(path) {
69
+ try {
70
+ return JSON.parse(readFileSync(path, "utf8"));
71
+ } catch {
72
+ return undefined;
73
+ }
74
+ }
75
+
76
+ /** What the project is built with. */
77
+ export function detect(root) {
78
+ const pkg = readJson(join(root, "package.json"));
79
+ const pm = existsSync(join(root, "pnpm-lock.yaml")) ? "pnpm" : existsSync(join(root, "yarn.lock")) ? "yarn" : existsSync(join(root, "bun.lockb")) || existsSync(join(root, "bun.lock")) ? "bun" : "npm";
80
+ const deps = pkg ? { ...pkg.dependencies, ...pkg.devDependencies } : {};
81
+ return {
82
+ pkg,
83
+ pm,
84
+ deps,
85
+ python: ["pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "pytest.ini", "tox.ini"].some((file) => existsSync(join(root, file))),
86
+ go: existsSync(join(root, "go.mod")),
87
+ rust: existsSync(join(root, "Cargo.toml")),
88
+ };
89
+ }
90
+
91
+ /** `npm run x` / `pnpm x` / `yarn x` / `bun run x`. */
92
+ export function runScript(pm, name) {
93
+ return pm === "npm" ? `npm run ${name}` : pm === "bun" ? `bun run ${name}` : `${pm} ${name}`;
94
+ }
95
+
96
+ const TEST_FILE = /(^|\/)(__tests__|tests?|spec|e2e)\/|\.(test|spec)\.[cm]?[jt]sx?$|(^|\/)test_[^/]+\.py$|_test\.(py|go)$/;
97
+
98
+ export function isTest(file) {
99
+ return TEST_FILE.test(file);
100
+ }
101
+
102
+ const CODE = /\.(c|m)?[jt]sx?$|\.(py|go|rs|rb|java|kt|swift|vue|svelte|cs|php)$/;
103
+
104
+ export function isCode(file) {
105
+ return CODE.test(file);
106
+ }
107
+
108
+ function stemOf(file) {
109
+ return basename(file, extname(file)).replace(/\.(test|spec)$/, "").replace(/^test_/, "").replace(/_test$/, "");
110
+ }
111
+
112
+ /** Test files that cover these files: the tests themselves, tests named after them, and tests that import them. */
113
+ export function testsFor(root, files, all = lines(sh("git", ["ls-files", "--cached", "--others", "--exclude-standard"], { cwd: root }).out)) {
114
+ const tests = all.filter(isTest);
115
+ const found = new Map();
116
+ for (const file of files) {
117
+ const hits = new Set();
118
+ if (isTest(file)) hits.add(file);
119
+ else if (isCode(file)) {
120
+ const stem = stemOf(file);
121
+ if (stem.length < 3 || stem === "index") {
122
+ // An index is named after its folder.
123
+ const folder = basename(dirname(file));
124
+ for (const test of tests) if (stemOf(test) === folder) hits.add(test);
125
+ } else {
126
+ for (const test of tests) if (stemOf(test) === stem) hits.add(test);
127
+ // Tests that import it by name.
128
+ const importers = sh("git", ["grep", "-l", "-E", `(from|import|require\\().*[/'"]${stem.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(\\.[a-z]+)?['"]`, "--", ...new Set(tests.map((test) => test.split("/")[0]))], { cwd: root });
129
+ for (const test of lines(importers.out)) if (isTest(test)) hits.add(test);
130
+ }
131
+ }
132
+ found.set(file, [...hits].sort());
133
+ }
134
+ return found;
135
+ }
136
+
137
+ /** Keep the last `max` lines, saying how many were cut. */
138
+ export function tail(text, max = 120) {
139
+ const rows = text.trimEnd().split("\n");
140
+ return rows.length <= max ? rows.join("\n") : [`… ${rows.length - max} earlier lines cut`, ...rows.slice(-max)].join("\n");
141
+ }
142
+
143
+ export function fail(message) {
144
+ console.error(message);
145
+ process.exit(2);
146
+ }
147
+
148
+ /** Files no review needs: lockfiles, build output, minified and generated files, snapshots. */
149
+ const NOISE = /(^|\/)(package-lock\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?|Cargo\.lock|poetry\.lock|go\.sum|composer\.lock)$|(^|\/)(dist|build|out|coverage|\.next|vendor|node_modules)\/|\.min\.(js|css)$|\.map$|\.snap$|(^|\/)__snapshots__\//;
150
+
151
+ export function isNoise(file) {
152
+ return NOISE.test(file);
153
+ }
154
+
155
+ const GENERATED_MARK = /@generated|DO NOT EDIT|auto-?generated|generated by|This file was automatically generated|Code generated .* DO NOT EDIT/i;
156
+
157
+ /** A file that says it is generated in its first lines. */
158
+ export function isGenerated(root, file) {
159
+ if (isNoise(file)) return true;
160
+ try {
161
+ const head = readFileSync(join(root, file), "utf8").slice(0, 600);
162
+ // Said in a comment, not code that merely mentions the words.
163
+ return head.split("\n").some((row) => /^\s*(\/\/|#|\/?\*|<!--|--)/.test(row) && GENERATED_MARK.test(row));
164
+ } catch {
165
+ return false;
166
+ }
167
+ }
168
+
169
+ export function tracked(root, ...paths) {
170
+ return lines(sh("git", ["ls-files", "--cached", "--others", "--exclude-standard", ...(paths.length ? ["--", ...paths] : [])], { cwd: root }).out);
171
+ }
172
+
173
+ const JS_EXT = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
174
+
175
+ /** Relative imports of a source file, resolved to project files (JS/TS and Python). */
176
+ export function importsOf(root, file, known) {
177
+ let text;
178
+ try {
179
+ text = readFileSync(join(root, file), "utf8");
180
+ } catch {
181
+ return [];
182
+ }
183
+ const dir = dirname(file);
184
+ const out = new Set();
185
+ const resolve = (spec) => {
186
+ const base = join(dir, spec).replace(/\\/g, "/");
187
+ const stripped = base.replace(/\.(m|c)?js$/, "");
188
+ for (const candidate of [base, ...JS_EXT.map((ext) => stripped + ext), ...JS_EXT.map((ext) => `${base}/index${ext}`)]) if (known.has(candidate)) return candidate;
189
+ return undefined;
190
+ };
191
+ if (/\.(m|c)?[jt]sx?$/.test(file)) {
192
+ for (const m of text.matchAll(/(?:import|export)\s[^'"]*?from\s*['"](\.{1,2}\/[^'"]+)['"]|import\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]\s*\)|require\(\s*['"](\.{1,2}\/[^'"]+)['"]\s*\)|^\s*import\s+['"](\.{1,2}\/[^'"]+)['"]/gm)) {
193
+ // A type-only import never runs, so it makes no cycle at runtime.
194
+ if (/^\s*(import|export)\s+type\s/.test(m[0])) continue;
195
+ const hit = resolve(m[1] ?? m[2] ?? m[3] ?? m[4]);
196
+ if (hit) out.add(hit);
197
+ }
198
+ } else if (file.endsWith(".py")) {
199
+ for (const m of text.matchAll(/^\s*from\s+(\.+)([\w.]*)\s+import/gm)) {
200
+ const up = m[1].length - 1;
201
+ const parts = dir.split("/").slice(0, dir.split("/").length - up);
202
+ const mod = [...parts, ...(m[2] ? m[2].split(".") : [])].join("/");
203
+ for (const candidate of [`${mod}.py`, `${mod}/__init__.py`]) if (known.has(candidate)) out.add(candidate);
204
+ }
205
+ }
206
+ return [...out];
207
+ }
208
+
209
+ /** The import graph of the project's JS/TS and Python files. */
210
+ export function importGraph(root) {
211
+ const files = tracked(root).filter((file) => /\.((m|c)?[jt]sx?|py)$/.test(file) && !isNoise(file));
212
+ const known = new Set(files);
213
+ const graph = new Map();
214
+ for (const file of files) graph.set(file, importsOf(root, file, known));
215
+ return graph;
216
+ }
217
+
218
+ /** Changed line ranges per file since `base` (new-side line numbers). */
219
+ export function changedRanges(root, base) {
220
+ const ranges = new Map();
221
+ const add = (args) => {
222
+ let file;
223
+ for (const row of sh("git", ["diff", "-U0", ...args], { cwd: root }).out.split("\n")) {
224
+ if (row.startsWith("+++ ")) file = row.startsWith("+++ b/") ? row.slice(6) : undefined;
225
+ const m = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(row);
226
+ if (m && file) ranges.set(file, [...(ranges.get(file) ?? []), [Number(m[1]), Number(m[1]) + Math.max(0, Number(m[2] ?? 1) - 1)]]);
227
+ }
228
+ };
229
+ if (base !== "HEAD") add([`${base}...HEAD`]);
230
+ add(["HEAD"]);
231
+ return ranges;
232
+ }
233
+
234
+ /** Top-level declarations with their line spans, by indentation and braces; good enough to name what a hunk touched. */
235
+ export function declarations(text, file) {
236
+ const rows = text.split("\n");
237
+ const patterns = file.endsWith(".py")
238
+ ? [/^(\s*)(?:async\s+)?def\s+(\w+)/, /^(\s*)class\s+(\w+)/]
239
+ : file.endsWith(".go")
240
+ ? [/^()func\s+(?:\([^)]*\)\s*)?(\w+)/, /^()type\s+(\w+)/]
241
+ : file.endsWith(".rs")
242
+ ? [/^(\s*)(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+(\w+)/, /^(\s*)(?:pub\s+)?(?:struct|enum|trait)\s+(\w+)/]
243
+ : [
244
+ /^(\s*)(?:export\s+)?(?:default\s+)?(?:async\s+)?function\*?\s+([\w$]+)/,
245
+ /^(\s*)(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+([\w$]+)/,
246
+ /^(\s*)(?:export\s+)?(?:interface|type|enum)\s+([\w$]+)/,
247
+ /^(\s*)(?:export\s+)?const\s+([\w$]+)\s*(?::[^=]+)?=\s*(?:async\s*)?(?:\([^)]*\)|[\w$]+)\s*(?::[^=]+)?=>/,
248
+ /^(\s{2,4})(?:public\s+|private\s+|protected\s+|static\s+|async\s+|get\s+|set\s+)*([\w$]+)\s*\([^)]*\)\s*(?::\s*[^{]+)?\{\s*$/,
249
+ ];
250
+ const found = [];
251
+ rows.forEach((row, index) => {
252
+ for (const pattern of patterns) {
253
+ const m = pattern.exec(row);
254
+ if (m && !/^(if|for|while|switch|catch|return)$/.test(m[2])) {
255
+ found.push({ name: m[2], indent: m[1].length, start: index + 1 });
256
+ break;
257
+ }
258
+ }
259
+ });
260
+ // A declaration ends where the next one at its indentation (or shallower) starts.
261
+ for (let i = 0; i < found.length; i++) {
262
+ const next = found.slice(i + 1).find((other) => other.indent <= found[i].indent);
263
+ found[i].end = next ? next.start - 1 : rows.length;
264
+ while (found[i].end > found[i].start && !rows[found[i].end - 1].trim()) found[i].end -= 1;
265
+ }
266
+ return found;
267
+ }