@mergelight/cli 0.1.18 → 0.1.20

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.
@@ -0,0 +1,182 @@
1
+ import { appendFileSync, mkdtempSync, writeFileSync } from "node:fs";
2
+ import { run } from "./run.js";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { fetchContext } from "./cloud.js";
6
+ import { fetchPullRequest } from "./github.js";
7
+ import { jobsToRun } from "./jobs.js";
8
+ import { runModel, TOOLING } from "./providers/index.js";
9
+ import { buildJobPrompt, caseBlindDisk, caseClashes, isJobCommit, JOB_SCHEMA, mirrorGit, runJobs } from "./run-jobs.js";
10
+ import { cacheDir, headGuarded, jobFilesFor, prepareWorkspace, skillsFor } from "./workspace.js";
11
+ /** Where a team turns on the plan that includes Jobs. */
12
+ export const JOBS_PLAN_URL = "https://mergelight.dev/dashboard/";
13
+ /**
14
+ * Why no job may run for this org, or null when they may. Jobs is part of a paid plan, and only the
15
+ * org's Mergelight server can say yes: no server, no answer, or no yes, and no job runs.
16
+ */
17
+ export function jobsGate(ctx, ownRepository = true) {
18
+ // The server's yes is for the run's own repository: GitHub signed the pass for it. Jobs for another
19
+ // repository don't run on it.
20
+ if (!ownRepository)
21
+ return "Jobs run only from the repository's own workflow, so no job ran.";
22
+ if (ctx.failed)
23
+ return "The Mergelight server couldn't be asked whether your plan includes Jobs, so no job ran. The next push asks again.";
24
+ if (ctx.jobs === true)
25
+ return null;
26
+ if (!ctx.answered && !ctx.connected)
27
+ return `Jobs is part of a paid plan, and needs your org's Mergelight server: set server in the workflow. No job ran. ${JOBS_PLAN_URL}`;
28
+ return `Your org's plan doesn't include Jobs, or the org isn't set up on Mergelight's server yet, so no job ran. ${JOBS_PLAN_URL}`;
29
+ }
30
+ /**
31
+ * Where the result goes when no --out is given: the runner's own temp folder in the Action, and a new
32
+ * private folder elsewhere, so no one else on the machine can know the path or plant a file there.
33
+ */
34
+ export function defaultJobsOut() {
35
+ if (process.env.RUNNER_TEMP)
36
+ return join(process.env.RUNNER_TEMP, "mergelight-jobs.json");
37
+ return join(mkdtempSync(join(tmpdir(), "mergelight-jobs-")), "result.json");
38
+ }
39
+ /** git's version, as [major, minor], or null when it can't be told. */
40
+ async function gitVersion() {
41
+ const m = /git version (\d+)\.(\d+)/.exec((await run("git", ["--version"]).catch(() => null))?.stdout ?? "");
42
+ return m ? [Number(m[1]), Number(m[2])] : null;
43
+ }
44
+ /** What a run did, in lines for the log. */
45
+ export function describeJobs(result) {
46
+ const lines = [];
47
+ if (result.skipped)
48
+ lines.push(result.skipped);
49
+ if (result.notRun)
50
+ lines.push(result.notRun);
51
+ for (const p of result.problems)
52
+ lines.push(`Left out ${p.source}: ${p.problem}.`);
53
+ for (const o of result.outcomes) {
54
+ const what = { changed: `changed ${o.files.length} file${o.files.length === 1 ? "" : "s"}`, nothing: "changed nothing", refused: "was dropped", failed: "failed" }[o.status];
55
+ lines.push(`Job "${o.name}" ${what}. ${o.summary}`);
56
+ }
57
+ if (!result.skipped && !result.notRun)
58
+ lines.push(result.changes.length ? `${result.changes.length} file${result.changes.length === 1 ? "" : "s"} to push.` : "Nothing to push.");
59
+ return lines;
60
+ }
61
+ /**
62
+ * Runs the team's jobs on a pull request and writes what they changed to a file. Nothing is pushed and
63
+ * nothing is posted: a separate step, with no AI and no AI login, checks the file again and pushes it.
64
+ */
65
+ export async function jobsCommand(ref, o) {
66
+ const progress = o.onProgress ?? (() => { });
67
+ const out = o.out ?? defaultJobsOut();
68
+ // A run that stops early never leaves an older result in place, and a path that can't be written
69
+ // fails now, before any AI time is spent.
70
+ writeFileSync(out, "", { mode: 0o600 });
71
+ const finish = (result) => {
72
+ // Only for this account: outside the Action it may sit in a shared temp folder.
73
+ writeFileSync(out, `${JSON.stringify(result, null, 2)}\n`, { mode: 0o600 });
74
+ for (const line of describeJobs(result))
75
+ o.log(line);
76
+ if (!o.out && !process.env.RUNNER_TEMP)
77
+ o.log(`The result is in ${out}.`);
78
+ // The workflow pushes only when there is something to push.
79
+ if (process.env.GITHUB_OUTPUT)
80
+ appendFileSync(process.env.GITHUB_OUTPUT, `changes=${result.changes.length}\nresult=${out}\n`);
81
+ // Every job that ran failed: that is the run failing, not a pull request with nothing to do.
82
+ return result.outcomes.length && result.outcomes.every((x) => x.status === "failed") ? 1 : 0;
83
+ };
84
+ // Files are written out and read back byte for byte only with git 2.42 or newer (GIT_ATTR_SOURCE).
85
+ const version = await gitVersion();
86
+ if (!version || version[0] < 2 || (version[0] === 2 && version[1] < 42)) {
87
+ o.log(`Jobs need git 2.42 or newer, and this machine has ${version ? version.join(".") : "a git that can't say"}. No job ran.`);
88
+ return 1;
89
+ }
90
+ progress(`Reading ${ref.owner}/${ref.repo}#${ref.number}`);
91
+ const pr = await fetchPullRequest(ref);
92
+ // Nothing a job does could be pushed to the default branch (push-jobs.ts), so no AI time is spent on it.
93
+ // Only the repository's own default branch: a fork's branch can have the same name.
94
+ if (pr.defaultBranch && pr.sameRepo && pr.headRef === pr.defaultBranch) {
95
+ return finish({ head: pr.headSha, outcomes: [], problems: [], changes: [], skipped: `The pull request comes from ${pr.headRef}, the repository's default branch, so no job runs.` });
96
+ }
97
+ progress("Checking out the code");
98
+ const ws = await prepareWorkspace(pr, o.at);
99
+ try {
100
+ const git = mirrorGit(ws.mirror);
101
+ const empty = { head: ws.headSha, outcomes: [], problems: [], changes: [] };
102
+ // A commit jobs made runs no jobs, so a job can't start itself again.
103
+ if (await isJobCommit(git, ws.headSha))
104
+ return finish({ ...empty, skipped: "The newest commit is one that jobs made, so no job runs on it." });
105
+ // One commit for the whole run, pinned while the workspace was prepared.
106
+ const teamBase = ws.teamBase;
107
+ const { jobs, problems, guarded: baseGuard, incomplete } = await jobFilesFor(ws.mirror, teamBase);
108
+ // The guard couldn't be worked out in full: no job runs rather than one with a smaller guard.
109
+ if (incomplete)
110
+ return finish({ ...empty, problems, notRun: incomplete });
111
+ if (!jobs.length)
112
+ return finish({ ...empty, problems, skipped: `There are no jobs in .mergelight/jobs on ${pr.baseRef}.` });
113
+ // On a disk that ignores letter case, two files that differ only in it would be written as one.
114
+ if (caseBlindDisk()) {
115
+ const clashes = await caseClashes(git, ws.headSha);
116
+ if (clashes.length)
117
+ return finish({ ...empty, problems, skipped: `This disk ignores letter case, and ${clashes.slice(0, 3).join(", ")} would be one file here, so no job runs.` });
118
+ }
119
+ const toRun = jobsToRun(jobs, ws.touchedPaths);
120
+ if (!toRun.length)
121
+ return finish({ ...empty, problems, skipped: "This pull request changes none of the files that start a job." });
122
+ // Asked only when a job would run, so a repository without jobs never calls the server for them.
123
+ const ownRepository = (process.env.GITHUB_REPOSITORY ?? "").toLowerCase() === `${ref.owner}/${ref.repo}`.toLowerCase();
124
+ const closed = jobsGate(await (o.context ?? fetchContext)({ log: o.log }), ownRepository);
125
+ if (closed)
126
+ return finish({ ...empty, problems, notRun: closed });
127
+ // The pull request's own links and imports are guarded too: one that makes AGENTS.md a link to a
128
+ // file a job may change would carry the job's change into what agents read. Its jobs never count.
129
+ const headGuard = await headGuarded(ws.mirror, ws.headSha, jobs);
130
+ if ("why" in headGuard)
131
+ return finish({ ...empty, problems, skipped: headGuard.why });
132
+ const guarded = [...new Set([...baseGuard, ...headGuard.guarded])].sort();
133
+ const provider = o.provider ?? "codex";
134
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
135
+ const result = await runJobs({
136
+ git,
137
+ head: ws.headSha,
138
+ jobs: toRun,
139
+ guarded,
140
+ problems,
141
+ onProgress: progress,
142
+ ask: async (job, dir, earlier, deadline) => {
143
+ // The skill comes from the base branch into the job's own folder, at .mergelight/skills, where the
144
+ // job's commands can always read it. No job may change anything under .mergelight, and that
145
+ // folder comes back from the tree when the job's files are read, so the copy is never pushed.
146
+ const [found] = job.skill ? await skillsFor(ws.mirror, teamBase, dir, [job.skill]) : [];
147
+ // A job without the skill it names would do something else than the team wrote.
148
+ if (job.skill && !found)
149
+ throw new Error(`its skill ${job.skill} couldn't be copied from ${pr.baseRef}`);
150
+ const prompt = buildJobPrompt({
151
+ job,
152
+ pr,
153
+ diff: ws.diff,
154
+ diffTruncated: ws.diffTruncated,
155
+ changedPaths: ws.touchedPaths,
156
+ conventions: ws.conventions,
157
+ skill: found ? { name: found.name, path: found.read } : undefined,
158
+ earlier,
159
+ tooling: TOOLING[provider],
160
+ guarded,
161
+ });
162
+ const answer = await runModel(provider, {
163
+ cwd: dir,
164
+ prompt,
165
+ schema: JOB_SCHEMA,
166
+ edit: true,
167
+ model: o.model,
168
+ effort: o.effort,
169
+ // Worked out right before the program starts, so nothing before it takes from its time.
170
+ deadline,
171
+ logFile: join(cacheDir(), "logs", `${pr.owner}-${pr.repo}-${pr.number}-${stamp}-job-${job.name}.log`),
172
+ });
173
+ return answer.output;
174
+ },
175
+ });
176
+ return finish(result);
177
+ }
178
+ finally {
179
+ if (!o.keep)
180
+ await ws.cleanup();
181
+ }
182
+ }
package/dist/jobs.js ADDED
@@ -0,0 +1,437 @@
1
+ import { matchesPath } from "./prompt.js";
2
+ import { frontMatterBlock, listValue, scalarValue, withoutComments } from "./repo-rules.js";
3
+ import { isSkillPath, withoutHidden } from "./skills.js";
4
+ /**
5
+ * Jobs: tasks a team writes once in its repository. On each pull request that needs one, the AI does the
6
+ * task and Mergelight pushes the result as one commit to the pull request's branch. This file reads and
7
+ * checks the job files. They are read from the base branch, like rules, so a pull request can't add a
8
+ * job, or widen one, for itself.
9
+ *
10
+ * ---
11
+ * name: translations
12
+ * on: locales/en.json
13
+ * may-change: locales/*.json
14
+ * ---
15
+ * When en.json gets new keys, add each one to every other file in locales/, translated.
16
+ *
17
+ * - `on`: the files whose change starts the job.
18
+ * - `may-change`: the only files the job may change, add or delete.
19
+ * - `skill` (optional): a skill folder in the repository that the job uses.
20
+ * - `name` (optional): the file's name without .md when left out.
21
+ */
22
+ export const JOB_FILE = /^\.mergelight\/jobs\/[^/]+\.md$/;
23
+ /** Limits: each job is an AI run of its own, on the team's plan. */
24
+ export const MAX_JOBS = 5;
25
+ export const MAX_JOB_TASK_CHARS = 8000;
26
+ /** How many job files are read at most. */
27
+ export const MAX_JOB_FILES = 20;
28
+ const NAME = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/;
29
+ /** The keys a job file's front matter may have. */
30
+ const JOB_KEYS = ["name", "on", "may-change", "skill"];
31
+ /**
32
+ * Folders a job can never change anything in, whatever its file says, wherever they sit: workflows and
33
+ * CI settings decide what runs, Mergelight's own files what a job may do, the folders AI agents take
34
+ * instructions from would carry a planted text into every later agent and review, and git's own folder
35
+ * is git's.
36
+ */
37
+ export const REFUSED_FOLDERS = [
38
+ ".github",
39
+ ".mergelight",
40
+ ".git",
41
+ // AI agents.
42
+ ".claude",
43
+ ".agents",
44
+ ".codex",
45
+ ".cursor",
46
+ ".gemini",
47
+ ".windsurf",
48
+ ".vscode",
49
+ ".junie",
50
+ ".roo",
51
+ ".kiro",
52
+ ".amazonq",
53
+ ".continue",
54
+ ".augment",
55
+ ".kilocode",
56
+ ".trae",
57
+ ".openhands",
58
+ ".opencode",
59
+ ".aiassistant",
60
+ ".qwen",
61
+ ".factory",
62
+ // Editors whose settings can start commands on a teammate's machine.
63
+ ".idx",
64
+ ".zed",
65
+ // CI services, git hooks and dev containers.
66
+ ".gitlab",
67
+ ".circleci",
68
+ ".woodpecker",
69
+ ".gitea",
70
+ ".forgejo",
71
+ ".buildkite",
72
+ // Only at the root, where Buildkite reads it: a folder of that name elsewhere is ordinary.
73
+ "/buildkite",
74
+ ".lefthook",
75
+ ".prow",
76
+ ".harness",
77
+ ".teamcity",
78
+ // Only at the root, where SourceHut reads it.
79
+ "/.builds",
80
+ ".husky",
81
+ ".devcontainer",
82
+ ".semaphore",
83
+ ".githooks",
84
+ ".mergify",
85
+ ".tekton",
86
+ // Names that are a file for some tools and a folder for others: either way, nothing in or of them.
87
+ ".clinerules",
88
+ ".rules",
89
+ ".tabnine",
90
+ ];
91
+ /**
92
+ * Files a job can never change, whatever its file says, in any folder. Only the file's own name counts,
93
+ * so a folder that happens to be called owners is ordinary.
94
+ */
95
+ export const REFUSED_FILES = [
96
+ // Who must approve, and what merges by itself.
97
+ "CODEOWNERS",
98
+ "OWNERS",
99
+ "OWNERS_ALIASES",
100
+ ".policy.yml",
101
+ ".pullapprove.yml",
102
+ ".mergify.yml",
103
+ "renovate.json",
104
+ "renovate.json5",
105
+ ".renovaterc",
106
+ ".renovaterc.json",
107
+ ".renovaterc.json5",
108
+ ".kodiak.toml",
109
+ "bors.toml",
110
+ // What AI agents and the review take instructions from. CONTRIBUTING.md is one of the review's conventions.
111
+ "AGENTS.md",
112
+ "AGENTS.override.md",
113
+ "AGENT.md",
114
+ "CLAUDE.md",
115
+ "CLAUDE.local.md",
116
+ "GEMINI.md",
117
+ "QWEN.md",
118
+ "CRUSH.md",
119
+ "WARP.md",
120
+ "CONTRIBUTING.md",
121
+ "CONVENTIONS.md",
122
+ "SKILL.md",
123
+ "airules.md",
124
+ ".mcp.json",
125
+ "opencode.json",
126
+ "crush.json",
127
+ ".crush.json",
128
+ ".augment-guidelines",
129
+ ".goosehints",
130
+ ".roorules",
131
+ ".roomodes",
132
+ ".continuerules",
133
+ ".aider.conf.yml",
134
+ ".cursorrules",
135
+ ".windsurfrules",
136
+ "opencode.jsonc",
137
+ // Other review bots' settings.
138
+ ".coderabbit.yaml",
139
+ ".coderabbit.yml",
140
+ ".pr_agent.toml",
141
+ // What runs: CI services and git hooks.
142
+ ".gitlab-ci.yml",
143
+ ".travis.yml",
144
+ ".drone.yml",
145
+ ".woodpecker.yml",
146
+ ".pre-commit-config.yaml",
147
+ "lefthook.yml",
148
+ "lefthook.yaml",
149
+ "lefthook.toml",
150
+ "lefthook-local.yml",
151
+ ".lefthook.yml",
152
+ ".lefthook.yaml",
153
+ ".woodpecker.yaml",
154
+ ".cirrus.star",
155
+ ".prow.yaml",
156
+ ".gitpod.yml",
157
+ ".devcontainer.json",
158
+ ".cirrus.yml",
159
+ "appveyor.yml",
160
+ ".appveyor.yml",
161
+ "cloudbuild.yaml",
162
+ "cloudbuild.yml",
163
+ "buildspec.yml",
164
+ "bitrise.yml",
165
+ "codemagic.yaml",
166
+ "Jenkinsfile",
167
+ "azure-pipelines.yml",
168
+ // Build services that run a build command from the repository.
169
+ "netlify.toml",
170
+ "netlify.yml",
171
+ "netlify.yaml",
172
+ "netlify.json",
173
+ "amplify.yml",
174
+ "amplify.yaml",
175
+ "vercel.json",
176
+ "vercel.ts",
177
+ "vercel.js",
178
+ "vercel.mjs",
179
+ "vercel.cjs",
180
+ "vercel.mts",
181
+ // Only at the root, where Heroku reads it and runs its scripts, such as postdeploy, on review apps. An
182
+ // app.json elsewhere, such as a translation namespace, is ordinary.
183
+ "/app.json",
184
+ "firebase.json",
185
+ "now.json",
186
+ "render.yaml",
187
+ "railway.json",
188
+ "railway.toml",
189
+ "wrangler.toml",
190
+ "wrangler.json",
191
+ "wrangler.jsonc",
192
+ "nixpacks.json",
193
+ "heroku.yml",
194
+ "Procfile",
195
+ ".platform.app.yaml",
196
+ "appspec.yml",
197
+ "fly.toml",
198
+ "nixpacks.toml",
199
+ "cloudbuild.json",
200
+ "codefresh.yml",
201
+ "codefresh.yaml",
202
+ "lefthook.json",
203
+ ".build.yml",
204
+ ".simple-git-hooks.json",
205
+ ".simple-git-hooks.js",
206
+ "simple-git-hooks.json",
207
+ "simple-git-hooks.js",
208
+ // Agents and bots that read their own settings.
209
+ "replit.md",
210
+ ".replit",
211
+ "replit.nix",
212
+ ".sourcery.yaml",
213
+ "greptile.json",
214
+ ".lefthook.json",
215
+ ".lefthook.toml",
216
+ "buildkite.yml",
217
+ "buildkite.yaml",
218
+ "buildkite.json",
219
+ "bitbucket-pipelines.yml",
220
+ // How git reads the rest.
221
+ ".gitmodules",
222
+ ".gitattributes",
223
+ ".lfsconfig",
224
+ ];
225
+ /** Both lists, for anyone who wants the whole of what a job may never change. */
226
+ export const REFUSED_PATHS = [...REFUSED_FOLDERS, ...REFUSED_FILES];
227
+ /** A pattern that leaves the repository, or names no file: read the way matchesPath reads it. */
228
+ function badPattern(pattern) {
229
+ const plain = pattern.trim().replace(/\/{2,}/g, "/").replace(/^(\.\/|\/)+/, "").replace(/\/+$/, "");
230
+ return !plain || plain.split("/").some((part) => part === "." || part === "..");
231
+ }
232
+ /** One job file: its job, or why it can't be one. Hidden characters are taken out first. */
233
+ export function parseJobFile(path, text) {
234
+ const block = frontMatterBlock(withoutHidden(text));
235
+ if (!block)
236
+ return { problem: "starts with no front matter, so it names no on and may-change paths" };
237
+ // A key written twice: readers disagree on which one counts, and these decide what a job may write.
238
+ const twice = ["name", "on", "may-change", "skill"].find((key) => (block.fm.match(new RegExp(`^${key}[ \\t]*:`, "gm")) ?? []).length > 1);
239
+ if (twice)
240
+ return { problem: `its front matter has ${twice} more than once` };
241
+ const named = scalarValue(block.fm, "name");
242
+ const name = named || path.slice(path.lastIndexOf("/") + 1).replace(/\.md$/, "");
243
+ if (!NAME.test(name))
244
+ return { problem: `its name "${name.slice(0, 60)}" must be lowercase letters, digits and dashes, start and end with a letter or digit, and be 40 long at most` };
245
+ // A list that goes on past a trailing comma on the next line: only the key's own line is read.
246
+ // A YAML list item that ends with a comma goes on past it the same way.
247
+ const cut = ["on", "may-change"].find((key) => scalarValue(block.fm, key)?.endsWith(",")) ?? (/^[ \t]*-[^\n#]*,[ \t]*(?:#.*)?$/m.test(block.fm) ? "list" : undefined);
248
+ if (cut === "list")
249
+ return { problem: "a list item in its front matter ends with a comma: write each path as an item of its own" };
250
+ if (cut)
251
+ return { problem: `its ${cut} line ends with a comma: write the whole list on one line, or as a YAML list` };
252
+ // "./name" means the root, as "/name" does: without that it would be "name" in any folder.
253
+ const rooted = (paths) => paths?.map((p) => p.replace(/^\.\//, "/"));
254
+ // A key with nothing on its line, then a path on an indented line that isn't a "- " item: the path isn't read.
255
+ const indented = (key) => new RegExp(`^${key}[ \\t]*:[ \\t]*(?:#.*)?\\r?\\n(?:[ \\t]*(?:#.*)?\\r?\\n)*[ \\t]+[^\\s#-]`, "m").test(block.fm);
256
+ const on = rooted(listValue(block.fm, "on"));
257
+ if (!on?.length)
258
+ return { problem: indented("on") ? "its on value goes on to an indented line, which isn't read: write the paths as a list" : "names no on paths, the files whose change starts the job" };
259
+ const mayChange = rooted(listValue(block.fm, "may-change"));
260
+ if (!mayChange?.length)
261
+ return { problem: indented("may-change") ? "its may-change value goes on to an indented line, which isn't read: write the paths as a list" : "names no may-change paths, the only files the job may change" };
262
+ // "!" excludes files in GitHub's path filters, but here it would be part of a name and exclude nothing.
263
+ const negated = [...on, ...mayChange].find((p) => p.startsWith("!"));
264
+ if (negated !== undefined)
265
+ return { problem: `the path "${negated.slice(0, 100)}" starts with !, but a job can't leave files out that way. List only the files it may change` };
266
+ // A [list] split over lines reads as "[a," and "b]": only the key's own line is read.
267
+ // Brackets that open and close, like Next.js's app/[locale], are part of a name.
268
+ const count = (p, ch) => p.split(ch).length - 1;
269
+ const split = [...on, ...mayChange].find((p) => count(p, "[") !== count(p, "]") || p.indexOf("]") < p.indexOf("["));
270
+ if (split !== undefined)
271
+ return { problem: `the path "${split.slice(0, 100)}" looks like part of a [list]: write the whole list on one line, or as a YAML list` };
272
+ // "locales/*/" reads as "locales/*", the files right in locales: the opposite of what it says.
273
+ const slash = [...on, ...mayChange].find((p) => /[*?][^/]*\/+$/.test(p) && !/(?:^|\/)\*\*\/+$/.test(p));
274
+ if (slash !== undefined)
275
+ return { problem: `the path "${slash.slice(0, 100)}" ends in a slash after a wildcard: write locales/* for the files in a folder, or locales for all of it` };
276
+ const bad = [...on, ...mayChange].find(badPattern);
277
+ if (bad !== undefined)
278
+ return { problem: `the path "${bad.slice(0, 100)}" leaves the repository or names no file. For every file, write **` };
279
+ // A YAML block or empty value ("|", ">-", "~") would be read as a path: only lists and one-line values are read.
280
+ const yamlBlock = [...on, ...mayChange].find((p) => /^(?:[|>](?:[1-9][+-]?|[+-][1-9]?)?|~|null)$/i.test(p));
281
+ if (yamlBlock !== undefined)
282
+ return { problem: `the path "${yamlBlock}" is a YAML block or an empty value: write the paths as a list, or on the key's own line` };
283
+ // A path on an indented line under the key's own value is part of it in YAML, but only the key's line is read.
284
+ const goesOn = ["on", "may-change", "skill"].find((key) => new RegExp(`^${key}[ \\t]*:[ \\t]*[^\\s#][^\\n]*\\n[ \\t]+[^\\s#-]`, "m").test(block.fm));
285
+ if (goesOn)
286
+ return { problem: goesOn === "skill" ? "its skill value goes on to an indented line, which isn't read: write the skill folder on the skill line itself" : `its ${goesOn} value goes on to an indented line, which isn't read: write the paths as a list` };
287
+ // A pattern is refused when what is in it is too: "owners" names a folder of ordinary files, not OWNERS.
288
+ // On purpose, a job that names only a refused file, like CODEOWNERS, is accepted: it can't change it
289
+ // anyway, and refusing it here would refuse every folder called owners too.
290
+ const refusedPattern = (p) => refusedPath(p) && refusedPath(`${p.replace(/\/+$/, "")}/x`);
291
+ if (mayChange.every(refusedPattern)) {
292
+ return { problem: "its may-change paths only name files a job can never change, like .github and .mergelight" };
293
+ }
294
+ const written = scalarValue(block.fm, "skill") ?? undefined;
295
+ // Written the way the paths above may be: "./.claude/skills/x/" and "/.claude/skills/x" are ".claude/skills/x".
296
+ const skill = written?.replace(/^(\.\/|\/)+/, "").replace(/\/+$/, "");
297
+ if (written === "")
298
+ return { problem: "its skill line names no folder: write one folder on the same line, like skill: .claude/skills/write-docs" };
299
+ if (written !== undefined && !isSkillPath(skill))
300
+ return { problem: `its skill "${written.slice(0, 100)}" isn't a folder in the repository, like .claude/skills/write-docs` };
301
+ // No job may change a skill folder, its own included, so one that may only change its own skill can do nothing.
302
+ // A pattern in no man's land: only files a job can never change, or only its own skill folder, which no job may change.
303
+ if (skill && mayChange.every((p) => refusedPattern(p) || matchesPath(`/${skill}`.toLowerCase(), p.replace(/^(\.\/|\/)+/, "").toLowerCase()))) {
304
+ return { problem: `its may-change paths only name files a job can never change, or its own skill folder, ${skill}` };
305
+ }
306
+ // Every line of the front matter must be one that is read: a job's own key, a list item under on or
307
+ // may-change, a blank line or a comment. Anything else (a typo in a key, a value that goes on to the next
308
+ // line, an item under a key that already has a value) would be dropped without a word.
309
+ let list = null;
310
+ for (const line of block.fm.split(/\r?\n/)) {
311
+ if (/^[ \t]*(?:#.*)?$/.test(line))
312
+ continue;
313
+ // YAML allows the items at the key's own indent too, and an item can hold a colon.
314
+ if (list && /^[ \t]*-[ \t]*\S/.test(line))
315
+ continue;
316
+ const keyLine = /^([^\s:#-][^:]*?)[ \t]*:[ \t]*(.*)$/.exec(line);
317
+ if (keyLine) {
318
+ const key = keyLine[1];
319
+ if (!JOB_KEYS.includes(key))
320
+ return { problem: `its front matter has a key a job doesn't know: ${key.slice(0, 40)}. A job knows name, on, may-change and skill` };
321
+ list = (key === "on" || key === "may-change") && /^(?:#.*)?$/.test(keyLine[2].trim()) ? key : null;
322
+ continue;
323
+ }
324
+ return { problem: `its front matter has a line that isn't read: "${line.trim().slice(0, 60)}". Write each key on a line of its own, and list items under on or may-change with nothing after the colon` };
325
+ }
326
+ // A quote that opens and never closes would let a comment or a typo widen what the job names.
327
+ for (const line of block.fm.split(/\r?\n/)) {
328
+ const value = /^(?:(?:on|may-change)[ \t]*:|[ \t]*-)[ \t]*(.*)$/.exec(line)?.[1] ?? "";
329
+ // A quote opens where a value or item starts, as in YAML, and must close before the line ends.
330
+ let quote = null;
331
+ for (let i = 0; i < value.length; i++) {
332
+ const ch = value[i];
333
+ if (quote) {
334
+ if (ch === quote && (i + 1 === value.length || /[\s,\]]/.test(value[i + 1])))
335
+ quote = null;
336
+ }
337
+ else if ((ch === '"' || ch === "'") && (i === 0 || /[\s,[]/.test(value[i - 1])))
338
+ quote = ch;
339
+ else if (ch === "#" && (i === 0 || /\s/.test(value[i - 1])))
340
+ break;
341
+ }
342
+ if (quote)
343
+ return { problem: `a path opens with a quote that never closes: ${line.trim().slice(0, 60)}` };
344
+ }
345
+ // HTML comments are what a team turned off, as in rule files.
346
+ const task = withoutComments(block.body).trim();
347
+ if (!task)
348
+ return { problem: "has no task under its front matter" };
349
+ if (task.length > MAX_JOB_TASK_CHARS)
350
+ return { problem: `its task is longer than ${MAX_JOB_TASK_CHARS.toLocaleString("en-US")} characters` };
351
+ return { job: { name, on, mayChange, ...(skill ? { skill } : {}), task, source: path } };
352
+ }
353
+ /**
354
+ * The repository's jobs, within the limits, and every job file that was left out with the reason. Files
355
+ * are taken by path, so which ones count past a limit doesn't change from run to run.
356
+ */
357
+ export function readJobs(files, hasSkill) {
358
+ const jobs = [];
359
+ const problems = [];
360
+ for (const f of [...files].sort((a, b) => a.path.localeCompare(b.path))) {
361
+ const parsed = parseJobFile(f.path, f.text);
362
+ if ("problem" in parsed)
363
+ problems.push({ source: f.path, problem: parsed.problem });
364
+ // Before the limits: a job that is left out mustn't take the place or the name of one that isn't.
365
+ else if (parsed.job.skill && hasSkill && !hasSkill(parsed.job.skill))
366
+ problems.push({ source: f.path, problem: `its skill ${parsed.job.skill} has no SKILL.md on the base branch` });
367
+ else if (jobs.some((j) => j.name === parsed.job.name))
368
+ problems.push({ source: f.path, problem: `${jobs.find((j) => j.name === parsed.job.name).source} already has a job named ${parsed.job.name}` });
369
+ else if (jobs.length >= MAX_JOBS)
370
+ problems.push({ source: f.path, problem: `only ${MAX_JOBS} jobs run in a repository` });
371
+ else
372
+ jobs.push(parsed.job);
373
+ }
374
+ return { jobs, problems };
375
+ }
376
+ /** The jobs that one of the changed files starts. */
377
+ export function jobsToRun(jobs, changedPaths) {
378
+ // As strictly as may-change, so a job never starts for files it may not change.
379
+ return jobs.filter((job) => changedPaths.some((file) => job.on.some((pattern) => matchesPath(pattern, file, false))));
380
+ }
381
+ /**
382
+ * A name in the form macOS and Windows compare names in: any letter case, and look-alike letters that
383
+ * fold to plain ones, like ſ to s and ı to i. Upper case first, so those fold too. And one way of writing
384
+ * accented letters: macOS takes é as one character and as e with an accent for the same name.
385
+ */
386
+ export function folded(path) {
387
+ return path.normalize("NFC").toUpperCase().toLowerCase().normalize("NFC");
388
+ }
389
+ /** A path no job may change, whatever its file says. In any letter case: on macOS and Windows, .GitAttributes is .gitattributes. */
390
+ export function refusedPath(path) {
391
+ const lower = folded(path);
392
+ const name = lower.replace(/\/+$/, "").split("/").pop() ?? "";
393
+ // Roo reads .roorules-<mode> for each mode, and lefthook reads lefthook-local.<any>.
394
+ if (/^lefthook-local\./.test(name) || /^\.lintstagedrc/.test(name) || /^lint-staged\.config\./.test(name))
395
+ return true;
396
+ // A name that starts with / counts only at the root.
397
+ const rooted = lower.replace(/^(\.\/|\/)+/, "").replace(/\/+$/, "");
398
+ return REFUSED_FOLDERS.some((refused) => matchesPath(folded(refused), lower)) || REFUSED_FILES.some((refused) => (refused.startsWith("/") ? folded(refused.slice(1)) === rooted : folded(refused) === name)) || name.startsWith(".roorules-");
399
+ }
400
+ /**
401
+ * Whether this job may change, add or delete the file. Never one in a skill folder: the job's own, or one
402
+ * in guarded, which holds every folder with a SKILL.md on the base branch (guardedFolders). A skill
403
+ * guides a job or a review, and a job mustn't rewrite what tells it or a review what to do. guarded only
404
+ * knows the base branch: the step that writes passes isLink for the pull request's own links.
405
+ */
406
+ export function mayChange(job, path, guarded = [], isLink = () => false) {
407
+ // A path that steps out of a folder could reach past what a pattern names.
408
+ const parts = path.split("/");
409
+ if (parts.some((part) => part === "." || part === ".." || part === ""))
410
+ return false;
411
+ // isLink tells about the branch being written, which can have links the base branch doesn't: a write
412
+ // at or through one would land wherever it leads.
413
+ if (parts.some((_, i) => isLink(parts.slice(0, i + 1).join("/"))))
414
+ return false;
415
+ if (refusedPath(path))
416
+ return false;
417
+ const lower = folded(path);
418
+ if ([...(job.skill ? [job.skill] : []), ...guarded].some((folder) => matchesPath(folded(`/${folder}`), lower)))
419
+ return false;
420
+ // Strictly: "locales/*" is the files right in locales, not a subfolder and all inside it.
421
+ return job.mayChange.some((pattern) => matchesPath(pattern, path, false));
422
+ }
423
+ /**
424
+ * The folders no job may change anything in: every folder with a SKILL.md in the given list of the base
425
+ * branch's paths, whether a job or a review uses it, and every job's skill folder.
426
+ */
427
+ export function guardedFolders(paths, jobs = []) {
428
+ const folders = new Set();
429
+ // In any letter case on purpose: on macOS, a folder's skill.md is what opens as its SKILL.md.
430
+ for (const p of paths)
431
+ if (/(^|\/)SKILL\.md$/i.test(p) && p.includes("/"))
432
+ folders.add(p.slice(0, p.lastIndexOf("/")));
433
+ for (const j of jobs)
434
+ if (j.skill)
435
+ folders.add(j.skill);
436
+ return [...folders].sort();
437
+ }