tslaws 0.6.4 → 0.8.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 (78) hide show
  1. package/README.md +16 -9
  2. package/dist/api.d.ts +10 -0
  3. package/dist/api.js +7 -0
  4. package/dist/browser.d.ts +2 -2
  5. package/dist/browser.js +2 -6
  6. package/dist/check.d.ts +2 -0
  7. package/dist/check.js +218 -56
  8. package/dist/cli.d.ts +18 -0
  9. package/dist/cli.js +189 -56
  10. package/dist/compile.d.ts +12 -0
  11. package/dist/compile.js +207 -6
  12. package/dist/coverage.d.ts +21 -1
  13. package/dist/coverage.js +33 -23
  14. package/dist/derived.d.ts +8 -0
  15. package/dist/derived.js +52 -0
  16. package/dist/e2e.d.ts +0 -9
  17. package/dist/e2e.js +0 -20
  18. package/dist/generators.d.ts +8 -8
  19. package/dist/generators.js +59 -99
  20. package/dist/github.d.ts +121 -0
  21. package/dist/github.js +266 -0
  22. package/dist/githubCli.d.ts +46 -0
  23. package/dist/githubCli.js +502 -0
  24. package/dist/globs.d.ts +3 -0
  25. package/dist/globs.js +24 -0
  26. package/dist/init.js +5 -5
  27. package/dist/lawFiles.d.ts +21 -0
  28. package/dist/lawFiles.js +95 -0
  29. package/dist/lawKinds.d.ts +38 -0
  30. package/dist/lawKinds.js +210 -0
  31. package/dist/lawNames.d.ts +6 -0
  32. package/dist/lawNames.js +22 -0
  33. package/dist/list.d.ts +22 -0
  34. package/dist/list.js +36 -0
  35. package/dist/lock.d.ts +39 -3
  36. package/dist/lock.js +107 -4
  37. package/dist/lower.d.ts +10 -0
  38. package/dist/lower.js +178 -0
  39. package/dist/mcp.d.ts +2 -8
  40. package/dist/mcp.js +40 -61
  41. package/dist/migrate/arbitraries.d.ts +23 -0
  42. package/dist/migrate/arbitraries.js +202 -0
  43. package/dist/migrate/convert.d.ts +20 -0
  44. package/dist/migrate/convert.js +915 -0
  45. package/dist/migrate/framework.d.ts +48 -0
  46. package/dist/migrate/framework.js +249 -0
  47. package/dist/migrate/index.d.ts +16 -0
  48. package/dist/migrate/index.js +155 -0
  49. package/dist/migrate/report.d.ts +35 -0
  50. package/dist/migrate/report.js +40 -0
  51. package/dist/migrate/source.d.ts +42 -0
  52. package/dist/migrate/source.js +163 -0
  53. package/dist/migrate/tests.d.ts +44 -0
  54. package/dist/migrate/tests.js +184 -0
  55. package/dist/plan.d.ts +50 -0
  56. package/dist/plan.js +118 -0
  57. package/dist/pool.d.ts +21 -0
  58. package/dist/pool.js +54 -0
  59. package/dist/promote.d.ts +30 -2
  60. package/dist/promote.js +133 -7
  61. package/dist/property.d.ts +12 -26
  62. package/dist/property.js +33 -74
  63. package/dist/propertyRun.d.ts +35 -0
  64. package/dist/propertyRun.js +79 -0
  65. package/dist/propertyWorker.js +7 -9
  66. package/dist/proposals.d.ts +43 -0
  67. package/dist/proposals.js +192 -0
  68. package/dist/regressions.js +23 -2
  69. package/dist/reporters.d.ts +3 -0
  70. package/dist/reporters.js +17 -0
  71. package/dist/smt.d.ts +16 -0
  72. package/dist/smt.js +52 -9
  73. package/dist/solvers.d.ts +31 -0
  74. package/dist/solvers.js +121 -0
  75. package/dist/symbolic.js +2 -2
  76. package/dist/types.d.ts +19 -0
  77. package/hooks/AGENTS.snippet.md +2 -2
  78. package/package.json +9 -7
