@a-t-h-i/bot-lobby 0.7.1 → 0.7.2
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.
- package/package.json +1 -1
- package/prompts/global.md +13 -0
- package/prompts/master.md +8 -8
- package/prompts/planner.md +14 -0
- package/src/classifier/knowledge.ts +22 -3
- package/src/execution/lint-setup.ts +409 -0
- package/src/execution/lint.ts +25 -13
- package/src/execution/verification.ts +65 -13
- package/src/lobby/planner.ts +2 -2
- package/src/master/master.ts +30 -13
- package/src/pi/tools.ts +1 -1
- package/src/schemas/configuration.ts +14 -1
- package/src/schemas/lint.ts +50 -0
- package/src/webui/api/index.ts +12 -1
- package/src/webui/api/settings.ts +39 -0
- package/src/webui/protocol.ts +5 -0
- package/src/workflow/workflow.ts +22 -7
- package/webui/dist/assets/{CodeSurface-Bdkhh84z.js → CodeSurface-12WUcZSS.js} +1 -1
- package/webui/dist/assets/{TerminalView-CsDNheS9.js → TerminalView-C1ez7iqT.js} +1 -1
- package/webui/dist/assets/index-BUrfox9b.js +117 -0
- package/webui/dist/assets/index-CoVxsMKn.css +2 -0
- package/webui/dist/build.json +39 -19
- package/webui/dist/index.html +2 -2
- package/webui/dist/assets/index-Bt0RLI3l.css +0 -2
- package/webui/dist/assets/index-C3Bn07Vr.js +0 -115
package/package.json
CHANGED
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
|
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]],
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
that must hold, prior work already landed, and the
|
|
148
|
-
|
|
149
|
-
|
|
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,
|
package/prompts/planner.md
CHANGED
|
@@ -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
|
|
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
|
}
|
|
@@ -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
|
+
}
|
package/src/execution/lint.ts
CHANGED
|
@@ -65,6 +65,8 @@ interface Linter {
|
|
|
65
65
|
/** The installed binary as `[command, ...leading args]`, looked for from `folder` up to the repository's top. */
|
|
66
66
|
binary(folder: string, top: string): string[] | undefined;
|
|
67
67
|
args(files: readonly string[]): string[];
|
|
68
|
+
/** Flags from Settings that go before the files (ESLint's `--rule`s). */
|
|
69
|
+
extra?(config: Pick<LintConfig, "eslintRules">): string[];
|
|
68
70
|
read(result: LintExecResult, folder: string, top: string): Parsed | undefined;
|
|
69
71
|
}
|
|
70
72
|
|
|
@@ -220,6 +222,7 @@ export const LINTERS: readonly Linter[] = [
|
|
|
220
222
|
extensions: JS,
|
|
221
223
|
binary: nodeBin("eslint", "eslint"),
|
|
222
224
|
args: (files) => ["--format", "json", ...files],
|
|
225
|
+
extra: (config) => Object.entries(config.eslintRules ?? {}).flatMap(([rule, level]) => ["--rule", `${rule}: ${level}`]),
|
|
223
226
|
read: eslintRead,
|
|
224
227
|
},
|
|
225
228
|
{
|
|
@@ -352,7 +355,7 @@ export function planLint(top: string, files: readonly string[], config: Pick<Lin
|
|
|
352
355
|
}
|
|
353
356
|
|
|
354
357
|
/** Run one planned linter over its files. */
|
|
355
|
-
export async function runPlan(plan: LintPlan, top: string, config: Pick<LintConfig, "command" | "timeoutMs"
|
|
358
|
+
export async function runPlan(plan: LintPlan, top: string, config: Pick<LintConfig, "command" | "timeoutMs"> & Partial<Pick<LintConfig, "eslintRules">>, exec: LintExec = execLint, signal?: AbortSignal): Promise<LintRun> {
|
|
356
359
|
const started = Date.now();
|
|
357
360
|
const folder = repoPath(top, plan.folder);
|
|
358
361
|
const files = plan.files;
|
|
@@ -373,7 +376,7 @@ export async function runPlan(plan: LintPlan, top: string, config: Pick<LintConf
|
|
|
373
376
|
}
|
|
374
377
|
const binary = plan.linter.binary(plan.folder, top);
|
|
375
378
|
if (!binary) return unavailable(plan.tool, folder, files, `${plan.tool} is configured${folder ? ` in ${folder}/` : ""} but not installed: install the project's dependencies there.`);
|
|
376
|
-
const result = await exec(binary[0]!, [...binary.slice(1), ...plan.linter.args(files.map((file) => argument(plan.folder, top, file)))], { cwd: plan.folder, timeoutMs: config.timeoutMs, ...(signal ? { signal } : {}) });
|
|
379
|
+
const result = await exec(binary[0]!, [...binary.slice(1), ...(plan.linter.extra?.({ eslintRules: config.eslintRules ?? {} }) ?? []), ...plan.linter.args(files.map((file) => argument(plan.folder, top, file)))], { cwd: plan.folder, timeoutMs: config.timeoutMs, ...(signal ? { signal } : {}) });
|
|
377
380
|
const ms = Date.now() - started;
|
|
378
381
|
if (result.code === null) return unavailable(plan.tool, folder, files, why(result, plan.tool, config.timeoutMs), ms);
|
|
379
382
|
const parsed = plan.linter.read(result, plan.folder, top);
|
|
@@ -382,22 +385,31 @@ export async function runPlan(plan: LintPlan, top: string, config: Pick<LintConf
|
|
|
382
385
|
}
|
|
383
386
|
|
|
384
387
|
/** A key for the touched files as they stand and the settings that lint them: equal keys, equal results. */
|
|
385
|
-
export function lintFingerprint(top: string, files: readonly string[], config: Pick<LintConfig, "command" | "extensions">): string {
|
|
388
|
+
export function lintFingerprint(top: string, files: readonly string[], config: Pick<LintConfig, "command" | "extensions"> & Partial<Pick<LintConfig, "eslintRules">>): string {
|
|
386
389
|
const hash = createHash("sha256");
|
|
387
|
-
hash.update(JSON.stringify([config.command, config.extensions]));
|
|
388
|
-
for (const file of [...files].sort()) {
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
}
|
|
396
|
-
hash.update(`\0${file}\0${stamp}`);
|
|
390
|
+
hash.update(JSON.stringify([config.command, config.extensions, config.eslintRules ?? {}]));
|
|
391
|
+
for (const file of [...files].sort()) hash.update(`\0${file}\0${stamp(join(top, file))}`);
|
|
392
|
+
// The linters' own configs above the files too: a rule switched in Settings (or by hand) lints again.
|
|
393
|
+
const folders = new Set<string>();
|
|
394
|
+
for (const file of files) for (const folder of upward(dirname(join(top, file)), top)) folders.add(folder);
|
|
395
|
+
const names = [...new Set([...LINTERS.flatMap((linter) => linter.configs), "package.json", "pyproject.toml"])];
|
|
396
|
+
for (const folder of [...folders].sort()) for (const name of names) {
|
|
397
|
+
const path = join(folder, name);
|
|
398
|
+
if (existsSync(path)) hash.update(`\0${relative(top, path)}\0${stamp(path)}`);
|
|
397
399
|
}
|
|
398
400
|
return hash.digest("hex").slice(0, 24);
|
|
399
401
|
}
|
|
400
402
|
|
|
403
|
+
function stamp(path: string): string {
|
|
404
|
+
try {
|
|
405
|
+
const stat = statSync(path);
|
|
406
|
+
return `${stat.size}:${stat.mtimeMs}`;
|
|
407
|
+
} catch {
|
|
408
|
+
// A deleted file keys as gone.
|
|
409
|
+
return "gone";
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
401
413
|
/** A linter the project configures, where, and whether its binary is there to run. */
|
|
402
414
|
export interface FoundLinter {
|
|
403
415
|
tool: string;
|