tslaws 0.10.0 → 1.0.0

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 (122) hide show
  1. package/README.md +7 -2
  2. package/bin/tslaws.js +8 -2
  3. package/dist/browser.d.ts +1 -1
  4. package/dist/browser.js +25 -5
  5. package/dist/bundled.js +2 -2
  6. package/dist/bundlerPlugins.d.ts +2 -0
  7. package/dist/bundlerPlugins.js +7 -0
  8. package/dist/certificates.d.ts +139 -0
  9. package/dist/certificates.js +433 -0
  10. package/dist/chc.d.ts +85 -0
  11. package/dist/chc.js +298 -0
  12. package/dist/check.d.ts +13 -1
  13. package/dist/check.js +211 -27
  14. package/dist/cli.d.ts +2 -0
  15. package/dist/cli.js +175 -34
  16. package/dist/compile.d.ts +15 -5
  17. package/dist/compile.js +198 -69
  18. package/dist/coverage.d.ts +38 -1
  19. package/dist/coverage.js +94 -12
  20. package/dist/e2eApi.js +3 -1
  21. package/dist/generators.js +12 -2
  22. package/dist/github.d.ts +49 -5
  23. package/dist/github.js +107 -24
  24. package/dist/githubCli.d.ts +28 -0
  25. package/dist/githubCli.js +1039 -211
  26. package/dist/hints.js +2 -1
  27. package/dist/init.js +42 -0
  28. package/dist/isolate.d.ts +28 -0
  29. package/dist/isolate.js +262 -0
  30. package/dist/isolatedCheck.d.ts +1 -0
  31. package/dist/isolatedCheck.js +16 -0
  32. package/dist/lawHost.d.ts +50 -0
  33. package/dist/lawHost.js +199 -0
  34. package/dist/lawRuntime.d.ts +39 -0
  35. package/dist/lawRuntime.js +242 -0
  36. package/dist/lock.d.ts +49 -9
  37. package/dist/lock.js +132 -21
  38. package/dist/mcp.js +28 -7
  39. package/dist/mutate.d.ts +4 -0
  40. package/dist/mutate.js +7 -1
  41. package/dist/plan.d.ts +1 -0
  42. package/dist/plan.js +4 -0
  43. package/dist/pluginHooks.d.ts +16 -0
  44. package/dist/pluginHooks.js +48 -0
  45. package/dist/pluginHost.d.ts +5 -0
  46. package/dist/pluginHost.js +43 -0
  47. package/dist/pluginWorker.d.ts +1 -0
  48. package/dist/pluginWorker.js +40 -0
  49. package/dist/plural.d.ts +2 -0
  50. package/dist/plural.js +4 -0
  51. package/dist/pool.d.ts +80 -7
  52. package/dist/pool.js +222 -11
  53. package/dist/projects.d.ts +43 -1
  54. package/dist/projects.js +283 -11
  55. package/dist/promote.d.ts +56 -2
  56. package/dist/promote.js +429 -13
  57. package/dist/property.js +5 -1
  58. package/dist/propertyWorker.js +7 -0
  59. package/dist/proposals.d.ts +52 -4
  60. package/dist/proposals.js +484 -21
  61. package/dist/reporters.js +5 -1
  62. package/dist/runtimeEnv.d.ts +13 -5
  63. package/dist/runtimeEnv.js +48 -10
  64. package/dist/sandbox.d.ts +98 -0
  65. package/dist/sandbox.js +673 -0
  66. package/dist/sandboxGuard.d.ts +56 -0
  67. package/dist/sandboxGuard.js +249 -0
  68. package/dist/seal.d.ts +9 -0
  69. package/dist/seal.js +426 -0
  70. package/dist/security/cli.d.ts +6 -0
  71. package/dist/security/cli.js +39 -0
  72. package/dist/security/cwe.d.ts +14 -0
  73. package/dist/security/cwe.js +40 -0
  74. package/dist/security/deps/cache.d.ts +28 -0
  75. package/dist/security/deps/cache.js +107 -0
  76. package/dist/security/deps/config.d.ts +16 -0
  77. package/dist/security/deps/config.js +43 -0
  78. package/dist/security/deps/imports.d.ts +4 -0
  79. package/dist/security/deps/imports.js +33 -0
  80. package/dist/security/deps/lockfiles.d.ts +23 -0
  81. package/dist/security/deps/lockfiles.js +153 -0
  82. package/dist/security/deps/osv.d.ts +66 -0
  83. package/dist/security/deps/osv.js +137 -0
  84. package/dist/security/deps/run.d.ts +54 -0
  85. package/dist/security/deps/run.js +135 -0
  86. package/dist/security/deps/severity.d.ts +26 -0
  87. package/dist/security/deps/severity.js +78 -0
  88. package/dist/security/generators.d.ts +9 -0
  89. package/dist/security/generators.js +36 -0
  90. package/dist/security/index.d.ts +27 -0
  91. package/dist/security/index.js +18 -0
  92. package/dist/security/integers.d.ts +31 -0
  93. package/dist/security/integers.js +105 -0
  94. package/dist/security/law.d.ts +54 -0
  95. package/dist/security/law.js +54 -0
  96. package/dist/security/pathTraversal.d.ts +29 -0
  97. package/dist/security/pathTraversal.js +146 -0
  98. package/dist/security/prototypePollution.d.ts +30 -0
  99. package/dist/security/prototypePollution.js +142 -0
  100. package/dist/security/redirect.d.ts +21 -0
  101. package/dist/security/redirect.js +154 -0
  102. package/dist/security/redos.d.ts +21 -0
  103. package/dist/security/redos.js +93 -0
  104. package/dist/security/validation.d.ts +25 -0
  105. package/dist/security/validation.js +89 -0
  106. package/dist/security/xss.d.ts +21 -0
  107. package/dist/security/xss.js +90 -0
  108. package/dist/settings.d.ts +20 -0
  109. package/dist/settings.js +32 -0
  110. package/dist/smt.d.ts +29 -1
  111. package/dist/smt.js +239 -107
  112. package/dist/smtWorker.d.ts +1 -0
  113. package/dist/smtWorker.js +26 -0
  114. package/dist/solvers.d.ts +9 -0
  115. package/dist/solvers.js +11 -5
  116. package/dist/symbolic.d.ts +54 -1
  117. package/dist/symbolic.js +239 -13
  118. package/dist/tsconfigResolve.d.ts +28 -0
  119. package/dist/tsconfigResolve.js +141 -0
  120. package/dist/types.d.ts +28 -0
  121. package/hooks/claude-hook.mjs +2 -0
  122. package/package.json +18 -6
package/dist/githubCli.js CHANGED
@@ -5,28 +5,45 @@
5
5
  // waits for an accept. Advisory: it runs the pull request's code, so it decides nothing about the lock.
6
6
  // command issue_comment: reads `/tslaws accept|reject ...`, checks the commenter may accept, and records the
7
7
  // fingerprints accepted in a comment of the bot's. Reads the pull request's files as data; runs none of it.
8
- // merge push to the configured branch: runs the laws on the merged code, accepts what passes (and, in comment
9
- // mode, what was accepted for that exact version) and commits tsc-laws.lock through the API as the bot.
10
- // The only place the lock is written.
11
- // verify pull_request_target: fails when a commit in the pull request that the bot did not make (with a signature
12
- // GitHub verified) touches tsc-laws.lock, or when the pull request changes the "github" section of
13
- // tslaws.json or a protected path. Reads the base branch's config, never the pull request's.
8
+ // merge push to the configured branch, or workflow_dispatch by someone with admin or maintain access: runs the
9
+ // laws on the branch's code, accepts what passes (and, in comment mode, what was accepted for that exact
10
+ // version) and commits tsc-laws.lock through the API as the bot. The only place the workflow writes the
11
+ // lock. While a project's "local" is true (the default) a person may also change its lock by hand, through
12
+ // `tslaws accept` or a merged pull request that a maintainer wrote and merged; merge accepts such a change
13
+ // as it stands and builds on it, and on demand it first checks where the branch's lock came from.
14
+ // verify pull_request_target: fails when the pull request changes a lock (unless the project's "local" is true
15
+ // and the pull request's author, and the author of each commit that changes the lock, has admin or maintain
16
+ // access), the "github" section of tslaws.json or a protected path. Reads the base branch's config, never
17
+ // the pull request's.
18
+ //
19
+ // From a monorepo root every mode covers all the projects in one process (`ctx.projects`): one sticky comment with a
20
+ // section per project, one commit for all the locks, approvals that count only for their own project, and a project
21
+ // list that verify and merge read from the base commit through the API, never from files the pull request controls.
14
22
  import { readFileSync, writeFileSync, appendFileSync, existsSync } from 'node:fs';
15
23
  import { createHash } from 'node:crypto';
16
24
  import { execFileSync } from 'node:child_process';
17
25
  import { join } from 'node:path';
18
- import { check, exemptionsOf } from "./check.js";
19
- import { readConfig } from "./coverage.js";
26
+ import { exemptionsOf } from "./check.js";
27
+ import { checkIsolated, readReport } from "./isolate.js";
28
+ import { extendsTarget, readConfig } from "./coverage.js";
29
+ import { discoverFromFiles, discoverySignature } from "./projects.js";
20
30
  import { readManifest } from "./compile.js";
21
- import { acceptedFingerprints, inert, recordComment, decide, parseCommands, isSharedBot, parseGithubConfig, proposalsOf, pullRequestVerdict, readApprovals, renderSticky, resolveNames, stickyMarkerFor, } from "./github.js";
22
- import { classifyLawFile, lockLevels } from "./lawKinds.js";
23
- import { acceptChanges, lockChanges, readLock, writeLockValue } from "./lock.js";
31
+ import { acceptedFingerprints, inert, recordComment, decide, parseCommands, isSharedBot, parseGithubConfig, proposalsOf, pullRequestVerdict, readApprovals, renderSticky, renderStickyAll, resolveNames, stickyMarkerFor, } from "./github.js";
32
+ import { lockLevels } from "./lawKinds.js";
33
+ import { acceptChanges, lawKey, lockChanges, readLock, writeLockValue } from "./lock.js";
24
34
  import { escapeGithubData, escapeGithubProperty } from "./reporters.js";
35
+ import { plural } from "./plural.js";
25
36
  /** A project-relative file as the repository names it: the project's prefix, then the path. */
26
37
  function repoPath(ctx, file) {
27
38
  const prefix = (ctx.projectPath ?? '').replace(/^\/+|\/+$/g, '');
28
- const clean = file.replaceAll('\\', '/');
29
- return prefix === '' ? clean : `${prefix}/${clean}`;
39
+ return joinRepo(prefix, file);
40
+ }
41
+ /** Two repo-relative paths joined; either may be ''. */
42
+ export function joinRepo(prefix, file) {
43
+ const clean = file.replaceAll('\\', '/').replace(/^\/+/, '');
44
+ if (prefix === '')
45
+ return clean;
46
+ return clean === '' ? prefix : `${prefix}/${clean}`;
30
47
  }
31
48
  /** `--project-path`, else where `cwd` sits inside its git repository (`git rev-parse --show-prefix`), else ''. */