@@ -0,0 +1,502 @@
1
+ // `tslaws github <report|command|merge|verify>`: the GitHub side of accepting laws. See github.ts for the policy.
2
+ //
3
+ // report pull_request: runs every law (proposals included), flags each proposal on its line, keeps one sticky
4
+ // comment up to date, and fails when an accepted law fails, a proposal fails, or (comment mode) a proposal
5
+ // waits for an accept. Advisory: it runs the pull request's code, so it decides nothing about the lock.
6
+ // command issue_comment: reads `/tslaws accept|reject ...`, checks the commenter may accept, and records the
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.
14
+ import { readFileSync, writeFileSync, appendFileSync, existsSync } from 'node:fs';
15
+ import { createHash } from 'node:crypto';
16
+ import { join } from 'node:path';
17
+ import { check, exemptionsOf } from "./check.js";
18
+ import { readConfig } from "./coverage.js";
19
+ import { readManifest } from "./compile.js";
20
+ import { acceptedFingerprints, inert, recordComment, decide, parseCommands, isSharedBot, parseGithubConfig, proposalsOf, pullRequestVerdict, readApprovals, renderSticky, resolveNames, stickyMarker, } from "./github.js";
21
+ import { classifyLawFile, lockLevels } from "./lawKinds.js";
22
+ import { acceptChanges, lockChanges, readLock, writeLockValue } from "./lock.js";
23
+ import { escapeGithubData, escapeGithubProperty } from "./reporters.js";
24
+ function restApi(env) {
25
+ const base = env.GITHUB_API_URL ?? 'https://api.github.com';
26
+ const token = env.GITHUB_TOKEN ?? env.GH_TOKEN;
27
+ if (token === undefined || token === '')
28
+ throw new Error('GITHUB_TOKEN is not set');
29
+ return async (method, path, body) => {
30
+ const response = await fetch(`${base}${path}`, {
31
+ method,
32
+ headers: {
33
+ authorization: `Bearer ${token}`,
34
+ accept: 'application/vnd.github+json',
35
+ 'x-github-api-version': '2022-11-28',
36
+ 'user-agent': 'tslaws',
37
+ ...(body === undefined ? {} : { 'content-type': 'application/json' }),
38
+ },
39
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
40
+ });
41
+ const text = await response.text();
42
+ if (!response.ok)
43
+ throw new Error(`GitHub ${method} ${path}: ${response.status} ${text.slice(0, 300)}`);
44
+ return text === '' ? undefined : JSON.parse(text);
45
+ };
46
+ }
47
+ async function all(api, path) {
48
+ const out = [];
49
+ for (let page = 1; page <= 30; page += 1) {
50
+ const batch = (await api('GET', `${path}${path.includes('?') ? '&' : '?'}per_page=100&page=${page}`));
51
+ out.push(...batch);
52
+ if (batch.length < 100)
53
+ break;
54
+ }
55
+ return out;
56
+ }
57
+ // ---- shared ---------------------------------------------------------------------------------------------------------
58
+ function repo(env) {
59
+ const name = env.GITHUB_REPOSITORY;
60
+ if (name === undefined || !/^[\w.-]+\/[\w.-]+$/.test(name))
61
+ throw new Error('GITHUB_REPOSITORY is not set');
62
+ return name;
63
+ }
64
+ function event(env) {
65
+ const path = env.GITHUB_EVENT_PATH;
66
+ return path !== undefined && existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : {};
67
+ }
68
+ /** The `github` section of a tslaws.json text, with defaults. It must exist: it names the bot every check trusts. */
69
+ export function githubConfigOf(text) {
70
+ const raw = text === undefined ? undefined : JSON.parse(text).github;
71
+ if (raw === undefined)
72
+ throw new Error('tslaws github needs a "github" section in tslaws.json');
73
+ return parseGithubConfig(raw);
74
+ }
75
+ /** What the lock would record if everything were accepted now. Compiles the project; runs none of it. */
76
+ /** The id git gives a file's content: what the contents API reports as a file's `sha`. */
77
+ function gitBlobSha(bytes) {
78
+ return createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex');
79
+ }
80
+ export function projectState(options) {
81
+ const lock = readLock(options.lockFile);
82
+ const laws = readManifest(options.compiler, options.files, options.cwd);
83
+ const exempt = exemptionsOf(options);
84
+ const mode = readConfig(options.cwd).levels ?? 'names';
85
+ const levels = mode === 'imports'
86
+ ? lockLevels(options.cwd, laws, 'imports')
87
+ : lock?.levels !== undefined
88
+ ? Object.fromEntries([...new Set(laws.map((l) => l.file.replaceAll('\\', '/')))].map((f) => [
89
+ f,
90
+ classifyLawFile(options.cwd, f, 'names').kind,
91
+ ]))
92
+ : undefined;
93
+ return { laws, exempt, levels, lock };
94
+ }
95
+ async function issueComments(api, name, pr) {
96
+ return all(api, `/repos/${name}/issues/${pr}/comments`);
97
+ }
98
+ async function upsertSticky(api, name, pr, bot, body, comments) {
99
+ const mine = comments.find((c) => c.user.login === bot && c.body.startsWith(stickyMarker));
100
+ if (mine === undefined)
101
+ await api('POST', `/repos/${name}/issues/${pr}/comments`, { body });
102
+ else if (mine.body !== body)
103
+ await api('PATCH', `/repos/${name}/issues/comments/${mine.id}`, { body });
104
+ }
105
+ function linkFor(env, sha) {
106
+ const server = env.GITHUB_SERVER_URL ?? 'https://github.com';
107
+ const name = env.GITHUB_REPOSITORY ?? '';
108
+ // Raw text: renderSticky makes the whole cell inert. Brackets and backticks would break the link's markdown.
109
+ return (p) => {
110
+ const label = p.name.replace(/[`[\]]/g, "'");
111
+ if (p.line === 0 || name === '')
112
+ return `${label} (${p.file})`;
113
+ return `[${label}](${server}/${name}/blob/${sha}/${p.file.split('/').map(encodeURIComponent).join('/')}#L${p.line})`;
114
+ };
115
+ }
116
+ /** A law name or path from the pull request, for a bot comment: inert, and quoted without a code span. */
117
+ function shown(text) {
118
+ return `“${inert(text)}”`;
119
+ }
120
+ function summary(env, text) {
121
+ if (env.GITHUB_STEP_SUMMARY !== undefined)
122
+ appendFileSync(env.GITHUB_STEP_SUMMARY, `${text}\n`);
123
+ }
124
+ function setOutput(env, key, value) {
125
+ if (env.GITHUB_OUTPUT !== undefined)
126
+ appendFileSync(env.GITHUB_OUTPUT, `${key}=${value}\n`);
127
+ }
128
+ // ---- report ---------------------------------------------------------------------------------------------------------
129
+ async function report(ctx) {
130
+ const config = githubConfigOf(readText(join(ctx.cwd, 'tslaws.json')));
131
+ const ev = event(ctx.env);
132
+ const pr = Number(ctx.flags.get('pr') ?? ev.pull_request?.number ?? NaN);
133
+ const sha = String(ev.pull_request?.head?.sha ?? ctx.env.GITHUB_SHA ?? '');
134
+ const checked = await check(ctx.options, true);
135
+ const state = projectState(ctx.options);
136
+ const proposals = proposalsOf(lockChanges(state.lock, state.laws, state.exempt, state.levels), checked);
137
+ let api;
138
+ let comments = [];
139
+ try {
140
+ api = ctx.api ?? restApi(ctx.env);
141
+ if (Number.isInteger(pr))
142
+ comments = await issueComments(api, repo(ctx.env), pr);
143
+ }
144
+ catch (error) {
145
+ ctx.err(`tslaws: cannot read the pull request's comments (${String(error)}); reporting without approvals\n`);
146
+ api = undefined;
147
+ }
148
+ const approvals = acceptedFingerprints(readApprovals(comments, config.bot));
149
+ const verdict = pullRequestVerdict(checked, proposals, config, approvals);
150
+ for (const p of proposals) {
151
+ const level = p.passes ? 'notice' : 'error';
152
+ const title = `tslaws proposal: ${p.name}`;
153
+ const message = p.outcome === undefined
154
+ ? 'did not run'
155
+ : `${p.reason}; if accepted: ${p.outcome.status}${p.outcome.counterexample ? `; counterexample ${p.outcome.counterexample}` : ''}`;
156
+ ctx.out(`::${level} file=${escapeGithubProperty(p.file)},line=${Math.max(1, p.line)},title=${escapeGithubProperty(title)}::${escapeGithubData(message)}\n`);
157
+ }
158
+ const body = renderSticky(proposals, config, approvals, linkFor(ctx.env, sha));
159
+ summary(ctx.env, body.replace(stickyMarker, ''));
160
+ if (api !== undefined && Number.isInteger(pr) && ctx.flags.has('comment')) {
161
+ try {
162
+ await upsertSticky(api, repo(ctx.env), pr, config.bot, body, comments);
163
+ }
164
+ catch (error) {
165
+ // A pull request from a fork gets a read-only token: the step summary and annotations still carry the report.
166
+ ctx.err(`tslaws: cannot write the sticky comment (${String(error)})\n`);
167
+ }
168
+ }
169
+ const outFile = ctx.flags.get('out');
170
+ if (typeof outFile === 'string')
171
+ writeFileSync(outFile, `${JSON.stringify({ sha, proposals, verdict }, null, 2)}\n`);
172
+ setOutput(ctx.env, 'proposals', String(proposals.length));
173
+ for (const problem of verdict.problems)
174
+ ctx.out(`${problem}\n`);
175
+ ctx.out(verdict.ok ? `tslaws: ${proposals.length} proposal(s), all passing\n` : 'tslaws: the pull request is not ready\n');
176
+ return verdict.ok ? 0 : 1;
177
+ }
178
+ function readText(path) {
179
+ return existsSync(path) ? readFileSync(path, 'utf8') : undefined;
180
+ }
181
+ // ---- command --------------------------------------------------------------------------------------------------------
182
+ const rank = { none: 0, read: 1, triage: 2, write: 3, maintain: 4, admin: 5 };
183
+ /** Why `login` may not accept on this pull request, or undefined when they may. */
184
+ export async function refusal(api, name, pr, login, type, config) {
185
+ if (type === 'Bot' || login.endsWith('[bot]'))
186
+ return 'bots cannot accept laws';
187
+ const permission = (await api('GET', `/repos/${name}/collaborators/${encodeURIComponent(login)}/permission`));
188
+ const level = Math.max(rank[permission.permission] ?? 0, rank[permission.role_name ?? ''] ?? 0);
189
+ if (level < rank.write)
190
+ return `@${login} needs write access to the repository`;
191
+ for (const kind of config.approvers) {
192
+ if (kind === 'author' && pr.user.login === login && pr.user.type !== 'Bot')
193
+ return undefined;
194
+ if (kind === 'reviewers') {
195
+ if ((pr.requested_reviewers ?? []).some((r) => r.login === login))
196
+ return undefined;
197
+ const reviews = await all(api, `/repos/${name}/pulls/${pr.number}/reviews`);
198
+ if (reviews.some((r) => r.user?.login === login && login !== pr.user.login))
199
+ return undefined;
200
+ }
201
+ if ((kind === 'write' || kind === 'maintain' || kind === 'admin') && level >= rank[kind])
202
+ return undefined;
203
+ }
204
+ return `@${login} is not one of the approvers this project names (${config.approvers.join(', ')})`;
205
+ }
206
+ async function command(ctx) {
207
+ // The base branch's config: the workflow checks the default branch out at the root and the pull request beside it.
208
+ const config = githubConfigOf(readText(join(String(ctx.flags.get('config-from') ?? ctx.cwd), 'tslaws.json')));
209
+ const ev = event(ctx.env);
210
+ if (ev.action !== 'created' || ev.issue?.pull_request === undefined)
211
+ return 0;
212
+ const body = String(ev.comment?.body ?? '');
213
+ const commands = parseCommands(body);
214
+ if (commands.length === 0)
215
+ return 0;
216
+ const api = ctx.api ?? restApi(ctx.env);
217
+ const name = repo(ctx.env);
218
+ const number = Number(ev.issue.number);
219
+ const reply = (text) => api('POST', `/repos/${name}/issues/${number}/comments`, { body: text });
220
+ const login = String(ev.comment.user.login);
221
+ const pr = (await api('GET', `/repos/${name}/pulls/${number}`));
222
+ if (config.accept !== 'comment') {
223
+ await reply(`@${login} this project accepts passing proposals on merge into \`${config.branch}\`; there is nothing to accept by comment.`);
224
+ return 0;
225
+ }
226
+ const refused = await refusal(api, name, pr, login, String(ev.comment.user.type ?? 'User'), config);
227
+ if (refused !== undefined) {
228
+ await reply(`Not recorded: ${refused}.`);
229
+ return 0;
230
+ }
231
+ const checkedOut = String(ctx.flags.get('head-sha') ?? '');
232
+ if (checkedOut !== pr.head.sha) {
233
+ await reply(`Not recorded: the pull request moved to ${pr.head.sha.slice(0, 7)} while this ran; say it again.`);
234
+ return 0;
235
+ }
236
+ const pinned = /@([0-9a-f]{7,40})\b/i.exec(body)?.[1];
237
+ if (pinned !== undefined && !pr.head.sha.startsWith(pinned.toLowerCase())) {
238
+ await reply(`Not recorded: you named ${pinned}, but the pull request is at ${pr.head.sha.slice(0, 7)}.`);
239
+ return 0;
240
+ }
241
+ const state = projectState(ctx.options);
242
+ const proposals = proposalsOf(lockChanges(state.lock, state.laws, state.exempt, state.levels), undefined);
243
+ const lines = [];
244
+ const records = [];
245
+ for (const cmd of commands) {
246
+ const { matched, unknown, ambiguous } = resolveNames(proposals, cmd);
247
+ if (unknown.length > 0)
248
+ lines.push(`- no proposal named ${unknown.map(shown).join(', ')}`);
249
+ if (ambiguous.length > 0)
250
+ lines.push(`- ${ambiguous.map(shown).join(', ')} names laws in several files; use \`file::name\``);
251
+ if (matched.length === 0)
252
+ continue;
253
+ records.push({
254
+ verb: cmd.verb,
255
+ by: login,
256
+ sha: pr.head.sha,
257
+ items: matched.map((p) => ({ key: p.key, fingerprint: p.fingerprint })),
258
+ });
259
+ lines.push(`- ${cmd.verb === 'accept' ? 'accepted' : 'withdrew'} ${matched.map((p) => `${shown(p.name)} (${shown(p.file)}, ${p.reason})`).join(', ')}`);
260
+ }
261
+ 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.' : ''}`;
262
+ await reply(text);
263
+ // The records go in a comment of their own that holds nothing else, the only shape readApprovals counts.
264
+ if (records.length > 0)
265
+ await reply(recordComment(records));
266
+ try {
267
+ await api('POST', `/repos/${name}/issues/comments/${ev.comment.id}/reactions`, {
268
+ content: records.length > 0 ? '+1' : 'confused',
269
+ });
270
+ }
271
+ catch {
272
+ // a reaction is a courtesy
273
+ }
274
+ if (records.length > 0 && config.approvePullRequest) {
275
+ const comments = await issueComments(api, name, number);
276
+ const approvals = acceptedFingerprints(readApprovals(comments, config.bot));
277
+ if (proposals.length > 0 && proposals.every((p) => approvals.has(p.fingerprint)))
278
+ await api('POST', `/repos/${name}/pulls/${number}/reviews`, {
279
+ commit_id: pr.head.sha,
280
+ event: 'APPROVE',
281
+ body: 'tslaws: every proposal in this pull request has been accepted.',
282
+ });
283
+ }
284
+ // Re-run the pull request's report so its check sees the new approvals.
285
+ const workflow = ctx.flags.get('rerun-workflow');
286
+ if (typeof workflow === 'string' && records.length > 0) {
287
+ const runs = (await api('GET', `/repos/${name}/actions/workflows/${encodeURIComponent(workflow)}/runs?head_sha=${pr.head.sha}&event=pull_request&per_page=5`));
288
+ const latest = runs.workflow_runs[0];
289
+ if (latest !== undefined)
290
+ await api('POST', `/repos/${name}/actions/runs/${latest.id}/rerun`);
291
+ }
292
+ return 0;
293
+ }
294
+ // ---- merge ----------------------------------------------------------------------------------------------------------
295
+ async function merge(ctx) {
296
+ const configText = readText(join(ctx.cwd, 'tslaws.json'));
297
+ const config = githubConfigOf(configText);
298
+ if (isSharedBot(config))
299
+ ctx.out(`::warning title=tslaws::"bot" is ${config.bot}, which every workflow can act as; only a ruleset on ${config.branch} that restricts tsc-laws.lock keeps other workflows from writing it. A dedicated GitHub App closes this.
300
+ `);
301
+ const ev = event(ctx.env);
302
+ const ref = String(ev.ref ?? ctx.env.GITHUB_REF ?? '');
303
+ if (ref !== `refs/heads/${config.branch}`) {
304
+ ctx.err(`tslaws: ${ref} is not refs/heads/${config.branch}; the lock is written only there\n`);
305
+ return 1;
306
+ }
307
+ if (ctx.env.GITHUB_EVENT_NAME !== undefined && ctx.env.GITHUB_EVENT_NAME !== 'push') {
308
+ ctx.err('tslaws: merge runs on push only\n');
309
+ return 1;
310
+ }
311
+ const commits = (ev.commits ?? []);
312
+ const touches = (c) => [...(c.modified ?? []), ...(c.added ?? []), ...(c.removed ?? [])].includes('tsc-laws.lock');
313
+ const api = ctx.api ?? restApi(ctx.env);
314
+ const name = repo(ctx.env);
315
+ const sha = String(ev.after ?? ctx.env.GITHUB_SHA ?? '');
316
+ // Made by the bot, as GitHub sees it: the account and a signature GitHub verified. The push payload's author name
317
+ // comes from the commit's e-mail address, which anyone can set, so it is not enough on its own.
318
+ const byBot = async (id) => {
319
+ const detail = (await api('GET', `/repos/${name}/commits/${id}`));
320
+ return detail.author?.login === config.bot && detail.commit.verification?.verified === true;
321
+ };
322
+ // The payload lists at most 20 commits; a longer push is never taken for the bot's.
323
+ if (commits.length > 0 && commits.length < 20 && commits.every(touches)) {
324
+ let all = true;
325
+ for (const c of commits)
326
+ if (!(await byBot(c.id)))
327
+ all = false;
328
+ if (all) {
329
+ ctx.out('tslaws: this push is the bot writing the lock; nothing to do\n');
330
+ return 0;
331
+ }
332
+ }
333
+ for (const c of commits.filter(touches))
334
+ if (!(await byBot(c.id))) {
335
+ ctx.err(`tslaws: commit ${c.id.slice(0, 7)} changed tsc-laws.lock but was not made by ${config.bot} with a verified signature; nothing accepted. Revert it.\n`);
336
+ return 1;
337
+ }
338
+ // The push event lists at most 20 commits, and their file lists can be cut short, so compare the lock itself: this
339
+ // push is not the bot's alone (that case returned above), so it must leave the lock exactly as it was.
340
+ const before = String(ev.before ?? '');
341
+ if (/^[0-9a-f]{40}$/.test(before) && !/^0+$/.test(before)) {
342
+ const lockAt = async (ref) => {
343
+ try {
344
+ return (await api('GET', `/repos/${name}/contents/tsc-laws.lock?ref=${ref}`)).sha;
345
+ }
346
+ catch {
347
+ return undefined;
348
+ }
349
+ };
350
+ if ((await lockAt(before)) !== (await lockAt(sha))) {
351
+ ctx.err(`tslaws: this push changed tsc-laws.lock, and not only through ${config.bot}; nothing accepted. Revert the change.
352
+ `);
353
+ return 1;
354
+ }
355
+ }
356
+ // Runs queue behind one another (the concurrency group), so this checkout can predate a lock commit that an earlier
357
+ // run made. Start from the lock on the branch, so this run never undoes what an earlier one accepted, once every
358
+ // commit since this push that changed the lock is shown to be the bot's.
359
+ const branchRef = encodeURIComponent(config.branch);
360
+ const headLock = (await api('GET', `/repos/${name}/contents/tsc-laws.lock?ref=${branchRef}`).catch(() => undefined));
361
+ const lockFile = ctx.options.lockFile;
362
+ const localBlob = existsSync(lockFile) ? gitBlobSha(readFileSync(lockFile)) : undefined;
363
+ if (headLock !== undefined && headLock.sha !== localBlob) {
364
+ const range = (await api('GET', `/repos/${name}/compare/${sha}...${branchRef}`));
365
+ const since = new Set(range.commits.map((c) => c.sha));
366
+ const touched = (await api('GET', `/repos/${name}/commits?sha=${branchRef}&path=tsc-laws.lock&per_page=100`));
367
+ let trusted = range.status === 'ahead' && range.ahead_by === range.commits.length && touched.length < 100;
368
+ for (const c of touched)
369
+ if (trusted && since.has(c.sha) && !(await byBot(c.sha)))
370
+ trusted = false;
371
+ if (!trusted) {
372
+ ctx.err(`tslaws: tsc-laws.lock on ${config.branch} has moved on since this push, and not only through ${config.bot}; nothing accepted
373
+ `);
374
+ return 1;
375
+ }
376
+ writeFileSync(lockFile, Buffer.from(headLock.content, 'base64'));
377
+ }
378
+ const pulls = (await api('GET', `/repos/${name}/commits/${sha}/pulls`));
379
+ const checked = await check(ctx.options, true);
380
+ const state = projectState(ctx.options);
381
+ const proposals = proposalsOf(lockChanges(state.lock, state.laws, state.exempt, state.levels), checked);
382
+ if (proposals.length === 0) {
383
+ ctx.out('tslaws: the lock already records every law\n');
384
+ return 0;
385
+ }
386
+ // Each record's author is checked again now: someone who lost write access, or a rule that changed since the
387
+ // comment, leaves their records out.
388
+ let records = [];
389
+ if (config.accept === 'comment')
390
+ for (const pr of pulls) {
391
+ const verdicts = new Map();
392
+ for (const record of readApprovals(await issueComments(api, name, pr.number), config.bot)) {
393
+ if (!verdicts.has(record.by))
394
+ verdicts.set(record.by, (await refusal(api, name, pr, record.by, 'User', config)) === undefined);
395
+ if (verdicts.get(record.by))
396
+ records.push(record);
397
+ else
398
+ ctx.err(`tslaws: ignoring the records of @${record.by} on #${pr.number}: no longer an approver\n`);
399
+ }
400
+ }
401
+ const approvals = acceptedFingerprints(records);
402
+ const decision = decide(proposals, config, approvals);
403
+ const accepted = proposals.filter((p) => decision.accept.has(p.fingerprint));
404
+ if (accepted.length > 0) {
405
+ const next = acceptChanges(state.lock, state.laws, state.exempt, state.levels, decision.accept);
406
+ writeLockValue(ctx.options.lockFile, next);
407
+ const text = readFileSync(ctx.options.lockFile, 'utf8');
408
+ if (!ctx.flags.has('dry-run')) {
409
+ // Through the contents API, so GitHub signs the commit as the bot and `verify` can tell it from a forgery. The
410
+ // lock this run started from is the one it replaces: if anything wrote the lock since, GitHub refuses the write.
411
+ await api('PUT', `/repos/${name}/contents/tsc-laws.lock`, {
412
+ 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')}`,
413
+ content: Buffer.from(text).toString('base64'),
414
+ branch: config.branch,
415
+ ...(headLock === undefined ? {} : { sha: headLock.sha }),
416
+ });
417
+ }
418
+ }
419
+ const lines = [
420
+ ...accepted.map((p) => `- ✅ ${shown(p.name)} (${shown(p.file)}, ${p.reason}) accepted${approvals.has(p.fingerprint) ? ` — @${approvals.get(p.fingerprint)}` : ''}`),
421
+ ...decision.held.map(({ proposal, why }) => `- 🚫 ${shown(proposal.name)} (${shown(proposal.file)}, ${proposal.reason}) not accepted: ${why}`),
422
+ ];
423
+ const note = `### tslaws on \`${config.branch}\`\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` : ''}`;
424
+ summary(ctx.env, note);
425
+ ctx.out(`${note}\n`);
426
+ for (const pr of pulls)
427
+ await api('POST', `/repos/${name}/issues/${pr.number}/comments`, { body: note }).catch(() => undefined);
428
+ setOutput(ctx.env, 'accepted', String(accepted.length));
429
+ return decision.held.length === 0 ? 0 : 1;
430
+ }
431
+ // ---- verify ---------------------------------------------------------------------------------------------------------
432
+ async function verify(ctx) {
433
+ const ev = event(ctx.env);
434
+ const pull = ev.pull_request;
435
+ if (pull === undefined) {
436
+ ctx.err('tslaws: verify runs on pull_request_target\n');
437
+ return 1;
438
+ }
439
+ const api = ctx.api ?? restApi(ctx.env);
440
+ const name = repo(ctx.env);
441
+ const contents = async (path, ref) => {
442
+ try {
443
+ const file = (await api('GET', `/repos/${name}/contents/${path}?ref=${ref}`));
444
+ return Buffer.from(file.content, 'base64').toString('utf8');
445
+ }
446
+ catch {
447
+ return undefined;
448
+ }
449
+ };
450
+ const baseText = await contents('tslaws.json', pull.base.sha);
451
+ const config = githubConfigOf(baseText);
452
+ const problems = [];
453
+ const files = await all(api, `/repos/${name}/pulls/${pull.number}/files`);
454
+ const changed = new Set(files.flatMap((f) => [f.filename, ...(f.previous_filename ? [f.previous_filename] : [])]));
455
+ const protectedPaths = String(ctx.flags.get('protect') ?? '')
456
+ .split(',')
457
+ .map((p) => p.trim())
458
+ .filter(Boolean);
459
+ for (const path of protectedPaths)
460
+ if (changed.has(path))
461
+ problems.push(`${path} is protected: change it in a pull request of its own, merged by an administrator`);
462
+ if (changed.has('tslaws.json')) {
463
+ const headText = await contents('tslaws.json', pull.head.sha);
464
+ const section = (text) => JSON.stringify(text === undefined ? undefined : JSON.parse(text).github);
465
+ try {
466
+ if (section(baseText) !== section(headText))
467
+ problems.push('the pull request changes the "github" section of tslaws.json, which decides who may accept laws');
468
+ }
469
+ catch {
470
+ problems.push('tslaws.json does not parse');
471
+ }
472
+ }
473
+ // The bot never commits to a pull request's branch: it writes the lock on ${config.branch} after the merge. So any
474
+ // change to the lock in the pull request's diff (the full list, paginated above) is a forgery. Checking the diff, not
475
+ // each commit, also covers commits whose file list GitHub truncates (the commit API lists at most 300 files).
476
+ if (changed.has('tsc-laws.lock'))
477
+ problems.push(`the pull request changes tsc-laws.lock; only ${config.bot} writes the lock, on merge into ${config.branch}`);
478
+ for (const problem of problems)
479
+ ctx.out(`::error::${escapeGithubData(problem)}\n`);
480
+ if (problems.length === 0)
481
+ ctx.out('tslaws: the lock and its settings are untouched by this pull request\n');
482
+ return problems.length === 0 ? 0 : 1;
483
+ }
484
+ // ---- entry ----------------------------------------------------------------------------------------------------------
485
+ export async function githubCommand(action, ctx) {
486
+ try {
487
+ if (action === 'report')
488
+ return await report(ctx);
489
+ if (action === 'command')
490
+ return await command(ctx);
491
+ if (action === 'merge')
492
+ return await merge(ctx);
493
+ if (action === 'verify')
494
+ return await verify(ctx);
495
+ }
496
+ catch (error) {
497
+ ctx.err(`tslaws github ${action}: ${error instanceof Error ? error.message : String(error)}\n`);
498
+ return 1;
499
+ }
500
+ ctx.err('usage: tslaws github report|command|merge|verify\n');
501
+ return 1;
502
+ }
@@ -0,0 +1,3 @@
1
+ export declare function globToRegExp(glob: string): RegExp;
2
+ /** A predicate for a list of globs: a path matches when an include glob matches and no `!` glob does. */
3
+ export declare function globMatcher(globs: string[]): (file: string) => boolean;
package/dist/globs.js ADDED
@@ -0,0 +1,24 @@
1
+ // Glob matching for the path settings of tslaws.json (`cover`, `laws`): `*` stays in one directory, `**` crosses them.
2
+ export function globToRegExp(glob) {
3
+ let out = '';
4
+ for (let i = 0; i < glob.length; i += 1) {
5
+ const ch = glob[i];
6
+ if (ch === '*' && glob[i + 1] === '*') {
7
+ out += '.*';
8
+ i += glob[i + 2] === '/' ? 2 : 1;
9
+ }
10
+ else if (ch === '*')
11
+ out += '[^/]*';
12
+ else if (ch === '?')
13
+ out += '[^/]';
14
+ else
15
+ out += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&');
16
+ }
17
+ return new RegExp(`^${out}$`);
18
+ }
19
+ /** A predicate for a list of globs: a path matches when an include glob matches and no `!` glob does. */
20
+ export function globMatcher(globs) {
21
+ const include = globs.filter((g) => !g.startsWith('!')).map(globToRegExp);
22
+ const exclude = globs.filter((g) => g.startsWith('!')).map((g) => globToRegExp(g.slice(1)));
23
+ return (file) => include.some((r) => r.test(file)) && !exclude.some((r) => r.test(file));
24
+ }
package/dist/init.js CHANGED
@@ -6,13 +6,13 @@ export const agentsBegin = '<!-- tslaws:begin -->';
6
6
  export const agentsEnd = '<!-- tslaws:end -->';
7
7
  export const nextStep = 'Next, a person at a terminal runs `tslaws accept` to record the laws in tsc-laws.lock.';
8
8
  const hooksDir = join(dirname(fileURLToPath(import.meta.url)), '..', 'hooks');
9
- const starterLaws = `// A starter law. A person owns this file: agents propose laws in *.proposed.laws.ts instead.
9
+ const starterLaws = `// A starter law, written as a call so it needs only stock TypeScript (with the tsc-laws compiler it can also be
10
+ // written as \`export law additionCommutes(a: int, b: int) { ... }\`). A person owns this file: agents propose laws in
11
+ // *.proposed.laws.ts instead.
10
12
  // Replace it with laws about your own code, then run \`tslaws accept\`.
11
- import type { int } from 'tslaws';
13
+ import { law, type int } from 'tslaws';
12
14
 
13
- export law additionCommutes(a: int, b: int) {
14
- return a + b === b + a;
15
- }
15
+ law('addition commutes', (a: int, b: int) => a + b === b + a);
16
16
  `;
17
17
  function writeFile(file, text) {
18
18
  mkdirSync(dirname(file), { recursive: true });
@@ -0,0 +1,21 @@
1
+ /** Directories no walk enters. */
2
+ export declare const ignoredDirs: Set<string>;
3
+ /** The tool-owned directory proposals live in, relative to the project root. */
4
+ export declare const proposalsDir = ".tslaws/proposals";
5
+ /** Whether the text declares a law at the top level (cheap test first, then the real scan). */
6
+ export declare function declaresLaw(text: string): boolean;
7
+ /** A predicate for files the `laws` globs of tslaws.json pick, which still have to declare a law to count. */
8
+ export declare function customLawFile(cwd: string, globs?: string[] | undefined): (file: string) => boolean;
9
+ /**
10
+ * The laws files of the tree, project-relative and sorted: `*.laws.ts` plus the files the `laws` globs find. With
11
+ * `proposed`, the in-tree `*.proposed.laws.ts` files instead (the usual proposals; `discoverProposals` finds the optional ones in `.tslaws/proposals`).
12
+ */
13
+ export declare function discoverLaws(cwd: string, proposed?: boolean): string[];
14
+ /** The files in `.tslaws/proposals/` (any name ending `.ts`), project-relative and sorted. */
15
+ export declare function discoverProposals(cwd: string): string[];
16
+ /** Whether a project-relative path is a laws file of the tree (not a proposal). */
17
+ export declare function isLawsFile(cwd: string, file: string): boolean;
18
+ /** Whether a project-relative path is inside the proposals directory. */
19
+ export declare function inProposals(file: string): boolean;
20
+ /** Whether a (possibly new) path is a name a laws file may have: `*.laws.ts`, or a path a `laws` glob picks. */
21
+ export declare function namesLawsFile(cwd: string, file: string): boolean;