@mergelight/cli 0.0.0-stage → 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.
Files changed (43) hide show
  1. package/LICENSE.md +110 -0
  2. package/README.md +113 -2
  3. package/dist/action-source.js +107 -0
  4. package/dist/checks.js +108 -0
  5. package/dist/cli.js +296 -0
  6. package/dist/cloud.js +330 -0
  7. package/dist/connect-claude.js +157 -0
  8. package/dist/connect.js +319 -0
  9. package/dist/github.js +65 -0
  10. package/dist/init.js +92 -0
  11. package/dist/mcp/findings.js +252 -0
  12. package/dist/mcp/server.js +168 -0
  13. package/dist/prompt.js +503 -0
  14. package/dist/providers/claude.js +102 -0
  15. package/dist/providers/codex.js +251 -0
  16. package/dist/providers/index.js +8 -0
  17. package/dist/publish/api.js +63 -0
  18. package/dist/publish/closed.js +88 -0
  19. package/dist/publish/diff-lines.js +50 -0
  20. package/dist/publish/handled.js +98 -0
  21. package/dist/publish/markdown.js +233 -0
  22. package/dist/publish/publish.js +397 -0
  23. package/dist/publish/state.js +82 -0
  24. package/dist/publish/team-checks.js +72 -0
  25. package/dist/render.js +129 -0
  26. package/dist/review.js +366 -0
  27. package/dist/run.js +57 -0
  28. package/dist/schema.js +155 -0
  29. package/dist/setup.js +180 -0
  30. package/dist/skills.js +127 -0
  31. package/dist/types.js +1 -0
  32. package/dist/update.js +36 -0
  33. package/dist/workspace.js +318 -0
  34. package/package.json +36 -4
  35. package/scripts/app-token.mjs +69 -0
  36. package/scripts/mask-login.mjs +26 -0
  37. package/scripts/refresh-login.mjs +171 -0
  38. package/scripts/save-claude-login.sh +22 -0
  39. package/scripts/save-login.sh +30 -0
  40. package/skills/mergelight/SKILL.md +66 -0
  41. package/templates/mergelight-approve.yml +21 -0
  42. package/templates/mergelight-refresh.yml +23 -0
  43. package/templates/mergelight.yml +42 -0
