tslaws 1.0.0 → 1.1.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.
package/README.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # tslaws
2
2
 
3
+ [![npm](https://img.shields.io/npm/v/tslaws)](https://www.npmjs.com/package/tslaws)
4
+ [![CI](https://github.com/Jordan-Hall/tsc-laws/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/Jordan-Hall/tsc-laws/actions/workflows/ci.yml)
5
+ [![License](https://img.shields.io/github/license/Jordan-Hall/tsc-laws)](https://github.com/Jordan-Hall/tsc-laws/blob/main/LICENSE)
6
+ [![tslaws](https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2FJordan-Hall%2Ftsc-laws%2Fmain%2Fdocs%2Fcertificates%2Fbadge-laws.json)](https://github.com/Jordan-Hall/tsc-laws/blob/main/docs/certificates/README.md)
7
+ [![certificates](https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2FJordan-Hall%2Ftsc-laws%2Fmain%2Fdocs%2Fcertificates%2Fbadge-certificates.json)](https://github.com/Jordan-Hall/tsc-laws/blob/main/docs/certificates/README.md)
8
+
3
9
  ```sh
4
10
  npm i -D tslaws # also installs the compiler for your platform (tslaws-compiler-<platform>)
5
11
  npx tslaws init
@@ -0,0 +1,64 @@
1
+ import type { Lock } from './lock.ts';
2
+ import type { LawResult } from './types.ts';
3
+ /** The shields.io endpoint schema: https://shields.io/badges/endpoint-badge */
4
+ export interface Endpoint {
5
+ schemaVersion: 1;
6
+ label: string;
7
+ message: string;
8
+ color: 'brightgreen' | 'yellow';
9
+ }
10
+ /** What a badge counts of one law. */
11
+ export interface Standing {
12
+ /** Z3 proved it (`proved`; a law that is only `bounded` or `tested` is not counted). */
13
+ proved: boolean;
14
+ /** A checker accepted a proof of it. */
15
+ certified: boolean;
16
+ }
17
+ export interface Badges {
18
+ laws: Endpoint;
19
+ certificates: Endpoint;
20
+ }
21
+ /** The files `tslaws badge` writes, and the repository's own gallery keeps beside its certificates. */
22
+ export declare const badgeFiles: {
23
+ readonly laws: "badge-laws.json";
24
+ readonly certificates: "badge-certificates.json";
25
+ };
26
+ /** Green when every law is proved (or certified), yellow otherwise, and for a project with no laws. */
27
+ export declare function badgesOf(laws: readonly Standing[]): Badges;
28
+ /**
29
+ * The standing of each law of a check. A law is certified when this run checked a proof of it, or when the lock records
30
+ * a certificate that is still for the law (`tslaws accept` verified it with Carcara before writing it).
31
+ */
32
+ export declare function standingsOf(results: readonly LawResult[], lock?: Lock): Standing[];
33
+ /** The text of the two files, one JSON object each. */
34
+ export declare function badgeTexts(badges: Badges): Record<string, string>;
35
+ /** Writes the two files into `dir` (made if missing) and returns their paths. */
36
+ export declare function writeBadges(dir: string, badges: Badges): string[];
37
+ /** `owner/name` of a GitHub remote URL (https, ssh or scp-style), or undefined for any other host. */
38
+ export declare function githubRepoOf(url: string): string | undefined;
39
+ /** The repository's GitHub name and top directory, from git; undefined parts when there is no repository or remote. */
40
+ export declare function gitFacts(cwd: string): {
41
+ repo?: string;
42
+ top?: string;
43
+ };
44
+ export interface MarkdownOptions {
45
+ /** `owner/name`; the markdown names `OWNER/REPO` when it is not known. */
46
+ repo?: string;
47
+ branch: string;
48
+ /** The directory of the two files, relative to the repository root, with `/` separators. */
49
+ dir: string;
50
+ /** Where both badges link; by default the certificates page in `dir` when `page` is set, else the project's lock. */
51
+ link?: string;
52
+ /** Whether `dir` holds a certificates page (see `writeCertificatesPage`). */
53
+ page?: boolean;
54
+ }
55
+ /** The markdown of both badges, ready to paste into a README. */
56
+ export declare function badgeMarkdown(options: MarkdownOptions): string;
57
+ /** `dir` as the repository root sees it (`/` separators), or as given when there is no repository. */
58
+ export declare function repoRelative(cwd: string, dir: string, top: string | undefined): string;
59
+ /**
60
+ * The certificates page of `tslaws badge`: every law with its status and, for a certified one, its proof files. They are
61
+ * copied from `.tslaws/certificates` into `certificates/` beside the page, so the page links files the repository holds.
62
+ * Writes nothing and returns false when no law is certified.
63
+ */
64
+ export declare function writeCertificatesPage(cwd: string, dir: string, results: readonly LawResult[], lock?: Lock): boolean;
package/dist/badge.js ADDED
@@ -0,0 +1,121 @@
1
+ // `tslaws badge`: the two shields.io endpoint badges of a project, "laws: N proved" and "certificates: N verified", as
2
+ // JSON files to commit, and the markdown that shows them. An endpoint badge reads its JSON from a URL, so a file in the
3
+ // repository served by raw.githubusercontent.com is enough: no GitHub Pages. See docs/certificates.md, "Badges".
4
+ import { spawnSync } from 'node:child_process';
5
+ import { copyFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';
6
+ import { join, relative, resolve } from 'node:path';
7
+ import { certificateName, certificatesDir } from "./certificates.js";
8
+ import { isCertified, lawKey } from "./lock.js";
9
+ /** The files `tslaws badge` writes, and the repository's own gallery keeps beside its certificates. */
10
+ export const badgeFiles = { laws: 'badge-laws.json', certificates: 'badge-certificates.json' };
11
+ function endpoint(label, count, total, verb) {
12
+ const all = total > 0 && count === total;
13
+ return {
14
+ schemaVersion: 1,
15
+ label,
16
+ message: all ? `${count} ${verb}` : `${count} of ${total} ${verb}`,
17
+ color: all ? 'brightgreen' : 'yellow',
18
+ };
19
+ }
20
+ /** Green when every law is proved (or certified), yellow otherwise, and for a project with no laws. */
21
+ export function badgesOf(laws) {
22
+ return {
23
+ laws: endpoint('laws', laws.filter((law) => law.proved).length, laws.length, 'proved'),
24
+ certificates: endpoint('certificates', laws.filter((law) => law.certified).length, laws.length, 'verified'),
25
+ };
26
+ }
27
+ /**
28
+ * The standing of each law of a check. A law is certified when this run checked a proof of it, or when the lock records
29
+ * a certificate that is still for the law (`tslaws accept` verified it with Carcara before writing it).
30
+ */
31
+ export function standingsOf(results, lock) {
32
+ return results.map((result) => ({
33
+ proved: result.status === 'proved',
34
+ certified: result.certificate?.status === 'certified' || isCertified(lock, lawKey(result.file, result.name)),
35
+ }));
36
+ }
37
+ /** The text of the two files, one JSON object each. */
38
+ export function badgeTexts(badges) {
39
+ return {
40
+ [badgeFiles.laws]: `${JSON.stringify(badges.laws, null, 2)}\n`,
41
+ [badgeFiles.certificates]: `${JSON.stringify(badges.certificates, null, 2)}\n`,
42
+ };
43
+ }
44
+ /** Writes the two files into `dir` (made if missing) and returns their paths. */
45
+ export function writeBadges(dir, badges) {
46
+ mkdirSync(dir, { recursive: true });
47
+ return Object.entries(badgeTexts(badges)).map(([name, text]) => {
48
+ writeFileSync(join(dir, name), text);
49
+ return join(dir, name);
50
+ });
51
+ }
52
+ /** `owner/name` of a GitHub remote URL (https, ssh or scp-style), or undefined for any other host. */
53
+ export function githubRepoOf(url) {
54
+ const match = /^(?:https?:\/\/(?:[^@/]+@)?|ssh:\/\/git@|git@)github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/i.exec(url.trim());
55
+ return match === null ? undefined : `${match[1]}/${match[2]}`;
56
+ }
57
+ /** The repository's GitHub name and top directory, from git; undefined parts when there is no repository or remote. */
58
+ export function gitFacts(cwd) {
59
+ const git = (...args) => {
60
+ const ran = spawnSync('git', args, { cwd, encoding: 'utf8' });
61
+ return ran.status === 0 ? ran.stdout.trim() : undefined;
62
+ };
63
+ const remote = git('remote', 'get-url', 'origin');
64
+ const top = git('rev-parse', '--show-toplevel');
65
+ return { repo: remote === undefined ? undefined : githubRepoOf(remote), top };
66
+ }
67
+ /** The markdown of both badges, ready to paste into a README. */
68
+ export function badgeMarkdown(options) {
69
+ const repo = options.repo ?? 'OWNER/REPO';
70
+ const dir = options.dir === '' || options.dir === '.' ? '' : `${options.dir.replace(/\/$/, '')}/`;
71
+ const raw = (file) => `https://img.shields.io/endpoint?url=${encodeURIComponent(`https://raw.githubusercontent.com/${repo}/${options.branch}/${dir}${file}`)}`;
72
+ const link = options.link ??
73
+ `https://github.com/${repo}/blob/${options.branch}/${options.page === true ? `${dir}README.md` : 'tsc-laws.lock'}`;
74
+ return [
75
+ `[![tslaws](${raw(badgeFiles.laws)})](${link})`,
76
+ `[![certificates](${raw(badgeFiles.certificates)})](${link})`,
77
+ ].join('\n');
78
+ }
79
+ /** `dir` as the repository root sees it (`/` separators), or as given when there is no repository. */
80
+ export function repoRelative(cwd, dir, top) {
81
+ const absolute = resolve(cwd, dir);
82
+ return relative(top ?? cwd, absolute).replaceAll('\\', '/');
83
+ }
84
+ /** The files a certified law leaves in `.tslaws/certificates`: its problem and proof, and for a loop the clauses and invariants. */
85
+ const proofExtensions = ['smt2', 'alethe', 'horn', 'inv'];
86
+ const cell = (text) => text.replaceAll('|', '\\|').replaceAll('\n', ' ');
87
+ /**
88
+ * The certificates page of `tslaws badge`: every law with its status and, for a certified one, its proof files. They are
89
+ * copied from `.tslaws/certificates` into `certificates/` beside the page, so the page links files the repository holds.
90
+ * Writes nothing and returns false when no law is certified.
91
+ */
92
+ export function writeCertificatesPage(cwd, dir, results, lock) {
93
+ const standings = standingsOf(results, lock);
94
+ if (!standings.some((standing) => standing.certified))
95
+ return false;
96
+ const saved = certificatesDir(cwd);
97
+ const rows = results.map((result, index) => {
98
+ const certified = standings[index].certified;
99
+ const name = certificateName(lawKey(result.file, result.name));
100
+ const present = proofExtensions.filter((ext) => existsSync(join(saved, `${name}.${ext}`)));
101
+ if (certified && present.length > 0)
102
+ mkdirSync(join(dir, 'certificates'), { recursive: true });
103
+ for (const ext of certified ? present : [])
104
+ copyFileSync(join(saved, `${name}.${ext}`), join(dir, 'certificates', `${name}.${ext}`));
105
+ const files = certified && present.length > 0 ? present.map((ext) => `[${ext}](certificates/${name}.${ext})`) : [];
106
+ return `| ${cell(result.name)} | ${cell(`${result.file}:${result.line}`)} | ${result.status} | ${certified ? 'certified' : 'not certified'} | ${files.length === 0 ? '-' : files.join(', ')} |`;
107
+ });
108
+ const count = standings.filter((standing) => standing.certified).length;
109
+ mkdirSync(dir, { recursive: true });
110
+ writeFileSync(join(dir, 'README.md'), [
111
+ '# Certificates',
112
+ '',
113
+ `${count} of ${results.length} laws are certified. For a certified law, cvc5 wrote an [Alethe](https://verit.loria.fr/documentation/alethe-spec.pdf) proof of its SMT-LIB problem and [Carcara](https://github.com/ufmg-smite/carcara) accepted it. A law the lock records a certificate for counts as certified, and its proof files are listed when this run saved them. Generated by \`tslaws badge\`; do not edit it by hand.`,
114
+ '',
115
+ '| Law | Source | Status | Certificate | Proof files |',
116
+ '| --- | --- | --- | --- | --- |',
117
+ ...rows,
118
+ '',
119
+ ].join('\n'));
120
+ return true;
121
+ }
package/dist/chc.d.ts CHANGED
@@ -43,6 +43,12 @@ export interface HornCertification {
43
43
  horn: string;
44
44
  invariants: string;
45
45
  }
46
+ /**
47
+ * The Z3 worker fell over: it threw, ran out of memory or exited, as opposed to answering `unknown` or running out of
48
+ * time. A proof must not read it as "no verdict", because that would quietly fall back to the bounded proof.
49
+ */
50
+ export declare class SolverCrash extends Error {
51
+ }
46
52
  export type ChcVerdict =
47
53
  /** A verified invariant for every loop; `notes` says which other solvers confirmed it or could not. */
48
54
  {
@@ -64,6 +70,11 @@ export type ChcVerdict =
64
70
  | {
65
71
  kind: 'disagree';
66
72
  reason: string;
73
+ }
74
+ /** The Z3 worker crashed, on every try: nothing is known, and it is not a give-up. */
75
+ | {
76
+ kind: 'crash';
77
+ reason: string;
67
78
  };
68
79
  /** The SMT-LIB script Spacer (and any other CHC solver) reads. */
69
80
  export declare function hornText(system: HornSystem, timeoutMs?: number): string;
@@ -78,7 +89,8 @@ export declare function hornText(system: HornSystem, timeoutMs?: number): string
78
89
  export declare function certificationProblem(horn: string, invariants: string): string | undefined;
79
90
  /**
80
91
  * Looks for an invariant for every loop in `system`, verifies it, and has the installed CHC solvers confirm it.
81
- * Never throws: anything that goes wrong is an `unknown` verdict, and the caller falls back to unrolling.
92
+ * Never throws: anything that goes wrong is an `unknown` verdict, and the caller falls back to unrolling. A crash of the
93
+ * Z3 worker is the exception to that fallback: it is a `crash` verdict, which the caller reports instead.
82
94
  */
83
95
  export declare function solveHorn(system: HornSystem, engine: Engine, timeoutMs: number): Promise<ChcVerdict>;
84
96
  /** Runs each installed solver (`TSLAWS_ELDARICA` and `TSLAWS_GOLEM`, else `eld` and `golem` on the PATH) on the system. */
package/dist/chc.js CHANGED
@@ -14,6 +14,12 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
14
14
  import { tmpdir } from 'node:os';
15
15
  import { extname, join } from 'node:path';
16
16
  import { budget, lowerPriority } from "./pool.js";
17
+ /**
18
+ * The Z3 worker fell over: it threw, ran out of memory or exited, as opposed to answering `unknown` or running out of
19
+ * time. A proof must not read it as "no verdict", because that would quietly fall back to the bounded proof.
20
+ */
21
+ export class SolverCrash extends Error {
22
+ }
17
23
  const unknown = (reason) => ({ kind: 'unknown', reason });
18
24
  /** Floating point and strings are outside what the CHC engines decide: the unrolled proof handles those. */
19
25
  const unmodelled = /FloatingPoint|\bfp\.|to_fp|\bstr\.|\bString\b|\bre\./;
@@ -191,7 +197,8 @@ async function verified(system, definitions, engine, timeoutMs) {
191
197
  }
192
198
  /**
193
199
  * Looks for an invariant for every loop in `system`, verifies it, and has the installed CHC solvers confirm it.
194
- * Never throws: anything that goes wrong is an `unknown` verdict, and the caller falls back to unrolling.
200
+ * Never throws: anything that goes wrong is an `unknown` verdict, and the caller falls back to unrolling. A crash of the
201
+ * Z3 worker is the exception to that fallback: it is a `crash` verdict, which the caller reports instead.
195
202
  */
196
203
  export async function solveHorn(system, engine, timeoutMs) {
197
204
  const query = hornText(system, timeoutMs);
@@ -231,6 +238,8 @@ export async function solveHorn(system, engine, timeoutMs) {
231
238
  return { kind: 'safe', invariants, notes, certification };
232
239
  }
233
240
  catch (error) {
241
+ if (error instanceof SolverCrash)
242
+ return { kind: 'crash', reason: error.message };
234
243
  return unknown(error.message);
235
244
  }
236
245
  }
package/dist/check.js CHANGED
@@ -168,6 +168,9 @@ export async function check(options, enforceLock) {
168
168
  }
169
169
  return verdict;
170
170
  };
171
+ // `only` (names) and `onlyKeys` (`file::name`) narrow the run; a law they leave out has no result and no event.
172
+ const keyed = (law) => options.onlyKeys === undefined || options.onlyKeys.includes(lawKey(law.file, law.name));
173
+ const selected = (law) => (options.only === undefined || options.only.includes(law.name)) && keyed(law);
171
174
  const sources = new Sources(options.cwd);
172
175
  // What a law reaches is syntactic and cheap; a project that cannot be read this way just has no locations.
173
176
  const exercisesFor = (law) => {
@@ -268,13 +271,13 @@ export async function check(options, enforceLock) {
268
271
  }
269
272
  }
270
273
  for (const law of laws) {
271
- if (law.problems.length > 0 && !blocked.has(lawKey(law.file, law.name)))
274
+ if (keyed(law) && law.problems.length > 0 && !blocked.has(lawKey(law.file, law.name)))
272
275
  add(law, 'error', 'manifest', { message: law.problems.join('; ') });
273
276
  }
274
277
  const covered = coverFiles(options.cwd, readConfig(options.cwd).cover ?? []);
275
278
  const compiled = [...new Set([...options.files, ...covered])];
276
- const nodeLaws = laws.filter((law) => law.problems.length === 0 && verdictOf(law.file).kind === 'node').length;
277
- const runsHere = laws.filter((law) => law.problems.length === 0 && verdictOf(law.file).kind !== 'browser').length;
279
+ const nodeLaws = laws.filter((law) => selected(law) && law.problems.length === 0 && verdictOf(law.file).kind === 'node').length;
280
+ const runsHere = laws.filter((law) => selected(law) && law.problems.length === 0 && verdictOf(law.file).kind !== 'browser').length;
278
281
  // The sandbox is on unless the person turned it off with `sandbox: false` (`--no-sandbox`), and a Node that cannot
279
282
  // enforce it is an error here, never a quiet fallback. End-to-end laws are no exception: see `allowE2e`.
280
283
  const sandboxed = runsHere > 0 && useSandbox(options);
@@ -312,7 +315,7 @@ export async function check(options, enforceLock) {
312
315
  }
313
316
  };
314
317
  const runBody = async (law, add) => {
315
- if (options.only !== undefined && !options.only.includes(law.name))
318
+ if (!selected(law))
316
319
  return;
317
320
  if (blocked.has(lawKey(law.file, law.name)))
318
321
  return;
@@ -578,7 +581,7 @@ export async function check(options, enforceLock) {
578
581
  // that slot. Browser and end-to-end laws also share one page and one server, so they queue for it first.
579
582
  const page = new Semaphore(1);
580
583
  await Promise.all(laws.map(async (law, index) => {
581
- const skipped = (options.only !== undefined && !options.only.includes(law.name)) || blocked.has(lawKey(law.file, law.name));
584
+ const skipped = !selected(law) || blocked.has(lawKey(law.file, law.name));
582
585
  if (skipped) {
583
586
  finished.set(index, []);
584
587
  flush();
@@ -587,7 +590,7 @@ export async function check(options, enforceLock) {
587
590
  const inSlot = () => budget.run(() => runOne(law, index));
588
591
  await (verdictOf(law.file).kind !== 'node' ? page.run(inSlot) : inSlot());
589
592
  }));
590
- if (enforceLock) {
593
+ if (enforceLock && options.onlyKeys === undefined) {
591
594
  const coverage = derived.coverage(() => analyzeCoverage({
592
595
  cwd: options.cwd,
593
596
  outDir: built.outDir,
package/dist/cli.d.ts CHANGED
@@ -1,5 +1,15 @@
1
1
  import type { CheckReport } from './check.ts';
2
2
  export declare function totals(report: CheckReport): string;
3
+ /**
4
+ * Where a run of one project writes and what it leaves alone. A root run gives each project its own: `out` can be a
5
+ * buffer, `skip` lists the projects nested below this one (so a root that is itself a project does not run theirs) and
6
+ * `tag` names the project on every ndjson line.
7
+ */
8
+ interface Run {
9
+ out: (text: string) => void;
10
+ skip: string[];
11
+ tag?: string;
12
+ }
3
13
  export declare function watched(filename: string | null): boolean;
4
14
  /** What a command needs from its caller. `home` is for unit tests; the CLI never sets it. */
5
15
  export interface CommandContext {
@@ -15,6 +25,11 @@ export interface CommandContext {
15
25
  export declare function acceptCommand(cwd: string, flags: Map<string, string | true>, files: string[], ctx: CommandContext): Promise<number>;
16
26
  /** `tslaws delegate <action> [--for D] [--root DIR]`; `argv` is everything after `delegate`. */
17
27
  export declare function runDelegateCommand(argv: string[], cwd: string, ctx: CommandContext): number;
28
+ /**
29
+ * `tslaws badge [--out DIR]`: the two endpoint badges of the project, from a check run now or from the `check --json`
30
+ * output in `--report`. Writes only the two files and prints the markdown; never touches the lock.
31
+ */
32
+ export declare function badgeCommand(cwd: string, flags: Map<string, string | true>, files: string[], ctx: CommandContext, run?: Run): Promise<number>;
18
33
  /** What `promote` and `propose` ask of their surroundings, beyond the context every command has. `ask`, `stdin` and `checkFile` are for unit tests; the CLI never sets them. */
19
34
  export interface ProposalContext extends CommandContext {
20
35
  ask?: (question: string) => Promise<string>;
@@ -33,3 +48,4 @@ export declare function proposeCommand(cwd: string, flags: Map<string, string |
33
48
  */
34
49
  export declare function promoteCommand(cwd: string, flags: Map<string, string | true>, files: string[], ctx: ProposalContext): Promise<number>;
35
50
  export declare function main(args: string[]): Promise<number>;
51
+ export {};
package/dist/cli.js CHANGED
@@ -23,6 +23,7 @@ import { mutate, renderMutation } from "./mutate.js";
23
23
  import { mutateDefaults, resolveSettings } from "./settings.js";
24
24
  import { serveUi } from "./ui.js";
25
25
  import { acceptGate, defaultDuration, describeGrants, fileHash, grantFor, logDelegatedAccept, parseDuration, personOnly, revokeFor, } from "./delegation.js";
26
+ import { badgeFiles, badgeMarkdown, badgesOf, gitFacts, repoRelative, standingsOf, writeBadges, writeCertificatesPage, } from "./badge.js";
26
27
  import { certificateLabel } from "./certificates.js";
27
28
  import { fileOfKey, lockFormat, lockOf, mergeScoped, readLock, scopeOf, writeLockValue } from "./lock.js";
28
29
  import { lockLevels } from "./lawKinds.js";
@@ -42,6 +43,7 @@ tslaws propose <file.ts> [--from PATH] write a proposal into .tslaws/proposals
42
43
  tslaws promote <proposal> [--to PATH] [--yes] move a proposal from .tslaws/proposals/ into the tree at a path you confirm (people only: needs a terminal; run accept afterwards). It prints the imports and helper code it would add and asks first, and refuses an import of a file outside the project, under .tslaws/, node_modules or .git, or git-ignored; --yes adds it without asking (it is still printed; it never lets promote run without a terminal). In-tree *.proposed.laws.ts files (the usual proposals) promote with --all or by name
43
44
  tslaws list [--json] the laws files and proposals of the project: the level each runs at (from its name, or its imports with levels: imports) and whether it is accepted, unaccepted or proposed (reads files and the lock; runs nothing)
44
45
  tslaws github report|command|merge|verify accept laws on GitHub: flag and run each proposal on a pull request, record /tslaws accept comments, and write tsc-laws.lock on merge or on demand (workflow_dispatch) (CI only; see "github" in tslaws.json)
46
+ tslaws badge [files...] [--out DIR] [--report FILE] [--repo OWNER/NAME] [--branch NAME] [--link URL] [--certify] write the shields.io endpoint badges "laws: N proved" and "certificates: N verified" (badge-laws.json and badge-certificates.json) into DIR (default badges) from a check, or from the check --json output in FILE, and print the markdown that shows them. When a law is certified it also writes DIR/README.md, a page of the laws, their status and their proof files (copied to DIR/certificates). The URLs name the GitHub repository from --repo, $GITHUB_REPOSITORY or the origin remote (else OWNER/REPO), and both badges link to --link (default: that page, or tsc-laws.lock on the branch when no law is certified; the branch defaults to main). Commit the files; see docs/certificates.md
45
47
  tslaws mcp [--compiler PATH] serve check, check_proposed, explain and propose as Model Context Protocol tools on stdio (cannot accept, promote or touch the lock)
46
48
  ${migrateUsage}
47
49
  ${securityUsage}
@@ -91,6 +93,10 @@ function parse(args) {
91
93
  'pr',
92
94
  'config-from',
93
95
  'results',
96
+ 'report',
97
+ 'repo',
98
+ 'branch',
99
+ 'link',
94
100
  'results-out',
95
101
  'head-sha',
96
102
  'rerun-workflow',
@@ -130,6 +136,7 @@ function parse(args) {
130
136
  arg === 'promote' ||
131
137
  arg === 'propose' ||
132
138
  arg === 'list' ||
139
+ arg === 'badge' ||
133
140
  arg === 'migrate' ||
134
141
  arg === 'delegate' ||
135
142
  arg === 'github' ||
@@ -432,6 +439,64 @@ function delegateCommand(cwd, action, flags, ctx) {
432
439
  out(`accept is lent to agents for ${granted.root} until ${granted.expires}\n`);
433
440
  return 0;
434
441
  }
442
+ /**
443
+ * `tslaws badge [--out DIR]`: the two endpoint badges of the project, from a check run now or from the `check --json`
444
+ * output in `--report`. Writes only the two files and prints the markdown; never touches the lock.
445
+ */
446
+ export async function badgeCommand(cwd, flags, files, ctx, run = direct) {
447
+ const err = ctx.err ?? stderrWrite;
448
+ const out = ctx.out ?? run.out;
449
+ for (const name of ['out', 'report', 'repo', 'branch', 'link']) {
450
+ if (flags.get(name) === true || flags.get(name) === '') {
451
+ err(`--${name} takes a value\n`);
452
+ return 1;
453
+ }
454
+ }
455
+ const text = (name) => {
456
+ const value = flags.get(name);
457
+ return typeof value === 'string' ? value : undefined;
458
+ };
459
+ const repoFlag = text('repo');
460
+ if (repoFlag !== undefined && !/^[\w.-]+\/[\w.-]+$/.test(repoFlag)) {
461
+ err('--repo takes OWNER/NAME\n');
462
+ return 1;
463
+ }
464
+ const report = text('report');
465
+ let results;
466
+ if (report !== undefined) {
467
+ const given = JSON.parse(readFileSync(resolve(cwd, report), 'utf8'));
468
+ if (!Array.isArray(given.results)) {
469
+ err(`${report} is not the output of \`tslaws check --json\` for one project (it has no results)\n`);
470
+ return 1;
471
+ }
472
+ results = given.results;
473
+ }
474
+ else {
475
+ const chosen = lawFiles(cwd, flags, files, run.skip);
476
+ if (chosen.length === 0) {
477
+ err('no laws files found (looking for *.laws.ts)\n');
478
+ return 1;
479
+ }
480
+ results = (await check({ ...options(cwd, flags, chosen), partial: files.length > 0 }, true)).results;
481
+ }
482
+ const dir = text('out') ?? 'badges';
483
+ const lock = readLock(join(cwd, 'tsc-laws.lock'));
484
+ const badges = badgesOf(standingsOf(results, lock));
485
+ writeBadges(resolve(cwd, dir), badges);
486
+ const page = writeCertificatesPage(cwd, resolve(cwd, dir), results, lock);
487
+ const git = gitFacts(cwd);
488
+ const repo = repoFlag ?? ctx.env.GITHUB_REPOSITORY ?? git.repo;
489
+ const where = repoRelative(cwd, dir, git.top);
490
+ const markdown = badgeMarkdown({ repo, branch: text('branch') ?? 'main', dir: where, link: text('link'), page });
491
+ out(`${badges.laws.label}: ${badges.laws.message}\n${badges.certificates.label}: ${badges.certificates.message}\n`);
492
+ out(`wrote ${where}/${badgeFiles.laws} and ${where}/${badgeFiles.certificates}; commit them and add to your README:\n\n`);
493
+ out(`${markdown}\n`);
494
+ if (page && text('link') === undefined)
495
+ out(`\nboth badges link to ${where}/README.md, the certificates page written beside them\n`);
496
+ if (repo === undefined)
497
+ out('\nreplace OWNER/REPO: no GitHub remote was found (name it with --repo OWNER/NAME)\n');
498
+ return 0;
499
+ }
435
500
  const readStdin = async () => {
436
501
  let text = '';
437
502
  for await (const chunk of process.stdin)
@@ -770,6 +835,8 @@ async function runOne(command, flags, files, cwd, run) {
770
835
  err: (text) => void process.stderr.write(text),
771
836
  });
772
837
  }
838
+ if (command === 'badge')
839
+ return badgeCommand(cwd, flags, files, { isTTY: process.stdin.isTTY === true, env: process.env }, run);
773
840
  if (command === 'accept')
774
841
  return acceptCommand(cwd, flags, files, { isTTY: process.stdin.isTTY === true, env: process.env, skip: run.skip });
775
842
  if (command === 'delegate')
package/dist/compile.js CHANGED
@@ -25,6 +25,9 @@ function launch(compiler, args, options) {
25
25
  }
26
26
  /** The compiler finds its lib files in TSC_TS_LIB_DIR; without it, use the TypeScript 7 libs scriptc ships. */
27
27
  function compilerEnv(cwd, compiler) {
28
+ // A caller outside the CLI (the API, a test) can reach here with no compiler resolved; say so, not a TypeError from dirname.
29
+ if (typeof compiler !== 'string')
30
+ throw new Error(noCompiler('none'));
28
31
  if (process.env.TSC_TS_LIB_DIR !== undefined)
29
32
  return process.env;
30
33
  // The npm compiler package keeps the lib files beside the executable.
@@ -44,11 +47,12 @@ function compilerEnv(cwd, compiler) {
44
47
  return process.env;
45
48
  }
46
49
  }
50
+ const noCompiler = (compiler) => `no tsc-laws compiler found (${compiler}): install the tslaws-compiler package for this platform, or set TSC_LAWS_BIN / --compiler to the compiler executable`;
47
51
  /** Lists the laws of `files` with the problems that stop them running. */
48
52
  /** Says what to do when the compiler cannot start, in particular when none was found at all. */
49
53
  function cannotRun(compiler, error) {
50
54
  if (error.code === 'ENOENT')
51
- return `no tsc-laws compiler found (${compiler}): install the tslaws-compiler package for this platform, or set TSC_LAWS_BIN / --compiler to the compiler executable`;
55
+ return noCompiler(compiler);
52
56
  return `cannot run ${compiler}: ${error.message}`;
53
57
  }
54
58
  /** The compiler name that selects the built-in path: stock TypeScript, with laws written as `law(...)` calls. */
package/dist/coverage.js CHANGED
@@ -316,6 +316,30 @@ export function coverFiles(cwd, globs) {
316
316
  walk(cwd);
317
317
  return found.sort();
318
318
  }
319
+ /** The interop helpers a compiler wraps around `require` for an ES module import: tsc's, tslib's and esbuild's. */
320
+ const interopHelpers = new Set(['__importStar', '__importDefault', '__toESM']);
321
+ /**
322
+ * The relative path in `require('./x')`, or in that call wrapped, possibly more than once, in an interop helper such as
323
+ * `__importStar(require('./x'))`. Undefined for anything else.
324
+ */
325
+ function relativeRequire(expression) {
326
+ let call = expression;
327
+ while (ts.isCallExpression(call) && call.arguments.length >= 1) {
328
+ const callee = call.expression;
329
+ const name = ts.isIdentifier(callee) ? callee.text : ts.isPropertyAccessExpression(callee) ? callee.name.text : '';
330
+ if (!interopHelpers.has(name))
331
+ break;
332
+ call = call.arguments[0];
333
+ }
334
+ if (ts.isCallExpression(call) &&
335
+ ts.isIdentifier(call.expression) &&
336
+ call.expression.text === 'require' &&
337
+ call.arguments.length === 1 &&
338
+ ts.isStringLiteral(call.arguments[0]) &&
339
+ call.arguments[0].text.startsWith('.'))
340
+ return call.arguments[0].text;
341
+ return undefined;
342
+ }
319
343
  function parseModule(jsFile, modules) {
320
344
  const known = modules.get(jsFile);
321
345
  if (known !== undefined)
@@ -338,13 +362,11 @@ function parseModule(jsFile, modules) {
338
362
  const init = declaration.initializer;
339
363
  if (ts.isArrowFunction(init) || ts.isFunctionExpression(init) || ts.isClassExpression(init))
340
364
  module.nodes.set(declaration.name.text, { name: declaration.name.text, body: init, exempt: exempt(statement) });
341
- else if (ts.isCallExpression(init) &&
342
- ts.isIdentifier(init.expression) &&
343
- init.expression.text === 'require' &&
344
- init.arguments.length === 1 &&
345
- ts.isStringLiteral(init.arguments[0]) &&
346
- init.arguments[0].text.startsWith('.')) {
347
- const base = resolve(dirname(jsFile), init.arguments[0].text);
365
+ else {
366
+ const specifier = relativeRequire(init);
367
+ if (specifier === undefined)
368
+ continue;
369
+ const base = resolve(dirname(jsFile), specifier);
348
370
  module.imports.set(declaration.name.text, /\.[cm]?js$/.test(base) ? base : `${base}.js`);
349
371
  }
350
372
  }
package/dist/githubCli.js CHANGED
@@ -25,9 +25,10 @@ import { execFileSync } from 'node:child_process';
25
25
  import { join } from 'node:path';
26
26
  import { exemptionsOf } from "./check.js";
27
27
  import { checkIsolated, readReport } from "./isolate.js";
28
+ import { useSandbox } from "./sandbox.js";
28
29
  import { extendsTarget, readConfig } from "./coverage.js";
29
30
  import { discoverFromFiles, discoverySignature } from "./projects.js";
30
- import { readManifest } from "./compile.js";
31
+ import { build, readManifest } from "./compile.js";
31
32
  import { acceptedFingerprints, inert, recordComment, decide, parseCommands, isSharedBot, parseGithubConfig, proposalsOf, pullRequestVerdict, readApprovals, renderSticky, renderStickyAll, resolveNames, stickyMarkerFor, } from "./github.js";
32
33
  import { lockLevels } from "./lawKinds.js";
33
34
  import { acceptChanges, lawKey, lockChanges, readLock, writeLockValue } from "./lock.js";
@@ -204,8 +205,7 @@ function plan(ctx, units, dirOf) {
204
205
  return { active, all };
205
206
  }
206
207
  /** 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);
208
+ function expectedOf(state) {
209
209
  return {
210
210
  laws: new Set(state.laws.map((law) => lawKey(law.file, law.name))),
211
211
  lock: new Set(Object.keys(state.lock?.laws ?? {})),
@@ -238,20 +238,67 @@ function resultsOf(ctx, file, mode, sha) {
238
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
239
  * credentials. Either way it is validated as data before anything acts on it.
240
240
  */
241
- async function runLaws(ctx, unit, mode, sha) {
241
+ async function runLaws(ctx, unit, mode, sha, state, only) {
242
242
  const file = ctx.flags.get('results');
243
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;
244
+ return runIsolated(unit, state, only);
245
+ return readReport(resultEntry(ctx, file, unit, mode, sha).report, expectedFor(state, only));
246
+ }
247
+ /**
248
+ * The merge job's report for the laws it has to prove. With a results file, a project the laws job reported nothing for
249
+ * has no report (undefined), and a report may lack a law: the caller holds every law without a result, so a results file
250
+ * that falls short fails closed per law instead of failing the whole run. Anything else wrong with it still throws.
251
+ */
252
+ async function mergeLaws(ctx, unit, sha, state, only) {
253
+ const file = ctx.flags.get('results');
254
+ if (typeof file !== 'string')
255
+ return runIsolated(unit, state, only);
256
+ const entry = resultEntry(ctx, file, unit, 'merge', sha);
257
+ if (entry.report === undefined)
258
+ return undefined;
259
+ return readReport(entry.report, { ...expectedFor(state), required: new Set() });
260
+ }
261
+ /** One project's entry of the results file, once it is known to come from this commit and this lock. */
262
+ function resultEntry(ctx, file, unit, mode, sha) {
263
+ const results = resultsOf(ctx, file, mode, sha);
264
+ const entry = Object.hasOwn(results.projects, unit.path) ? results.projects[unit.path] : undefined;
248
265
  if (entry === undefined)
249
266
  throw new Error(`${file} has no results for ${label(unit)}`);
250
267
  if (typeof entry.error === 'string')
251
268
  throw new Error(entry.error);
252
269
  if (entry.lockSha !== lockShaOf(unit))
253
270
  throw new Error(`${label(unit)}'s lock is not the one its laws were run against`);
254
- return readReport(entry.report, expectedOf(unit));
271
+ return entry;
272
+ }
273
+ /** What a report must hold: every law, or just the ones a partial run was asked for. */
274
+ const expectedFor = (state, only) => ({
275
+ ...expectedOf(state),
276
+ ...(only === undefined ? {} : { required: new Set(only) }),
277
+ });
278
+ /** The laws of a project run in a child with no credentials: all of them, or only the laws with these keys. */
279
+ function runIsolated(unit, state, only) {
280
+ const options = only === undefined ? unit.options : { ...unit.options, onlyKeys: [...only] };
281
+ return checkIsolated(options, true, expectedFor(state, only));
282
+ }
283
+ /**
284
+ * What a run that proves nothing still has to find out, as the run of every law used to: that the project builds, and
285
+ * that the sandbox can be enforced here. A failure is thrown, so the run fails as it did when every law ran.
286
+ */
287
+ function assertRunnable(unit, state) {
288
+ if (state.laws.length === 0)
289
+ return;
290
+ useSandbox(unit.options);
291
+ const built = build(unit.options.compiler, unit.options.files, unit.options.cwd);
292
+ if (!built.ok)
293
+ throw new Error(`the project does not compile:
294
+ ${built.diagnostics}`);
295
+ }
296
+ /**
297
+ * The laws a merge has to run in a project: the ones the lock does not record as they are. A removal or an exemption runs
298
+ * nothing, and a law the lock records is neither proposed nor accepted by a merge, so proving it again would change nothing.
299
+ */
300
+ function lawsToProve(changes) {
301
+ return changes.filter((c) => c.kind === 'law' && c.reason !== 'removed').map((c) => c.key);
255
302
  }
256
303
  /** `--results-out <file>`: run the laws of every project and write the reports, doing nothing else. Needs no token. */
257
304
  async function collect(ctx, mode, file) {
@@ -262,7 +309,17 @@ async function collect(ctx, mode, file) {
262
309
  for (const { unit } of active) {
263
310
  const entry = { lockSha: lockShaOf(unit) };
264
311
  try {
265
- entry.report = await checkIsolated(unit.options, true, expectedOf(unit));
312
+ const state = projectState(unit.options);
313
+ if (mode === 'report')
314
+ entry.report = await runIsolated(unit, state);
315
+ else {
316
+ // A merge acts only on what the lock does not record, which it works out again from the same lock and files.
317
+ const only = lawsToProve(lockChanges(state.lock, state.laws, state.exempt, state.levels));
318
+ if (only.length > 0)
319
+ entry.report = await runIsolated(unit, state, only);
320
+ else
321
+ assertRunnable(unit, state);
322
+ }
266
323
  }
267
324
  catch (error) {
268
325
  entry.error = error instanceof Error ? error.message : String(error);
@@ -284,8 +341,8 @@ async function report(ctx) {
284
341
  const ran = [];
285
342
  for (const a of active) {
286
343
  try {
287
- const checked = await runLaws(ctx, a.unit, 'report', sha);
288
344
  const state = projectState(a.unit.options);
345
+ const checked = await runLaws(ctx, a.unit, 'report', sha, state);
289
346
  ran.push({
290
347
  active: a,
291
348
  checked,
@@ -1010,11 +1067,20 @@ async function merge(ctx) {
1010
1067
  }
1011
1068
  writeFileSync(lockFile, Buffer.from(headLock.content, 'base64'));
1012
1069
  }
1070
+ // What the lock does not record yet is all a merge acts on, and the files alone tell what that is. A project the
1071
+ // lock already records runs nothing, and otherwise only the laws that changed run: a law the lock records is
1072
+ // neither proposed nor accepted here, so proving it again would change nothing.
1013
1073
  let checked;
1014
1074
  let state;
1075
+ let changes;
1015
1076
  try {
1016
- checked = await runLaws(ctx, unit, 'merge', sha);
1017
1077
  state = projectState(unit.options);
1078
+ changes = lockChanges(state.lock, state.laws, state.exempt, state.levels);
1079
+ const toRun = lawsToProve(changes);
1080
+ if (toRun.length > 0)
1081
+ checked = await mergeLaws(ctx, unit, sha, state, toRun);
1082
+ else
1083
+ assertRunnable(unit, state);
1018
1084
  }
1019
1085
  catch (error) {
1020
1086
  if (!monorepo)
@@ -1022,9 +1088,9 @@ async function merge(ctx) {
1022
1088
  stop(`tslaws: ${label(unit)} could not be checked: ${error instanceof Error ? error.message : String(error)}`);
1023
1089
  continue;
1024
1090
  }
1025
- const proposals = proposalsOf(lockChanges(state.lock, state.laws, state.exempt, state.levels), checked, unit.path);
1091
+ const proposals = proposalsOf(changes, checked, unit.path);
1026
1092
  if (proposals.length === 0) {
1027
- ctx.out(`tslaws: ${monorepo ? `${label(unit)}: ` : ''}the lock already records every law\n`);
1093
+ ctx.out(`tslaws: ${monorepo ? `${label(unit)}: ` : ''}the lock already records every law; no law ran\n`);
1028
1094
  continue;
1029
1095
  }
1030
1096
  // Each record's author is checked again now, against this project's own approvers: someone who lost write access,
@@ -1047,7 +1113,14 @@ async function merge(ctx) {
1047
1113
  const approvals = dispatched
1048
1114
  ? new Map(proposals.map((p) => [p.fingerprint, actor]))
1049
1115
  : acceptedFingerprints(records, unit.path);
1050
- const decision = decide(proposals, config, approvals);
1116
+ // A law that had to run and has no result (the laws job reported nothing for it) is held whatever `requirePassing` says.
1117
+ const unproven = (p) => p.outcome === undefined && p.kind === 'law' && p.reason !== 'removed';
1118
+ const decision = decide(proposals.filter((p) => !unproven(p)), config, approvals);
1119
+ for (const proposal of proposals.filter(unproven))
1120
+ decision.held.push({
1121
+ proposal,
1122
+ why: 'changed after the laws job ran, or has no result there; run the workflow again',
1123
+ });
1051
1124
  const wins = proposals.filter((p) => decision.accept.has(p.fingerprint));
1052
1125
  if (wins.length > 0) {
1053
1126
  const next = acceptChanges(state.lock, state.laws, state.exempt, state.levels, decision.accept);
package/dist/isolate.d.ts CHANGED
@@ -10,6 +10,11 @@ export interface Expected {
10
10
  laws: ReadonlySet<string>;
11
11
  lock: ReadonlySet<string>;
12
12
  exempt: ReadonlySet<string>;
13
+ /**
14
+ * The laws the report must name, when it covers only some of them (a partial run, see `onlyKeys`). Default: every law.
15
+ * It may still name any other law of the project.
16
+ */
17
+ required?: ReadonlySet<string>;
13
18
  }
14
19
  /**
15
20
  * A report as plain data, or an error. A child (or a results file) is untrusted, so each result is rebuilt from the fields
package/dist/isolate.js CHANGED
@@ -200,7 +200,7 @@ export function readReport(value, expected) {
200
200
  results.push(result);
201
201
  }
202
202
  const got = new Set(results.filter((r) => r.status !== 'uncovered').map((r) => lawKey(r.file, r.name)));
203
- for (const key of expected.laws)
203
+ for (const key of expected.required ?? expected.laws)
204
204
  if (!got.has(key))
205
205
  return fail(`${key} has no result`);
206
206
  const compileOk = report.compileOk;
package/dist/lawHost.js CHANGED
@@ -5,7 +5,7 @@
5
5
  import { readFileSync } from 'node:fs';
6
6
  import { createRequire } from 'node:module';
7
7
  import { join } from 'node:path';
8
- import { installLawRuntime, loadResolver, runtimeFile, useTransforms } from "./lawRuntime.js";
8
+ import { evictLoaded, installLawRuntime, loadResolver, runtimeFile, useTransforms, } from "./lawRuntime.js";
9
9
  import { arbitraryOf } from "./plan.js";
10
10
  import { isDiscard, jsPath, runLaw, summarise } from "./propertyRun.js";
11
11
  import { installLoaderHooks, setImportMetaEnv } from "./runtimeEnv.js";
@@ -135,9 +135,7 @@ function load(outDir, law, env, fresh) {
135
135
  lockDown();
136
136
  }
137
137
  // The process outlives a check, and the code may have been recompiled since the last one.
138
- for (const file of Object.keys(require.cache))
139
- if (file.startsWith(outDir))
140
- delete require.cache[file];
138
+ evictLoaded(require.cache, outDir);
141
139
  const fn = require(jsPath(outDir, law.file))[law.symbol ?? law.name];
142
140
  if (typeof fn !== 'function')
143
141
  throw new Error('compiled module does not export the law');
@@ -25,6 +25,12 @@ export interface Transforms {
25
25
  export declare function transformSource(file: string, extension: string): string;
26
26
  /** Replaces how this thread transforms files; used by the sandboxed law process, which cannot run the real ones. */
27
27
  export declare function useTransforms(next: Transforms): void;
28
+ /**
29
+ * Drops from `cache` what a run must load again: every file under `outDir` (the build may have recompiled it) and every
30
+ * file the plugin hooks loaded. A template keeps the modules it imported; left cached it would share them with no one
31
+ * once the law's own copies are fresh.
32
+ */
33
+ export declare function evictLoaded(cache: Record<string, unknown>, outDir: string): void;
28
34
  /** The runtime a project registered, as the last build left it. */
29
35
  export declare function runtimeOf(cwd: string): LawRuntime | undefined;
30
36
  /** Loads what the resolver needs, while no law is running. A law process calls it once its project is installed. */
@@ -30,11 +30,34 @@ export function transformSource(file, extension) {
30
30
  define: importMetaDefines(file),
31
31
  }).code;
32
32
  }
33
- let transforms = { source: transformSource, plugin: transformPluginFile };
33
+ let transforms = {
34
+ source: transformSource,
35
+ plugin: transformPluginFile,
36
+ };
34
37
  /** Replaces how this thread transforms files; used by the sandboxed law process, which cannot run the real ones. */
35
38
  export function useTransforms(next) {
36
39
  transforms = next;
37
40
  }
41
+ /** The project files a `bundlerPlugins` hook loaded in this thread: they sit outside the output directory. */
42
+ const pluginLoaded = new Set();
43
+ /** Runs the plugin transform and remembers the file, so the next run can drop it from the module cache. */
44
+ function transformPlugin(...args) {
45
+ pluginLoaded.add(args[0]);
46
+ return transforms.plugin(...args);
47
+ }
48
+ /**
49
+ * Drops from `cache` what a run must load again: every file under `outDir` (the build may have recompiled it) and every
50
+ * file the plugin hooks loaded. A template keeps the modules it imported; left cached it would share them with no one
51
+ * once the law's own copies are fresh.
52
+ */
53
+ export function evictLoaded(cache, outDir) {
54
+ for (const file of Object.keys(cache))
55
+ if (file.startsWith(outDir))
56
+ delete cache[file];
57
+ for (const file of pluginLoaded)
58
+ delete cache[file];
59
+ pluginLoaded.clear();
60
+ }
38
61
  /** The runtime a project registered, as the last build left it. */
39
62
  export function runtimeOf(cwd) {
40
63
  return projects.get(outDirOf(cwd));
@@ -75,7 +98,13 @@ export function installLawRuntime(runtime) {
75
98
  if (hooked)
76
99
  return;
77
100
  hooked = true;
78
- installPluginHooks({ ownerOf, beside, transform: (...args) => transforms.plugin(...args) });
101
+ installPluginHooks({
102
+ ownerOf,
103
+ beside,
104
+ twin: twinOf,
105
+ twinOfSpecifier,
106
+ transform: transformPlugin,
107
+ });
79
108
  const internals = Module;
80
109
  const original = internals._resolveFilename;
81
110
  internals._resolveFilename = function (request, parent, ...rest) {
@@ -84,15 +113,19 @@ export function installLawRuntime(runtime) {
84
113
  const mapped = bare && namedInPaths(request, parent) ? resolveThroughTypeScript(request, parent) : undefined;
85
114
  if (mapped !== undefined)
86
115
  return mapped;
116
+ let found;
87
117
  try {
88
- return original.call(this, request, parent, ...rest);
118
+ found = original.call(this, request, parent, ...rest);
89
119
  }
90
120
  catch (error) {
91
- const found = bare ? resolveThroughTypeScript(request, parent) : beside(request, parent);
92
- if (found === undefined)
121
+ const other = bare
122
+ ? resolveThroughTypeScript(request, parent)
123
+ : (beside(request, parent) ?? twinOfSpecifier(request, parent?.filename));
124
+ if (other === undefined)
93
125
  throw error;
94
- return found;
126
+ found = other;
95
127
  }
128
+ return twinOf(found, parent?.filename) ?? found;
96
129
  };
97
130
  // Node loads an unknown extension as JavaScript. A project format (`.tsrx`) goes through its `bundlerPlugins` instead.
98
131
  const plain = internals._extensions['.js'];
@@ -101,7 +134,7 @@ export function installLawRuntime(runtime) {
101
134
  if (!pluginExtensionNeeded(extension))
102
135
  return plain.call(this, module, file);
103
136
  const owner = ownerOf(file);
104
- module._compile(transforms.plugin(file, owner?.cwd ?? process.cwd(), owner?.bundlerPlugins ?? [], 'cjs'), file);
137
+ module._compile(transformPlugin(file, owner?.cwd ?? process.cwd(), owner?.bundlerPlugins ?? [], 'cjs'), file);
105
138
  };
106
139
  for (const extension of ['.ts', '.tsx', '.mts', '.cts'])
107
140
  internals._extensions[extension] = (module, file) => {
@@ -114,6 +147,52 @@ function ownerOf(file) {
114
147
  const holding = all.filter((p) => file.startsWith(p.cwd + sep)).sort((a, b) => b.cwd.length - a.cwd.length);
115
148
  return holding[0] ?? all.at(-1);
116
149
  }
150
+ /**
151
+ * The compiled copy of a project `.ts` file that a file in a project format (`.tsrx`) imports. The plugin's output keeps
152
+ * its imports as written, so `../i18n` finds the source, which the sandbox does not serve and which would be a second
153
+ * instance beside the one the law gets. The build's copy is the same module the law's own imports reach, and it is
154
+ * already in the reviewed set (the build's tree). Nothing else is remapped: undefined when `importer` is not such a
155
+ * file, `file` is not a source the build compiled, or no copy exists.
156
+ */
157
+ function twinOf(file, importer) {
158
+ if (importer === undefined || !pluginExtensionNeeded(extname(importer)))
159
+ return undefined;
160
+ if (!/\.[cm]?tsx?$/.test(file) || /\.d\.[cm]?ts$/.test(file))
161
+ return undefined;
162
+ const owner = ownerOf(importer);
163
+ if (owner === undefined || !file.startsWith(owner.cwd + sep))
164
+ return undefined;
165
+ const root = compiledRoot(owner);
166
+ if (file.startsWith(root + sep))
167
+ return undefined;
168
+ const twin = resolve(root, relative(owner.cwd, file)).replace(/\.[cm]?tsx?$/, '.js');
169
+ return existsSync(twin) ? twin : undefined;
170
+ }
171
+ const jsToTs = {
172
+ '.js': ['.ts', '.tsx'],
173
+ '.jsx': ['.tsx'],
174
+ '.mjs': ['.mts'],
175
+ '.cjs': ['.cts'],
176
+ };
177
+ /**
178
+ * The twin for a NodeNext-style specifier a plugin's output keeps (`./i18n.js` for `i18n.ts`): Node finds no `.js` file
179
+ * beside the source, so the specifier names the source it stands for, and that source's compiled copy is used.
180
+ */
181
+ function twinOfSpecifier(request, importer) {
182
+ if (importer === undefined || !request.startsWith('.'))
183
+ return undefined;
184
+ const named = resolve(dirname(importer), request);
185
+ const extension = extname(named);
186
+ for (const replacement of jsToTs[extension] ?? []) {
187
+ const source = named.slice(0, -extension.length) + replacement;
188
+ if (!existsSync(source))
189
+ continue;
190
+ const twin = twinOf(source, importer);
191
+ if (twin !== undefined)
192
+ return twin;
193
+ }
194
+ return undefined;
195
+ }
117
196
  /**
118
197
  * A relative import of a file the compiler does not write out (a template, a stylesheet) names the file beside the
119
198
  * source, not beside the compiled output.
@@ -7,6 +7,10 @@ export interface PluginHookHost {
7
7
  beside(request: string, parent: {
8
8
  filename: string;
9
9
  }): string | undefined;
10
+ /** The build's compiled copy of a project `.ts` file that a file in a project format imports, if it has one. */
11
+ twin(file: string, importer: string | undefined): string | undefined;
12
+ /** The same for a `./x.js` specifier that stands for `x.ts` (what Node cannot resolve beside the source). */
13
+ twinOfSpecifier(request: string, importer: string | undefined): string | undefined;
10
14
  /** The source Node can run for a file in a project format (see `transformPluginFile` in pluginHost.ts). */
11
15
  transform(file: string, cwd: string, plugins: readonly string[], format: 'cjs' | 'esm'): string;
12
16
  }
@@ -20,16 +20,21 @@ export function installPluginHooks(host) {
20
20
  return installed;
21
21
  registerHooks({
22
22
  resolve(specifier, context, nextResolve) {
23
+ const parent = context.parentURL?.startsWith('file:') ? fileURLToPath(context.parentURL) : undefined;
24
+ let resolved;
23
25
  try {
24
- return nextResolve(specifier, context);
26
+ resolved = nextResolve(specifier, context);
25
27
  }
26
28
  catch (error) {
27
- const parent = context.parentURL?.startsWith('file:') ? fileURLToPath(context.parentURL) : undefined;
28
- const file = parent === undefined ? undefined : host.beside(specifier, { filename: parent });
29
+ const file = parent === undefined
30
+ ? undefined
31
+ : (host.beside(specifier, { filename: parent }) ?? host.twinOfSpecifier(specifier, parent));
29
32
  if (file === undefined)
30
33
  throw error;
31
34
  return { url: pathToFileURL(file).href, shortCircuit: true };
32
35
  }
36
+ const twin = resolved.url.startsWith('file:') ? host.twin(fileURLToPath(resolved.url), parent) : undefined;
37
+ return twin === undefined ? resolved : { ...resolved, url: pathToFileURL(twin).href, format: 'commonjs' };
33
38
  },
34
39
  load(url, context, nextLoad) {
35
40
  if (!url.startsWith('file:'))
@@ -40,7 +45,11 @@ export function installPluginHooks(host) {
40
45
  const owner = host.ownerOf(file);
41
46
  const commonjs = context.conditions.includes('require');
42
47
  const source = host.transform(file, owner?.cwd ?? process.cwd(), owner?.bundlerPlugins ?? [], commonjs ? 'cjs' : 'esm');
43
- return { format: commonjs ? 'commonjs' : 'module', source, shortCircuit: true };
48
+ return {
49
+ format: commonjs ? 'commonjs' : 'module',
50
+ source,
51
+ shortCircuit: true,
52
+ };
44
53
  },
45
54
  });
46
55
  installed = true;
@@ -2,7 +2,7 @@ import { readFileSync } from 'node:fs';
2
2
  import { createRequire } from 'node:module';
3
3
  import { join } from 'node:path';
4
4
  import { parentPort } from 'node:worker_threads';
5
- import { installLawRuntime, runtimeFile } from "./lawRuntime.js";
5
+ import { evictLoaded, installLawRuntime, runtimeFile } from "./lawRuntime.js";
6
6
  import { arbitraryOf } from "./plan.js";
7
7
  import { jsPath, runLaw, summarise } from "./propertyRun.js";
8
8
  import { installLoaderHooks, setImportMetaEnv } from "./runtimeEnv.js";
@@ -19,10 +19,8 @@ parentPort.on('message', async (request) => {
19
19
  const generators = plans.map(arbitraryOf);
20
20
  // The build left the project's module resolution beside the output (aliases from its tsconfig, TypeScript sources).
21
21
  installLawRuntime(JSON.parse(readFileSync(join(outDir, runtimeFile), 'utf8')));
22
- // The worker outlives a check, and the code may have been recompiled since the last one.
23
- for (const loaded of Object.keys(require.cache))
24
- if (loaded.startsWith(outDir))
25
- delete require.cache[loaded];
22
+ // The worker outlives a check, and the code may have been recompiled since the last one. Files a plugin loaded go too.
23
+ evictLoaded(require.cache, outDir);
26
24
  const fn = require(jsPath(outDir, law.file))[law.symbol ?? law.name];
27
25
  parentPort.postMessage({ ok: summarise(await runLaw(fn, generators, options), options) });
28
26
  }
package/dist/smt.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { Worker } from 'node:worker_threads';
1
2
  import { type Certificate, type CertifyMode } from './certificates.ts';
2
3
  import { type SolverName } from './solvers.ts';
3
4
  import type { ManifestLaw } from './types.ts';
@@ -51,9 +52,16 @@ export interface ProveInput {
51
52
  root: string;
52
53
  };
53
54
  }
55
+ /**
56
+ * Starts the Z3 workers with `start` from now on and ends the idle ones, which were started the old way; the returned
57
+ * function puts the first way back. For tests that make a worker crash.
58
+ */
59
+ export declare function startSolverWorkersWith(start: () => Worker): () => void;
54
60
  /**
55
61
  * Runs the query, and runs it again in a fresh worker when the solver itself fell over (a WebAssembly allocation that
56
- * fails on a machine short of memory). A query that merely ran too long is not retried: it would only run long again.
62
+ * fails on a machine short of memory). Idle workers are ended first, so the retry has their memory. A query that merely
63
+ * ran too long is not retried: it would only run long again. A crash that outlasts the retries throws `SolverCrash`,
64
+ * never `Unsupported`, so a proof cannot take it for a solver that gave up.
57
65
  */
58
66
  export declare function solve(query: string, values: string, timeoutMs: number): Promise<{
59
67
  out: string;
package/dist/smt.js CHANGED
@@ -18,7 +18,7 @@ import { budget, jobs, WorkerPool } from "./pool.js";
18
18
  import { dirname, join } from 'node:path';
19
19
  import ts from 'typescript';
20
20
  import { certificateName, certify, certifyHorn, problemText, } from "./certificates.js";
21
- import { hornText, runExternalSolvers, solveHorn } from "./chc.js";
21
+ import { hornText, runExternalSolvers, SolverCrash, solveHorn, } from "./chc.js";
22
22
  import { lawKey } from "./lock.js";
23
23
  import { SolverUnavailable, secondOpinion } from "./solvers.js";
24
24
  import { Executor, SpuriousModel, Unsupported, and, not } from "./symbolic.js";
@@ -238,10 +238,26 @@ function startWorker() {
238
238
  return w;
239
239
  }
240
240
  // Each Z3 instance holds a large WebAssembly heap; more than four at once run out of memory on the bigger queries.
241
- const solvers = new WorkerPool(startWorker, () => Math.min(4, jobs()));
241
+ let spawnWorker = startWorker;
242
+ const solvers = new WorkerPool(() => spawnWorker(), () => Math.min(4, jobs()));
243
+ /**
244
+ * Starts the Z3 workers with `start` from now on and ends the idle ones, which were started the old way; the returned
245
+ * function puts the first way back. For tests that make a worker crash.
246
+ */
247
+ export function startSolverWorkersWith(start) {
248
+ const before = spawnWorker;
249
+ spawnWorker = start;
250
+ solvers.close();
251
+ return () => {
252
+ spawnWorker = before;
253
+ solvers.close();
254
+ };
255
+ }
242
256
  /**
243
257
  * Runs the query, and runs it again in a fresh worker when the solver itself fell over (a WebAssembly allocation that
244
- * fails on a machine short of memory). A query that merely ran too long is not retried: it would only run long again.
258
+ * fails on a machine short of memory). Idle workers are ended first, so the retry has their memory. A query that merely
259
+ * ran too long is not retried: it would only run long again. A crash that outlasts the retries throws `SolverCrash`,
260
+ * never `Unsupported`, so a proof cannot take it for a solver that gave up.
245
261
  */
246
262
  export async function solve(query, values, timeoutMs) {
247
263
  for (let attempt = 0;; attempt += 1) {
@@ -250,12 +266,17 @@ export async function solve(query, values, timeoutMs) {
250
266
  return await budget.run(() => solveOnce(query, values, timeoutMs));
251
267
  }
252
268
  catch (error) {
253
- if (attempt >= 2 || !(error instanceof Unsupported) || !error.message.startsWith('the solver crashed'))
269
+ if (!(error instanceof SolverCrash))
254
270
  throw error;
271
+ if (attempt >= crashRetries)
272
+ throw new SolverCrash(`${error.message} (the query was tried on ${plural(attempt + 1, 'fresh worker')})`);
273
+ solvers.close();
255
274
  await new Promise((done) => setTimeout(done, 400 * (attempt + 1)));
256
275
  }
257
276
  }
258
277
  }
278
+ /** How many times a query is run again after the solver crashed. */
279
+ const crashRetries = 2;
259
280
  /** One try: gives up on the whole worker after the timeout plus a grace period. */
260
281
  async function solveOnce(query, values, timeoutMs) {
261
282
  const current = await solvers.acquire();
@@ -265,6 +286,7 @@ async function solveOnce(query, values, timeoutMs) {
265
286
  clearTimeout(timer);
266
287
  current.off('message', onMessage);
267
288
  current.off('error', onError);
289
+ current.off('exit', onExit);
268
290
  };
269
291
  const kill = () => {
270
292
  solvers.discard(current);
@@ -280,7 +302,7 @@ async function solveOnce(query, values, timeoutMs) {
280
302
  drop();
281
303
  if (reply.error !== undefined) {
282
304
  kill();
283
- reject(new Unsupported(`the solver crashed: ${reply.error}`));
305
+ reject(new SolverCrash(`the Z3 solver crashed: ${reply.error}`));
284
306
  }
285
307
  else {
286
308
  solvers.release(current);
@@ -290,10 +312,17 @@ async function solveOnce(query, values, timeoutMs) {
290
312
  const onError = (error) => {
291
313
  drop();
292
314
  kill();
293
- reject(new Unsupported(`the solver crashed: ${error.message}`));
315
+ reject(new SolverCrash(`the Z3 solver crashed: ${error.message}`));
316
+ };
317
+ // A worker that ends without a word (an abort inside WebAssembly) would otherwise be waited for until the timeout.
318
+ const onExit = (code) => {
319
+ drop();
320
+ kill();
321
+ reject(new SolverCrash(`the Z3 solver crashed: its worker exited with code ${code}`));
294
322
  };
295
323
  current.on('message', onMessage);
296
324
  current.on('error', onError);
325
+ current.on('exit', onExit);
297
326
  current.postMessage({ id, query, values });
298
327
  });
299
328
  }
@@ -361,6 +390,9 @@ export async function proveLaw(input) {
361
390
  catch (error) {
362
391
  if (error instanceof Unsupported)
363
392
  return { kind: 'unsupported', reason: error.message };
393
+ // Not `unsupported`: that would let a law that was merely not proved because Z3 fell over pass as tested.
394
+ if (error instanceof SolverCrash)
395
+ return { kind: 'error', message: error.message };
364
396
  if (error instanceof SolverUnavailable)
365
397
  return { kind: 'error', message: error.message };
366
398
  throw error;
@@ -502,6 +534,8 @@ async function attemptWith(input, intLimit, theory) {
502
534
  const verdict = await solveHorn(hornSystem(executor, decl, facts, holds, safe), { z3: solve, external: runExternalSolvers }, input.timeoutMs);
503
535
  if (verdict.kind === 'disagree')
504
536
  return { kind: 'unsupported', reason: verdict.reason };
537
+ if (verdict.kind === 'crash')
538
+ throw new SolverCrash(verdict.reason);
505
539
  if (verdict.kind !== 'safe')
506
540
  return undefined;
507
541
  const assumptions = [...assumptionsFor(input.shapes, intLimit), ...verdict.invariants, ...verdict.notes];
package/dist/types.d.ts CHANGED
@@ -102,6 +102,11 @@ export interface CheckOptions {
102
102
  regressionExamples?: string[];
103
103
  /** Check only the laws with these names; the others are skipped without a result or an event. */
104
104
  only?: string[];
105
+ /**
106
+ * Check only the laws with these keys (`file::name`), and leave the coverage analysis out: the run is a partial one. Set
107
+ * by `github merge`, which needs the outcome of the laws the lock does not record yet and nothing else.
108
+ */
109
+ onlyKeys?: string[];
105
110
  /** Told as the check proceeds: which laws there are, which is running, each result, and frames of a browser page. */
106
111
  onEvent?: (event: LawEvent) => void;
107
112
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tslaws",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Runs and checks `law` declarations compiled by tsc-laws: property tests, SMT proofs, tamper lock.",
5
5
  "bin": {
6
6
  "tslaws": "bin/tslaws.js"
@@ -63,7 +63,7 @@
63
63
  },
64
64
  "scripts": {
65
65
  "build": "tsc -p tsconfig.json",
66
- "test": "node --test --test-concurrency=1 test/*.test.ts",
66
+ "test": "node --test --test-concurrency=3 --import ./test/setup.ts test/*.test.ts",
67
67
  "check": "node bin/tslaws.js check",
68
68
  "laws": "node bin/tslaws.js check laws/core.laws.ts",
69
69
  "check:watch": "node bin/tslaws.js check --watch"
@@ -89,11 +89,11 @@
89
89
  }
90
90
  },
91
91
  "optionalDependencies": {
92
- "tslaws-compiler-darwin-arm64": "1.0.0",
93
- "tslaws-compiler-darwin-x64": "1.0.0",
94
- "tslaws-compiler-linux-arm64-gnu": "1.0.0",
95
- "tslaws-compiler-linux-x64-gnu": "1.0.0",
96
- "tslaws-compiler-win32-x64-msvc": "1.0.0"
92
+ "tslaws-compiler-darwin-arm64": "1.1.0",
93
+ "tslaws-compiler-darwin-x64": "1.1.0",
94
+ "tslaws-compiler-linux-arm64-gnu": "1.1.0",
95
+ "tslaws-compiler-linux-x64-gnu": "1.1.0",
96
+ "tslaws-compiler-win32-x64-msvc": "1.1.0"
97
97
  },
98
98
  "publishConfig": {
99
99
  "access": "public"