@a-t-h-i/bot-lobby 0.7.1 → 0.7.3

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 (50) hide show
  1. package/THIRD_PARTY_NOTICES.md +17 -0
  2. package/package.json +1 -1
  3. package/prompts/global.md +13 -0
  4. package/prompts/lobby-chat.md +2 -2
  5. package/prompts/master.md +8 -8
  6. package/prompts/planner.md +14 -0
  7. package/src/classifier/knowledge.ts +22 -3
  8. package/src/classifier/lobby.ts +4 -3
  9. package/src/execution/lint-setup.ts +409 -0
  10. package/src/execution/lint.ts +25 -13
  11. package/src/execution/verification.ts +65 -13
  12. package/src/index.ts +3 -0
  13. package/src/lobby/host.ts +5 -0
  14. package/src/lobby/keys.ts +1 -0
  15. package/src/lobby/planner.ts +2 -2
  16. package/src/lobby/runtime.ts +12 -0
  17. package/src/lobby/service.ts +23 -0
  18. package/src/master/master.ts +30 -13
  19. package/src/pi/commands.ts +23 -2
  20. package/src/pi/events.ts +3 -1
  21. package/src/pi/start-task-tool.ts +80 -0
  22. package/src/pi/tools.ts +1 -1
  23. package/src/schemas/configuration.ts +14 -1
  24. package/src/schemas/lint.ts +50 -0
  25. package/src/text.ts +22 -0
  26. package/src/webui/api/index.ts +14 -2
  27. package/src/webui/api/sessions.ts +6 -0
  28. package/src/webui/api/settings.ts +39 -0
  29. package/src/webui/dev/fake-service.ts +1 -0
  30. package/src/webui/protocol.ts +6 -0
  31. package/src/workflow/workflow.ts +22 -7
  32. package/webui/dist/apple-touch-icon.png +0 -0
  33. package/webui/dist/assets/{CodeSurface-Bdkhh84z.js → CodeSurface-CL7RbdNJ.js} +1 -1
  34. package/webui/dist/assets/{TerminalView-CsDNheS9.js → TerminalView-BrZ9qW_T.js} +1 -1
  35. package/webui/dist/assets/index-5eWi36H6.js +117 -0
  36. package/webui/dist/assets/index-Crl5pWLp.css +2 -0
  37. package/webui/dist/build.json +51 -31
  38. package/webui/dist/icon-192.png +0 -0
  39. package/webui/dist/icon-512.png +0 -0
  40. package/webui/dist/icon-maskable-192.png +0 -0
  41. package/webui/dist/icon-maskable-512.png +0 -0
  42. package/webui/dist/index.html +2 -2
  43. package/webui/dist/licenses/sounds.txt +33 -0
  44. package/webui/dist/sounds/attention.mp3 +0 -0
  45. package/webui/dist/sounds/done.mp3 +0 -0
  46. package/webui/dist/sounds/error.mp3 +0 -0
  47. package/webui/dist/sounds/question.mp3 +0 -0
  48. package/webui/dist/sounds/sent.mp3 +0 -0
  49. package/webui/dist/assets/index-Bt0RLI3l.css +0 -2
  50. package/webui/dist/assets/index-C3Bn07Vr.js +0 -115
@@ -98,3 +98,20 @@ License 2.0, https://www.apache.org/licenses/LICENSE-2.0), Shiki and its
98
98
  grammars (`shiki`, `@shikijs/*`, Pine Wu and Anthony Fu, MIT; each grammar
99
99
  keeps its own licence, listed in `@shikijs/langs`) and `diff` (Kevin Decker,
100
100
  BSD 3-Clause).
