@mergelight/cli 0.1.14 → 0.1.15
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/dist/checks.js +108 -0
- package/dist/cli.js +49 -5
- package/dist/cloud.js +330 -0
- package/dist/mcp/findings.js +5 -0
- package/dist/prompt.js +251 -5
- package/dist/providers/codex.js +26 -0
- package/dist/publish/handled.js +22 -4
- package/dist/publish/markdown.js +3 -1
- package/dist/publish/publish.js +40 -10
- package/dist/publish/team-checks.js +72 -0
- package/dist/render.js +23 -0
- package/dist/review.js +101 -6
- package/dist/schema.js +49 -0
- package/dist/skills.js +127 -0
- package/dist/workspace.js +184 -3
- package/package.json +1 -1
package/dist/review.js
CHANGED
|
@@ -3,10 +3,12 @@ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { actionsUsedBy, fetchActionSources, notRead } from "./action-source.js";
|
|
5
5
|
import { fetchPullRequest } from "./github.js";
|
|
6
|
-
import { buildHunterPrompt, buildSweepPrompt, buildVerifierPrompt, focusesFor, } from "./prompt.js";
|
|
6
|
+
import { buildCheckPrompt, buildHunterPrompt, buildSweepPrompt, buildVerifierPrompt, focusesFor, ruleApplies, usedMemories, } from "./prompt.js";
|
|
7
7
|
import { LimitError, LoginError } from "./providers/codex.js";
|
|
8
8
|
import { claudeAvailable, runModel, TOOLING } from "./providers/index.js";
|
|
9
|
-
import { candidateSchema, reviewSchema } from "./schema.js";
|
|
9
|
+
import { candidateSchema, checkSchema, reviewSchema, reviewSchemaWithDecisions } from "./schema.js";
|
|
10
|
+
import { CHECK_TIMEOUT_MS, startTeamChecks } from "./checks.js";
|
|
11
|
+
import { run } from "./run.js";
|
|
10
12
|
import { cacheDir, prepareWorkspace } from "./workspace.js";
|
|
11
13
|
/**
|
|
12
14
|
* Stable id for a finding: the file plus the code it points at, ignoring
|
|
@@ -106,6 +108,19 @@ function forProvider(dir, input, provider) {
|
|
|
106
108
|
writeFileSync(join(dir, diffFile), input.diff);
|
|
107
109
|
return { ...input, tooling, diffFile };
|
|
108
110
|
}
|
|
111
|
+
/** The diff one of the team's checks reads: at most this much of it goes into the question. */
|
|
112
|
+
const MAX_CHECK_DIFF = 150_000;
|
|
113
|
+
/**
|
|
114
|
+
* The whole change to the files a check is about. Unlike the reviewers' diff it leaves nothing out:
|
|
115
|
+
* a check that names a lockfile or a generated file must see what changed in it, removed lines included.
|
|
116
|
+
*/
|
|
117
|
+
async function checkDiff(dir, base, head, files) {
|
|
118
|
+
// The names come from git itself and go back to it as they are: never as options, never as patterns.
|
|
119
|
+
const r = await run("git", ["--literal-pathspecs", "-C", dir, "diff", "-U5", "--no-color", "--no-ext-diff", "--no-renames", `${base}...${head}`, "--", ...files.slice(0, 50)], { timeoutMs: 60_000 });
|
|
120
|
+
if (r.code !== 0)
|
|
121
|
+
return { text: "", cut: true, missing: true };
|
|
122
|
+
return r.stdout.length > MAX_CHECK_DIFF ? { text: r.stdout.slice(0, MAX_CHECK_DIFF), cut: true } : { text: r.stdout, cut: files.length > 50 };
|
|
123
|
+
}
|
|
109
124
|
/**
|
|
110
125
|
* The verifier: tries to disprove every candidate, merges duplicates, rates the
|
|
111
126
|
* rest and picks the few that matter most. Exported so the eval can replay the
|
|
@@ -115,7 +130,8 @@ export async function verifyCandidates(dir, input, found, opts) {
|
|
|
115
130
|
const result = await runModel(opts.provider, {
|
|
116
131
|
cwd: dir,
|
|
117
132
|
prompt: buildVerifierPrompt(forProvider(dir, input, opts.provider), found),
|
|
118
|
-
|
|
133
|
+
// Only a verifier that was given the team's earlier decisions is asked which one it used.
|
|
134
|
+
schema: input.memories?.length ? reviewSchemaWithDecisions : reviewSchema,
|
|
119
135
|
model: opts.model,
|
|
120
136
|
effort: opts.effort,
|
|
121
137
|
logFile: opts.logFile,
|
|
@@ -131,6 +147,45 @@ export async function verifyCandidates(dir, input, found, opts) {
|
|
|
131
147
|
.sort((a, b) => ORDER[a.class] - ORDER[b.class] || a.file.localeCompare(b.file) || a.line - b.line);
|
|
132
148
|
return { summary: review.summary, findings, rejected: review.rejected, model: result.model, cost_usd: result.cost_usd ?? null };
|
|
133
149
|
}
|
|
150
|
+
/** Every rule a team can have for one repository: 50 for the org and 50 of its own. None is dropped. */
|
|
151
|
+
const MAX_RULES = 100;
|
|
152
|
+
/** The summary, with what the reader must know about the team's rules: a guarded file was changed, or the rules couldn't be read. */
|
|
153
|
+
export function summaryWith(summary, needsHuman, rulesUnread) {
|
|
154
|
+
// As code, so a name like __init__.py shows as it is and not as bold text.
|
|
155
|
+
const code = (path) => `\`${path.replace(/`/g, "'").replace(/[\u0000-\u001f\u007f]/g, "?")}\``;
|
|
156
|
+
const guarded = needsHuman.length
|
|
157
|
+
? ` It changes ${needsHuman.slice(0, 3).map(code).join(", ")}${needsHuman.length > 3 ? ` and ${needsHuman.length - 3} more` : ""}, which your team marked as always needing a human.`
|
|
158
|
+
: "";
|
|
159
|
+
// A team may have rules that would have changed this review. Running without them must never be silent.
|
|
160
|
+
const unread = rulesUnread ? " Mergelight couldn't get your team's rules, skills, checks and earlier decisions from its server, so this review ran without them." : "";
|
|
161
|
+
return `${summary}${guarded}${unread}`;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* The light, with the team's "always needs a human" files taken into account. Such a file keeps a
|
|
165
|
+
* pull request from going green by itself. It never makes a light better: red stays red.
|
|
166
|
+
*/
|
|
167
|
+
export function lightWith(findings, needsHuman) {
|
|
168
|
+
const light = mergeLight(findings);
|
|
169
|
+
return light === "green" && needsHuman.length ? "yellow" : light;
|
|
170
|
+
}
|
|
171
|
+
/** The changed files that match a "needs a human" rule of the team. */
|
|
172
|
+
export function filesNeedingHuman(rules, changedFiles) {
|
|
173
|
+
const guards = (rules ?? []).filter((r) => r.kind === "needs_human" && r.paths?.length);
|
|
174
|
+
return changedFiles.filter((file) => guards.some((r) => ruleApplies(r, [file])));
|
|
175
|
+
}
|
|
176
|
+
/** Most recent first, as the server sends them. Enough for the files of one pull request, and not a wall of old decisions. */
|
|
177
|
+
const MAX_MEMORIES = 30;
|
|
178
|
+
/**
|
|
179
|
+
* A decision is about one problem in one file, so only those in files this pull request changes are
|
|
180
|
+
* passed on. One made on this very pull request is left out: the verifier already gets it with the
|
|
181
|
+
* earlier rounds, and reviewing its own pull request again must not count as a use that keeps it alive.
|
|
182
|
+
*/
|
|
183
|
+
export function memoriesFor(memories, changedFiles, pullRequest) {
|
|
184
|
+
// The same file, however its path was written down: src/a.ts, ./src/a.ts or /src/a.ts.
|
|
185
|
+
const plain = (path) => path.replace(/^(\.\/|\/)+/, "");
|
|
186
|
+
const changed = new Set(changedFiles.map(plain));
|
|
187
|
+
return (memories ?? []).filter((m) => changed.has(plain(m.file)) && m.pr !== pullRequest).slice(0, MAX_MEMORIES);
|
|
188
|
+
}
|
|
134
189
|
export async function reviewPullRequest(ref, opts = {}) {
|
|
135
190
|
const started = Date.now();
|
|
136
191
|
const progress = opts.onProgress ?? (() => { });
|
|
@@ -140,9 +195,17 @@ export async function reviewPullRequest(ref, opts = {}) {
|
|
|
140
195
|
progress(`Reading ${ref.owner}/${ref.repo}#${ref.number}`);
|
|
141
196
|
const pr = await fetchPullRequest(ref);
|
|
142
197
|
progress("Checking out the code");
|
|
143
|
-
const ws = await prepareWorkspace(pr, opts.at);
|
|
198
|
+
const ws = await prepareWorkspace(pr, opts.at, opts.skills);
|
|
199
|
+
const skillsMissing = (opts.skills?.length ?? 0) - ws.skills.length;
|
|
200
|
+
if (skillsMissing > 0)
|
|
201
|
+
progress(`${skillsMissing} of the skill folders your team picked ${skillsMissing === 1 ? "has" : "have"} no SKILL.md on the base branch, or couldn't be read: left out. Name the real folder, not a link to it`);
|
|
202
|
+
if (ws.skills.length)
|
|
203
|
+
progress(`Using your team's skill${ws.skills.length === 1 ? "" : "s"}: ${ws.skills.map((s) => s.name).join(", ")}`);
|
|
204
|
+
if (ws.conventions.length)
|
|
205
|
+
progress(`Using ${ws.conventions.map((c) => c.path).join(", ")} from ${pr.baseRef}`);
|
|
144
206
|
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
145
207
|
const log = (step) => join(cacheDir(), "logs", `${pr.owner}-${pr.repo}-${pr.number}-${stamp}-${step}.log`);
|
|
208
|
+
let checksRun = null;
|
|
146
209
|
try {
|
|
147
210
|
const input = {
|
|
148
211
|
pr,
|
|
@@ -152,6 +215,11 @@ export async function reviewPullRequest(ref, opts = {}) {
|
|
|
152
215
|
diff: ws.diff,
|
|
153
216
|
diffTruncated: ws.diffTruncated,
|
|
154
217
|
previous: opts.previous,
|
|
218
|
+
memories: memoriesFor(opts.memories, ws.changedFiles.map((f) => f.path), pr.number),
|
|
219
|
+
// Matched against every path the pull request touches, exactly as git has it.
|
|
220
|
+
skills: ws.skills,
|
|
221
|
+
conventions: ws.conventions,
|
|
222
|
+
rules: (opts.rules ?? []).filter((r) => r.kind === "rule" && ruleApplies(r, ws.touchedPaths)).slice(0, MAX_RULES),
|
|
155
223
|
};
|
|
156
224
|
// Step 1: hunters, one per area, in parallel. One failing doesn't sink the review.
|
|
157
225
|
const addedTo = ws.changedFiles.filter((f) => f.added > 0).map((f) => f.path);
|
|
@@ -215,6 +283,21 @@ export async function reviewPullRequest(ref, opts = {}) {
|
|
|
215
283
|
}
|
|
216
284
|
});
|
|
217
285
|
}
|
|
286
|
+
// The team's own checks run next to the verifier. They never fail the review and never hold it up
|
|
287
|
+
// for long: each ends as an answer or as an error of its own.
|
|
288
|
+
const teamChecks = opts.checks?.length
|
|
289
|
+
? startTeamChecks(opts.checks, ws.touchedPaths, async (check, files) => (await runModel(provider, {
|
|
290
|
+
cwd: ws.dir,
|
|
291
|
+
prompt: buildCheckPrompt({ ...input, tooling: TOOLING[provider] }, check, files, await checkDiff(ws.dir, ws.mergeBase, ws.headSha, files)),
|
|
292
|
+
schema: checkSchema,
|
|
293
|
+
model: hunterModel,
|
|
294
|
+
effort,
|
|
295
|
+
logFile: log(`check-${check.id}`),
|
|
296
|
+
timeoutMs: CHECK_TIMEOUT_MS,
|
|
297
|
+
projectDocs: false,
|
|
298
|
+
})).output, progress)
|
|
299
|
+
: null;
|
|
300
|
+
checksRun = teamChecks;
|
|
218
301
|
// Step 2: the verifier tries to disprove each candidate and sorts the rest.
|
|
219
302
|
// Opus checks better than Codex: in the eval it posted a third less and kept the same finds.
|
|
220
303
|
const verifyWith = opts.verifyWith ?? (provider === "claude" || (await claudeAvailable()) ? "claude" : "codex");
|
|
@@ -228,6 +311,9 @@ export async function reviewPullRequest(ref, opts = {}) {
|
|
|
228
311
|
logFile: log("verify"),
|
|
229
312
|
onCommand: (cmd) => progress(`Checking ${found.length} candidates: ${cmd.replace(/\s+/g, " ").slice(0, 80)}`, true),
|
|
230
313
|
});
|
|
314
|
+
// Every path the pull request touches counts here, the lockfiles and generated files the reviewers skip included.
|
|
315
|
+
const needsHuman = filesNeedingHuman(opts.rules, ws.touchedPaths);
|
|
316
|
+
const team_checks = teamChecks ? await teamChecks.done : null;
|
|
231
317
|
const firstHunt = hunts.find((h) => h.status === "fulfilled");
|
|
232
318
|
const servedModel = firstHunt?.status === "fulfilled" ? firstHunt.value.model : null;
|
|
233
319
|
return {
|
|
@@ -243,9 +329,12 @@ export async function reviewPullRequest(ref, opts = {}) {
|
|
|
243
329
|
},
|
|
244
330
|
provider: { name: provider, model: servedModel, effort },
|
|
245
331
|
verifier: { name: verifyWith, model: verified.model, effort, cost_usd: verified.cost_usd },
|
|
246
|
-
light:
|
|
247
|
-
summary: verified.summary,
|
|
332
|
+
light: lightWith(verified.findings, needsHuman),
|
|
333
|
+
summary: summaryWith(verified.summary, needsHuman, opts.rulesUnread === true),
|
|
334
|
+
...(needsHuman.length ? { needs_human: needsHuman } : {}),
|
|
248
335
|
findings: verified.findings,
|
|
336
|
+
...(input.memories?.length ? { used_memories: usedMemories(input.memories, verified.rejected, found) } : {}),
|
|
337
|
+
...(team_checks?.length ? { team_checks } : {}),
|
|
249
338
|
...(unread.length ? { not_read: unread } : {}),
|
|
250
339
|
stats: {
|
|
251
340
|
duration_ms: Date.now() - started,
|
|
@@ -263,6 +352,12 @@ export async function reviewPullRequest(ref, opts = {}) {
|
|
|
263
352
|
};
|
|
264
353
|
}
|
|
265
354
|
finally {
|
|
355
|
+
// The checkout is about to go. A check that is still waiting for its turn must not start in it.
|
|
356
|
+
// What the checks answered so far goes to the caller, whether the review worked or not.
|
|
357
|
+
if (checksRun) {
|
|
358
|
+
checksRun.stop();
|
|
359
|
+
opts.onTeamChecks?.(await checksRun.done);
|
|
360
|
+
}
|
|
266
361
|
if (opts.keep)
|
|
267
362
|
progress(`Kept the checkout at ${ws.dir}`);
|
|
268
363
|
else
|
package/dist/schema.js
CHANGED
|
@@ -27,6 +27,30 @@ export const candidateSchema = {
|
|
|
27
27
|
},
|
|
28
28
|
},
|
|
29
29
|
};
|
|
30
|
+
/** The answer to one of the team's own checks. */
|
|
31
|
+
export const checkSchema = {
|
|
32
|
+
type: "object",
|
|
33
|
+
additionalProperties: false,
|
|
34
|
+
required: ["verdict", "summary", "problems"],
|
|
35
|
+
properties: {
|
|
36
|
+
verdict: { type: "string", enum: ["pass", "fail", "unsure"], description: "pass: you read the change and it does what the check asks. fail: you can name the place where it does not. unsure: you couldn't see enough to tell." },
|
|
37
|
+
summary: { type: "string", description: "One or two plain sentences: what you checked and what you found." },
|
|
38
|
+
problems: {
|
|
39
|
+
type: "array",
|
|
40
|
+
description: "When it fails: each place that breaks the check, 10 at most. Empty when it passes.",
|
|
41
|
+
items: {
|
|
42
|
+
type: "object",
|
|
43
|
+
additionalProperties: false,
|
|
44
|
+
required: ["file", "line", "note"],
|
|
45
|
+
properties: {
|
|
46
|
+
file: { type: "string" },
|
|
47
|
+
line: { type: "integer", description: "The line in the head version, or 0 when no one line stands for it." },
|
|
48
|
+
note: { type: "string", description: "One sentence: what is wrong here." },
|
|
49
|
+
},
|
|
50
|
+
},
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
};
|
|
30
54
|
export const reviewSchema = {
|
|
31
55
|
type: "object",
|
|
32
56
|
additionalProperties: false,
|
|
@@ -104,3 +128,28 @@ export const reviewSchema = {
|
|
|
104
128
|
},
|
|
105
129
|
},
|
|
106
130
|
};
|
|
131
|
+
/**
|
|
132
|
+
* The review schema for a verifier that was given the team's earlier decisions. Each rejected
|
|
133
|
+
* candidate then names the decision that caused it, or null. Reviews without decisions keep the
|
|
134
|
+
* plain schema, so nothing changes for them.
|
|
135
|
+
*/
|
|
136
|
+
export const reviewSchemaWithDecisions = {
|
|
137
|
+
...reviewSchema,
|
|
138
|
+
properties: {
|
|
139
|
+
...reviewSchema.properties,
|
|
140
|
+
rejected: {
|
|
141
|
+
...reviewSchema.properties.rejected,
|
|
142
|
+
items: {
|
|
143
|
+
...reviewSchema.properties.rejected.items,
|
|
144
|
+
required: ["candidate", "reason", "decision"],
|
|
145
|
+
properties: {
|
|
146
|
+
...reviewSchema.properties.rejected.items.properties,
|
|
147
|
+
decision: {
|
|
148
|
+
type: ["string", "null"],
|
|
149
|
+
description: "The id of the team's earlier decision that is why you rejected it, like M12. Null when you rejected it for any other reason.",
|
|
150
|
+
},
|
|
151
|
+
},
|
|
152
|
+
},
|
|
153
|
+
},
|
|
154
|
+
},
|
|
155
|
+
};
|
package/dist/skills.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { lstatSync, mkdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { run } from "./run.js";
|
|
4
|
+
const MAX_SKILLS = 10;
|
|
5
|
+
const MAX_FILES = 30;
|
|
6
|
+
const MAX_FILE_BYTES = 60_000;
|
|
7
|
+
const MAX_SKILL_BYTES = 200_000;
|
|
8
|
+
/** The copy is a help, not a need: a git call that hangs, or a copy that takes too long, is given up. */
|
|
9
|
+
const GIT_TIMEOUT_MS = 20_000;
|
|
10
|
+
const IMPORT_TIMEOUT_MS = 60_000;
|
|
11
|
+
export { GIT_TIMEOUT_MS as SKILL_GIT_TIMEOUT_MS, IMPORT_TIMEOUT_MS as SKILL_IMPORT_TIMEOUT_MS };
|
|
12
|
+
/** A folder in the repository, written plainly: no wildcards, no "..", no leading slash. */
|
|
13
|
+
export function isSkillPath(v) {
|
|
14
|
+
return typeof v === "string" && /^[\w.@+\-]+(\/[\w.@+\-]+)*$/.test(v) && v.length <= 200 && !v.split("/").some((part) => part === ".." || part === ".");
|
|
15
|
+
}
|
|
16
|
+
/** One line of plain text from a skill's own words, cut to size. */
|
|
17
|
+
function line(text, max) {
|
|
18
|
+
return text.replace(/[\u0000-\u001f\u007f-\u009f\u200e\u200f\u2028-\u202e\u2066-\u2069]+/g, " ").replace(/ {2,}/g, " ").trim().slice(0, max).trim();
|
|
19
|
+
}
|
|
20
|
+
/** The name and description from the top of a SKILL.md, the way Claude Code and Codex write them. */
|
|
21
|
+
export function describeSkill(markdown, folder) {
|
|
22
|
+
const front = /^---\r?\n([\s\S]*?)\r?\n---/.exec(markdown)?.[1] ?? "";
|
|
23
|
+
const lines = front.split(/\r?\n/);
|
|
24
|
+
const field = (key) => {
|
|
25
|
+
const at = lines.findIndex((l) => l.startsWith(`${key}:`));
|
|
26
|
+
if (at < 0)
|
|
27
|
+
return "";
|
|
28
|
+
const first = lines[at].slice(key.length + 1).trim();
|
|
29
|
+
// The text can go on over the lines below, indented: after a block marker like > or |, or as a long line that wraps.
|
|
30
|
+
const more = [];
|
|
31
|
+
for (const l of lines.slice(at + 1)) {
|
|
32
|
+
if (l.trim() && !/^[ \t]/.test(l))
|
|
33
|
+
break;
|
|
34
|
+
more.push(l.trim());
|
|
35
|
+
}
|
|
36
|
+
const value = [/^[>|][+-]?\d?$/.test(first) ? "" : first, ...more].filter(Boolean).join(" ");
|
|
37
|
+
return value.replace(/^(["'])(.*)\1$/, "$2");
|
|
38
|
+
};
|
|
39
|
+
const body = markdown.replace(/^---\r?\n[\s\S]*?\r?\n---/, "");
|
|
40
|
+
const firstLine = body.split("\n").map((l) => l.replace(/^#+\s*/, "").trim()).find(Boolean) ?? "";
|
|
41
|
+
return {
|
|
42
|
+
name: line(field("name"), 80) || line(folder.split("/").pop() ?? "skill", 80),
|
|
43
|
+
description: line(field("description"), 400) || line(firstLine, 400),
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* An empty folder in the checkout for the copies. The checkout holds the pull request's own files,
|
|
48
|
+
* so it could carry a link or a file at this very place: to send the copies somewhere else on the
|
|
49
|
+
* machine, to put files of its own next to a skill, or to stop the copy and so switch the team's
|
|
50
|
+
* skills off. Whatever the pull request put there is removed first, and a link is never written through.
|
|
51
|
+
*/
|
|
52
|
+
function emptySkillsFolder(checkout) {
|
|
53
|
+
const root = join(checkout, ".mergelight");
|
|
54
|
+
const there = lstatSync(root, { throwIfNoEntry: false });
|
|
55
|
+
// Removing a link or a file removes that entry alone, never what a link points at.
|
|
56
|
+
if (there && !there.isDirectory())
|
|
57
|
+
rmSync(root, { force: true });
|
|
58
|
+
const dir = join(root, "skills");
|
|
59
|
+
rmSync(dir, { recursive: true, force: true });
|
|
60
|
+
mkdirSync(dir, { recursive: true });
|
|
61
|
+
return realpathSync(dir) === join(realpathSync(checkout), ".mergelight", "skills") ? dir : null;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Copies the team's picked skill folders into the checkout, from the base branch (the commit in `base`) and
|
|
65
|
+
* never from the pull request. A pull request can change a skill's file, and its author must not be able to
|
|
66
|
+
* tell the reviewer what to do that way: the copy the reviewer reads is the one the team already merged.
|
|
67
|
+
*
|
|
68
|
+
* Only ordinary files are copied. A link in the folder could point anywhere, so it is left out.
|
|
69
|
+
*/
|
|
70
|
+
export async function importSkills(mirror, base, checkout, folders, git = (args) => run("git", ["-C", mirror, ...args], { timeoutMs: GIT_TIMEOUT_MS }), now = Date.now) {
|
|
71
|
+
const skills = [];
|
|
72
|
+
const into = emptySkillsFolder(checkout);
|
|
73
|
+
if (!into)
|
|
74
|
+
return skills;
|
|
75
|
+
const deadline = now() + IMPORT_TIMEOUT_MS;
|
|
76
|
+
for (const [index, folder] of folders.filter(isSkillPath).slice(0, MAX_SKILLS).entries()) {
|
|
77
|
+
if (now() > deadline)
|
|
78
|
+
break;
|
|
79
|
+
const listed = await git(["ls-tree", "-r", "-z", base, "--", `${folder}/`]);
|
|
80
|
+
if (listed.code !== 0)
|
|
81
|
+
continue;
|
|
82
|
+
const files = listed.stdout
|
|
83
|
+
.split("\0")
|
|
84
|
+
.filter(Boolean)
|
|
85
|
+
.map((entry) => /^(\d{6}) (\w+) ([0-9a-f]{40,64})\t([\s\S]+)$/.exec(entry))
|
|
86
|
+
.filter((m) => Boolean(m) && m[2] === "blob" && (m[1] === "100644" || m[1] === "100755"))
|
|
87
|
+
.map((m) => ({ sha: m[3], path: m[4] }))
|
|
88
|
+
.filter((f) => f.path.startsWith(`${folder}/`) && isSkillPath(f.path));
|
|
89
|
+
const main = files.find((f) => f.path === `${folder}/SKILL.md`);
|
|
90
|
+
// No SKILL.md on the base branch: there is no skill there yet, whatever the pull request adds.
|
|
91
|
+
// A folder that is a link to another folder has none either: git lists the link, not what is behind it.
|
|
92
|
+
if (!main)
|
|
93
|
+
continue;
|
|
94
|
+
const target = join(".mergelight", "skills", String(index + 1));
|
|
95
|
+
let total = 0;
|
|
96
|
+
let markdown = "";
|
|
97
|
+
for (const file of [main, ...files.filter((f) => f !== main)].slice(0, MAX_FILES)) {
|
|
98
|
+
if (now() > deadline)
|
|
99
|
+
break;
|
|
100
|
+
const sized = await git(["cat-file", "-s", file.sha]);
|
|
101
|
+
const size = sized.code === 0 ? Number(sized.stdout.trim()) : NaN;
|
|
102
|
+
const read = Number.isFinite(size) && size <= MAX_FILE_BYTES && total + size <= MAX_SKILL_BYTES ? await git(["cat-file", "blob", file.sha]) : null;
|
|
103
|
+
if (!read || read.code !== 0) {
|
|
104
|
+
if (file === main)
|
|
105
|
+
break;
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
const content = read.stdout;
|
|
109
|
+
// Not text: a picture, or a file in another encoding. It was read as text, so a copy would be a broken one.
|
|
110
|
+
if (content.includes("\uFFFD") && file !== main)
|
|
111
|
+
continue;
|
|
112
|
+
total += size;
|
|
113
|
+
if (file === main)
|
|
114
|
+
markdown = content;
|
|
115
|
+
// Without its SKILL.md there is no skill, so its other files aren't read or copied either.
|
|
116
|
+
if (!markdown)
|
|
117
|
+
break;
|
|
118
|
+
const dest = join(into, String(index + 1), file.path.slice(folder.length + 1));
|
|
119
|
+
mkdirSync(dirname(dest), { recursive: true });
|
|
120
|
+
writeFileSync(dest, content);
|
|
121
|
+
}
|
|
122
|
+
if (!markdown)
|
|
123
|
+
continue;
|
|
124
|
+
skills.push({ ...describeSkill(markdown, folder), read: `${target}/SKILL.md` });
|
|
125
|
+
}
|
|
126
|
+
return skills;
|
|
127
|
+
}
|
package/dist/workspace.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { existsSync, mkdirSync, mkdtempSync, rmSync, statSync } from "node:fs";
|
|
1
|
+
import { existsSync, lstatSync, mkdirSync, mkdtempSync, rmSync, statSync } from "node:fs";
|
|
2
2
|
import { homedir, tmpdir } from "node:os";
|
|
3
|
-
import { join } from "node:path";
|
|
3
|
+
import { join, posix } from "node:path";
|
|
4
4
|
import { run, runOk } from "./run.js";
|
|
5
|
+
import { importSkills, SKILL_GIT_TIMEOUT_MS, SKILL_IMPORT_TIMEOUT_MS } from "./skills.js";
|
|
5
6
|
/** Lockfiles and generated files are left out of the diff the model sees. */
|
|
6
7
|
const EXCLUDES = [
|
|
7
8
|
"package-lock.json",
|
|
@@ -30,6 +31,172 @@ export function cacheDir() {
|
|
|
30
31
|
function git(args, cwd) {
|
|
31
32
|
return runOk("git", ["-c", "credential.helper=", "-c", "credential.helper=!gh auth git-credential", ...args], { cwd, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } });
|
|
32
33
|
}
|
|
34
|
+
/**
|
|
35
|
+
* Mergelight's own folder in the checkout, for the files it writes there: a diff too large for the
|
|
36
|
+
* prompt, and the team's skills. The checkout holds the pull request's files, so the pull request
|
|
37
|
+
* could have put a link at one of those names, to make a write land somewhere else on the machine.
|
|
38
|
+
* A link or a file in the way is removed, never written through.
|
|
39
|
+
*/
|
|
40
|
+
export function ownFolder(checkout) {
|
|
41
|
+
const dir = join(checkout, ".mergelight");
|
|
42
|
+
if (lstatSync(dir, { throwIfNoEntry: false })?.isDirectory() === false)
|
|
43
|
+
rmSync(dir, { force: true });
|
|
44
|
+
mkdirSync(dir, { recursive: true });
|
|
45
|
+
// Removing a link removes the link alone, not what it points at.
|
|
46
|
+
for (const name of ["pr.diff", "skills"])
|
|
47
|
+
rmSync(join(dir, name), { recursive: true, force: true });
|
|
48
|
+
return dir;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Skill folders Codex finds by itself and offers to the model. In the checkout they are the pull
|
|
52
|
+
* request's, so its author could plant one that tells the reviewers what to skip. Codex has a switch
|
|
53
|
+
* to stop that, but not every version has it, so the folders go. The diff still shows them.
|
|
54
|
+
*/
|
|
55
|
+
export const AGENT_SKILL_FOLDERS = [".agents/skills", ".codex/skills"];
|
|
56
|
+
export function removeAgentSkills(checkout) {
|
|
57
|
+
for (const folder of AGENT_SKILL_FOLDERS) {
|
|
58
|
+
const parent = join(checkout, folder.split("/")[0]);
|
|
59
|
+
const kind = lstatSync(parent, { throwIfNoEntry: false });
|
|
60
|
+
if (!kind)
|
|
61
|
+
continue;
|
|
62
|
+
// .codex or .agents can be a link the pull request made, to a folder anywhere on the machine.
|
|
63
|
+
// Going through it would delete that folder's skills. A link or a file goes, alone.
|
|
64
|
+
if (!kind.isDirectory()) {
|
|
65
|
+
rmSync(parent, { force: true });
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
// rmSync removes a link at this name without following it.
|
|
69
|
+
rmSync(join(parent, "skills"), { recursive: true, force: true });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Copies the team's skills, and never lets that stop or hold up a review. The mirror has no file
|
|
74
|
+
* contents of its own, so reading a skill the pull request changed asks GitHub for it: with the
|
|
75
|
+
* same login as every other git call here, never with a prompt, and never for long.
|
|
76
|
+
*/
|
|
77
|
+
async function skillsFor(mirror, base, checkout, folders) {
|
|
78
|
+
if (!folders.length)
|
|
79
|
+
return [];
|
|
80
|
+
const gitInMirror = (args) => run("git", ["-c", "credential.helper=", "-c", "credential.helper=!gh auth git-credential", "-C", mirror, ...args], {
|
|
81
|
+
env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
|
|
82
|
+
timeoutMs: SKILL_GIT_TIMEOUT_MS,
|
|
83
|
+
});
|
|
84
|
+
let timer;
|
|
85
|
+
// A last stop, for a git process that doesn't end even when told to.
|
|
86
|
+
const gaveUp = new Promise((resolve) => {
|
|
87
|
+
timer = setTimeout(() => resolve([]), SKILL_IMPORT_TIMEOUT_MS + 2 * SKILL_GIT_TIMEOUT_MS);
|
|
88
|
+
timer.unref();
|
|
89
|
+
});
|
|
90
|
+
try {
|
|
91
|
+
return await Promise.race([importSkills(mirror, base, checkout, folders, gitInMirror).catch(() => []), gaveUp]);
|
|
92
|
+
}
|
|
93
|
+
finally {
|
|
94
|
+
clearTimeout(timer);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/** The root instruction files whose conventions the reviewers follow, read from the base branch. */
|
|
98
|
+
export const CONVENTION_FILES = ["AGENTS.md", "CLAUDE.md", "CONTRIBUTING.md", ".github/CONTRIBUTING.md", "docs/CONTRIBUTING.md", ".github/copilot-instructions.md"];
|
|
99
|
+
/** Per file, so one long file can't fill every prompt. */
|
|
100
|
+
export const MAX_CONVENTION_CHARS = 12_000;
|
|
101
|
+
/** All files together, and how many. */
|
|
102
|
+
export const MAX_CONVENTIONS_CHARS = 40_000;
|
|
103
|
+
export const MAX_CONVENTION_FILES = 12;
|
|
104
|
+
/** A file larger than this isn't read at all. */
|
|
105
|
+
const MAX_CONVENTION_BYTES = 256_000;
|
|
106
|
+
/** Which instruction files apply: the root ones, AGENTS.md or CLAUDE.md in a folder above a changed file, and .github/instructions. */
|
|
107
|
+
export function conventionPaths(all, changedPaths) {
|
|
108
|
+
const folders = new Set();
|
|
109
|
+
for (const changed of changedPaths) {
|
|
110
|
+
const parts = changed.split("/").slice(0, -1);
|
|
111
|
+
for (let i = 1; i <= parts.length; i++)
|
|
112
|
+
folders.add(parts.slice(0, i).join("/"));
|
|
113
|
+
}
|
|
114
|
+
const present = new Set(all);
|
|
115
|
+
const root = CONVENTION_FILES.filter((p) => present.has(p));
|
|
116
|
+
const github = all.filter((p) => p.startsWith(".github/instructions/") && p.endsWith(".instructions.md")).sort();
|
|
117
|
+
const nested = all
|
|
118
|
+
.filter((p) => {
|
|
119
|
+
const at = p.lastIndexOf("/");
|
|
120
|
+
return at > 0 && ["AGENTS.md", "CLAUDE.md"].includes(p.slice(at + 1)) && folders.has(p.slice(0, at));
|
|
121
|
+
})
|
|
122
|
+
// Closest to the root first: a folder's file comes before the ones in its subfolders.
|
|
123
|
+
.sort((a, b) => a.split("/").length - b.split("/").length || a.localeCompare(b));
|
|
124
|
+
// The rules closest to the changed code come before .github/instructions, so they aren't the ones crowded out.
|
|
125
|
+
return [...root, ...nested, ...github];
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* The team's instruction files as the base branch has them. The checkout is the pull request's, and
|
|
129
|
+
* its author could add or rewrite AGENTS.md there to steer the reviewers. A file that is a link is
|
|
130
|
+
* followed once, to a file inside the repository. A file that is missing, too large, or can't be
|
|
131
|
+
* read in time is left out: it never stops a review.
|
|
132
|
+
*/
|
|
133
|
+
export async function conventionsFor(mirror, base, changedPaths = []) {
|
|
134
|
+
const git = (args) => run("git", ["-c", "credential.helper=", "-c", "credential.helper=!gh auth git-credential", "-C", mirror, ...args], {
|
|
135
|
+
env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
|
|
136
|
+
timeoutMs: SKILL_GIT_TIMEOUT_MS,
|
|
137
|
+
}).catch(() => null);
|
|
138
|
+
const listed = await git(["ls-tree", "-r", "-z", "--full-tree", base]);
|
|
139
|
+
if (listed?.code !== 0)
|
|
140
|
+
return [];
|
|
141
|
+
const tree = new Map();
|
|
142
|
+
for (const entry of listed.stdout.split("\0")) {
|
|
143
|
+
const m = /^(\d{6}) blob ([0-9a-f]{40,64})\t([\s\S]+)$/.exec(entry);
|
|
144
|
+
if (m)
|
|
145
|
+
tree.set(m[3], { mode: m[1], sha: m[2] });
|
|
146
|
+
}
|
|
147
|
+
const blob = async (sha) => {
|
|
148
|
+
const sized = await git(["cat-file", "-s", sha]);
|
|
149
|
+
if (sized?.code !== 0 || !(Number(sized.stdout.trim()) <= MAX_CONVENTION_BYTES))
|
|
150
|
+
return null;
|
|
151
|
+
const read = await git(["cat-file", "blob", sha]);
|
|
152
|
+
return read?.code === 0 ? read.stdout : null;
|
|
153
|
+
};
|
|
154
|
+
const read = async (path) => {
|
|
155
|
+
let file = tree.get(path);
|
|
156
|
+
if (file?.mode === "120000") {
|
|
157
|
+
// A link: git keeps the target's path as its content.
|
|
158
|
+
const target = (await blob(file.sha))?.trim() ?? "";
|
|
159
|
+
const resolved = posix.normalize(posix.join(posix.dirname(path), target));
|
|
160
|
+
if (!target || target.startsWith("/") || resolved === ".." || resolved.startsWith("../"))
|
|
161
|
+
return null;
|
|
162
|
+
file = tree.get(resolved);
|
|
163
|
+
}
|
|
164
|
+
if (!file || (file.mode !== "100644" && file.mode !== "100755"))
|
|
165
|
+
return null;
|
|
166
|
+
const text = (await blob(file.sha))?.trim();
|
|
167
|
+
return text ? { path, sha: file.sha, text } : null;
|
|
168
|
+
};
|
|
169
|
+
const found = await Promise.all(conventionPaths([...tree.keys()], changedPaths).slice(0, MAX_CONVENTION_FILES * 2).map(read));
|
|
170
|
+
const conventions = [];
|
|
171
|
+
const seen = new Set();
|
|
172
|
+
let total = 0;
|
|
173
|
+
for (const f of found) {
|
|
174
|
+
// AGENTS.md and CLAUDE.md are often one file and a link to it: the text goes in once.
|
|
175
|
+
if (!f || seen.has(f.sha) || conventions.length >= MAX_CONVENTION_FILES)
|
|
176
|
+
continue;
|
|
177
|
+
const room = Math.min(MAX_CONVENTION_CHARS, MAX_CONVENTIONS_CHARS - total);
|
|
178
|
+
if (room <= 0)
|
|
179
|
+
break;
|
|
180
|
+
seen.add(f.sha);
|
|
181
|
+
conventions.push({ path: f.path, text: f.text.slice(0, room), truncated: f.text.length > room });
|
|
182
|
+
total += Math.min(f.text.length, room);
|
|
183
|
+
}
|
|
184
|
+
return conventions;
|
|
185
|
+
}
|
|
186
|
+
/** The answer, or the fallback once the time is up, for work that must never hold up a review. */
|
|
187
|
+
async function withDeadline(work, ms, fallback) {
|
|
188
|
+
let timer;
|
|
189
|
+
const gaveUp = new Promise((resolve) => {
|
|
190
|
+
timer = setTimeout(() => resolve(fallback), ms);
|
|
191
|
+
timer.unref();
|
|
192
|
+
});
|
|
193
|
+
try {
|
|
194
|
+
return await Promise.race([work.catch(() => fallback), gaveUp]);
|
|
195
|
+
}
|
|
196
|
+
finally {
|
|
197
|
+
clearTimeout(timer);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
33
200
|
async function hasCommit(mirror, sha) {
|
|
34
201
|
const r = await run("git", ["-C", mirror, "cat-file", "-e", `${sha}^{commit}`]);
|
|
35
202
|
return r.code === 0;
|
|
@@ -67,7 +234,7 @@ async function withLock(dir, fn) {
|
|
|
67
234
|
* Keeps a blobless bare mirror of the repository in the cache, fetches the PR,
|
|
68
235
|
* and checks out the commit under review in a temporary worktree.
|
|
69
236
|
*/
|
|
70
|
-
export async function prepareWorkspace(pr, at) {
|
|
237
|
+
export async function prepareWorkspace(pr, at, skillFolders = []) {
|
|
71
238
|
const mirror = join(cacheDir(), "repos", pr.owner, `${pr.repo}.git`);
|
|
72
239
|
mkdirSync(join(cacheDir(), "repos", pr.owner), { recursive: true });
|
|
73
240
|
if (!existsSync(mirror)) {
|
|
@@ -117,8 +284,19 @@ export async function prepareWorkspace(pr, at) {
|
|
|
117
284
|
const [added, removed, path] = line.split("\t");
|
|
118
285
|
return { path: path ?? "", added: Number(added) || 0, removed: Number(removed) || 0 };
|
|
119
286
|
});
|
|
287
|
+
// -z gives each path as it is, ended by a NUL. Without it git puts quotes around a name with odd characters in it.
|
|
288
|
+
const touchedPaths = (await git(["diff", "--name-only", "-z", "--no-renames", "--no-color", "--no-ext-diff", range], mirror)).stdout.split("\0").filter(Boolean);
|
|
120
289
|
const dir = mkdtempSync(join(tmpdir(), `mergelight-${pr.repo}-${pr.number}-`));
|
|
121
290
|
await git(["worktree", "add", "--quiet", "--detach", dir, headSha], mirror);
|
|
291
|
+
ownFolder(dir);
|
|
292
|
+
removeAgentSkills(dir);
|
|
293
|
+
// From the base branch as it is now: what the team merged. Not from the pull request, and not from
|
|
294
|
+
// the commit it branched from either. Its author picks that commit, and could pick one from
|
|
295
|
+
// before a skill was written or tightened.
|
|
296
|
+
// The same goes for the instruction files.
|
|
297
|
+
const teamBase = haveBaseBranch ? `refs/mergelight/base/${pr.baseRef}` : baseCandidate;
|
|
298
|
+
const skills = await skillsFor(mirror, teamBase, dir, skillFolders);
|
|
299
|
+
const conventions = await withDeadline(conventionsFor(mirror, teamBase, touchedPaths), SKILL_IMPORT_TIMEOUT_MS + 2 * SKILL_GIT_TIMEOUT_MS, []);
|
|
122
300
|
return {
|
|
123
301
|
dir,
|
|
124
302
|
mergeBase,
|
|
@@ -127,6 +305,9 @@ export async function prepareWorkspace(pr, at) {
|
|
|
127
305
|
diffStat,
|
|
128
306
|
diffTruncated: diff.length > MAX_INLINE_DIFF,
|
|
129
307
|
changedFiles,
|
|
308
|
+
touchedPaths,
|
|
309
|
+
skills,
|
|
310
|
+
conventions,
|
|
130
311
|
cleanup: async () => {
|
|
131
312
|
await run("git", ["-C", mirror, "worktree", "remove", "--force", dir]);
|
|
132
313
|
rmSync(dir, { recursive: true, force: true });
|