32
49
  export function projectPathOf(cwd, flag) {
@@ -109,28 +126,21 @@ export function projectState(options) {
109
126
  const laws = readManifest(options.compiler, options.files, options.cwd);
110
127
  const exempt = exemptionsOf(options);
111
128
  const mode = readConfig(options.cwd).levels ?? 'names';
112
- const levels = mode === 'imports'
113
- ? lockLevels(options.cwd, laws, 'imports')
114
- : lock?.levels !== undefined
115
- ? Object.fromEntries([...new Set(laws.map((l) => l.file.replaceAll('\\', '/')))].map((f) => [
116
- f,
117
- classifyLawFile(options.cwd, f, 'names').kind,
118
- ]))
119
- : undefined;
129
+ // Levels by name record nothing: a lock that still records them is a change until accepted again.
130
+ const levels = mode === 'imports' ? lockLevels(options.cwd, laws, 'imports') : undefined;
120
131
  return { laws, exempt, levels, lock };
121
132
  }
122
133
  async function issueComments(api, name, pr) {
123
134
  return all(api, `/repos/${name}/issues/${pr}/comments`);
124
135
  }
125
- async function upsertSticky(api, name, pr, bot, body, comments, project) {
126
- const marker = stickyMarkerFor(project);
127
- const mine = comments.find((c) => c.user.login === bot && c.body.startsWith(marker));
136
+ async function upsertSticky(api, name, pr, bots, body, comments, marker) {
137
+ const mine = comments.find((c) => bots.includes(c.user.login) && c.body.startsWith(marker));
128
138
  if (mine === undefined)
129
139
  await api('POST', `/repos/${name}/issues/${pr}/comments`, { body });
130
140
  else if (mine.body !== body)
131
141
  await api('PATCH', `/repos/${name}/issues/comments/${mine.id}`, { body });
132
142
  }
133
- function linkFor(env, sha, ctx) {
143
+ function linkFor(env, sha, project) {
134
144
  const server = env.GITHUB_SERVER_URL ?? 'https://github.com';
135
145
  const name = env.GITHUB_REPOSITORY ?? '';
136
146
  // Raw text: renderSticky makes the whole cell inert. Brackets and backticks would break the link's markdown.
@@ -138,7 +148,7 @@ function linkFor(env, sha, ctx) {
138
148
  const label = p.name.replace(/[`[\]]/g, "'");
139
149
  if (p.line === 0 || name === '')
140
150
  return `${label} (${p.file})`;
141
- return `[${label}](${server}/${name}/blob/${sha}/${repoPath(ctx, p.file).split('/').map(encodeURIComponent).join('/')}#L${p.line})`;
151
+ return `[${label}](${server}/${name}/blob/${sha}/${joinRepo(project, p.file).split('/').map(encodeURIComponent).join('/')}#L${p.line})`;
142
152
  };
143
153
  }
144
154
  /** A law name or path from the pull request, for a bot comment: inert, and quoted without a code span. */
@@ -153,15 +163,147 @@ function setOutput(env, key, value) {
153
163
  if (env.GITHUB_OUTPUT !== undefined)
154
164
  appendFileSync(env.GITHUB_OUTPUT, `${key}=${value}\n`);
155
165
  }
156
- // ---- report ---------------------------------------------------------------------------------------------------------
166
+ // ---- units ----------------------------------------------------------------------------------------------------------
167
+ /** The projects a run covers: one (the directory it runs in), or every selected project of a monorepo root. */
168
+ function unitsOf(ctx) {
169
+ return ctx.projects ?? [{ cwd: ctx.cwd, rel: '', path: repoPath(ctx, ''), options: ctx.options }];
170
+ }
171
+ const label = (unit) => (unit.path === '' ? '.' : unit.path);
172
+ /** The `github` settings in the tslaws.json of `dir`, `extends` followed (the project's own keys win); undefined if none. */
173
+ function configIn(dir) {
174
+ const raw = readConfig(dir).github;
175
+ return raw === undefined ? undefined : parseGithubConfig(raw);
176
+ }
177
+ /**
178
+ * The projects the shared flow covers, each with its own settings. A project with no `github` section is left out of a
179
+ * root run (and is an error in a single-project run, as it always was); so is one whose flow is `own`.
180
+ */
181
+ function plan(ctx, units, dirOf) {
182
+ const monorepo = ctx.projects !== undefined;
183
+ const active = [];
184
+ const all = [];
185
+ for (const unit of units) {
186
+ const config = configIn(dirOf(unit));
187
+ if (config === undefined) {
188
+ if (!monorepo)
189
+ throw new Error('tslaws github needs a "github" section in tslaws.json');
190
+ ctx.out(`::notice title=tslaws::${escapeGithubData(label(unit))} has no "github" section; the shared flow leaves it out\n`);
191
+ continue;
192
+ }
193
+ all.push({ unit, config });
194
+ if (monorepo && config.flow === 'own') {
195
+ ctx.out(`::notice title=tslaws::${escapeGithubData(label(unit))} has "flow": "own"; its own workflow covers it\n`);
196
+ continue;
197
+ }
198
+ active.push({ unit, config });
199
+ }
200
+ if (monorepo && all.length === 0)
201
+ throw new Error('no project here has a "github" section in tslaws.json');
202
+ if (monorepo && active.length === 0)
203
+ ctx.out('tslaws: every project with a "github" section runs its own flow; nothing to do here\n');
204
+ return { active, all };
205
+ }
206
+ /** The laws a project has, as this process sees them: a compile that runs none of the project. A report is held to it. */
207
+ function expectedOf(unit) {
208
+ const state = projectState(unit.options);
209
+ return {
210
+ laws: new Set(state.laws.map((law) => lawKey(law.file, law.name))),
211
+ lock: new Set(Object.keys(state.lock?.laws ?? {})),
212
+ exempt: new Set(state.exempt),
213
+ };
214
+ }
215
+ const lockShaOf = (unit) => existsSync(unit.options.lockFile) ? gitBlobSha(readFileSync(unit.options.lockFile)) : '';
216
+ const resultsRead = new WeakMap();
217
+ function resultsOf(ctx, file, mode, sha) {
218
+ const known = resultsRead.get(ctx.flags);
219
+ if (known !== undefined)
220
+ return known;
221
+ let value;
222
+ try {
223
+ value = JSON.parse(readFileSync(file, 'utf8'));
224
+ }
225
+ catch (error) {
226
+ throw new Error(`cannot read the results in ${file}: ${error instanceof Error ? error.message : String(error)}`);
227
+ }
228
+ if (typeof value !== 'object' || value === null || value.version !== 1 || typeof value.projects !== 'object')
229
+ throw new Error(`${file} is not a tslaws results file`);
230
+ if (value.mode !== mode)
231
+ throw new Error(`${file} holds results for ${String(value.mode)}, not ${mode}`);
232
+ if (value.sha !== sha)
233
+ throw new Error(`${file} was made for commit ${String(value.sha).slice(0, 7)}, but this run is for ${sha.slice(0, 7)}`);
234
+ resultsRead.set(ctx.flags, value);
235
+ return value;
236
+ }
237
+ /**
238
+ * The report of one project's laws: from the results file when `--results` names one, else from a run in a child with no
239
+ * credentials. Either way it is validated as data before anything acts on it.
240
+ */
241
+ async function runLaws(ctx, unit, mode, sha) {
242
+ const file = ctx.flags.get('results');
243
+ if (typeof file !== 'string')
244
+ return checkIsolated(unit.options, true, expectedOf(unit));
245
+ const entry = Object.hasOwn(resultsOf(ctx, file, mode, sha).projects, unit.path)
246
+ ? resultsOf(ctx, file, mode, sha).projects[unit.path]
247
+ : undefined;
248
+ if (entry === undefined)
249
+ throw new Error(`${file} has no results for ${label(unit)}`);
250
+ if (typeof entry.error === 'string')
251
+ throw new Error(entry.error);
252
+ if (entry.lockSha !== lockShaOf(unit))
253
+ throw new Error(`${label(unit)}'s lock is not the one its laws were run against`);
254
+ return readReport(entry.report, expectedOf(unit));
255
+ }
256
+ /** `--results-out <file>`: run the laws of every project and write the reports, doing nothing else. Needs no token. */
257
+ async function collect(ctx, mode, file) {
258
+ const { active } = plan(ctx, unitsOf(ctx), (u) => u.cwd);
259
+ const ev = event(ctx.env);
260
+ const sha = String(mode === 'report' ? (ev.pull_request?.head?.sha ?? ctx.env.GITHUB_SHA) : (ev.after ?? ctx.env.GITHUB_SHA));
261
+ const projects = {};
262
+ for (const { unit } of active) {
263
+ const entry = { lockSha: lockShaOf(unit) };
264
+ try {
265
+ entry.report = await checkIsolated(unit.options, true, expectedOf(unit));
266
+ }
267
+ catch (error) {
268
+ entry.error = error instanceof Error ? error.message : String(error);
269
+ }
270
+ projects[unit.path] = entry;
271
+ }
272
+ writeFileSync(file, JSON.stringify({ version: 1, mode, sha, projects }));
273
+ ctx.out(`tslaws: ran the laws of ${active.length} project${active.length === 1 ? '' : 's'}; results are in ${file}\n`);
274
+ return 0;
275
+ }
157
276
  async function report(ctx) {
158
- const config = githubConfigOf(readText(join(ctx.cwd, 'tslaws.json')));
277
+ const monorepo = ctx.projects !== undefined;
278
+ const { active } = plan(ctx, unitsOf(ctx), (u) => u.cwd);
279
+ if (active.length === 0)
280
+ return 0;
159
281
  const ev = event(ctx.env);
160
282
  const pr = Number(ctx.flags.get('pr') ?? ev.pull_request?.number ?? NaN);
161
283
  const sha = String(ev.pull_request?.head?.sha ?? ctx.env.GITHUB_SHA ?? '');
162
- const checked = await check(ctx.options, true);
163
- const state = projectState(ctx.options);
164
- const proposals = proposalsOf(lockChanges(state.lock, state.laws, state.exempt, state.levels), checked);
284
+ const ran = [];
285
+ for (const a of active) {
286
+ try {
287
+ const checked = await runLaws(ctx, a.unit, 'report', sha);
288
+ const state = projectState(a.unit.options);
289
+ ran.push({
290
+ active: a,
291
+ checked,
292
+ proposals: proposalsOf(lockChanges(state.lock, state.laws, state.exempt, state.levels), checked, a.unit.path),
293
+ });
294
+ }
295
+ catch (error) {
296
+ if (!monorepo)
297
+ throw error;
298
+ // One project that cannot run must not hide the others' reports.
299
+ ran.push({
300
+ active: a,
301
+ checked: undefined,
302
+ proposals: [],
303
+ failed: error instanceof Error ? error.message : String(error),
304
+ });
305
+ }
306
+ }
165
307
  let api;
166
308
  let comments = [];
167
309
  try {
@@ -173,48 +315,108 @@ async function report(ctx) {
173
315
  ctx.err(`tslaws: cannot read the pull request's comments (${String(error)}); reporting without approvals\n`);
174
316
  api = undefined;
175
317
  }
176
- const approvals = acceptedFingerprints(readApprovals(comments, config.bot));
177
- const verdict = pullRequestVerdict(checked, proposals, config, approvals);
178
- for (const p of proposals) {
179
- const level = p.passes ? 'notice' : 'error';
180
- const title = `tslaws proposal: ${p.name}`;
181
- const message = p.outcome === undefined
182
- ? 'did not run'
183
- : `${p.reason}; if accepted: ${p.outcome.status}${p.outcome.counterexample ? `; counterexample ${p.outcome.counterexample}` : ''}`;
184
- ctx.out(`::${level} file=${escapeGithubProperty(repoPath(ctx, p.file))},line=${Math.max(1, p.line)},title=${escapeGithubProperty(title)}::${escapeGithubData(message)}\n`);
185
- }
186
- const project = repoPath(ctx, '');
187
- const body = renderSticky(proposals, config, approvals, linkFor(ctx.env, sha, ctx), project);
188
- summary(ctx.env, body.replace(stickyMarkerFor(project), ''));
318
+ const reports = ran.map(({ active: a, checked, proposals, failed }) => {
319
+ // Only the records of this project count, and only those its own bot wrote.
320
+ const approvals = acceptedFingerprints(readApprovals(comments, a.config.bot), a.unit.path);
321
+ const verdict = checked === undefined
322
+ ? { ok: false, problems: [`the project could not be checked: ${failed ?? 'unknown error'}`] }
323
+ : pullRequestVerdict(checked, proposals, a.config, approvals);
324
+ return { active: a, proposals, approvals, verdict };
325
+ });
326
+ for (const { active: a, proposals } of reports)
327
+ for (const p of proposals) {
328
+ const level = p.passes ? 'notice' : 'error';
329
+ const title = `tslaws proposal: ${p.name}`;
330
+ const message = p.outcome === undefined
331
+ ? 'did not run'
332
+ : `${p.reason}; if accepted: ${p.outcome.status}${p.outcome.counterexample ? `; counterexample ${p.outcome.counterexample}` : ''}`;
333
+ ctx.out(`::${level} file=${escapeGithubProperty(joinRepo(a.unit.path, p.file))},line=${Math.max(1, p.line)},title=${escapeGithubProperty(title)}::${escapeGithubData(message)}\n`);
334
+ }
335
+ const rootPath = repoPath(ctx, '');
336
+ const marker = stickyMarkerFor(rootPath);
337
+ const body = monorepo
338
+ ? renderStickyAll(reports.map((r) => ({
339
+ project: r.active.unit.path,
340
+ proposals: r.proposals,
341
+ config: r.active.config,
342
+ approvals: r.approvals,
343
+ link: linkFor(ctx.env, sha, r.active.unit.path),
344
+ })), marker)
345
+ : (() => {
346
+ const [only] = reports;
347
+ return renderSticky(only.proposals, only.active.config, only.approvals, linkFor(ctx.env, sha, rootPath), rootPath);
348
+ })();
349
+ summary(ctx.env, body.replace(marker, ''));
350
+ const bots = [...new Set(active.map((a) => a.config.bot))];
189
351
  if (api !== undefined && Number.isInteger(pr) && ctx.flags.has('comment')) {
190
352
  try {
191
- await upsertSticky(api, repo(ctx.env), pr, config.bot, body, comments, project);
353
+ await upsertSticky(api, repo(ctx.env), pr, bots, body, comments, marker);
354
+ // A root run's one comment replaces the per-project comments an earlier, per-project workflow left.
355
+ if (monorepo)
356
+ for (const { unit } of active) {
357
+ if (unit.path === rootPath)
358
+ continue;
359
+ const old = stickyMarkerFor(unit.path);
360
+ for (const c of comments)
361
+ if (bots.includes(c.user.login) && c.body.startsWith(old))
362
+ await api('DELETE', `/repos/${repo(ctx.env)}/issues/comments/${c.id}`).catch(() => undefined);
363
+ }
192
364
  }
193
365
  catch (error) {
194
366
  // A pull request from a fork gets a read-only token: the step summary and annotations still carry the report.
195
367
  ctx.err(`tslaws: cannot write the sticky comment (${String(error)})\n`);
196
368
  }
197
369
  }
370
+ const proposals = reports.flatMap((r) => r.proposals);
371
+ const ok = reports.every((r) => r.verdict.ok);
198
372
  const outFile = ctx.flags.get('out');
199
- if (typeof outFile === 'string')
200
- writeFileSync(outFile, `${JSON.stringify({ sha, proposals, verdict }, null, 2)}\n`);
373
+ if (typeof outFile === 'string') {
374
+ const verdict = {
375
+ ok,
376
+ problems: reports.flatMap((r) => r.verdict.problems.map((p) => (monorepo ? `[${label(r.active.unit)}] ${p}` : p))),
377
+ };
378
+ const projects = monorepo
379
+ ? {
380
+ projects: reports.map((r) => ({ project: r.active.unit.path, proposals: r.proposals, verdict: r.verdict })),
381
+ }
382
+ : {};
383
+ writeFileSync(outFile, `${JSON.stringify({ sha, proposals, verdict, ...projects }, null, 2)}\n`);
384
+ }
201
385
  setOutput(ctx.env, 'proposals', String(proposals.length));
202
- for (const problem of verdict.problems)
203
- ctx.out(`${problem}\n`);
204
- ctx.out(verdict.ok ? `tslaws: ${proposals.length} proposal(s), all passing\n` : 'tslaws: the pull request is not ready\n');
205
- return verdict.ok ? 0 : 1;
206
- }
207
- function readText(path) {
208
- return existsSync(path) ? readFileSync(path, 'utf8') : undefined;
386
+ for (const r of reports)
387
+ for (const problem of r.verdict.problems)
388
+ ctx.out(`${monorepo ? `[${label(r.active.unit)}] ` : ''}${problem}\n`);
389
+ ctx.out(ok
390
+ ? `tslaws: ${plural(proposals.length, 'proposal')}${monorepo ? ` in ${plural(reports.length, 'project')}` : ''}, all passing\n`
391
+ : 'tslaws: the pull request is not ready\n');
392
+ return ok ? 0 : 1;
209
393
  }
210
394
  // ---- command --------------------------------------------------------------------------------------------------------
211
395
  const rank = { none: 0, read: 1, triage: 2, write: 3, maintain: 4, admin: 5 };
396
+ /** The repository permission `login` holds, as a rank (0 for a non-collaborator). Throws when GitHub cannot say. */
397
+ async function permissionRank(api, name, login) {
398
+ const permission = (await api('GET', `/repos/${name}/collaborators/${encodeURIComponent(login)}/permission`));
399
+ return Math.max(rank[permission?.permission ?? ''] ?? 0, rank[permission?.role_name ?? ''] ?? 0);
400
+ }
401
+ /**
402
+ * Whether `login` has `admin` or `maintain` access: the people who may change tsc-laws.lock by hand or run the merge
403
+ * job on demand. A bot never counts, and neither does a login whose permission cannot be read.
404
+ */
405
+ export async function maintains(api, name, login, type = 'User') {
406
+ if (type === 'Bot' || login.endsWith('[bot]'))
407
+ return false;
408
+ try {
409
+ return (await permissionRank(api, name, login)) >= rank.maintain;
410
+ }
411
+ catch {
412
+ return false;
413
+ }
414
+ }
212
415
  /** Why `login` may not accept on this pull request, or undefined when they may. */
213
416
  export async function refusal(api, name, pr, login, type, config) {
214
417
  if (type === 'Bot' || login.endsWith('[bot]'))
215
418
  return 'bots cannot accept laws';
216
- const permission = (await api('GET', `/repos/${name}/collaborators/${encodeURIComponent(login)}/permission`));
217
- const level = Math.max(rank[permission.permission] ?? 0, rank[permission.role_name ?? ''] ?? 0);
419
+ const level = await permissionRank(api, name, login);
218
420
  if (level < rank.write)
219
421
  return `@${login} needs write access to the repository`;
220
422
  for (const kind of config.approvers) {
@@ -232,9 +434,77 @@ export async function refusal(api, name, pr, login, type, config) {
232
434
  }
233
435
  return `@${login} is not one of the approvers this project names (${config.approvers.join(', ')})`;
234
436
  }
437
+ /**
438
+ * Whether the bot may approve the pull request: every project with proposals, whatever its flow, has all of them
439
+ * accepted here and has opted in with `approvePullRequest`. A project that was declined, skipped, runs its own flow, or
440
+ * cannot be read counts against it, so one project's acceptance never approves another's pending proposals.
441
+ */
442
+ async function everyProposalAccepted(all, eligible, byProject, comments) {
443
+ let any = false;
444
+ for (const a of all) {
445
+ const counted = eligible.some((e) => e.unit.path === a.unit.path);
446
+ let proposals;
447
+ try {
448
+ proposals =
449
+ byProject.get(a.unit.path) ??
450
+ (() => {
451
+ const state = projectState(a.unit.options);
452
+ return proposalsOf(lockChanges(state.lock, state.laws, state.exempt, state.levels), undefined, a.unit.path);
453
+ })();
454
+ }
455
+ catch {
456
+ return false;
457
+ }
458
+ if (proposals.length === 0)
459
+ continue;
460
+ any = true;
461
+ if (!counted || !a.config.approvePullRequest)
462
+ return false;
463
+ const approvals = acceptedFingerprints(readApprovals(comments, a.config.bot), a.unit.path);
464
+ if (!proposals.every((p) => approvals.has(p.fingerprint)))
465
+ return false;
466
+ }
467
+ return any;
468
+ }
469
+ /**
470
+ * Whether the projects this run decided over are the projects the base commit has. The list in the pull request's own
471
+ * checkout can be steered by the pull request, so before approving, the base's list is read through the API and the
472
+ * pull request must not change how projects are found, nor any project's `github` (so `flow`), `standalone` or lock.
473
+ * It also must not add or remove a project. Anything unreadable counts as a change: no approval.
474
+ */
475
+ async function discoveryHolds(ctx, api, name, pr, discovered) {
476
+ const problems = [];
477
+ try {
478
+ const read = readerOf(api, name);
479
+ const changed = await changedFiles(api, name, pr);
480
+ const { baseSide, headSide } = await inspectMonorepo(api, name, read, pr, changed, repoPath(ctx, ''), problems);
481
+ const head = new Set(headSide.paths);
482
+ const decided = new Set(discovered);
483
+ for (const rel of baseSide.paths) {
484
+ if (!head.has(rel))
485
+ problems.push(`${rel || '.'} is a project on the base and not on the pull request`);
486
+ if (!decided.has(rel))
487
+ problems.push(`${rel || '.'} is a project on the base that this run did not read`);
488
+ }
489
+ const base = new Set(baseSide.paths);
490
+ for (const rel of headSide.paths)
491
+ if (!base.has(rel))
492
+ problems.push(`${rel || '.'} is a new project`);
493
+ }
494
+ catch (error) {
495
+ problems.push(error instanceof Error ? error.message : String(error));
496
+ }
497
+ if (problems.length > 0)
498
+ ctx.out(`::notice title=tslaws::${escapeGithubData(`not approving the pull request: ${problems[0]}${problems.length > 1 ? ` (and ${problems.length - 1} more)` : ''}`)}\n`);
499
+ return problems.length === 0;
500
+ }
235
501
  async function command(ctx) {
502
+ const monorepo = ctx.projects !== undefined;
236
503
  // The base branch's config: the workflow checks the default branch out at the root and the pull request beside it.
237
- const config = githubConfigOf(readText(join(String(ctx.flags.get('config-from') ?? ctx.cwd), 'tslaws.json')));
504
+ const trusted = String(ctx.flags.get('config-from') ?? ctx.cwd);
505
+ const { active, all } = plan(ctx, unitsOf(ctx), (u) => join(trusted, u.rel));
506
+ if (active.length === 0)
507
+ return 0;
238
508
  const ev = event(ctx.env);
239
509
  if (ev.action !== 'created' || ev.issue?.pull_request === undefined)
240
510
  return 0;
@@ -247,14 +517,41 @@ async function command(ctx) {
247
517
  const number = Number(ev.issue.number);
248
518
  const reply = (text) => api('POST', `/repos/${name}/issues/${number}/comments`, { body: text });
249
519
  const login = String(ev.comment.user.login);
250
- const pr = (await api('GET', `/repos/${name}/pulls/${number}`));
251
- if (config.accept !== 'comment') {
252
- await reply(`@${login} this project accepts passing proposals on merge into \`${config.branch}\`; there is nothing to accept by comment.`);
520
+ // A command that cannot be followed records nothing, even beside commands that can: a `--project` with no directory
521
+ // would otherwise read as "every project".
522
+ const unusable = commands.find((c) => c.error !== undefined);
523
+ if (unusable !== undefined) {
524
+ await reply(`@${login} Not recorded: ${unusable.error}.`);
253
525
  return 0;
254
526
  }
255
- const refused = await refusal(api, name, pr, login, String(ev.comment.user.type ?? 'User'), config);
256
- if (refused !== undefined) {
257
- await reply(`Not recorded: ${refused}.`);
527
+ const pr = (await api('GET', `/repos/${name}/pulls/${number}`));
528
+ // Each project decides for itself: its own mode and its own approvers. The commenter accepts only where they may.
529
+ const eligible = [];
530
+ const declined = [];
531
+ for (const a of active) {
532
+ if (a.config.accept !== 'comment') {
533
+ const text = `this project accepts passing proposals on merge into \`${a.config.branch}\`; there is nothing to accept by comment`;
534
+ if (!monorepo) {
535
+ await reply(`@${login} ${text}.`);
536
+ return 0;
537
+ }
538
+ declined.push(`- ${shown(label(a.unit))}: ${text}`);
539
+ continue;
540
+ }
541
+ const refused = await refusal(api, name, pr, login, String(ev.comment.user.type ?? 'User'), a.config);
542
+ if (refused !== undefined) {
543
+ if (!monorepo) {
544
+ await reply(`Not recorded: ${refused}.`);
545
+ return 0;
546
+ }
547
+ declined.push(`- ${shown(label(a.unit))}: not recorded, ${refused}`);
548
+ continue;
549
+ }
550
+ eligible.push(a);
551
+ }
552
+ if (eligible.length === 0) {
553
+ if (declined.length > 0)
554
+ await reply(`@${login}\n${declined.join('\n')}`);
258
555
  return 0;
259
556
  }
260
557
  const checkedOut = String(ctx.flags.get('head-sha') ?? '');
@@ -267,25 +564,38 @@ async function command(ctx) {
267
564
  await reply(`Not recorded: you named ${pinned}, but the pull request is at ${pr.head.sha.slice(0, 7)}.`);
268
565
  return 0;
269
566
  }
270
- const state = projectState(ctx.options);
271
- const proposals = proposalsOf(lockChanges(state.lock, state.laws, state.exempt, state.levels), undefined);
272
- const lines = [];
567
+ const byProject = new Map();
568
+ for (const a of eligible) {
569
+ const state = projectState(a.unit.options);
570
+ byProject.set(a.unit.path, proposalsOf(lockChanges(state.lock, state.laws, state.exempt, state.levels), undefined, a.unit.path));
571
+ }
572
+ const proposals = [...byProject.values()].flat();
573
+ const lines = [...declined];
273
574
  const records = [];
575
+ const where = (p) => (monorepo ? `${shown(p.project ?? '')}, ` : '');
274
576
  for (const cmd of commands) {
275
577
  const { matched, unknown, ambiguous } = resolveNames(proposals, cmd);
276
578
  if (unknown.length > 0)
277
579
  lines.push(`- no proposal named ${unknown.map(shown).join(', ')}`);
278
580
  if (ambiguous.length > 0)
279
- lines.push(`- ${ambiguous.map(shown).join(', ')} names laws in several files; use \`file::name\``);
581
+ lines.push(monorepo
582
+ ? `- ${ambiguous.map(shown).join(', ')} names laws in several files or projects; use the path from the repository root with \`::name\`, or add \`--project <dir>\``
583
+ : `- ${ambiguous.map(shown).join(', ')} names laws in several files; use \`file::name\``);
280
584
  if (matched.length === 0)
281
585
  continue;
282
- records.push({
283
- verb: cmd.verb,
284
- by: login,
285
- sha: pr.head.sha,
286
- items: matched.map((p) => ({ key: p.key, fingerprint: p.fingerprint })),
287
- });
288
- lines.push(`- ${cmd.verb === 'accept' ? 'accepted' : 'withdrew'} ${matched.map((p) => `${shown(p.name)} (${shown(p.file)}, ${p.reason})`).join(', ')}`);
586
+ // One record per project, each carrying its project: it counts for that project's lock and nowhere else.
587
+ for (const path of new Set(matched.map((p) => p.project ?? ''))) {
588
+ records.push({
589
+ verb: cmd.verb,
590
+ by: login,
591
+ sha: pr.head.sha,
592
+ project: path,
593
+ items: matched
594
+ .filter((p) => (p.project ?? '') === path)
595
+ .map((p) => ({ key: p.key, fingerprint: p.fingerprint })),
596
+ });
597
+ }
598
+ lines.push(`- ${cmd.verb === 'accept' ? 'accepted' : 'withdrew'} ${matched.map((p) => `${shown(p.name)} (${where(p)}${shown(p.file)}, ${p.reason})`).join(', ')}`);
289
599
  }
290
600
  const text = `@${login} at ${pr.head.sha.slice(0, 7)}:\n${lines.join('\n') || '- nothing matched'}\n\n${records.length > 0 ? 'Recorded. The laws are written to `tsc-laws.lock` on merge, if they still pass and have not changed since.' : ''}`;
291
601
  await reply(text);
@@ -300,10 +610,10 @@ async function command(ctx) {
300
610
  catch {
301
611
  // a reaction is a courtesy
302
612
  }
303
- if (records.length > 0 && config.approvePullRequest) {
613
+ if (records.length > 0 && eligible.some((a) => a.config.approvePullRequest)) {
304
614
  const comments = await issueComments(api, name, number);
305
- const approvals = acceptedFingerprints(readApprovals(comments, config.bot));
306
- if (proposals.length > 0 && proposals.every((p) => approvals.has(p.fingerprint)))
615
+ if ((await everyProposalAccepted(all, eligible, byProject, comments)) &&
616
+ (!monorepo || (await discoveryHolds(ctx, api, name, pr, ctx.discovered ?? all.map((a) => a.unit.rel)))))
307
617
  await api('POST', `/repos/${name}/pulls/${number}/reviews`, {
308
618
  commit_id: pr.head.sha,
309
619
  event: 'APPROVE',
@@ -320,147 +630,646 @@ async function command(ctx) {
320
630
  }
321
631
  return 0;
322
632
  }
323
- // ---- merge ----------------------------------------------------------------------------------------------------------
633
+ /**
634
+ * The contents API URL of a repository path. Every segment and the ref are encoded, so a `?`, `#`, `&` or `%` in a name
635
+ * a pull request controls cannot add to or override the query string (for example the `ref`).
636
+ */
637
+ function contentsUrl(name, path, ref) {
638
+ const encoded = path.split('/').map(encodeURIComponent).join('/');
639
+ return `/repos/${name}/contents/${encoded}${ref === undefined ? '' : `?ref=${encodeURIComponent(ref)}`}`;
640
+ }
641
+ function readerOf(api, name) {
642
+ return async (path, ref) => {
643
+ let file;
644
+ try {
645
+ file = (await api('GET', contentsUrl(name, path, ref)));
646
+ }
647
+ catch {
648
+ return undefined;
649
+ }
650
+ // A symlink, a submodule or a directory is not a blob: refuse it rather than read it as missing.
651
+ if (Array.isArray(file) || (file.type !== undefined && file.type !== 'file') || typeof file.content !== 'string')
652
+ throw new Error(`${path} is not a regular file at ${ref.slice(0, 7)} (a symlink, a submodule or a directory)`);
653
+ return Buffer.from(file.content, 'base64').toString('utf8');
654
+ };
655
+ }
656
+ /** `tsc-laws.lock` by name, wherever it is. */
657
+ const isLock = (path) => path === 'tsc-laws.lock' || path.endsWith('/tsc-laws.lock');
658
+ /**
659
+ * The projects a commit has, from the repository's tree and the three files that decide it, read through the API:
660
+ * paths relative to the monorepo root (`prefix` is where that root sits in the repository). Never from a checkout, so
661
+ * a pull request cannot change what is read by changing its own files.
662
+ */
663
+ async function projectsAt(api, name, read, sha, prefix) {
664
+ const tree = await treeAt(api, name, sha);
665
+ const lead = prefix === '' ? '' : `${prefix}/`;
666
+ const files = (tree.tree ?? [])
667
+ .filter((entry) => entry.type === 'blob' && entry.path.startsWith(lead))
668
+ .map((entry) => entry.path.slice(lead.length));
669
+ const inputs = {};
670
+ const [tslaws, packageJson, pnpmWorkspace] = await Promise.all(['tslaws.json', 'package.json', 'pnpm-workspace.yaml'].map((file) => read(joinRepo(prefix, file), sha)));
671
+ if (tslaws !== undefined)
672
+ inputs.tslaws = tslaws;
673
+ if (packageJson !== undefined)
674
+ inputs.packageJson = packageJson;
675
+ if (pnpmWorkspace !== undefined)
676
+ inputs.pnpmWorkspace = pnpmWorkspace;
677
+ return { paths: discoverFromFiles(files, inputs), inputs, truncated: tree.truncated === true, locks: tree.locks };
678
+ }
679
+ /** Every blob of a commit's tree, and the blob id of each `tsc-laws.lock`: a changed id is a changed lock. */
680
+ async function treeAt(api, name, sha) {
681
+ const got = (await api('GET', `/repos/${name}/git/trees/${encodeURIComponent(sha)}?recursive=1`));
682
+ const tree = got.tree ?? [];
683
+ const locks = new Map();
684
+ for (const entry of tree)
685
+ if (entry.type === 'blob' && isLock(entry.path))
686
+ locks.set(entry.path, entry.sha ?? '');
687
+ return { tree, truncated: got.truncated === true, locks };
688
+ }
689
+ /** The locks that differ between two commits: added, removed or changed, by repository path. */
690
+ function lockDifferences(base, head) {
691
+ const paths = new Set([...base.keys(), ...head.keys()]);
692
+ return [...paths].filter((path) => base.get(path) !== head.get(path)).sort();
693
+ }
694
+ /**
695
+ * A project's `github` section and `standalone` flag at a commit, with every file read to find them: its tslaws.json
696
+ * and the files it `extends`, the project's own keys winning, as `readConfig` does on disk.
697
+ */
698
+ async function settingsAt(read, ref, dir) {
699
+ const files = [];
700
+ let standalone = false;
701
+ const load = async (path, first, trail) => {
702
+ if (trail.includes(path))
703
+ throw new Error(`${path}: "extends" forms a cycle (${[...trail, path].join(' -> ')})`);
704
+ if (!files.includes(path))
705
+ files.push(path);
706
+ const text = await read(path, ref);
707
+ if (text === undefined) {
708
+ // The project's own file may be absent (a project with no tslaws.json); an `extends` target that cannot be read is
709
+ // not, because the settings would then be a guess.
710
+ if (first)
711
+ return undefined;
712
+ throw new Error(`${path} is named by "extends" and cannot be read at ${ref.slice(0, 7)}`);
713
+ }
714
+ let json;
715
+ try {
716
+ json = JSON.parse(text);
717
+ }
718
+ catch {
719
+ // The parser's message quotes the file's text, which is not ours to echo into a log.
720
+ throw new Error(`${path} is not valid JSON`);
721
+ }
722
+ if (typeof json !== 'object' || json === null || Array.isArray(json))
723
+ throw new Error(`${path} is not an object`);
724
+ if (first)
725
+ standalone = json.standalone === true;
726
+ // The same rules loadMerged applies to the files on disk (coverage.ts), so both sides resolve one target.
727
+ const inherited = json.extends === undefined ? undefined : await load(extendsTarget(path, json.extends), false, [...trail, path]);
728
+ const own = json.github;
729
+ if (own === undefined)
730
+ return inherited;
731
+ const plain = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
732
+ return plain(inherited) && plain(own) ? { ...inherited, ...own } : own;
733
+ };
734
+ const github = await load(joinRepo(dir, 'tslaws.json'), true, []);
735
+ return { github, standalone, files };
736
+ }
324
737
  async function merge(ctx) {
325
- const lockPath = repoPath(ctx, 'tsc-laws.lock');
326
- const configText = readText(join(ctx.cwd, 'tslaws.json'));
327
- const config = githubConfigOf(configText);
328
- if (isSharedBot(config))
329
- ctx.out(`::warning title=tslaws::"bot" is ${config.bot}, which every workflow can act as; only a ruleset on ${config.branch} that restricts ${lockPath} keeps other workflows from writing it. A dedicated GitHub App closes this.
330
- `);
738
+ const monorepo = ctx.projects !== undefined;
739
+ const rootPath = repoPath(ctx, '');
740
+ const failures = [];
741
+ const fail = (text) => {
742
+ failures.push(text);
743
+ ctx.err(`${text}\n`);
744
+ };
745
+ let units = unitsOf(ctx);
331
746
  const ev = event(ctx.env);
332
747
  const ref = String(ev.ref ?? ctx.env.GITHUB_REF ?? '');
333
- if (ref !== `refs/heads/${config.branch}`) {
334
- ctx.err(`tslaws: ${ref} is not refs/heads/${config.branch}; the lock is written only there\n`);
748
+ const sha = String(ev.after ?? ctx.env.GITHUB_SHA ?? '');
749
+ const before = String(ev.before ?? '');
750
+ const known = /^[0-9a-f]{40}$/.test(before) && !/^0+$/.test(before);
751
+ const api = ctx.api ?? restApi(ctx.env);
752
+ const name = repo(ctx.env);
753
+ if (monorepo && known) {
754
+ // The projects the base of this push had count too, whatever the pushed files now say discovers.
755
+ try {
756
+ const base = await projectsAt(api, name, readerOf(api, name), before, rootPath);
757
+ if (base.truncated)
758
+ fail('tslaws: the repository is too large for the API to list its files; cannot check the projects');
759
+ const here = new Set(ctx.discovered ?? units.map((u) => u.rel));
760
+ for (const rel of base.paths) {
761
+ if (here.has(rel))
762
+ continue;
763
+ const options = ctx.optionsFor?.(rel);
764
+ if (options === undefined) {
765
+ ctx.out(`::notice title=tslaws::${escapeGithubData(rel || '.')} was a project before this push and is gone\n`);
766
+ continue;
767
+ }
768
+ fail(`tslaws: ${rel || '.'} was a project before this push and still exists, but is no longer discovered; its lock is checked here anyway`);
769
+ units = [...units, { cwd: join(ctx.cwd, rel), rel, path: joinRepo(rootPath, rel), options }];
770
+ }
771
+ }
772
+ catch (error) {
773
+ fail(`tslaws: cannot read the projects of ${before.slice(0, 7)} (${String(error)})`);
774
+ }
775
+ }
776
+ const { active, all } = plan(ctx, units, (u) => u.cwd);
777
+ for (const a of active)
778
+ if (isSharedBot(a.config))
779
+ ctx.out(`::warning title=tslaws::"bot" is ${a.config.bot}, which every workflow can act as; only a ruleset on ${a.config.branch} that restricts ${joinRepo(a.unit.path, 'tsc-laws.lock')} keeps other workflows from writing it. A dedicated GitHub App closes this.
780
+ `);
781
+ const onBranch = active.filter((a) => ref === `refs/heads/${a.config.branch}`);
782
+ if (active.length === 0)
783
+ return 0;
784
+ if (onBranch.length === 0) {
785
+ const branches = [...new Set(active.map((a) => `refs/heads/${a.config.branch}`))];
786
+ ctx.err(`tslaws: ${ref} is not ${branches.join(' or ') || 'a branch any project writes'}; the lock is written only there\n`);
335
787
  return 1;
336
788
  }
337
- if (ctx.env.GITHUB_EVENT_NAME !== undefined && ctx.env.GITHUB_EVENT_NAME !== 'push') {
338
- ctx.err('tslaws: merge runs on push only\n');
789
+ const eventName = ctx.env.GITHUB_EVENT_NAME;
790
+ if (eventName !== undefined && eventName !== 'push' && eventName !== 'workflow_dispatch') {
791
+ ctx.err('tslaws: merge runs on push and workflow_dispatch only\n');
339
792
  return 1;
340
793
  }
794
+ // On demand there is no push and no pull request, so whoever started the run is the authority, and only someone
795
+ // with admin or maintain access may start it. A re-run keeps GITHUB_ACTOR (who first started the workflow) and names
796
+ // the person who re-ran it in GITHUB_TRIGGERING_ACTOR, so both must qualify.
797
+ const dispatched = eventName === 'workflow_dispatch';
798
+ const starter = String(ctx.env.GITHUB_ACTOR ?? ev.sender?.login ?? '');
799
+ const rerunner = String(ctx.env.GITHUB_TRIGGERING_ACTOR ?? '');
800
+ const actor = rerunner === '' ? starter : rerunner;
801
+ if (dispatched)
802
+ for (const login of new Set(rerunner === '' ? [starter] : [starter, rerunner])) {
803
+ if (login === '' || !(await maintains(api, name, login))) {
804
+ ctx.err(`tslaws: ${login === '' ? 'nobody' : `@${login}`} needs admin or maintain access to run this on demand\n`);
805
+ return 1;
806
+ }
807
+ }
808
+ const branch = ref.slice('refs/heads/'.length);
809
+ // A run can wait in the queue while the branch moves on. It would then test an older checkout and write its lock over
810
+ // the newer commits, so an on-demand run must be on the branch's current head, read from the API.
811
+ if (dispatched) {
812
+ const head = (await api('GET', `/repos/${name}/git/ref/heads/${encodeURIComponent(branch)}`).catch(() => undefined));
813
+ const current = head?.object?.sha;
814
+ const checkedOut = String(ctx.env.GITHUB_SHA ?? '');
815
+ if (current === undefined || checkedOut === '' || current !== checkedOut) {
816
+ ctx.err(`tslaws: ${current === undefined
817
+ ? `the head of ${branch} could not be read`
818
+ : `${branch} is at ${current.slice(0, 7)} but this run checked out ${checkedOut === '' ? 'no commit' : checkedOut.slice(0, 7)}`}; nothing accepted. Run it again on the current head.
819
+ `);
820
+ return 1;
821
+ }
822
+ }
341
823
  const commits = (ev.commits ?? []);
342
- const touches = (c) => [...(c.modified ?? []), ...(c.added ?? []), ...(c.removed ?? [])].includes(lockPath);
343
- const api = ctx.api ?? restApi(ctx.env);
344
- const name = repo(ctx.env);
345
- const sha = String(ev.after ?? ctx.env.GITHUB_SHA ?? '');
824
+ const pathsOf = (c) => [...(c.modified ?? []), ...(c.added ?? []), ...(c.removed ?? [])];
825
+ const lockOf = (unit) => joinRepo(unit.path, 'tsc-laws.lock');
826
+ // Every lock this repository has, with the bot that may write it where its settings are known.
827
+ const botsOf = new Map();
828
+ for (const a of all)
829
+ botsOf.set(lockOf(a.unit), [a.config.bot]);
830
+ const anyBot = [...new Set(all.map((a) => a.config.bot))];
831
+ for (const rel of ctx.discovered ?? []) {
832
+ const lock = joinRepo(joinRepo(rootPath, rel), 'tsc-laws.lock');
833
+ if (botsOf.has(lock))
834
+ continue;
835
+ let bot;
836
+ try {
837
+ bot = configIn(join(ctx.cwd, rel))?.bot;
838
+ }
839
+ catch {
840
+ bot = undefined;
841
+ }
842
+ botsOf.set(lock, bot === undefined ? anyBot : [bot]);
843
+ }
844
+ const watched = (path) => (monorepo ? isLock(path) : onBranch.some((a) => lockOf(a.unit) === path));
845
+ const touches = (c) => pathsOf(c).filter(watched);
346
846
  // Made by the bot, as GitHub sees it: the account and a signature GitHub verified. The push payload's author name
347
847
  // comes from the commit's e-mail address, which anyone can set, so it is not enough on its own.
348
- const byBot = async (id) => {
349
- const detail = (await api('GET', `/repos/${name}/commits/${id}`));
350
- return detail.author?.login === config.bot && detail.commit.verification?.verified === true;
848
+ const details = new Map();
849
+ const byBot = async (id, bots) => {
850
+ if (!details.has(id))
851
+ details.set(id, api('GET', `/repos/${name}/commits/${id}`));
852
+ const detail = await details.get(id);
853
+ return bots.includes(detail.author?.login ?? '') && detail.commit.verification?.verified === true;
854
+ };
855
+ const botsFor = (path) => botsOf.get(path) ?? anyBot;
856
+ // Or, while the project's "local" is true, one that reached its branch through a merged pull request where the pull
857
+ // request's author, the person who merged it, and the commit's own author (as GitHub sees them) all have admin
858
+ // or maintain access: that person changed the lock by hand and answers for it.
859
+ const people = new Map();
860
+ const maintainer = async (person) => {
861
+ if (person === undefined || person === null || person.login === '')
862
+ return false;
863
+ if (!people.has(person.login))
864
+ people.set(person.login, await maintains(api, name, person.login, person.type));
865
+ return people.get(person.login) === true;
351
866
  };
867
+ const viaMaintainer = async (id, branchName) => {
868
+ const detail = (await api('GET', `/repos/${name}/commits/${id}`).catch(() => undefined));
869
+ if (!(await maintainer(detail?.author)))
870
+ return false;
871
+ const found = await api('GET', `/repos/${name}/commits/${id}/pulls`).catch(() => undefined);
872
+ for (const listed of Array.isArray(found) ? found : []) {
873
+ if ((listed.merged_at ?? null) === null && listed.merged !== true)
874
+ continue;
875
+ if (listed.base.ref !== branchName)
876
+ continue;
877
+ if (!(await maintainer(listed.user)))
878
+ continue;
879
+ // The list omits who merged it.
880
+ const full = (await api('GET', `/repos/${name}/pulls/${listed.number}`).catch(() => undefined));
881
+ if (await maintainer(full?.merged_by))
882
+ return true;
883
+ }
884
+ return false;
885
+ };
886
+ const trustedLock = async (id, config) => (await byBot(id, [config.bot])) || (config.local && (await viaMaintainer(id, config.branch)));
887
+ // Every commit from `from` to `to` that changed the lock is trusted, and the range is whole (no gap, no cut list).
888
+ const lockTrustedBetween = async (from, to, lockPath, config) => {
889
+ const range = (await api('GET', `/repos/${name}/compare/${from}...${to}`));
890
+ const since = new Set(range.commits.map((c) => c.sha));
891
+ const touched = (await api('GET', `/repos/${name}/commits?sha=${to}&path=${encodeURIComponent(lockPath)}&per_page=100`));
892
+ if (range.status !== 'ahead' || range.ahead_by !== range.commits.length || touched.length >= 100)
893
+ return false;
894
+ for (const c of touched)
895
+ if (since.has(c.sha) && !(await trustedLock(c.sha, config)))
896
+ return false;
897
+ return true;
898
+ };
899
+ const who = (config) => config.local
900
+ ? `${config.bot} with a verified signature, nor merged through a pull request from someone with admin or maintain access`
901
+ : `${config.bot} with a verified signature`;
352
902
  // The payload lists at most 20 commits; a longer push is never taken for the bot's.
353
- if (commits.length > 0 && commits.length < 20 && commits.every(touches)) {
354
- let all = true;
903
+ if (!dispatched && commits.length > 0 && commits.length < 20 && commits.every((c) => touches(c).length > 0)) {
904
+ let bots = true;
355
905
  for (const c of commits)
356
- if (!(await byBot(c.id)))
357
- all = false;
358
- if (all) {
906
+ for (const path of touches(c))
907
+ if (!(await byBot(c.id, botsFor(path))))
908
+ bots = false;
909
+ if (bots && failures.length === 0) {
359
910
  ctx.out('tslaws: this push is the bot writing the lock; nothing to do\n');
360
911
  return 0;
361
912
  }
362
913
  }
363
- for (const c of commits.filter(touches))
364
- if (!(await byBot(c.id))) {
365
- ctx.err(`tslaws: commit ${c.id.slice(0, 7)} changed ${lockPath} but was not made by ${config.bot} with a verified signature; nothing accepted. Revert it.\n`);
366
- return 1;
914
+ // A lock that belongs to no project here (one a pull request added, or a project it dropped from discovery) is
915
+ // outside every flow: nothing may change it but the bot.
916
+ if (monorepo) {
917
+ const owned = new Set(onBranch.map((a) => lockOf(a.unit)));
918
+ for (const c of commits)
919
+ for (const path of touches(c))
920
+ if (!owned.has(path) && !(await byBot(c.id, botsFor(path))))
921
+ fail(`tslaws: commit ${c.id.slice(0, 7)} changed ${path} but was not made by ${botsFor(path).join(' or ')} with a verified signature; revert it`);
922
+ }
923
+ const pulls = dispatched ? [] : (await api('GET', `/repos/${name}/commits/${sha}/pulls`));
924
+ const commentsOf = new Map();
925
+ const commentsFor = (pr) => {
926
+ if (!commentsOf.has(pr.number))
927
+ commentsOf.set(pr.number, issueComments(api, name, pr.number));
928
+ return commentsOf.get(pr.number);
929
+ };
930
+ const verdicts = new Map();
931
+ const writes = [];
932
+ const sections = [];
933
+ let held = 0;
934
+ let accepted = 0;
935
+ for (const { unit, config } of onBranch) {
936
+ const lockPath = lockOf(unit);
937
+ const lockFile = unit.options.lockFile;
938
+ // Per project: one project's failure leaves the others' locks to be written.
939
+ const stop = (text) => {
940
+ fail(text);
941
+ sections.push(`- 🚫 ${shown(label(unit))}: not accepted: ${text.replace(/^tslaws: /, '')}`);
942
+ };
943
+ // On demand, the run builds on the lock as the branch holds it, so where that lock came from matters: the latest
944
+ // commit that changed it must be trusted. (The bot refuses to build on an untrusted lock, and a maintainer answers
945
+ // for the lock they merge, so an older change under a trusted commit was vouched for by whoever made that commit.)
946
+ if (dispatched) {
947
+ // No pull request means no author or reviewers to match, so the project's access levels decide: whoever starts
948
+ // or re-runs the job must reach the lowest level its "approvers" names (admin when it names only admin), and
949
+ // never less than maintain.
950
+ const levels = config.approvers.flatMap((kind) => (kind in rank ? [rank[kind]] : []));
951
+ const needed = Math.max(rank.maintain, ...(levels.length > 0 ? [Math.min(...levels)] : []));
952
+ let short;
953
+ for (const login of new Set(rerunner === '' ? [starter] : [starter, rerunner]))
954
+ if (short === undefined && (await permissionRank(api, name, login).catch(() => 0)) < needed)
955
+ short = login;
956
+ if (short !== undefined) {
957
+ stop(`tslaws: @${short} needs ${needed >= rank.admin ? 'admin' : 'admin or maintain'} access to accept in this project on demand (its approvers are ${config.approvers.join(', ')}); nothing accepted.`);
958
+ continue;
959
+ }
960
+ const latest = await api('GET', `/repos/${name}/commits?sha=${encodeURIComponent(config.branch)}&path=${encodeURIComponent(lockPath)}&per_page=1`).catch(() => undefined);
961
+ const newest = Array.isArray(latest) ? latest[0] : undefined;
962
+ if (!Array.isArray(latest) ||
963
+ (newest !== undefined && !(await trustedLock(newest.sha, config).catch(() => false)))) {
964
+ stop(`tslaws: ${newest === undefined ? `the history of ${lockPath} on ${config.branch} could not be read` : `the latest commit that changed ${lockPath} on ${config.branch} (${newest.sha.slice(0, 7)}) was not made by ${who(config)}`}; nothing accepted. Merge the lock through a pull request from a maintainer, or revert that commit.`);
965
+ continue;
966
+ }
367
967
  }
368
- // The push event lists at most 20 commits, and their file lists can be cut short, so compare the lock itself: this
369
- // push is not the bot's alone (that case returned above), so it must leave the lock exactly as it was.
370
- const before = String(ev.before ?? '');
371
- if (/^[0-9a-f]{40}$/.test(before) && !/^0+$/.test(before)) {
372
- const lockAt = async (ref) => {
968
+ const mine = commits.filter((c) => pathsOf(c).includes(lockPath));
969
+ let refused = false;
970
+ for (const c of mine)
971
+ if (!refused && !(await trustedLock(c.id, config))) {
972
+ stop(`tslaws: commit ${c.id.slice(0, 7)} changed ${lockPath} but was not made by ${who(config)}; nothing accepted. Revert it.`);
973
+ refused = true;
974
+ }
975
+ if (refused)
976
+ continue;
977
+ // The push event lists at most 20 commits, and their file lists can be cut short, so compare the lock itself: this
978
+ // push is not the bot's alone (that case returned above), so it must leave the lock exactly as it was, or change it
979
+ // only through commits shown to be trusted.
980
+ const lockAt = async (at) => {
373
981
  try {
374
- return (await api('GET', `/repos/${name}/contents/${lockPath}?ref=${ref}`)).sha;
982
+ return (await api('GET', contentsUrl(name, lockPath, at))).sha;
375
983
  }
376
984
  catch {
377
985
  return undefined;
378
986
  }
379
987
  };
380
- if ((await lockAt(before)) !== (await lockAt(sha))) {
381
- ctx.err(`tslaws: this push changed ${lockPath}, and not only through ${config.bot}; nothing accepted. Revert the change.
382
- `);
383
- return 1;
988
+ if (known &&
989
+ (await lockAt(before)) !== (await lockAt(sha)) &&
990
+ !(config.local && (await lockTrustedBetween(before, sha, lockPath, config).catch(() => false)))) {
991
+ stop(`tslaws: this push changed ${lockPath}, and not only through ${config.bot}; nothing accepted. Revert the change.`);
992
+ continue;
384
993
  }
385
- }
386
- // Runs queue behind one another (the concurrency group), so this checkout can predate a lock commit that an earlier
387
- // run made. Start from the lock on the branch, so this run never undoes what an earlier one accepted, once every
388
- // commit since this push that changed the lock is shown to be the bot's.
389
- const branchRef = encodeURIComponent(config.branch);
390
- const headLock = (await api('GET', `/repos/${name}/contents/${lockPath}?ref=${branchRef}`).catch(() => undefined));
391
- const lockFile = ctx.options.lockFile;
392
- const localBlob = existsSync(lockFile) ? gitBlobSha(readFileSync(lockFile)) : undefined;
393
- if (headLock !== undefined && headLock.sha !== localBlob) {
394
- const range = (await api('GET', `/repos/${name}/compare/${sha}...${branchRef}`));
395
- const since = new Set(range.commits.map((c) => c.sha));
396
- const touched = (await api('GET', `/repos/${name}/commits?sha=${branchRef}&path=${encodeURIComponent(lockPath)}&per_page=100`));
397
- let trusted = range.status === 'ahead' && range.ahead_by === range.commits.length && touched.length < 100;
398
- for (const c of touched)
399
- if (trusted && since.has(c.sha) && !(await byBot(c.sha)))
400
- trusted = false;
401
- if (!trusted) {
402
- ctx.err(`tslaws: ${lockPath} on ${config.branch} has moved on since this push, and not only through ${config.bot}; nothing accepted
403
- `);
404
- return 1;
994
+ // Runs queue behind one another (the concurrency group), so this checkout can predate a lock commit that an earlier
995
+ // run made. Start from the lock on the branch, so this run never undoes what an earlier one accepted, once every
996
+ // commit since this push that changed the lock is shown to be the bot's.
997
+ const branchRef = encodeURIComponent(config.branch);
998
+ const headLock = (await api('GET', contentsUrl(name, lockPath, config.branch)).catch(() => undefined));
999
+ const localBlob = existsSync(lockFile) ? gitBlobSha(readFileSync(lockFile)) : undefined;
1000
+ // With results from another job, the lock they were made against must be the branch's lock now: a lock that is gone (or
1001
+ // cannot be read) counts as movement when the checkout has one, so a stale lock is never written back.
1002
+ if (typeof ctx.flags.get('results') === 'string' && headLock?.sha !== localBlob) {
1003
+ stop(`tslaws: ${lockPath} on ${config.branch} has moved on since the laws ran on this checkout; nothing accepted. Run the workflow again.`);
1004
+ continue;
405
1005
  }
406
- writeFileSync(lockFile, Buffer.from(headLock.content, 'base64'));
407
- }
408
- const pulls = (await api('GET', `/repos/${name}/commits/${sha}/pulls`));
409
- const checked = await check(ctx.options, true);
410
- const state = projectState(ctx.options);
411
- const proposals = proposalsOf(lockChanges(state.lock, state.laws, state.exempt, state.levels), checked);
412
- if (proposals.length === 0) {
413
- ctx.out('tslaws: the lock already records every law\n');
414
- return 0;
415
- }
416
- // Each record's author is checked again now: someone who lost write access, or a rule that changed since the
417
- // comment, leaves their records out.
418
- let records = [];
419
- if (config.accept === 'comment')
420
- for (const pr of pulls) {
421
- const verdicts = new Map();
422
- for (const record of readApprovals(await issueComments(api, name, pr.number), config.bot)) {
423
- if (!verdicts.has(record.by))
424
- verdicts.set(record.by, (await refusal(api, name, pr, record.by, 'User', config)) === undefined);
425
- if (verdicts.get(record.by))
426
- records.push(record);
427
- else
428
- ctx.err(`tslaws: ignoring the records of @${record.by} on #${pr.number}: no longer an approver\n`);
1006
+ if (headLock !== undefined && headLock.sha !== localBlob) {
1007
+ if (!(await lockTrustedBetween(sha, branchRef, lockPath, config))) {
1008
+ stop(`tslaws: ${lockPath} on ${config.branch} has moved on since this push, and not only through ${config.bot}${config.local ? ' or a maintainer' : ''}; nothing accepted`);
1009
+ continue;
429
1010
  }
1011
+ writeFileSync(lockFile, Buffer.from(headLock.content, 'base64'));
430
1012
  }
431
- const approvals = acceptedFingerprints(records);
432
- const decision = decide(proposals, config, approvals);
433
- const accepted = proposals.filter((p) => decision.accept.has(p.fingerprint));
434
- if (accepted.length > 0) {
435
- const next = acceptChanges(state.lock, state.laws, state.exempt, state.levels, decision.accept);
436
- writeLockValue(ctx.options.lockFile, next);
437
- const text = readFileSync(ctx.options.lockFile, 'utf8');
438
- if (!ctx.flags.has('dry-run')) {
1013
+ let checked;
1014
+ let state;
1015
+ try {
1016
+ checked = await runLaws(ctx, unit, 'merge', sha);
1017
+ state = projectState(unit.options);
1018
+ }
1019
+ catch (error) {
1020
+ if (!monorepo)
1021
+ throw error;
1022
+ stop(`tslaws: ${label(unit)} could not be checked: ${error instanceof Error ? error.message : String(error)}`);
1023
+ continue;
1024
+ }
1025
+ const proposals = proposalsOf(lockChanges(state.lock, state.laws, state.exempt, state.levels), checked, unit.path);
1026
+ if (proposals.length === 0) {
1027
+ ctx.out(`tslaws: ${monorepo ? `${label(unit)}: ` : ''}the lock already records every law\n`);
1028
+ continue;
1029
+ }
1030
+ // Each record's author is checked again now, against this project's own approvers: someone who lost write access,
1031
+ // or a rule that changed since the comment, leaves their records out.
1032
+ const records = [];
1033
+ if (config.accept === 'comment')
1034
+ for (const pr of pulls)
1035
+ for (const record of readApprovals(await commentsFor(pr), config.bot)) {
1036
+ if ((record.project ?? '') !== unit.path)
1037
+ continue;
1038
+ const key = `${unit.path}\0${pr.number}\0${record.by}`;
1039
+ if (!verdicts.has(key))
1040
+ verdicts.set(key, (await refusal(api, name, pr, record.by, 'User', config)) === undefined);
1041
+ if (verdicts.get(key))
1042
+ records.push(record);
1043
+ else
1044
+ ctx.err(`tslaws: ignoring the records of @${record.by} on #${pr.number}: no longer an approver\n`);
1045
+ }
1046
+ // The maintainer who started a run on demand accepts everything that passes, as an approver would on a pull request.
1047
+ const approvals = dispatched
1048
+ ? new Map(proposals.map((p) => [p.fingerprint, actor]))
1049
+ : acceptedFingerprints(records, unit.path);
1050
+ const decision = decide(proposals, config, approvals);
1051
+ const wins = proposals.filter((p) => decision.accept.has(p.fingerprint));
1052
+ if (wins.length > 0) {
1053
+ const next = acceptChanges(state.lock, state.laws, state.exempt, state.levels, decision.accept);
1054
+ // A certificate would come from the run of the laws, which is not trusted with the lock: readReport drops them, and a
1055
+ // lock written here records none (a record the lock already holds stays only while its law and problem match).
1056
+ writeLockValue(lockFile, next);
1057
+ writes.push({
1058
+ path: lockPath,
1059
+ text: readFileSync(lockFile, 'utf8'),
1060
+ was: headLock?.sha,
1061
+ unit,
1062
+ accepted: wins,
1063
+ approvals,
1064
+ });
1065
+ }
1066
+ accepted += wins.length;
1067
+ held += decision.held.length;
1068
+ sections.push([
1069
+ ...(monorepo ? [`#### \`${label(unit).replace(/`/g, "'")}\`\n`] : []),
1070
+ ...wins.map((p) => `- ✅ ${shown(p.name)} (${shown(p.file)}, ${p.reason}) accepted${approvals.has(p.fingerprint) ? ` — @${approvals.get(p.fingerprint)}` : ''}`),
1071
+ ...decision.held.map(({ proposal, why }) => `- 🚫 ${shown(proposal.name)} (${shown(proposal.file)}, ${proposal.reason}) not accepted: ${why}`),
1072
+ ].join('\n'));
1073
+ }
1074
+ if (writes.length > 0 && !ctx.flags.has('dry-run')) {
1075
+ const detail = (w) => w.accepted
1076
+ .map((p) => `- ${monorepo ? `${joinRepo(w.unit.path, '')}`.replace(/\/$/, '') + (w.unit.path === '' ? '' : ': ') : ''}${p.key} (${p.reason}${p.outcome ? `, ${p.outcome.status}` : ''}${w.approvals.has(p.fingerprint) ? `, accepted by @${w.approvals.get(p.fingerprint)}` : ''})`)
1077
+ .join('\n');
1078
+ const count = writes.reduce((n, w) => n + w.accepted.length, 0);
1079
+ const message = `chore(tslaws): accept ${count} law change${count === 1 ? '' : 's'}${writes.length > 1 ? ` in ${writes.length} projects` : ''}${pulls[0] ? ` from #${pulls[0].number}` : dispatched ? ` on request of @${actor}` : ''}\n\n${writes.map(detail).join('\n')}`;
1080
+ if (writes.length === 1) {
1081
+ const [only] = writes;
439
1082
  // Through the contents API, so GitHub signs the commit as the bot and `verify` can tell it from a forgery. The
440
1083
  // lock this run started from is the one it replaces: if anything wrote the lock since, GitHub refuses the write.
441
- await api('PUT', `/repos/${name}/contents/${lockPath}`, {
442
- message: `chore(tslaws): accept ${accepted.length} law change${accepted.length === 1 ? '' : 's'}${pulls[0] ? ` from #${pulls[0].number}` : ''}\n\n${accepted.map((p) => `- ${p.key} (${p.reason}${p.outcome ? `, ${p.outcome.status}` : ''}${approvals.has(p.fingerprint) ? `, accepted by @${approvals.get(p.fingerprint)}` : ''})`).join('\n')}`,
443
- content: Buffer.from(text).toString('base64'),
444
- branch: config.branch,
445
- ...(headLock === undefined ? {} : { sha: headLock.sha }),
1084
+ await api('PUT', contentsUrl(name, only.path), {
1085
+ message,
1086
+ content: Buffer.from(only.text).toString('base64'),
1087
+ branch,
1088
+ ...(only.was === undefined ? {} : { sha: only.was }),
446
1089
  });
447
1090
  }
1091
+ else {
1092
+ await commitTogether(api, name, branch, writes, message);
1093
+ }
448
1094
  }
449
- const lines = [
450
- ...accepted.map((p) => `- ✅ ${shown(p.name)} (${shown(p.file)}, ${p.reason}) accepted${approvals.has(p.fingerprint) ? ` — @${approvals.get(p.fingerprint)}` : ''}`),
451
- ...decision.held.map(({ proposal, why }) => `- 🚫 ${shown(proposal.name)} (${shown(proposal.file)}, ${proposal.reason}) not accepted: ${why}`),
452
- ];
453
1095
  const where = repoPath(ctx, '');
454
- const note = `### tslaws on \`${config.branch}\`${where === '' ? '' : ` (\`${where}\`)`}\n\n${lines.join('\n')}\n${decision.held.length > 0 ? `\n\`tslaws check\` fails on \`${config.branch}\` until the held proposals are fixed or removed.\n` : ''}`;
455
- summary(ctx.env, note);
456
- ctx.out(`${note}\n`);
457
- for (const pr of pulls)
458
- await api('POST', `/repos/${name}/issues/${pr.number}/comments`, { body: note }).catch(() => undefined);
459
- setOutput(ctx.env, 'accepted', String(accepted.length));
460
- return decision.held.length === 0 ? 0 : 1;
1096
+ const note = `### tslaws on \`${branch}\`${monorepo || where === '' ? '' : ` (\`${where}\`)`}\n\n${sections.join('\n')}\n${held > 0 ? `\n\`tslaws check\` fails on \`${branch}\` until the held proposals are fixed or removed.\n` : ''}`;
1097
+ if (sections.length > 0) {
1098
+ summary(ctx.env, note);
1099
+ ctx.out(`${note}\n`);
1100
+ for (const pr of pulls)
1101
+ await api('POST', `/repos/${name}/issues/${pr.number}/comments`, { body: note }).catch(() => undefined);
1102
+ }
1103
+ setOutput(ctx.env, 'accepted', String(accepted));
1104
+ if (failures.length > 0 && writes.length > 0)
1105
+ ctx.out(`tslaws: wrote ${plural(writes.length, 'lock')}; ${plural(failures.length, 'problem')} above ${failures.length === 1 ? 'leaves' : 'leave'} the job failed\n`);
1106
+ return held === 0 && failures.length === 0 ? 0 : 1;
1107
+ }
1108
+ /**
1109
+ * Several locks in one commit, through the git data API: the parent is the branch's head now, each lock must still be
1110
+ * the one this run built on, and the branch moves by a plain (never forced) update, so GitHub refuses it if anything
1111
+ * landed in between.
1112
+ */
1113
+ async function commitTogether(api, name, branch, writes, message) {
1114
+ const ref = encodeURIComponent(branch);
1115
+ const head = (await api('GET', `/repos/${name}/git/ref/heads/${ref}`)).object.sha;
1116
+ for (const w of writes) {
1117
+ let now;
1118
+ try {
1119
+ now = (await api('GET', contentsUrl(name, w.path, head))).sha;
1120
+ }
1121
+ catch {
1122
+ now = undefined;
1123
+ }
1124
+ if (now !== w.was)
1125
+ throw new Error(`${w.path} changed on ${branch} while this ran; nothing written`);
1126
+ }
1127
+ const parent = (await api('GET', `/repos/${name}/git/commits/${head}`));
1128
+ const tree = (await api('POST', `/repos/${name}/git/trees`, {
1129
+ base_tree: parent.tree.sha,
1130
+ tree: writes.map((w) => ({ path: w.path, mode: '100644', type: 'blob', content: w.text })),
1131
+ }));
1132
+ const made = (await api('POST', `/repos/${name}/git/commits`, { message, tree: tree.sha, parents: [head] }));
1133
+ await api('PATCH', `/repos/${name}/git/refs/heads/${ref}`, { sha: made.sha, force: false });
1134
+ }
1135
+ /**
1136
+ * What a project's settings were and are. Always read at both commits and compared: the list of changed files is capped
1137
+ * by the API, so it cannot be what decides whether to look.
1138
+ */
1139
+ async function checkProjectAt(read, pull, problems, dir) {
1140
+ const configPath = joinRepo(dir, 'tslaws.json');
1141
+ const base = await settingsAt(read, pull.base.sha, dir);
1142
+ let head;
1143
+ try {
1144
+ head = await settingsAt(read, pull.head.sha, dir);
1145
+ }
1146
+ catch (error) {
1147
+ problems.push(`${configPath} does not read on the pull request: ${error instanceof Error ? error.message : String(error)}`);
1148
+ }
1149
+ if (head !== undefined) {
1150
+ if (JSON.stringify(base.github) !== JSON.stringify(head.github))
1151
+ problems.push(`the pull request changes the "github" section of ${configPath}, which decides who may accept laws`);
1152
+ else if (base.standalone !== head.standalone)
1153
+ problems.push(`the pull request changes "standalone" in ${configPath}, which decides whether root runs cover it`);
1154
+ }
1155
+ return base.github === undefined ? undefined : parseGithubConfig(base.github);
1156
+ }
1157
+ /**
1158
+ * Why a pull request may not change `lockPath`, for a project whose base settings are `config`. With "local" on, a
1159
+ * maintainer's pull request may: its author needs admin or maintain access, and so does the author of each commit that
1160
+ * changes the lock, so a maintainer cannot carry someone else's lock through. Without it, only the bot writes the lock.
1161
+ */
1162
+ async function lockChangeProblems(api, name, pull, lockPath, config, evidence) {
1163
+ if (!config.local)
1164
+ return [`the pull request changes ${lockPath}; only ${config.bot} writes the lock, on merge into ${config.branch}`];
1165
+ evidence.author ??= maintains(api, name, pull.user.login, pull.user.type);
1166
+ if (!(await evidence.author))
1167
+ return [
1168
+ `the pull request changes ${lockPath}; only ${config.bot} writes the lock, on merge into ${config.branch}, unless its author has admin or maintain access to the repository`,
1169
+ ];
1170
+ // GitHub lists at most 300 files for a commit; a full list may hide the lock, so it counts as touching it. It lists at
1171
+ // most 250 commits for a pull request; a full list may hide a commit, so the pull request cannot be checked. The
1172
+ // author is the one GitHub matches from the commit's e-mail, which anyone with push access to the branch can set: the
1173
+ // pull request's author, a maintainer, answers for what is pushed to it, and the ruleset is the hard control.
1174
+ evidence.commits ??= (async () => {
1175
+ const listed = await all(api, `/repos/${name}/pulls/${pull.number}/commits`);
1176
+ const list = [];
1177
+ // At the limit the pull request fails whatever its commits say, so they are not read.
1178
+ for (const c of listed.length >= 250 ? [] : listed) {
1179
+ const detail = (await api('GET', `/repos/${name}/commits/${c.sha}`));
1180
+ list.push({ sha: c.sha, author: detail.author, files: detail.files ?? [] });
1181
+ }
1182
+ return { full: listed.length >= 250, list };
1183
+ })();
1184
+ const { full, list } = await evidence.commits;
1185
+ const problems = [];
1186
+ if (full)
1187
+ problems.push(`the pull request changes ${lockPath} and has 250 or more commits, more than GitHub lists; split it so each commit can be checked`);
1188
+ for (const c of list) {
1189
+ const touchesLock = c.files.length >= 300 || c.files.some((f) => f.filename === lockPath || f.previous_filename === lockPath);
1190
+ if (touchesLock && !(await maintains(api, name, c.author?.login ?? '', c.author?.type)))
1191
+ problems.push(`commit ${c.sha.slice(0, 7)} in the pull request changes ${lockPath}, but ${c.author?.login ? `@${c.author.login} does not` : 'its author does not'} have admin or maintain access to the repository`);
1192
+ }
1193
+ return problems;
1194
+ }
1195
+ /** The most files the pull request files API lists (30 pages of 100); a pull request with more is cut short. */
1196
+ const filesListLimit = 3000;
1197
+ /**
1198
+ * The files a pull request changes, with the old name of each file it renames. Fails when the list cannot be the whole
1199
+ * of it: at the API's cap, or not the number GitHub says the pull request changes. The security checks do not decide
1200
+ * from this list alone, but a list that may be short is never used.
1201
+ */
1202
+ async function changedFiles(api, name, pull) {
1203
+ const files = await all(api, `/repos/${name}/pulls/${pull.number}/files`);
1204
+ if (files.length >= filesListLimit)
1205
+ throw new Error(`the pull request changes ${filesListLimit} files or more, which the API cannot list in full; nothing can be checked`);
1206
+ if (files.length !== pull.changed_files)
1207
+ throw new Error(`GitHub lists ${plural(files.length, 'changed file')} for the pull request but reports ${pull.changed_files === undefined ? 'no count of files' : plural(pull.changed_files, 'file')} changed; nothing can be checked`);
1208
+ return new Set(files.flatMap((f) => [f.filename, ...(f.previous_filename ? [f.previous_filename] : [])]));
1209
+ }
1210
+ /**
1211
+ * Everything a pull request must not change from under a monorepo's checks, read through the API at the base and at the
1212
+ * head: the project list (and how it is found), each project's `github` and `standalone` settings, and any lock. Adds a
1213
+ * line to `problems` for each. Returns what it read, for a caller that decides more from it. A lock change is a problem
1214
+ * unless `maintainersMayChangeLocks` and its project's base settings have "local" on and a maintainer wrote it.
1215
+ */
1216
+ async function inspectMonorepo(api, name, read, pull, changed, rootPath, problems, maintainersMayChangeLocks = false) {
1217
+ const checkProject = (dir) => checkProjectAt(read, pull, problems, dir);
1218
+ // Every project of the base and every project of the head, read through the API: a pull request that edits the
1219
+ // files that discover projects cannot hide a project from this check.
1220
+ const baseSide = await projectsAt(api, name, read, pull.base.sha, rootPath);
1221
+ const headSide = await projectsAt(api, name, read, pull.head.sha, rootPath);
1222
+ if (baseSide.truncated || headSide.truncated)
1223
+ problems.push('the repository is too large for the API to list its files; the projects cannot be checked');
1224
+ const label = (rel) => joinRepo(rootPath, rel) || '.';
1225
+ const headSet = new Set(headSide.paths);
1226
+ for (const rel of baseSide.paths)
1227
+ if (!headSet.has(rel))
1228
+ problems.push(`${label(rel)} is a project on ${pull.base.ref} but the pull request no longer discovers it, so its lock would go unwatched: restore it, or merge this in a pull request of its own by an administrator`);
1229
+ const inputs = [
1230
+ ['tslaws.json', 'tslaws'],
1231
+ ['package.json', 'packageJson'],
1232
+ ['pnpm-workspace.yaml', 'pnpmWorkspace'],
1233
+ ];
1234
+ for (const [file, key] of inputs) {
1235
+ const path = joinRepo(rootPath, file);
1236
+ const was = baseSide.inputs[key];
1237
+ const now = headSide.inputs[key];
1238
+ const sig = (text) => (text === undefined ? 'absent' : discoverySignature({ [key]: text }));
1239
+ if (sig(was) !== sig(now))
1240
+ problems.push(`the pull request changes how projects are discovered (${path}), which decides what this check watches`);
1241
+ }
1242
+ const union = [...new Set([...baseSide.paths, ...headSide.paths])];
1243
+ const configs = new Map();
1244
+ const evidence = {};
1245
+ // Every project, whatever the pull request changed: a settings file need not end in .json (an `extends` base in a
1246
+ // .jsonc file, say), so no extension decides whether to look. checkProject compares only the files a project reads.
1247
+ for (const rel of union)
1248
+ try {
1249
+ configs.set(rel, await checkProject(joinRepo(rootPath, rel)));
1250
+ }
1251
+ catch (error) {
1252
+ problems.push(`${label(rel)}: ${error instanceof Error ? error.message : String(error)}`);
1253
+ }
1254
+ // Any lock the pull request touches, in a project or not: the bot writes locks, after the merge. Found by comparing the
1255
+ // two trees' blob ids (not only the files list, which can be cut short).
1256
+ for (const file of new Set([...lockDifferences(baseSide.locks, headSide.locks), ...[...changed].filter(isLock)])) {
1257
+ const owner = union.find((rel) => joinRepo(rootPath, joinRepo(rel, 'tsc-laws.lock')) === file);
1258
+ const config = owner === undefined ? undefined : configs.get(owner);
1259
+ if (config !== undefined && maintainersMayChangeLocks) {
1260
+ // The project's own settings, as the base has them: a maintainer may change its lock while its "local" is true.
1261
+ problems.push(...(await lockChangeProblems(api, name, pull, file, config, evidence)));
1262
+ continue;
1263
+ }
1264
+ problems.push(config === undefined
1265
+ ? `the pull request changes ${file}; a lock changes only when the bot writes it on merge, and this one is ${owner === undefined ? 'outside every project' : 'in a project with no "github" settings'}`
1266
+ : `the pull request changes ${file}; only ${config.bot} writes the lock, on merge into ${config.branch}`);
1267
+ }
1268
+ return { baseSide, headSide, union };
461
1269
  }
462
1270
  // ---- verify ---------------------------------------------------------------------------------------------------------
463
1271
  async function verify(ctx) {
1272
+ const monorepo = ctx.projects !== undefined;
464
1273
  const ev = event(ctx.env);
465
1274
  const pull = ev.pull_request;
466
1275
  if (pull === undefined) {
@@ -469,22 +1278,10 @@ async function verify(ctx) {
469
1278
  }
470
1279
  const api = ctx.api ?? restApi(ctx.env);
471
1280
  const name = repo(ctx.env);
472
- const contents = async (path, ref) => {
473
- try {
474
- const file = (await api('GET', `/repos/${name}/contents/${path}?ref=${ref}`));
475
- return Buffer.from(file.content, 'base64').toString('utf8');
476
- }
477
- catch {
478
- return undefined;
479
- }
480
- };
481
- const lockPath = repoPath(ctx, 'tsc-laws.lock');
482
- const configPath = repoPath(ctx, 'tslaws.json');
483
- const baseText = await contents(configPath, pull.base.sha);
484
- const config = githubConfigOf(baseText);
1281
+ const read = readerOf(api, name);
1282
+ const rootPath = repoPath(ctx, '');
485
1283
  const problems = [];
486
- const files = await all(api, `/repos/${name}/pulls/${pull.number}/files`);
487
- const changed = new Set(files.flatMap((f) => [f.filename, ...(f.previous_filename ? [f.previous_filename] : [])]));
1284
+ const changed = await changedFiles(api, name, pull);
488
1285
  const protectedPaths = String(ctx.flags.get('protect') ?? '')
489
1286
  .split(',')
490
1287
  .map((p) => p.trim())
@@ -492,22 +1289,31 @@ async function verify(ctx) {
492
1289
  for (const path of protectedPaths)
493
1290
  if (changed.has(path))
494
1291
  problems.push(`${path} is protected: change it in a pull request of its own, merged by an administrator`);
495
- if (changed.has(configPath)) {
496
- const headText = await contents(configPath, pull.head.sha);
497
- const section = (text) => JSON.stringify(text === undefined ? undefined : JSON.parse(text).github);
498
- try {
499
- if (section(baseText) !== section(headText))
500
- problems.push(`the pull request changes the "github" section of ${configPath}, which decides who may accept laws`);
501
- }
502
- catch {
503
- problems.push(`${configPath} does not parse`);
504
- }
1292
+ const checkProject = (dir) => checkProjectAt(read, pull, problems, dir);
1293
+ if (!monorepo) {
1294
+ // One project, as a package's own workflow runs it: its lock and its settings only.
1295
+ const configPath = joinRepo(rootPath, 'tslaws.json');
1296
+ const lockPath = joinRepo(rootPath, 'tsc-laws.lock');
1297
+ const config = await checkProject(rootPath);
1298
+ if (config === undefined)
1299
+ throw new Error('tslaws github needs a "github" section in tslaws.json');
1300
+ // The bot never commits to a pull request's branch: it writes the lock on ${config.branch} after the merge. So any
1301
+ // change to the lock in the pull request's diff (the full list, paginated above) is a forgery. Checking the diff, not
1302
+ // each commit, also covers commits whose file list GitHub truncates (the commit API lists at most 300 files). With
1303
+ // "local" on, a pull request from someone with admin or maintain access may change it: see lockChangeProblems.
1304
+ const [baseTree, headTree] = await Promise.all([
1305
+ treeAt(api, name, pull.base.sha),
1306
+ treeAt(api, name, pull.head.sha),
1307
+ ]);
1308
+ if (baseTree.truncated || headTree.truncated)
1309
+ problems.push('the repository is too large for the API to list its files; the lock cannot be checked');
1310
+ if (changed.has(lockPath) || lockDifferences(baseTree.locks, headTree.locks).includes(lockPath))
1311
+ problems.push(...(await lockChangeProblems(api, name, pull, lockPath, config, {})));
1312
+ void configPath;
1313
+ }
1314
+ else {
1315
+ await inspectMonorepo(api, name, read, pull, changed, rootPath, problems, true);
505
1316
  }
506
- // The bot never commits to a pull request's branch: it writes the lock on ${config.branch} after the merge. So any
507
- // change to the lock in the pull request's diff (the full list, paginated above) is a forgery. Checking the diff, not
508
- // each commit, also covers commits whose file list GitHub truncates (the commit API lists at most 300 files).
509
- if (changed.has(lockPath))
510
- problems.push(`the pull request changes ${lockPath}; only ${config.bot} writes the lock, on merge into ${config.branch}`);
511
1317
  for (const problem of problems)
512
1318
  ctx.out(`::error::${escapeGithubData(problem)}\n`);
513
1319
  if (problems.length === 0)
@@ -517,6 +1323,28 @@ async function verify(ctx) {
517
1323
  // ---- entry ----------------------------------------------------------------------------------------------------------
518
1324
  export async function githubCommand(action, ctx) {
519
1325
  try {
1326
+ const out = ctx.flags.get('results-out');
1327
+ if (out !== undefined || ctx.flags.has('results')) {
1328
+ if (action !== 'report' && action !== 'merge') {
1329
+ ctx.err('tslaws github: --results and --results-out are for report and merge\n');
1330
+ return 1;
1331
+ }
1332
+ if (out !== undefined && ctx.flags.has('results')) {
1333
+ ctx.err('tslaws github: use --results-out to run the laws or --results to act on them, not both\n');
1334
+ return 1;
1335
+ }
1336
+ if (out !== undefined) {
1337
+ if (typeof out !== 'string') {
1338
+ ctx.err('tslaws github: --results-out needs a file\n');
1339
+ return 1;
1340
+ }
1341
+ return await collect(ctx, action, out);
1342
+ }
1343
+ if (typeof ctx.flags.get('results') !== 'string') {
1344
+ ctx.err('tslaws github: --results needs a file\n');
1345
+ return 1;
1346
+ }
1347
+ }
520
1348
  if (action === 'report')
521
1349
  return await report(ctx);
522
1350
  if (action === 'command')