101
+
102
+ ## Sounds
103
+
104
+ The five sounds in `webui/public/sounds` (shipped in `webui/dist/sounds`) were
105
+ converted to MP3 and levelled in loudness; nothing else was changed. Full
106
+ details are in `webui/public/licenses/sounds.txt`.
107
+
108
+ - `question.mp3` and `attention.mp3`: "dialog-question" and
109
+ "message-new-email" from the Ocean Sound Theme for KDE Plasma by Guilherme
110
+ Marçal Silva (https://invent.kde.org/plasma/ocean-sound-theme), CC BY-SA 4.0
111
+ (https://creativecommons.org/licenses/by-sa/4.0/). The changed files are
112
+ shared under the same license.
113
+ - `done.mp3` and `error.mp3`: "NFCSuccess" and "NFCFailure" from the Android
114
+ Open Source Project (`frameworks/base/data/sounds`), Apache License 2.0.
115
+ - `sent.mp3`: "audio-volume-change" from the elementary OS sound theme
116
+ (https://github.com/elementary/sound-theme), from Freesound user
117
+ ianslattery, CC0 1.0.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a-t-h-i/bot-lobby",
3
- "version": "0.7.1",
3
+ "version": "0.7.3",
4
4
  "description": "Structured multi-agent software engineering orchestrator for Pi",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
package/prompts/global.md CHANGED
@@ -15,6 +15,19 @@ Perform your assigned responsibility precisely and remain within your domain.
15
15
  - Do not invent requirements; ask when they are genuinely ambiguous.
16
16
  - Report conclusions, evidence, decisions, findings and blockers concisely.
17
17
 
18
+ ## Talking to the user
19
+
20
+ Write to the user the way a person would in chat: short, direct, plain words.
21
+
22
+ - Lead with the answer or the result. Usually one to three sentences is enough.
23
+ - Say what changed, not how you got there: "Renamed `fetchUser` to
24
+ `loadUser` and added three number arguments" beats paragraphs of process.
25
+ - Skip jargon when plain words work, and skip preamble, recaps, headings and
26
+ long bullet lists unless the user asked for detail.
27
+ - Give more only when it matters: a blocker, a decision only the user can
28
+ make, a risk or something that failed. Then say what you need from them.
29
+ - Required report formats still apply; keep each section brief within them.
30
+
18
31
  ## Following your brief
19
32
 
20
33
  The Master that instructs you plans the work and knows the whole task; you may
@@ -26,8 +26,8 @@ and read your reply.
26
26
  one you chose; do not stop to ask.
27
27
  - If the work turns out large (many areas, a new dependency, an architecture
28
28
  change, a decision only the user can make), do not start it: say what it
29
- would take, and suggest `/plan` to plan it with the panel or `/task` to hand
30
- it to the team.
29
+ would take and say the Master can start it as a task for the team (or the
30
+ user can type `/plan` to plan it with the panel).
31
31
  - A bot-lobby task may be running in this working tree at the same time:
32
32
  touch only the files the message needs, re-read a file right before you
33
33
  edit it, and never revert changes you did not make.
package/prompts/master.md CHANGED
@@ -140,14 +140,14 @@ structured assignment there, so send that step as a prose `task`. Fields:
140
140
  - Optional `discoveryLimit` (default two, never reset by a retry or
141
141
  revision; raising it needs an explicit allowance decision).
142
142
  - Optional `contextPack`: the exact context the worker needs on turn one —
143
- `{version: 1, files: [{path, ranges: [[start, end]], fingerprint,
144
- snippet}], invariants, priorWork, verification}`. Give exact paths with
145
- line ranges, bounded snippets (at most 2,000 characters each; 24,000 for
146
- the whole pack), content fingerprints from your own reads, the invariants
147
- that must hold, prior work already landed, and the verification you expect.
148
- The engine validates the pack before launch and refreshes stale
149
- fingerprints at dispatch, so the worker never re-discovers what you already
150
- know. Batch it instead of sending a scout or making the worker re-read
143
+ `{version: 1, files: [{path, ranges: [[start, end]], snippet}],
144
+ invariants, priorWork, verification}`. Give exact paths with line ranges,
145
+ bounded snippets copied verbatim from your own reads (file text only, no
146
+ line-number prefixes; at most 2,000 characters each; 24,000 for the whole
147
+ pack), the invariants that must hold, prior work already landed, and the
148
+ verification you expect. Leave `fingerprint` out: the engine fingerprints
149
+ each file at dispatch, keeps a snippet that still matches, and re-reads one
150
+ that went stale, so the worker never re-discovers what you already know. Batch it instead of sending a scout or making the worker re-read
151
151
  everything.
152
152
 
153
153
  The engine validates every brief before a batch starts; fix a rejected one,
@@ -12,6 +12,20 @@ assumption the user can overrule. You never
12
12
  write code and never change files; you may read the repository to ask
13
13
  informed questions and to ground the plan in what exists.
14
14
 
15
+ ## Talking to the user
16
+
17
+ Write to the user the way a person would in chat: short, direct, plain words.
18
+
19
+ - Lead with the answer or the result. Usually one to three sentences is enough.
20
+ - Say what changed, not how you got there: "Renamed `fetchUser` to
21
+ `loadUser` and added three number arguments" beats paragraphs of process.
22
+ - Skip jargon when plain words work, and skip preamble, recaps, headings and
23
+ long bullet lists unless the user asked for detail.
24
+ - Give more only when it matters: a blocker, a decision only the user can
25
+ make, a risk or something that failed. Then say what you need from them.
26
+ - The output format below still applies: keep questions to one plain
27
+ sentence each, and keep your notes to the user short.
28
+
15
29
  ## Each turn
16
30
 
17
31
  You receive the conversation so far (every member's questions and the user's
@@ -124,6 +124,24 @@ export function isProtectedKnowledge(content: string): boolean {
124
124
  return content.includes(PINNED_MARKER);
125
125
  }
126
126
 
127
+ /** The user's own annotations: `> Note from the user…` lines and their quoted continuation lines. */
128
+ export function userNoteLines(content: string): string[] {
129
+ const out: string[] = [];
130
+ let inNote = false;
131
+ for (const line of content.split("\n")) {
132
+ if (/^> Note from the user\b/.test(line)) inNote = true;
133
+ else if (!line.startsWith(">")) inNote = false;
134
+ if (inNote) out.push(line);
135
+ }
136
+ return out;
137
+ }
138
+
139
+ /** The user notes a trimmed or left-out section would lose, kept with the entry they annotate named by the note itself. */
140
+ function notesLeftOut(whole: string, kept: string): string {
141
+ const lost = userNoteLines(whole).filter((line) => !kept.includes(line));
142
+ return lost.length ? `\n\nUser notes on the part left out (never trimmed):\n${lost.join("\n")}` : "";
143
+ }
144
+
127
145
  /** `(1.2k chars)` — the size note each injected section header carries. */
128
146
  export function sectionSizeNote(chars: number): string {
129
147
  return chars >= 1000 ? `${(Math.round(chars / 100) / 10).toFixed(1)}k chars` : `${chars} chars`;
@@ -146,7 +164,8 @@ export interface StartupBudgetResult {
146
164
 
147
165
  /**
148
166
  * One combined budget across every injected knowledge section of a prompt.
149
- * Protected content (pinned rules, user annotations) is never truncated: when
167
+ * Protected content (pinned rules) is never truncated, and user annotations
168
+ * (`> Note from the user`) in a trimmed or left-out section are carried whole: when
150
169
  * it alone exceeds the budget it is kept whole and a diagnostic names the
151
170
  * file and its size. Anything else is kept whole while it fits, clipped once,
152
171
  * then left out with a note saying where the whole content is. The same
@@ -179,7 +198,7 @@ export function applyStartupBudget(sections: readonly StartupSection[], budget:
179
198
  if (!section.content) return section;
180
199
  if (section.protected) return { ...section, content: withSize(section.content) };
181
200
  if (remaining <= 0) {
182
- return { ...section, content: `_Left out to hold the startup knowledge budget; the whole content is ${section.path ?? `in ${section.name}`}._` };
201
+ return { ...section, content: `_Left out to hold the startup knowledge budget; the whole content is ${section.path ?? `in ${section.name}`}._${notesLeftOut(section.content, "")}` };
183
202
  }
184
203
  if (section.content.length <= remaining) {
185
204
  remaining -= section.content.length;
@@ -187,7 +206,7 @@ export function applyStartupBudget(sections: readonly StartupSection[], budget:
187
206
  }
188
207
  const clipped = clip(section.content, remaining).trimEnd();
189
208
  remaining = 0;
190
- return { ...section, content: `${withSize(clipped)}\n\n_Trimmed to hold the startup knowledge budget; the whole content is ${section.path ?? `in ${section.name}`}._` };
209
+ return { ...section, content: `${withSize(clipped)}\n\n_Trimmed to hold the startup knowledge budget; the whole content is ${section.path ?? `in ${section.name}`}._${notesLeftOut(section.content, clipped)}` };
191
210
  });
192
211
  return { sections: budgeted, diagnostics };
193
212
  }
@@ -3,8 +3,9 @@
3
3
  * the last few lines of the conversation) and picks the agent whose area it
4
4
  * is, so a frontend question goes to DESIGN, a library question to RESEARCH,
5
5
  * "how does this work" to a scout and a question about the project's saved
6
- * knowledge to the oracle's knowledge lookup. Anything it is unsure of, and
7
- * every message while it is off, goes to the Master.
6
+ * knowledge to the oracle's knowledge lookup. Work too big for one quick
7
+ * change goes to the Master, who starts a task for it (start_task). Anything
8
+ * it is unsure of, and every message while it is off, goes to the Master.
8
9
  */
9
10
  import type { ChatAgent } from "../lobby/prompts.ts";
10
11
  import type { Classifier } from "./classifier.ts";
@@ -15,7 +16,7 @@ import { clip } from "./limits.ts";
15
16
  export type ChatRoute = ChatAgent | "knowledge";
16
17
 
17
18
  const ROUTES: Record<ChatRoute, string> = {
18
- master: "The Master (the orchestrator): general conversation, the team's tasks and plans, anything across several areas of the project, or anything no single agent below clearly owns",
19
+ master: "The Master (the orchestrator): general conversation, the team's tasks and plans, anything across several areas of the project, a request for work too big for one quick change (a new feature, an architecture change, work that needs tests and review), which the Master hands to the team as a task, or anything no single agent below clearly owns",
19
20
  designer: "DESIGN: the frontend, meaning pages, components, styling, layout, UX, on-screen copy and browser code, whether a question about it or a change to it",
20
21
  backend: "DEV: backend code, meaning APIs, data and databases, server logic, integrations, scripts, build and tooling, whether a question about it or a change to it",
21
22
  qa: "QA: tests, meaning writing, running or fixing them, test strategy, how to verify a change, or checking work for bugs",
@@ -0,0 +1,409 @@
1
+ /**
2
+ * The Settings page's linting wizard: which linters the project configures
3
+ * and whether each is installed, the commands that install (or set up) one,
4
+ * and a short list of common rules per linter that the page can switch.
5
+ *
6
+ * Rules live where the linter reads them, so the editor, CI and the lint gate
7
+ * all agree: Biome's `biome.json`, Oxlint's `.oxlintrc.json` and Ruff's
8
+ * `[lint]` table are edited in place. ESLint's config is code (a flat
9
+ * `eslint.config.js`), which cannot be edited safely, so its rules are kept in
10
+ * bot-lobby's config and passed to the gate's ESLint run as `--rule` flags.
11
+ * A JSON config with comments is not rewritten (that would drop them): its
12
+ * rules read as they are and the page sends the user to the code viewer.
13
+ *
14
+ * Nothing here runs a command: the page types install commands into its own
15
+ * terminal, where the user watches them and answers any prompt.
16
+ */
17
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
18
+ import { dirname, join, relative } from "node:path";
19
+ import type { LintConfig, LintRuleLevel } from "../schemas/configuration.ts";
20
+ import type { LintSetup, LintSetupLinter, LintSetupOffer, RuleChoice } from "../schemas/lint.ts";
21
+ import { findLinters, type FoundLinter } from "./lint.ts";
22
+
23
+ export type { LintRuleInfo, LintSetup, LintSetupLinter, LintSetupOffer, LintSetupStep, RuleChoice } from "../schemas/lint.ts";
24
+
25
+ interface RuleDef {
26
+ id: string;
27
+ label: string;
28
+ help: string;
29
+ }
30
+
31
+ const RULES: Record<string, RuleDef[]> = {
32
+ ESLint: [
33
+ { id: "no-unused-vars", label: "Unused variables", help: "a variable, argument or import that is never read" },
34
+ { id: "no-console", label: "console calls", help: "console.log and friends left in the code" },
35
+ { id: "no-debugger", label: "debugger statements", help: "a debugger left in" },
36
+ { id: "eqeqeq", label: "Strict equality", help: "=== and !== instead of == and !=" },
37
+ { id: "prefer-const", label: "Prefer const", help: "let that is never reassigned" },
38
+ { id: "no-var", label: "No var", help: "let or const instead of var" },
39
+ { id: "curly", label: "Braces on blocks", help: "braces around every if, else and loop body" },
40
+ { id: "no-empty", label: "Empty blocks", help: "a block with nothing in it" },
41
+ ],
42
+ Biome: [
43
+ { id: "correctness/noUnusedVariables", label: "Unused variables", help: "a variable that is never read" },
44
+ { id: "correctness/noUnusedImports", label: "Unused imports", help: "an import nothing uses" },
45
+ { id: "suspicious/noExplicitAny", label: "Explicit any", help: "a type written as any" },
46
+ { id: "suspicious/noConsole", label: "console calls", help: "console.log and friends left in the code" },
47
+ { id: "suspicious/noDebugger", label: "debugger statements", help: "a debugger left in" },
48
+ { id: "style/useConst", label: "Prefer const", help: "let that is never reassigned" },
49
+ { id: "style/noNonNullAssertion", label: "Non-null assertions", help: "the ! after a value that might be null" },
50
+ { id: "complexity/noForEach", label: "No forEach", help: "for…of instead of .forEach" },
51
+ ],
52
+ Oxlint: [
53
+ { id: "no-unused-vars", label: "Unused variables", help: "a variable, argument or import that is never read" },
54
+ { id: "no-console", label: "console calls", help: "console.log and friends left in the code" },
55
+ { id: "no-debugger", label: "debugger statements", help: "a debugger left in" },
56
+ { id: "eqeqeq", label: "Strict equality", help: "=== and !== instead of == and !=" },
57
+ { id: "no-empty", label: "Empty blocks", help: "a block with nothing in it" },
58
+ { id: "typescript/no-explicit-any", label: "Explicit any", help: "a type written as any" },
59
+ ],
60
+ Ruff: [
61
+ { id: "F401", label: "Unused imports", help: "F401: an import nothing uses" },
62
+ { id: "E501", label: "Line too long", help: "E501: a line over the configured length" },
63
+ { id: "B", label: "Likely bugs", help: "B: flake8-bugbear's checks for common mistakes" },
64
+ { id: "I", label: "Import order", help: "I: imports sorted as isort sorts them" },
65
+ { id: "UP", label: "Modern syntax", help: "UP: pyupgrade's newer forms for your Python version" },
66
+ { id: "SIM", label: "Simpler code", help: "SIM: flake8-simplify's shorter equivalents" },
67
+ { id: "T20", label: "print calls", help: "T20: print and pprint left in the code" },
68
+ { id: "N", label: "Naming", help: "N: pep8-naming's names for classes, functions and variables" },
69
+ ],
70
+ };
71
+
72
+ const LEVELS: Record<string, LintRuleLevel[]> = { ESLint: ["off", "warn", "error"], Biome: ["off", "warn", "error"], Oxlint: ["off", "warn", "error"], Ruff: ["off", "error"] };
73
+
74
+ export class LintSetupError extends Error {}
75
+
76
+ function readText(path: string): string | undefined {
77
+ try {
78
+ return readFileSync(path, "utf8");
79
+ } catch {
80
+ return undefined;
81
+ }
82
+ }
83
+
84
+ const rel = (top: string, path: string) => relative(top, path).split("\\").join("/");
85
+
86
+ /** Folders from `start` up to `top`, nearest first. */
87
+ function upward(start: string, top: string): string[] {
88
+ const out: string[] = [];
89
+ let folder = start;
90
+ for (;;) {
91
+ out.push(folder);
92
+ if (folder === top) break;
93
+ const parent = dirname(folder);
94
+ if (parent === folder || rel(top, parent).startsWith("..")) break;
95
+ folder = parent;
96
+ }
97
+ return out;
98
+ }
99
+
100
+ type NodeManager = "npm" | "pnpm" | "yarn" | "bun";
101
+
102
+ function nodeManager(folder: string, top: string): NodeManager {
103
+ for (const at of upward(folder, top)) {
104
+ if (existsSync(join(at, "pnpm-lock.yaml"))) return "pnpm";
105
+ if (existsSync(join(at, "yarn.lock"))) return "yarn";
106
+ if (existsSync(join(at, "bun.lock")) || existsSync(join(at, "bun.lockb"))) return "bun";
107
+ if (existsSync(join(at, "package-lock.json"))) return "npm";
108
+ }
109
+ return "npm";
110
+ }
111
+
112
+ const ADD_DEV: Record<NodeManager, string> = { npm: "npm install -D", pnpm: "pnpm add -D", yarn: "yarn add -D", bun: "bun add -d" };
113
+ const RUN_BIN: Record<NodeManager, string> = { npm: "npx", pnpm: "pnpm exec", yarn: "yarn", bun: "bunx" };
114
+
115
+ function pythonAdd(folder: string, top: string): string {
116
+ for (const at of upward(folder, top)) {
117
+ if (existsSync(join(at, "uv.lock"))) return "uv add --dev ruff";
118
+ if (existsSync(join(at, "poetry.lock"))) return "poetry add --group dev ruff";
119
+ }
120
+ return "python -m pip install ruff";
121
+ }
122
+
123
+ /** A command run from `folder` (repository-relative) in a terminal that starts at the top. */
124
+ function inFolder(folder: string, command: string): string {
125
+ return folder ? `cd ${/^[\w./-]+$/.test(folder) ? folder : JSON.stringify(folder)} && ${command}` : command;
126
+ }
127
+
128
+ function installCommands(tool: string, folder: string, top: string): string[] {
129
+ const at = join(top, folder);
130
+ if (tool === "Ruff") return [inFolder(folder, pythonAdd(at, top))];
131
+ const manager = nodeManager(at, top);
132
+ if (tool === "ESLint") return [inFolder(folder, `${ADD_DEV[manager]} eslint @eslint/js`)];
133
+ if (tool === "Biome") return [inFolder(folder, `${ADD_DEV[manager]} -E @biomejs/biome`)];
134
+ if (tool === "Oxlint") return [inFolder(folder, `${ADD_DEV[manager]} oxlint`)];
135
+ return [];
136
+ }
137
+
138
+ // ---------------------------------------------------------------------------
139
+ // JSON configs (Biome, Oxlint)
140
+
141
+ interface JsonFile {
142
+ path: string;
143
+ data?: Record<string, unknown>;
144
+ indent: string;
145
+ /** Why it cannot be rewritten. */
146
+ locked?: string;
147
+ }
148
+
149
+ function readJson(path: string): JsonFile {
150
+ const text = readText(path) ?? "";
151
+ const indent = /\n([ \t]+)"/.exec(text)?.[1] ?? " ";
152
+ try {
153
+ const data = JSON.parse(text) as unknown;
154
+ if (!data || typeof data !== "object" || Array.isArray(data)) return { path, indent, locked: "is not a JSON object" };
155
+ return { path, data: data as Record<string, unknown>, indent };
156
+ } catch {
157
+ return { path, indent, locked: "has comments or is not plain JSON, so switching rules here would rewrite it; edit it in the code viewer" };
158
+ }
159
+ }
160
+
161
+ function writeJson(file: JsonFile): void {
162
+ writeFileSync(file.path, `${JSON.stringify(file.data, null, file.indent)}\n`);
163
+ }
164
+
165
+ function levelOf(value: unknown): RuleChoice {
166
+ const raw = Array.isArray(value) ? value[0] : value && typeof value === "object" ? (value as { level?: unknown }).level : value;
167
+ if (raw === "off" || raw === "allow" || raw === 0 || raw === "0") return "off";
168
+ if (raw === "warn" || raw === "info" || raw === 1 || raw === "1") return "warn";
169
+ if (raw === "error" || raw === "deny" || raw === "on" || raw === 2 || raw === "2") return "error";
170
+ return "default";
171
+ }
172
+
173
+ function child(parent: Record<string, unknown>, key: string): Record<string, unknown> {
174
+ const value = parent[key];
175
+ if (value && typeof value === "object" && !Array.isArray(value)) return value as Record<string, unknown>;
176
+ const made: Record<string, unknown> = {};
177
+ parent[key] = made;
178
+ return made;
179
+ }
180
+
181
+ /** Biome: `linter.rules.<group>.<name>`, a level or `{ level, options }` (whose options are kept). */
182
+ function biomeRule(data: Record<string, unknown>, id: string, level?: RuleChoice): RuleChoice {
183
+ const [group, name] = id.split("/") as [string, string];
184
+ const rules = (data.linter as Record<string, unknown> | undefined)?.rules as Record<string, unknown> | undefined;
185
+ const current = (rules?.[group] as Record<string, unknown> | undefined)?.[name];
186
+ if (level === undefined) return levelOf(current);
187
+ const groupNode = child(child(child(data, "linter"), "rules"), group);
188
+ if (level === "default") delete groupNode[name];
189
+ else if (current && typeof current === "object" && !Array.isArray(current)) groupNode[name] = { ...(current as object), level };
190
+ else groupNode[name] = level;
191
+ return level;
192
+ }
193
+
194
+ /** Oxlint: `rules.<name>`, a level or `[level, options]`. */
195
+ function oxlintRule(data: Record<string, unknown>, id: string, level?: RuleChoice): RuleChoice {
196
+ const current = (data.rules as Record<string, unknown> | undefined)?.[id];
197
+ if (level === undefined) return levelOf(current);
198
+ const rules = child(data, "rules");
199
+ if (level === "default") delete rules[id];
200
+ else rules[id] = Array.isArray(current) ? [level, ...current.slice(1)] : level;
201
+ return level;
202
+ }
203
+
204
+ // ---------------------------------------------------------------------------
205
+ // Ruff's TOML: only the `extend-select` and `ignore` arrays of its lint table are touched.
206
+
207
+ interface RuffFile {
208
+ path: string;
209
+ /** `[lint]` in ruff.toml, `[tool.ruff.lint]` in pyproject.toml. */
210
+ header: string;
211
+ }
212
+
213
+ function ruffFile(folder: string): RuffFile | undefined {
214
+ for (const name of [".ruff.toml", "ruff.toml"]) if (existsSync(join(folder, name))) return { path: join(folder, name), header: "lint" };
215
+ const pyproject = join(folder, "pyproject.toml");
216
+ if (/^\[tool\.ruff[\].]/m.test(readText(pyproject) ?? "")) return { path: pyproject, header: "tool.ruff.lint" };
217
+ return undefined;
218
+ }
219
+
220
+ /** The lint table's body: where it starts and ends in `text` (end is the next table or the end). */
221
+ function tableSpan(text: string, header: string): { start: number; end: number } | undefined {
222
+ const match = new RegExp(`^\\[${header.replace(/\./g, "\\.")}\\][ \\t]*(?:#.*)?$`, "m").exec(text);
223
+ if (!match) return undefined;
224
+ const start = match.index + match[0].length;
225
+ const next = /^\[/m.exec(text.slice(start));
226
+ return { start, end: next ? start + next.index : text.length };
227
+ }
228
+
229
+ /** `key = [ ... ]` inside the span: where it is and the codes in it. */
230
+ function tomlArray(text: string, span: { start: number; end: number }, key: string): { start: number; end: number; items: string[] } | undefined {
231
+ const body = text.slice(span.start, span.end);
232
+ const match = new RegExp(`^[ \\t]*${key.replace(/-/g, "\\-")}[ \\t]*=[ \\t]*\\[`, "m").exec(body);
233
+ if (!match) return undefined;
234
+ const open = span.start + match.index + match[0].length;
235
+ const close = text.indexOf("]", open);
236
+ if (close < 0 || close > span.end) return undefined;
237
+ const items = [...text.slice(open, close).matchAll(/"([^"]*)"|'([^']*)'/g)].map((found) => found[1] ?? found[2] ?? "").filter(Boolean);
238
+ let end = close + 1;
239
+ while (end < text.length && text[end] !== "\n") end += 1;
240
+ return { start: span.start + match.index, end, items };
241
+ }
242
+
243
+ function ruffArrays(text: string, header: string): { select: string[]; ignore: string[] } {
244
+ const span = tableSpan(text, header);
245
+ if (!span) return { select: [], ignore: [] };
246
+ return {
247
+ select: [...(tomlArray(text, span, "select")?.items ?? []), ...(tomlArray(text, span, "extend-select")?.items ?? [])],
248
+ ignore: [...(tomlArray(text, span, "ignore")?.items ?? []), ...(tomlArray(text, span, "extend-ignore")?.items ?? [])],
249
+ };
250
+ }
251
+
252
+ function ruffLevel(text: string, header: string, id: string): RuleChoice {
253
+ const { select, ignore } = ruffArrays(text, header);
254
+ if (ignore.includes(id)) return "off";
255
+ if (select.includes(id)) return "error";
256
+ return "default";
257
+ }
258
+
259
+ function setTomlArray(text: string, header: string, key: string, change: (items: string[]) => string[]): string {
260
+ let span = tableSpan(text, header);
261
+ if (!span) {
262
+ const items = change([]);
263
+ if (items.length === 0) return text;
264
+ const lead = text.length === 0 || text.endsWith("\n\n") ? "" : text.endsWith("\n") ? "\n" : "\n\n";
265
+ return `${text}${lead}[${header}]\n${key} = ${JSON.stringify(items).replace(/,/g, ", ")}\n`;
266
+ }
267
+ const found = tomlArray(text, span, key);
268
+ const items = change(found?.items ?? []);
269
+ const line = `${key} = ${JSON.stringify(items).replace(/,/g, ", ")}`;
270
+ if (found) return items.length === 0 ? text.slice(0, found.start) + text.slice(found.end + 1) : text.slice(0, found.start) + line + text.slice(found.end);
271
+ if (items.length === 0) return text;
272
+ span = tableSpan(text, header)!;
273
+ return `${text.slice(0, span.start)}\n${line}${text.slice(span.start)}`;
274
+ }
275
+
276
+ function setRuffRule(file: RuffFile, id: string, level: RuleChoice): void {
277
+ let text = readText(file.path) ?? "";
278
+ const without = (items: string[]) => items.filter((item) => item !== id);
279
+ text = setTomlArray(text, file.header, "extend-select", (items) => (level === "error" ? [...without(items), id] : without(items)));
280
+ text = setTomlArray(text, file.header, "ignore", (items) => (level === "off" ? [...without(items), id] : without(items)));
281
+ writeFileSync(file.path, text);
282
+ }
283
+
284
+ // ---------------------------------------------------------------------------
285
+
286
+ function jsonConfig(tool: string, folder: string): string | undefined {
287
+ const names = tool === "Biome" ? ["biome.json", "biome.jsonc"] : tool === "Oxlint" ? [".oxlintrc.json"] : [];
288
+ return names.map((name) => join(folder, name)).find((path) => existsSync(path));
289
+ }
290
+
291
+ function eslintConfig(folder: string): string | undefined {
292
+ const names = ["eslint.config.js", "eslint.config.mjs", "eslint.config.cjs", "eslint.config.ts", "eslint.config.mts", "eslint.config.cts", ".eslintrc.json", ".eslintrc", ".eslintrc.js", ".eslintrc.cjs", ".eslintrc.yml", ".eslintrc.yaml", "package.json"];
293
+ return names.map((name) => join(folder, name)).find((path) => existsSync(path));
294
+ }
295
+
296
+ function describe(found: FoundLinter, top: string, config: Pick<LintConfig, "eslintRules">): LintSetupLinter {
297
+ const folder = join(top, found.folder);
298
+ const defs = RULES[found.tool] ?? [];
299
+ const base = { ...found, levels: LEVELS[found.tool] ?? ["off", "warn", "error"], install: found.installed ? [] : installCommands(found.tool, found.folder, top) };
300
+ if (found.tool === "ESLint") {
301
+ const path = eslintConfig(folder);
302
+ return {
303
+ ...base,
304
+ ...(path ? { config: rel(top, path) } : {}),
305
+ rulesAt: "gate",
306
+ rules: defs.map((def) => ({ ...def, level: config.eslintRules[def.id] ?? "default" })),
307
+ note: "ESLint's config is code, so these are added when the lint gate runs ESLint (as --rule flags), on top of the project's config. To make one the project's own, add it to the config.",
308
+ };
309
+ }
310
+ if (found.tool === "Ruff") {
311
+ const file = ruffFile(folder);
312
+ const text = file ? readText(file.path) ?? "" : "";
313
+ return {
314
+ ...base,
315
+ ...(file ? { config: rel(top, file.path) } : {}),
316
+ rulesAt: file ? "file" : "read",
317
+ rules: defs.map((def) => ({ ...def, level: file ? ruffLevel(text, file.header, def.id) : "default" })),
318
+ ...(file ? {} : { note: "No Ruff config file was found to write to." }),
319
+ };
320
+ }
321
+ const path = jsonConfig(found.tool, folder);
322
+ const file = path ? readJson(path) : undefined;
323
+ const read = (def: RuleDef): RuleChoice => (file?.data ? (found.tool === "Biome" ? biomeRule(file.data, def.id) : oxlintRule(file.data, def.id)) : "default");
324
+ return {
325
+ ...base,
326
+ ...(path ? { config: rel(top, path) } : {}),
327
+ rulesAt: file?.data ? "file" : "read",
328
+ rules: defs.map((def) => ({ ...def, level: read(def) })),
329
+ ...(file?.locked && path ? { note: `${rel(top, path)} ${file.locked}.` } : {}),
330
+ };
331
+ }
332
+
333
+ const JS_TOOLS = ["ESLint", "Biome", "Oxlint"];
334
+
335
+ function offers(top: string, found: FoundLinter[]): LintSetupOffer[] {
336
+ const js = existsSync(join(top, "package.json"));
337
+ const python = ["pyproject.toml", "requirements.txt", "setup.py", "setup.cfg"].some((name) => existsSync(join(top, name)));
338
+ const hasJs = found.some((linter) => JS_TOOLS.includes(linter.tool));
339
+ const hasRuff = found.some((linter) => linter.tool === "Ruff");
340
+ const either = !js && !python;
341
+ const manager = nodeManager(top, top);
342
+ const out: LintSetupOffer[] = [];
343
+ if ((js || either) && !hasJs) {
344
+ out.push(
345
+ { tool: "ESLint", blurb: "The most widely used JavaScript and TypeScript linter, with a plugin for nearly everything.", steps: [{ label: "Install and create a config (it asks a few questions)", command: "npm init @eslint/config@latest" }] },
346
+ { tool: "Biome", blurb: "One fast tool that lints and formats JavaScript, TypeScript, JSON and CSS.", steps: [{ label: "Install", command: `${ADD_DEV[manager]} -E @biomejs/biome` }, { label: "Create biome.json", command: `${RUN_BIN[manager]} biome init` }] },
347
+ { tool: "Oxlint", blurb: "A very fast linter with ESLint's common rules built in.", steps: [{ label: "Install", command: `${ADD_DEV[manager]} oxlint` }, { label: "Create .oxlintrc.json", command: `${RUN_BIN[manager]} oxlint --init` }] },
348
+ );
349
+ }
350
+ if ((python || either) && !hasRuff) {
351
+ out.push({ tool: "Ruff", blurb: "A very fast Python linter that covers Flake8, isort, pyupgrade and more.", steps: [{ label: "Install", command: pythonAdd(top, top) }, { label: "Create ruff.toml", create: "ruff.toml" }] });
352
+ }
353
+ return out;
354
+ }
355
+
356
+ /** Everything the wizard shows. */
357
+ export function lintSetup(top: string, config: Pick<LintConfig, "eslintRules">, found: FoundLinter[] = findLinters(top)): LintSetup {
358
+ return { linters: found.map((linter) => describe(linter, top, config)), offers: offers(top, found) };
359
+ }
360
+
361
+ /**
362
+ * Switch one rule of a found linter. For ESLint the caller saves the returned
363
+ * `eslintRules`; for the others the config file is written here.
364
+ */
365
+ export function setLintRule(top: string, config: Pick<LintConfig, "eslintRules">, change: { tool: string; folder: string; rule: string; level: RuleChoice }): { eslintRules?: LintConfig["eslintRules"] } {
366
+ const defs = RULES[change.tool];
367
+ if (!defs?.some((def) => def.id === change.rule)) throw new LintSetupError(`${change.rule} is not one of ${change.tool}'s rules here.`);
368
+ if (change.level !== "default" && !(LEVELS[change.tool] ?? []).includes(change.level)) throw new LintSetupError(`${change.tool} has no ${change.level} level.`);
369
+ const found = findLinters(top).find((linter) => linter.tool === change.tool && linter.folder === change.folder);
370
+ if (!found) throw new LintSetupError(`${change.tool} is not configured in ${change.folder || "the project root"}.`);
371
+ const folder = join(top, found.folder);
372
+ if (change.tool === "ESLint") {
373
+ const rules = { ...config.eslintRules };
374
+ if (change.level === "default") delete rules[change.rule];
375
+ else rules[change.rule] = change.level;
376
+ return { eslintRules: rules };
377
+ }
378
+ if (change.tool === "Ruff") {
379
+ const file = ruffFile(folder);
380
+ if (!file) throw new LintSetupError("No Ruff config file was found to write to.");
381
+ setRuffRule(file, change.rule, change.level);
382
+ return {};
383
+ }
384
+ const path = jsonConfig(change.tool, folder);
385
+ const file = path ? readJson(path) : undefined;
386
+ if (!path || !file?.data) throw new LintSetupError(path && file?.locked ? `${rel(top, path)} ${file.locked}.` : `No ${change.tool} config file was found to write to.`);
387
+ if (change.tool === "Biome") biomeRule(file.data, change.rule, change.level);
388
+ else oxlintRule(file.data, change.rule, change.level);
389
+ writeJson(file);
390
+ return {};
391
+ }
392
+
393
+ const RUFF_STARTER = `# Ruff's settings: https://docs.astral.sh/ruff/configuration/
394
+ line-length = 100
395
+
396
+ [lint]
397
+ # Pyflakes and pycodestyle errors are on by default; these add a few common families.
398
+ extend-select = ["I", "B", "UP"]
399
+ ignore = []
400
+ `;
401
+
402
+ /** Write a starter config at the project's top (Ruff only; the JavaScript linters create their own with an init command). */
403
+ export function createLintConfig(top: string, name: string): string {
404
+ if (name !== "ruff.toml") throw new LintSetupError(`bot-lobby does not create ${name}; run the linter's own init command.`);
405
+ const path = join(top, name);
406
+ if (existsSync(path)) throw new LintSetupError(`${name} already exists.`);
407
+ writeFileSync(path, RUFF_STARTER);
408
+ return name;
409
+ }