package/dist/run.js ADDED
@@ -0,0 +1,57 @@
1
+ import { spawn } from "node:child_process";
2
+ export class CommandError extends Error {
3
+ command;
4
+ result;
5
+ constructor(command, result) {
6
+ const detail = (result.stderr || result.stdout).trim().split("\n").slice(-8).join("\n");
7
+ super(`${command} failed with exit code ${result.code}${detail ? `:\n${detail}` : ""}`);
8
+ this.command = command;
9
+ this.result = result;
10
+ }
11
+ }
12
+ /** Run a command without a shell. Resolves with its output, whatever the exit code. */
13
+ export function run(cmd, args, opts = {}) {
14
+ return new Promise((resolve, reject) => {
15
+ const child = spawn(cmd, args, {
16
+ cwd: opts.cwd,
17
+ env: opts.env ?? process.env,
18
+ stdio: ["pipe", "pipe", "pipe"],
19
+ });
20
+ let stdout = "";
21
+ let stderr = "";
22
+ let timer;
23
+ if (opts.timeoutMs) {
24
+ timer = setTimeout(() => child.kill("SIGTERM"), opts.timeoutMs);
25
+ }
26
+ child.stdout.setEncoding("utf8");
27
+ child.stderr.setEncoding("utf8");
28
+ child.stdout.on("data", (chunk) => {
29
+ stdout += chunk;
30
+ opts.onStdout?.(chunk);
31
+ });
32
+ child.stderr.on("data", (chunk) => {
33
+ stderr += chunk;
34
+ });
35
+ child.on("error", (err) => {
36
+ if (timer)
37
+ clearTimeout(timer);
38
+ reject(err);
39
+ });
40
+ child.on("close", (code, signal) => {
41
+ if (timer)
42
+ clearTimeout(timer);
43
+ resolve({ stdout, stderr, code: code ?? (signal ? 128 : 1) });
44
+ });
45
+ child.stdin.on("error", () => {
46
+ /* the process may exit before reading all input */
47
+ });
48
+ child.stdin.end(opts.input ?? "");
49
+ });
50
+ }
51
+ /** Run a command and throw a CommandError if it exits non-zero. */
52
+ export async function runOk(cmd, args, opts = {}) {
53
+ const result = await run(cmd, args, opts);
54
+ if (result.code !== 0)
55
+ throw new CommandError(`${cmd} ${args.slice(0, 3).join(" ")}`, result);
56
+ return result;
57
+ }
package/dist/schema.js ADDED
@@ -0,0 +1,155 @@
1
+ /**
2
+ * JSON Schema for the model's final answer. It is passed to the provider as a
3
+ * structured output schema, so it follows the strict rules: every object lists
4
+ * all its properties as required and allows nothing else.
5
+ */
6
+ export const candidateSchema = {
7
+ type: "object",
8
+ additionalProperties: false,
9
+ required: ["candidates"],
10
+ properties: {
11
+ candidates: {
12
+ type: "array",
13
+ items: {
14
+ type: "object",
15
+ additionalProperties: false,
16
+ required: ["title", "file", "line", "end_line", "scenario", "impact", "evidence"],
17
+ properties: {
18
+ title: { type: "string" },
19
+ file: { type: "string" },
20
+ line: { type: "integer" },
21
+ end_line: { type: "integer" },
22
+ scenario: { type: "string" },
23
+ impact: { type: "string" },
24
+ evidence: { type: "string" },
25
+ },
26
+ },
27
+ },
28
+ },
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
+ };
54
+ export const reviewSchema = {
55
+ type: "object",
56
+ additionalProperties: false,
57
+ required: ["summary", "findings", "rejected", "top"],
58
+ properties: {
59
+ top: {
60
+ type: "array",
61
+ description: "Up to 3 finding numbers, counting from 1 in the order of findings, that a senior reviewer would hold the merge for, most important first.",
62
+ items: { type: "integer" },
63
+ },
64
+ rejected: {
65
+ type: "array",
66
+ description: "Candidates you rejected, with the reason.",
67
+ items: {
68
+ type: "object",
69
+ additionalProperties: false,
70
+ required: ["candidate", "reason"],
71
+ properties: {
72
+ candidate: { type: "string", description: "The candidate id, like C3." },
73
+ reason: { type: "string" },
74
+ },
75
+ },
76
+ },
77
+ summary: {
78
+ type: "string",
79
+ description: "Two plain sentences for someone who does not read code: what the pull request does, and whether it looks safe to merge.",
80
+ },
81
+ findings: {
82
+ type: "array",
83
+ items: {
84
+ type: "object",
85
+ additionalProperties: false,
86
+ required: [
87
+ "class",
88
+ "title",
89
+ "file",
90
+ "line",
91
+ "end_line",
92
+ "how_it_happens",
93
+ "likelihood",
94
+ "severity",
95
+ "what_breaks",
96
+ "fix",
97
+ "fix_cost",
98
+ "recommendation",
99
+ "verdict",
100
+ "confidence",
101
+ "same_as",
102
+ ],
103
+ properties: {
104
+ class: { type: "string", enum: ["bug", "risk", "hardening"] },
105
+ title: { type: "string", description: "Under 80 characters, plain words." },
106
+ file: { type: "string", description: "Path relative to the repository root." },
107
+ line: { type: "integer", description: "First line of the problem in the head version of the file." },
108
+ end_line: { type: "integer", description: "Last line of the problem in the head version of the file." },
109
+ how_it_happens: { type: "string", description: "The concrete trigger, in one or two plain sentences." },
110
+ likelihood: { type: "string", enum: ["common", "plausible", "rare", "theoretical"] },
111
+ severity: {
112
+ type: "string",
113
+ enum: ["major", "minor"],
114
+ description: "major: breaks something, loses data or money, or exposes data. minor: a small but real visible problem.",
115
+ },
116
+ what_breaks: { type: "string", description: "The user-visible or data consequence." },
117
+ fix: { type: "string", description: "The smallest fix that solves it, in one or two sentences." },
118
+ fix_cost: { type: "string", enum: ["trivial", "small", "medium", "large"] },
119
+ recommendation: { type: "string", enum: ["fix", "decide", "leave"] },
120
+ verdict: { type: "string", description: "One short plain sentence a non-engineer understands." },
121
+ confidence: { type: "string", enum: ["high", "medium", "low"] },
122
+ same_as: {
123
+ type: ["string", "null"],
124
+ description: "The id of the problem from an earlier review that this finding is, or null.",
125
+ },
126
+ },
127
+ },
128
+ },
129
+ },
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/setup.js ADDED
@@ -0,0 +1,180 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ import { createInterface } from "node:readline/promises";
6
+ import { fileURLToPath } from "node:url";
7
+ import { run, runOk } from "./run.js";
8
+ export const INSTALL_URL = "https://github.com/apps/mergelight-ai/installations/new";
9
+ const SECRET = "CODEX_AUTH_JSON";
10
+ const BRANCH = "mergelight-setup";
11
+ const REFRESH = "mergelight-refresh.yml";
12
+ const WORKFLOWS = ["mergelight.yml", "mergelight-approve.yml", REFRESH];
13
+ const SKIP_MARKER = "github.event.pull_request.head.repo.full_name == github.repository";
14
+ const ACTION = "mergelightai/mergelight";
15
+ /** The note in each template saying why it isn't pinned, which stops being true once it is. */
16
+ const NOT_PINNED_NOTE = /^[ \t]*# Not pinned, on purpose[^\n]*\n(?:[ \t]*#[^\n]*\n)*/m;
17
+ /** The workflow files, adjusted for this repository, and pinned to a release if one is given. */
18
+ export function workflowFiles(skipBranches = [], pin) {
19
+ const dir = join(dirname(fileURLToPath(import.meta.url)), "..", "templates");
20
+ return WORKFLOWS.map((name) => {
21
+ let content = readFileSync(join(dir, name), "utf8");
22
+ if (name === "mergelight.yml" && skipBranches.length) {
23
+ if (!content.includes(SKIP_MARKER))
24
+ throw new Error(`${name} has changed: can't add the branches to skip.`);
25
+ // GitHub expressions quote strings with single quotes, doubled inside, and fromJSON needs double quotes.
26
+ const json = JSON.stringify(skipBranches).replace(/'/g, "''");
27
+ // A function, so a $ in a branch name stays a $.
28
+ content = content.replace(SKIP_MARKER, () => `${SKIP_MARKER} &&\n !contains(fromJSON('${json}'), github.head_ref)`);
29
+ }
30
+ if (pin) {
31
+ if (!content.includes(`${ACTION}@v0`))
32
+ throw new Error(`${name} has changed: can't pin it.`);
33
+ content = content.replace(NOT_PINNED_NOTE, (note) => {
34
+ const indent = note.match(/^[ \t]*/)[0];
35
+ return `${indent}# Pinned to a release, so new code only runs here once you merge an update.\n${indent}# Mergelight says on your pull requests when a new version is out.\n`;
36
+ }).replaceAll(`${ACTION}@v0`, () => `${ACTION}@${pin.sha} # ${pin.tag}`);
37
+ }
38
+ return { name, content };
39
+ });
40
+ }
41
+ /** The latest release, as a commit. */
42
+ async function latestPin(deps) {
43
+ const tag = (await deps.gh(["api", `repos/${ACTION}/releases/latest`, "--jq", ".tag_name"])).trim();
44
+ const sha = (await deps.gh(["api", `repos/${ACTION}/commits/${tag}`, "--jq", ".sha"])).trim();
45
+ return { sha, tag };
46
+ }
47
+ /** A ChatGPT login is only useful in CI if it can refresh itself. */
48
+ export function checkAuthJson(raw) {
49
+ let auth;
50
+ try {
51
+ auth = JSON.parse(raw);
52
+ }
53
+ catch {
54
+ throw new Error("Codex wrote a login file that can't be read. Run setup again.");
55
+ }
56
+ if (auth.auth_mode !== "chatgpt" || !auth.tokens?.refresh_token) {
57
+ throw new Error("That wasn't a ChatGPT login. Log in with your ChatGPT account, or use openai-api-key in the workflow.");
58
+ }
59
+ }
60
+ async function hasFile(deps, repo, path, ref) {
61
+ try {
62
+ const out = await deps.gh(["api", `repos/${repo}/contents/${path}?ref=${encodeURIComponent(ref)}`]);
63
+ const file = JSON.parse(out);
64
+ return { sha: file.sha, content: Buffer.from(file.content, "base64").toString("utf8") };
65
+ }
66
+ catch {
67
+ return null;
68
+ }
69
+ }
70
+ /** Puts the workflows on a branch and opens a pull request. Returns its URL, or null if there's nothing to add. */
71
+ async function openWorkflowPr(deps, opts, base) {
72
+ const { repo } = opts;
73
+ const files = workflowFiles(opts.skipBranches, opts.pin !== false ? await latestPin(deps) : undefined);
74
+ const missing = [];
75
+ for (const f of files) {
76
+ const onBase = await hasFile(deps, repo, `.github/workflows/${f.name}`, base);
77
+ if (onBase?.content !== f.content)
78
+ missing.push(f);
79
+ }
80
+ if (!missing.length)
81
+ return null;
82
+ const baseSha = (await deps.gh(["api", `repos/${repo}/git/ref/heads/${base}`, "--jq", ".object.sha"])).trim();
83
+ try {
84
+ await deps.gh(["api", "-X", "POST", `repos/${repo}/git/refs`, "-f", `ref=refs/heads/${BRANCH}`, "-f", `sha=${baseSha}`]);
85
+ }
86
+ catch {
87
+ // Left by an earlier setup. The files below are brought up to date on it.
88
+ }
89
+ for (const f of missing) {
90
+ const path = `.github/workflows/${f.name}`;
91
+ const existing = await hasFile(deps, repo, path, BRANCH);
92
+ if (existing?.content === f.content)
93
+ continue;
94
+ await deps.gh([
95
+ "api", "-X", "PUT", `repos/${repo}/contents/${path}`,
96
+ "-f", `message=chore(ci): add ${f.name}`,
97
+ "-f", `content=${Buffer.from(f.content).toString("base64")}`,
98
+ "-f", `branch=${BRANCH}`,
99
+ ...(existing ? ["-f", `sha=${existing.sha}`] : []),
100
+ ]);
101
+ }
102
+ const open = JSON.parse(await deps.gh(["api", `repos/${repo}/pulls?head=${repo.split("/")[0]}:${BRANCH}&state=open`]));
103
+ if (open[0])
104
+ return open[0].html_url;
105
+ const created = await deps.gh([
106
+ "api", "-X", "POST", `repos/${repo}/pulls`,
107
+ "-f", "title=chore(ci): add Mergelight review",
108
+ "-f", `head=${BRANCH}`,
109
+ "-f", `base=${base}`,
110
+ "-f", "body=Adds Mergelight's code review. This pull request reviews itself, so you can see it working before you merge.",
111
+ "--jq", ".html_url",
112
+ ]);
113
+ return created.trim();
114
+ }
115
+ /** Sets up one repository: the app, the Codex login, then a pull request with the workflows. */
116
+ export async function setup(opts, deps) {
117
+ const { repo, yes } = opts;
118
+ const info = JSON.parse(await deps.gh(["api", `repos/${repo}`]));
119
+ const base = opts.base ?? info.default_branch;
120
+ deps.log(`1 of 3: install the Mergelight AI app on ${repo}`);
121
+ if (yes) {
122
+ deps.log(` Skipped asking. If it isn't installed: ${INSTALL_URL}`);
123
+ }
124
+ else {
125
+ await deps.open(INSTALL_URL);
126
+ await deps.confirm(` Installed? Press Enter to continue. ${INSTALL_URL} `);
127
+ }
128
+ deps.log("2 of 3: Codex login");
129
+ const secrets = JSON.parse(await deps.gh(["secret", "list", "--repo", repo, "--json", "name"]));
130
+ if (secrets.some((s) => s.name === SECRET) && !opts.relogin) {
131
+ deps.log(` ${repo} already has one.`);
132
+ }
133
+ else {
134
+ const auth = await deps.codexLogin();
135
+ checkAuthJson(auth);
136
+ await deps.gh(["secret", "set", SECRET, "--repo", repo], auth);
137
+ deps.log(` Saved. It refreshes itself from now on.`);
138
+ }
139
+ deps.log(`3 of 3: add the workflows to ${base}`);
140
+ const url = await openWorkflowPr(deps, opts, base);
141
+ if (url)
142
+ deps.log(`\nDone. Merge this to turn it on, it's reviewing itself now:\n${url}`);
143
+ else
144
+ deps.log(`\nDone. ${repo} already has the workflows on ${base}.`);
145
+ return 0;
146
+ }
147
+ /** Logs in with a separate Codex home, so CI never shares a login with your own machine. */
148
+ export async function codexLogin() {
149
+ const home = mkdtempSync(join(tmpdir(), "mergelight-codex-login-"));
150
+ try {
151
+ writeFileSync(join(home, "config.toml"), 'cli_auth_credentials_store = "file"\n');
152
+ const code = await new Promise((resolve, reject) => {
153
+ const child = spawn("codex", ["login"], { stdio: "inherit", env: { ...process.env, CODEX_HOME: home } });
154
+ child.on("error", reject);
155
+ child.on("close", (c) => resolve(c ?? 1));
156
+ });
157
+ const file = join(home, "auth.json");
158
+ if (code !== 0 || !existsSync(file))
159
+ throw new Error("Codex login didn't finish.");
160
+ return readFileSync(file, "utf8");
161
+ }
162
+ finally {
163
+ rmSync(home, { recursive: true, force: true });
164
+ }
165
+ }
166
+ export function realDeps() {
167
+ return {
168
+ gh: async (args, input) => (await runOk("gh", args, input === undefined ? {} : { input })).stdout,
169
+ codexLogin,
170
+ open: async (url) => {
171
+ await run(process.platform === "darwin" ? "open" : "xdg-open", [url]).catch(() => undefined);
172
+ },
173
+ confirm: async (question) => {
174
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
175
+ await rl.question(question);
176
+ rl.close();
177
+ },
178
+ log: (message) => console.log(message),
179
+ };
180
+ }
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/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/dist/update.js ADDED
@@ -0,0 +1,36 @@
1
+ import { readFileSync } from "node:fs";
2
+ /**
3
+ * A moving tag like @v0 gets each release by itself. A pinned commit doesn't, so the review
4
+ * tells those people when there's a newer release. It's only a hint, so anything going wrong
5
+ * here just means no hint.
6
+ */
7
+ const CURRENT = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
8
+ const parts = (version) => version.replace(/^v/, "").split(".").map(Number);
9
+ export function isNewer(candidate, than) {
10
+ const [a, b] = [parts(candidate), parts(than)];
11
+ for (let i = 0; i < 3; i++) {
12
+ const diff = (a[i] ?? 0) - (b[i] ?? 0);
13
+ if (diff)
14
+ return diff > 0;
15
+ }
16
+ return false;
17
+ }
18
+ /** The changes a release's generated notes list, without the version bumps. */
19
+ export function releaseNews(notes) {
20
+ return [...notes.matchAll(/^\* (.+?) by @\S+ in https:\/\/\S+$/gm)].map((m) => m[1]).filter((title) => !/^Release v\d/.test(title));
21
+ }
22
+ /** What a pinned run is missing, if there's a newer release. */
23
+ export async function newerVersion(api, current = CURRENT, ref = process.env.MERGELIGHT_ACTION_REF) {
24
+ if (!/^[0-9a-f]{40}$/i.test(ref ?? ""))
25
+ return null;
26
+ try {
27
+ const releases = await api.get("/repos/mergelightai/mergelight/releases?per_page=30");
28
+ const newer = releases.filter((r) => !r.draft && !r.prerelease && isNewer(r.tag_name, current)).sort((a, b) => (isNewer(a.tag_name, b.tag_name) ? -1 : 1));
29
+ if (!newer.length)
30
+ return null;
31
+ return { tag: newer[0].tag_name, current: `v${current.replace(/^v/, "")}`, news: newer.flatMap((r) => releaseNews(r.body ?? "")) };
32
+ }
33
+ catch {
34
+ return null;
35
+ }
36
+ }