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
package/README.md CHANGED
@@ -35,6 +35,7 @@ ordinary identifier.
35
35
  ```
36
36
  $ tslaws check
37
37
  PROVED clampWithinBounds (src/math.laws.ts:5) [smt]
38
+ assuming: number parameters exclude NaN and ±Infinity
38
39
  BOUNDED sortOrders (src/math.laws.ts:11) [smt]
39
40
  holds within bounds: int values stay within ±2^26; arrays hold at most 4 elements; loops run at most 4 times
40
41
  FAILED sortKeepsLength (src/math.laws.ts:17) [property]
@@ -67,6 +68,12 @@ Two things, both required for exit status 0:
67
68
  | `tampered` | A law changed, was added or removed since `tsc-laws.lock` was accepted, or a coverage exemption is not in it. Fails the check. |
68
69
  | `error` | The law cannot run: not exported, a parameter has no type, no generator for a type, load failure. |
69
70
 
71
+ A `proved` or `bounded` result also lists the domain assumptions its proof rests on, for the parameter types of that law
72
+ only: `number` parameters exclude NaN and ±Infinity, `int` parameters stay within ±(2^53 − 1), and `string` parameters use
73
+ only characters up to U+FFFF with a length cap. They show as `assuming: …` in text output, as `assumptions` in JSON and
74
+ ndjson, and in the step-summary Detail cell and the `::notice` of a `bounded` result. A law whose parameters need none
75
+ (`boolean`, `bigint`) prints as before.
76
+
70
77
  `tslaws check` exits 0 only when every law is `proved`, `bounded` or `tested`, nothing is `uncovered`, the files compile, and
71
78
  the lock matches.
72
79
 
@@ -133,7 +140,7 @@ Anything else leaves the law `tested`, or a `law proved` `open`, with the reason
133
140
 
134
141
  ## Browser laws
135
142
 
136
- A law file named `*.browser.laws.ts` runs in a real browser (Chrome, Edge or Chromium; `TSLAWS_BROWSER` names another
143
+ A laws file that imports `tslaws/browser` (directly or through a helper module of yours) runs in a real browser (Chrome, Edge or Chromium; `TSLAWS_BROWSER` names another
137
144
  executable). Node generates and shrinks the inputs; each one is sent to a page where the compiled law and your code run
138
145
  against a live DOM. The law may be `async`. `tslaws/browser` has `mount`, `settle`, `click`, `type` and `fire`, and works with
139
146
  any framework or none: `mount(el => render(el))` accepts whatever renders into an element and may return its unmount.
@@ -141,7 +148,7 @@ any framework or none: `mount(el => render(el))` accepts whatever renders into a
141
148
  `mountComponent` with the React, Angular, DOM and custom-element adapters tests one component in isolation with props generated from its props type (function-typed props included), plus `spy`, `rendersSame` and Testing Library style queries.
142
149
  Browser laws are `tested`, never `proved`. See [docs/laws.md](../../docs/laws.md#browser-laws).
143
150
 
144
- A `*.browser.laws.ts` file that imports `tslaws/e2e` instead is an end-to-end law: it runs in Node and drives your whole running app through a real browser (`page()`, `open`, `newPage`, `route`, `settle`, `accessible`). Configure `e2e.server` in `tslaws.json` and the runner starts and stops your dev server. See [End-to-end laws](../../docs/laws.md#end-to-end-laws).
151
+ A laws file that imports `tslaws/e2e` instead is an end-to-end law (a file that reaches both is an error; by default the level comes from the name, `.browser.laws.ts` or `.e2e.laws.ts`, and `"levels": "imports"` in `tslaws.json` makes the imports decide instead): it runs in Node and drives your whole running app through a real browser (`page()`, `open`, `newPage`, `route`, `settle`, `accessible`). Configure `e2e.server` in `tslaws.json` and the runner starts and stops your dev server. See [End-to-end laws](../../docs/laws.md#end-to-end-laws).
145
152
 
146
153
  - **Frameworks:** `tslaws.json` `compilerOptions` (`jsx`, `jsxFactory`, `jsxFragmentFactory`, `jsxImportSource`, `experimentalDecorators`,
147
154
  `emitDecoratorMetadata`, `useDefineForClassFields`, `lib`, `types`, `strict`, ...) and `.tsx` sources let React, Angular and any DOM
@@ -160,14 +167,14 @@ See [docs/laws.md](../../docs/laws.md#the-dashboard).
160
167
  `tslaws mutate [files...] [--max N] [--seed N] [--json]` mutation-tests the laws: it mutates the covered code, re-runs the laws against each mutant, and lists the survivors no law caught. It handles `.tsx`/`.jsx` and projects with a lock, and takes the run flags of `check`. See [docs/laws.md](../../docs/laws.md#mutation-testing).
161
168
 
162
169
  - **Other source formats:** `tslaws.json` `bundlerPlugins` lists esbuild plugin modules (paths relative to the file) that teach the browser bundler formats like `.tsrx`. See [docs/laws.md](../../docs/laws.md#bundler-plugins).
163
- - **Settings:** `tslaws.json` `runs`, `bound`, `proofTimeoutMs` and `propertyTimeoutMs` set the run defaults; a command line flag beats them. See [docs/laws.md](../../docs/laws.md#settings).
170
+ - **Settings:** `tslaws.json` `runs`, `bound`, `proofTimeoutMs` and `propertyTimeoutMs` set the run defaults; a command line flag beats them. `"solvers": ["z3", "cvc5"]` makes cvc5 confirm every Z3 proof (set `TSLAWS_CVC5` to its path, or put it on the PATH). See [docs/laws.md](../../docs/laws.md#settings).
164
171
 
165
172
  ## Agents cannot move the goalposts
166
173
 
167
174
  `tsc-laws.lock` holds a hash of every law declaration and the list of coverage exemptions. A change, an added law, a removed
168
175
  law or a new `@tslaws-exempt` fails the check until a person runs `tslaws accept`, which refuses to run without a terminal,
169
- under `CI`, or with `TSLAWS_AGENT` set, unless a person has lent it for a limited time with `tslaws delegate grant`. Agents propose laws in `*.proposed.laws.ts` and try them with `tslaws check
170
- --proposed` (no lock, no coverage gate); a person moves them into a `*.laws.ts` file and accepts.
176
+ under `CI`, or with `TSLAWS_AGENT` set, unless a person has lent it for a limited time with `tslaws delegate grant`. Agents propose laws in `*.proposed.laws.ts` files (or optionally in `.tslaws/proposals/`, outside the tree and git-ignored; `tslaws propose` or the MCP tool) and try them with `tslaws check
177
+ --proposed` (no lock, no coverage gate); a person moves one into the tree with `tslaws promote` and accepts. Every laws file in the tree must be in the lock.
171
178
 
172
179
  `hooks/claude-hook.mjs` is a Claude Code hook that blocks `git commit` and sends an agent back to work when the check fails;
173
180
  `hooks/claude-settings.example.json` wires it up and `hooks/AGENTS.snippet.md` tells the agent the rules.
@@ -199,13 +206,13 @@ tslaws check [files...] [--json] [--summary] [--watch] [--runs N] [--seed N] [--
199
206
  - `check --reporter text|json|junit|github` picks the output: `junit` is JUnit XML for CI test reports, `github` prints workflow
200
207
  annotations and appends a table to `GITHUB_STEP_SUMMARY`. See "CI reporters" in `docs/laws.md`.
201
208
 
202
- - `tslaws mcp` serves `tslaws_check`, `tslaws_check_proposed`, `tslaws_explain` and `tslaws_propose` over MCP (stdio) for
203
- agents; it cannot accept laws or touch the lock. `tslaws promote` is the person's step that moves proposed laws into the
204
- accepted file. See [docs/laws.md](../../docs/laws.md#agent-integration-mcp).
209
+ - `tslaws mcp` serves `tslaws_check`, `tslaws_check_proposed`, `tslaws_explain`, `tslaws_list` and `tslaws_propose` over MCP (stdio) for
210
+ agents; it cannot accept laws, promote a proposal or touch the lock. `tslaws promote <proposal> [--to PATH]` is the person's step that moves a proposal into the
211
+ tree; `tslaws propose <file.ts>` writes one; `tslaws list [--json]` says which files are laws files, at what level, and whether each is accepted. See [docs/laws.md](../../docs/laws.md#agent-integration-mcp).
205
212
  - Counterexamples are kept in `.tslaws/regressions` (committable) and replayed before the random search, so a fixed bug cannot
206
213
  return unnoticed. `check --no-regressions` skips the corpus; `tslaws regressions [list|clear]` shows or deletes it.
207
214
 
208
- Without files, every `*.laws.ts` under the current directory is used. The compiler is `--compiler`, `TSC_LAWS_BIN`, or
215
+ Without files, every `*.laws.ts` under the current directory is used, and every file the `"laws"` globs of `tslaws.json` pick that declares a law. The compiler is `--compiler`, `TSC_LAWS_BIN`, or
209
216
  `tsc-laws` on `PATH`; it finds its lib files through `TSC_TS_LIB_DIR`, or the TypeScript 7 libs scriptc installs in
210
217
  `node_modules/@scriptc/*`.
211
218
 
package/dist/api.d.ts CHANGED
@@ -57,3 +57,13 @@ type Registry = Map<string, fc.Arbitrary<unknown>>;
57
57
  export declare function arbitraryRegistry(): Registry;
58
58
  /** Registers the generator used for every parameter whose type is named `typeName`. */
59
59
  export declare function arbitrary<T>(typeName: string, generator: fc.Arbitrary<T>): void;
60
+ /** What a law may return: `false` fails it, anything else holds. A law may be async (browser laws wait for the page). */
61
+ export type LawBody = (...args: any[]) => boolean | void | Promise<boolean | void>;
62
+ export interface LawDeclare {
63
+ /** Declares a law: `law('name', (x: int) => holds(x))`. Parameters need type annotations, inputs are generated from them. */
64
+ (name: string, body: LawBody): void;
65
+ /** A law the prover must prove for every input; `open` when it cannot. */
66
+ proved(name: string, body: LawBody): void;
67
+ }
68
+ /** Declares a law. `tslaws` lowers these calls to checked functions before it runs them; they never run as written. */
69
+ export declare const law: LawDeclare;
package/dist/api.js CHANGED
@@ -101,3 +101,10 @@ export function arbitraryRegistry() {
101
101
  export function arbitrary(typeName, generator) {
102
102
  arbitraryRegistry().set(typeName, generator);
103
103
  }
104
+ function notRun() {
105
+ throw new Error('law() declares a specification and is run by `tslaws check`, not called at runtime');
106
+ }
107
+ /** Declares a law. `tslaws` lowers these calls to checked functions before it runs them; they never run as written. */
108
+ export const law = Object.assign((_name, _body) => notRun(), {
109
+ proved: (_name, _body) => notRun(),
110
+ });
package/dist/browser.d.ts CHANGED
@@ -2,8 +2,6 @@ import { type Browser } from 'playwright-core';
2
2
  import type * as fc from 'fast-check';
3
3
  import { type PropertyOutcome } from './property.ts';
4
4
  import type { CheckOptions } from './types.ts';
5
- /** `a.browser.laws.ts` runs in a browser. */
6
- export declare function isBrowserLawFile(file: string): boolean;
7
5
  export type BrowserEngine = 'chromium' | 'firefox' | 'webkit';
8
6
  /** The engine to use: the requested one, else `TSLAWS_BROWSER_ENGINE`, else chromium. Throws on an unknown name. */
9
7
  export declare function resolveEngine(requested?: string, env?: NodeJS.ProcessEnv): BrowserEngine;
@@ -17,6 +15,8 @@ export declare function closeBrowser(): Promise<void>;
17
15
  export interface BrowserLaw {
18
16
  file: string;
19
17
  name: string;
18
+ /** The exported function the law lowers to; defaults to `name`. */
19
+ symbol?: string;
20
20
  jsFile: string;
21
21
  generators: fc.Arbitrary<unknown>[];
22
22
  }
package/dist/browser.js CHANGED
@@ -9,10 +9,6 @@ import { readConfig } from "./coverage.js";
9
9
  import { chromium, firefox, webkit } from 'playwright-core';
10
10
  import { toWire } from "./generators.js";
11
11
  import { runProperty, summarise } from "./property.js";
12
- /** `a.browser.laws.ts` runs in a browser. */
13
- export function isBrowserLawFile(file) {
14
- return /\.browser\.laws\.[cm]?ts$/.test(file);
15
- }
16
12
  function findBrowser() {
17
13
  const fromEnv = process.env.TSLAWS_BROWSER;
18
14
  if (fromEnv !== undefined && fromEnv !== '')
@@ -226,7 +222,7 @@ async function bundleOf(jsFile, cwd) {
226
222
  /** Runs the counterexample once more, leaves the DOM as it is, and photographs the page. Best effort. */
227
223
  async function capture(page, law, args, options) {
228
224
  try {
229
- await page.evaluate(([name, input]) => window.__runLaw(name, input, true), [law.name, toWire(args)]);
225
+ await page.evaluate(([name, input]) => window.__runLaw(name, input, true), [law.symbol ?? law.name, toWire(args)]);
230
226
  const relative = `.tslaws/screenshots/${law.name.replace(/[^\w-]/g, '_')}.png`;
231
227
  mkdirSync(join(options.cwd, '.tslaws/screenshots'), { recursive: true });
232
228
  await page.screenshot({ path: join(options.cwd, relative) });
@@ -273,7 +269,7 @@ export async function runBrowserLaw(law, options) {
273
269
  await page.addScriptTag({ content: code });
274
270
  await page.addScriptTag({ content: harness });
275
271
  const call = async (...args) => {
276
- const outcome = (await page.evaluate(([name, input, pause]) => window.__runLaw(name, input, false, pause), [law.name, toWire(args), calls++ < 12 ? (options.browserPauseMs ?? 0) : 0]));
272
+ const outcome = (await page.evaluate(([name, input, pause]) => window.__runLaw(name, input, false, pause), [law.symbol ?? law.name, toWire(args), calls++ < 12 ? (options.browserPauseMs ?? 0) : 0]));
277
273
  if (outcome.error !== undefined) {
278
274
  const error = new Error(outcome.error.message);
279
275
  error.name = outcome.error.name ?? 'Error';
package/dist/check.d.ts CHANGED
@@ -4,6 +4,8 @@ export interface CheckReport {
4
4
  compileDiagnostics: string;
5
5
  compileOk: boolean;
6
6
  lockMissing: boolean;
7
+ /** Things worth a person's attention that do not fail the check: a file name that its imports do not back. */
8
+ notices: string[];
7
9
  /** Whether every law holds and nothing is open, failed or tampered with. */
8
10
  ok: boolean;
9
11
  }
package/dist/check.js CHANGED
@@ -1,16 +1,45 @@
1
- import { readFileSync } from 'node:fs';
2
1
  import { createRequire } from 'node:module';
3
- import { join } from 'node:path';
2
+ import { resolve } from 'node:path';
4
3
  import ts from 'typescript';
5
4
  import { build, readManifest } from "./compile.js";
6
- import { compilerOptions, declarationFiles, isDiscard, jsPath, runLawGuarded, typesOf, } from "./property.js";
5
+ import { compilerOptions, declarationFiles, isDiscard, jsPath, runLawGuarded, warmWorkers, typesOf, } from "./property.js";
7
6
  import { analyzeCoverage, coverFiles, readConfig } from "./coverage.js";
7
+ import { derivedStore } from "./derived.js";
8
+ import { jobs } from "./pool.js";
8
9
  import { compareLock, lawKey, readLock } from "./lock.js";
10
+ import { crossCheck, disagreement } from "./propertyRun.js";
9
11
  import { proveLaw } from "./smt.js";
10
12
  import { decodeExample, loadExamples, regressionMessage, saveExample } from "./regressions.js";
11
13
  import { closeBrowser, runBrowserLaw } from "./browser.js";
12
- import { ensureServer, importsBoth, lawMode, runE2eLaw, stopServer } from "./e2e.js";
14
+ import { ensureServer, runE2eLaw, stopServer } from "./e2e.js";
15
+ import { inProposals } from "./lawFiles.js";
16
+ import { classifyLawFile } from "./lawKinds.js";
17
+ import { normaliseProposal } from "./proposals.js";
13
18
  import { declarationOf, exercisesOf, markFailing, Sources } from "./exercises.js";
19
+ /** Runs at most `limit` tasks at once. */
20
+ class Semaphore {
21
+ free;
22
+ queue = [];
23
+ constructor(limit) {
24
+ this.free = limit;
25
+ }
26
+ async run(task) {
27
+ if (this.free > 0)
28
+ this.free -= 1;
29
+ else
30
+ await new Promise((resolve) => this.queue.push(resolve));
31
+ try {
32
+ return await task();
33
+ }
34
+ finally {
35
+ const next = this.queue.shift();
36
+ if (next === undefined)
37
+ this.free += 1;
38
+ else
39
+ next();
40
+ }
41
+ }
42
+ }
14
43
  /** The `@tslaws-exempt` functions of the project, for `tslaws accept` to record. */
15
44
  export function exemptionsOf(options) {
16
45
  const covered = coverFiles(options.cwd, readConfig(options.cwd).cover ?? []);
@@ -26,9 +55,32 @@ export function exemptionsOf(options) {
26
55
  }).exempt;
27
56
  }
28
57
  export async function check(options, enforceLock) {
58
+ // A proposal placed in .tslaws/proposals by hand may write its imports from the project root; store them where they resolve.
59
+ for (const file of options.files)
60
+ if (inProposals(file))
61
+ normaliseProposal(options.cwd, file);
29
62
  const laws = readManifest(options.compiler, options.files, options.cwd);
30
63
  const results = [];
31
64
  const blocked = new Set();
65
+ const notices = [];
66
+ // The level of a laws file comes from its name (the default) or its imports (`levels: "imports"`); looked at once per file.
67
+ const config = readConfig(options.cwd);
68
+ const levelsMode = config.levels ?? 'names';
69
+ // Who records a law in the lock: a person locally, or the tslaws workflow on merge when "github" is configured.
70
+ const acceptor = readConfig(options.cwd).github !== undefined
71
+ ? 'it is accepted by the tslaws workflow when the pull request merges'
72
+ : 'a person must run `tslaws accept`';
73
+ const verdicts = new Map();
74
+ const verdictOf = (file) => {
75
+ let verdict = verdicts.get(file);
76
+ if (verdict === undefined) {
77
+ verdict = classifyLawFile(options.cwd, file, levelsMode);
78
+ verdicts.set(file, verdict);
79
+ for (const notice of verdict.notices)
80
+ notices.push(notice);
81
+ }
82
+ return verdict;
83
+ };
32
84
  const sources = new Sources(options.cwd);
33
85
  // What a law reaches is syntactic and cheap; a project that cannot be read this way just has no locations.
34
86
  const exercisesFor = (law) => {
@@ -39,17 +91,41 @@ export async function check(options, enforceLock) {
39
91
  return [];
40
92
  }
41
93
  };
94
+ // Laws the lock does not record as they are now: they still run, and their result is reported as what the law would
95
+ // be once accepted, under a `tampered` status that keeps the check failing until the lock records them.
96
+ const pending = new Map();
42
97
  const add = (law, status, method, extra = {}) => {
43
98
  const exercises = status === 'tampered' ? [] : (extra.exercises ?? exercisesFor(law));
44
- const result = {
45
- file: law.file,
46
- name: law.name,
47
- line: law.line,
48
- status,
49
- method,
50
- ...extra,
51
- ...(exercises.length > 0 ? { exercises } : {}),
52
- };
99
+ const proposed = status === 'tampered' || status === 'uncovered' ? undefined : pending.get(lawKey(law.file, law.name));
100
+ const result = proposed === undefined
101
+ ? {
102
+ file: law.file,
103
+ name: law.name,
104
+ line: law.line,
105
+ status,
106
+ method,
107
+ ...extra,
108
+ ...(exercises.length > 0 ? { exercises } : {}),
109
+ }
110
+ : {
111
+ file: law.file,
112
+ name: law.name,
113
+ line: law.line,
114
+ status: 'tampered',
115
+ method: 'lock',
116
+ message: proposed.message,
117
+ ...(extra.seed === undefined ? {} : { seed: extra.seed }),
118
+ ...(extra.runs === undefined ? {} : { runs: extra.runs }),
119
+ ...(extra.screenshot === undefined ? {} : { screenshot: extra.screenshot }),
120
+ proposal: {
121
+ reason: proposed.reason,
122
+ status: status,
123
+ method,
124
+ ...(extra.counterexample === undefined ? {} : { counterexample: extra.counterexample }),
125
+ ...(extra.message === undefined ? {} : { message: extra.message }),
126
+ },
127
+ ...(exercises.length > 0 ? { exercises } : {}),
128
+ };
53
129
  results.push(result);
54
130
  blocked.add(lawKey(law.file, law.name));
55
131
  options.onEvent?.({ type: 'result', result });
@@ -61,7 +137,14 @@ export async function check(options, enforceLock) {
61
137
  lock = readLock(options.lockFile);
62
138
  lockMissing = lock === undefined;
63
139
  const byKey = new Map(laws.map((l) => [lawKey(l.file, l.name), l]));
64
- for (const violation of compareLock(lock?.laws, laws)) {
140
+ // With levels from imports (or a lock that recorded levels), the resolved level of each laws file is part of the lock.
141
+ const levels = levelsMode === 'imports' || lock?.levels !== undefined
142
+ ? {
143
+ locked: lock?.levels,
144
+ now: Object.fromEntries([...new Set(laws.map((l) => l.file.replaceAll('\\', '/')))].map((f) => [f, verdictOf(f).kind])),
145
+ }
146
+ : undefined;
147
+ for (const violation of compareLock(lock?.laws, laws, levels)) {
65
148
  const law = byKey.get(violation.key);
66
149
  if (law === undefined) {
67
150
  const [file, name] = violation.key.split('::');
@@ -72,13 +155,17 @@ export async function check(options, enforceLock) {
72
155
  status: 'tampered',
73
156
  method: 'lock',
74
157
  message: 'law was removed since the lock was accepted',
158
+ proposal: { reason: 'removed', status: 'proved', method: 'lock', message: 'removing a law runs nothing' },
75
159
  });
76
160
  }
77
161
  else {
78
- add(law, 'tampered', 'lock', {
162
+ pending.set(violation.key, {
163
+ reason: violation.reason,
79
164
  message: violation.reason === 'added'
80
- ? 'law is not in the lock; a person must run `tslaws accept`'
81
- : 'law changed since the lock was accepted',
165
+ ? `law is not in the lock; ${acceptor}`
166
+ : violation.reason === 'level'
167
+ ? `the level this laws file runs at (node, browser or e2e) changed since the lock was accepted; ${acceptor}`
168
+ : 'law changed since the lock was accepted',
82
169
  });
83
170
  }
84
171
  }
@@ -89,53 +176,61 @@ export async function check(options, enforceLock) {
89
176
  }
90
177
  const covered = coverFiles(options.cwd, readConfig(options.cwd).cover ?? []);
91
178
  const compiled = [...new Set([...options.files, ...covered])];
179
+ warmWorkers(laws.filter((law) => law.problems.length === 0 && verdictOf(law.file).kind === 'node').length);
92
180
  const built = build(options.compiler, compiled, options.cwd);
93
- const program = ts.createProgram(declarationFiles(built.outDir), compilerOptions);
181
+ // What the type checker works out is kept with the build it came from, so an unchanged project skips the checker.
182
+ const derived = derivedStore(options.cwd, built.key);
183
+ let programOf;
184
+ const program = () => (programOf ??= built.program ?? ts.createProgram(declarationFiles(built.outDir), compilerOptions));
185
+ const sourceCwd = built.program === undefined ? undefined : options.cwd;
94
186
  const require = createRequire(import.meta.url);
95
- for (const law of laws) {
187
+ const runOne = async (law, index) => {
188
+ const buffered = [];
189
+ try {
190
+ await runBody(law, (l, status, method, extra = {}) => {
191
+ buffered.push(() => add(l, status, method, extra));
192
+ });
193
+ }
194
+ finally {
195
+ finished.set(index, buffered);
196
+ flush();
197
+ }
198
+ };
199
+ const runBody = async (law, add) => {
96
200
  if (options.only !== undefined && !options.only.includes(law.name))
97
- continue;
201
+ return;
98
202
  if (blocked.has(lawKey(law.file, law.name)))
99
- continue;
203
+ return;
100
204
  options.onEvent?.({ type: 'start', file: law.file, name: law.name });
101
205
  let types;
102
206
  try {
103
- types = typesOf(program, built.outDir, law);
207
+ types = derived.law(law, () => typesOf(program(), built.outDir, law, sourceCwd));
104
208
  }
105
209
  catch (error) {
106
210
  add(law, 'error', 'generators', { message: error.message });
107
- continue;
211
+ return;
108
212
  }
109
- let source = '';
110
- try {
111
- source = readFileSync(join(options.cwd, law.file), 'utf8');
213
+ const verdict = verdictOf(law.file);
214
+ if (verdict.error !== undefined) {
215
+ add(law, 'error', 'manifest', { message: verdict.error });
216
+ return;
112
217
  }
113
- catch {
114
- // The compiler already reported an unreadable file.
115
- }
116
- if (importsBoth(source)) {
117
- add(law, 'error', 'manifest', {
118
- message: `${law.file}: a browser laws file is either component level (tslaws/browser) or end-to-end (tslaws/e2e), not both`,
119
- });
120
- continue;
121
- }
122
- const mode = lawMode(law.file, source);
123
- const browser = mode === 'component';
124
- const e2e = mode === 'e2e';
218
+ const browser = verdict.kind === 'browser';
219
+ const e2e = verdict.kind === 'e2e';
125
220
  const method = browser ? 'browser' : e2e ? 'e2e' : 'property';
126
221
  let fn;
127
222
  // A browser law touches the DOM when it loads, so only the browser loads it.
128
223
  if (!browser) {
129
224
  try {
130
- fn = require(jsPath(built.outDir, law.file))[law.name];
225
+ fn = require(jsPath(built.outDir, law.file))[law.symbol ?? law.name];
131
226
  }
132
227
  catch (error) {
133
228
  add(law, 'error', 'load', { message: `cannot load compiled law: ${error.message}` });
134
- continue;
229
+ return;
135
230
  }
136
231
  if (typeof fn !== 'function') {
137
232
  add(law, 'error', 'load', { message: 'compiled module does not export the law' });
138
- continue;
233
+ return;
139
234
  }
140
235
  }
141
236
  let details;
@@ -156,18 +251,24 @@ export async function check(options, enforceLock) {
156
251
  details = e2e
157
252
  ? await runE2eLaw({ file: law.file, name: law.name, fn: fn, generators: types.generators }, lawOptions, await ensureServer(e2eConfig ?? {}, options.cwd), limitMs)
158
253
  : browser
159
- ? await runBrowserLaw({ file: law.file, name: law.name, jsFile: jsPath(built.outDir, law.file), generators: types.generators }, lawOptions)
160
- : await runLawGuarded(built.outDir, law, lawOptions);
254
+ ? await runBrowserLaw({
255
+ file: law.file,
256
+ name: law.name,
257
+ symbol: law.symbol,
258
+ jsFile: jsPath(built.outDir, law.file),
259
+ generators: types.generators,
260
+ }, lawOptions)
261
+ : await runLawGuarded(built.outDir, law, lawOptions, types.plans);
161
262
  }
162
263
  catch (error) {
163
264
  add(law, 'error', method, { message: error.message });
164
- continue;
265
+ return;
165
266
  }
166
267
  if (details === 'timeout') {
167
268
  add(law, 'error', method, {
168
269
  message: `property test ran longer than ${limitMs / 1000}s; the law or the code it calls may not terminate`,
169
270
  });
170
- continue;
271
+ return;
171
272
  }
172
273
  if (details.failed) {
173
274
  if (details.counterexample === undefined) {
@@ -192,7 +293,7 @@ export async function check(options, enforceLock) {
192
293
  message: details.regression ? `${regressionMessage} (${details.counterexample}): ${reason}` : reason,
193
294
  });
194
295
  }
195
- continue;
296
+ return;
196
297
  }
197
298
  // Browser and async laws are tested, never proved: the prover cannot model a DOM or an await.
198
299
  const unprovable = browser || e2e ? 'runs in a browser' : fn.constructor.name === 'AsyncFunction' ? 'is async' : undefined;
@@ -206,7 +307,7 @@ export async function check(options, enforceLock) {
206
307
  : 'marked proved but proving is disabled'
207
308
  : undefined,
208
309
  });
209
- continue;
310
+ return;
210
311
  }
211
312
  const holds = (inputs) => {
212
313
  try {
@@ -223,9 +324,39 @@ export async function check(options, enforceLock) {
223
324
  bound: options.bound,
224
325
  timeoutMs: options.proofTimeoutMs,
225
326
  holds,
327
+ solvers: config.solvers,
226
328
  });
227
- if (proof.kind === 'proved')
228
- add(law, 'proved', 'smt', { runs: details.numRuns, seed: details.seed });
329
+ const assumed = (list) => (list.length > 0 ? { assumptions: list } : {});
330
+ if (proof.kind === 'proved') {
331
+ // The property run above used generators inside the proved domain; a short one is topped up before the proof stands.
332
+ const passed = details;
333
+ const rerun = (runs) => runLawGuarded(built.outDir, law, { ...lawOptions, runs, seed: passed.seed }, types.plans);
334
+ let disagrees;
335
+ try {
336
+ disagrees = await crossCheck(details, types.plans.length, rerun);
337
+ }
338
+ catch (error) {
339
+ add(law, 'error', 'smt', { message: error.message });
340
+ return;
341
+ }
342
+ if (disagrees === 'timeout')
343
+ add(law, 'error', 'smt', {
344
+ message: `proved, but the cross-check run in JavaScript ran longer than ${limitMs / 1000}s`,
345
+ });
346
+ else if (disagrees !== undefined) {
347
+ if (!options.noRegressions && disagrees.encoded !== undefined)
348
+ saveExample(options.cwd, law.file, law.name, decodeExample(disagrees.encoded));
349
+ add(law, 'failed', 'smt', {
350
+ exercises: markFailing(exercisesFor(law), disagrees.stack, built.outDir),
351
+ runs: disagrees.numRuns,
352
+ seed: disagrees.seed,
353
+ counterexample: disagrees.counterexample,
354
+ message: disagreement(disagrees),
355
+ });
356
+ }
357
+ else
358
+ add(law, 'proved', 'smt', { runs: details.numRuns, seed: details.seed, ...assumed(proof.assumptions) });
359
+ }
229
360
  else if (proof.kind === 'bounded') {
230
361
  // `law proved` promises every input; a bounded proof is the most Z3 could show.
231
362
  const message = `holds within bounds: ${proof.limits.join('; ')}`;
@@ -236,8 +367,15 @@ export async function check(options, enforceLock) {
236
367
  message: `marked proved but only ${message}`,
237
368
  });
238
369
  else
239
- add(law, 'bounded', 'smt', { runs: details.numRuns, seed: details.seed, message });
370
+ add(law, 'bounded', 'smt', {
371
+ runs: details.numRuns,
372
+ seed: details.seed,
373
+ message,
374
+ ...assumed(proof.assumptions),
375
+ });
240
376
  }
377
+ else if (proof.kind === 'error')
378
+ add(law, 'error', 'smt', { message: proof.message });
241
379
  else if (proof.kind === 'refuted')
242
380
  add(law, 'failed', 'smt', { counterexample: proof.model, message: 'refuted by the prover' });
243
381
  else if (law.proved)
@@ -248,15 +386,38 @@ export async function check(options, enforceLock) {
248
386
  });
249
387
  else
250
388
  add(law, 'tested', 'property', { runs: details.numRuns, seed: details.seed, message: proof.reason });
251
- }
389
+ };
390
+ const finished = new Map();
391
+ let nextToFlush = 0;
392
+ const flush = () => {
393
+ for (let ready = finished.get(nextToFlush); ready !== undefined; ready = finished.get(nextToFlush)) {
394
+ for (const emit of ready)
395
+ emit();
396
+ finished.delete(nextToFlush);
397
+ nextToFlush += 1;
398
+ }
399
+ };
400
+ // Property laws and proofs share the cores; browser and end-to-end laws share one page and one server, so they queue.
401
+ const lanes = { cpu: new Semaphore(jobs()), page: new Semaphore(1) };
402
+ await Promise.all(laws.map(async (law, index) => {
403
+ const skipped = (options.only !== undefined && !options.only.includes(law.name)) || blocked.has(lawKey(law.file, law.name));
404
+ if (skipped) {
405
+ finished.set(index, []);
406
+ flush();
407
+ return;
408
+ }
409
+ const lane = verdictOf(law.file).kind !== 'node' ? lanes.page : lanes.cpu;
410
+ await lane.run(() => runOne(law, index));
411
+ }));
252
412
  if (enforceLock) {
253
- const coverage = analyzeCoverage({
413
+ const coverage = derived.coverage(() => analyzeCoverage({
254
414
  cwd: options.cwd,
255
415
  outDir: built.outDir,
256
416
  lawFiles: options.files,
257
417
  coverFiles: covered,
258
- program,
259
- });
418
+ program: program(),
419
+ moduleOf: sourceCwd === undefined ? undefined : (file) => resolve(sourceCwd, file),
420
+ }));
260
421
  for (const { file, name } of coverage.uncovered) {
261
422
  results.push({
262
423
  file,
@@ -277,7 +438,8 @@ export async function check(options, enforceLock) {
277
438
  line: 0,
278
439
  status: 'tampered',
279
440
  method: 'lock',
280
- message: 'exempted from coverage but not in the lock; a person must run `tslaws accept`',
441
+ message: `exempted from coverage but not in the lock; ${acceptor}`,
442
+ proposal: { reason: 'exempt', status: 'proved', method: 'lock', message: 'an exemption runs nothing' },
281
443
  });
282
444
  }
283
445
  }
@@ -286,5 +448,5 @@ export async function check(options, enforceLock) {
286
448
  const ok = built.ok &&
287
449
  !lockMissing &&
288
450
  results.every((r) => r.status === 'proved' || r.status === 'bounded' || r.status === 'tested');
289
- return { results, compileDiagnostics: built.diagnostics, compileOk: built.ok, lockMissing, ok };
451
+ return { results, compileDiagnostics: built.diagnostics, compileOk: built.ok, lockMissing, notices, ok };
290
452
  }
package/dist/cli.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export declare function watched(filename: string | null): boolean;
1
2
  /** What a command needs from its caller. `home` is for unit tests; the CLI never sets it. */
2
3
  export interface CommandContext {
3
4
  isTTY: boolean;
@@ -10,4 +11,21 @@ export interface CommandContext {
10
11
  export declare function acceptCommand(cwd: string, flags: Map<string, string | true>, files: string[], ctx: CommandContext): Promise<number>;
11
12
  /** `tslaws delegate <action> [--for D] [--root DIR]`; `argv` is everything after `delegate`. */
12
13
  export declare function runDelegateCommand(argv: string[], cwd: string, ctx: CommandContext): number;
14
+ /** 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. */
15
+ export interface ProposalContext extends CommandContext {
16
+ ask?: (question: string) => Promise<string>;
17
+ stdin?: () => Promise<string>;
18
+ checkFile?: (file: string) => Promise<Map<string, string>>;
19
+ }
20
+ /**
21
+ * `tslaws propose <file> [--from PATH]`: writes a proposal into `.tslaws/proposals/` from `--from PATH` or from stdin.
22
+ * Anyone may run it, agents included: it writes only that directory and never touches the lock or the tree.
23
+ */
24
+ export declare function proposeCommand(cwd: string, flags: Map<string, string | true>, files: string[], ctx: ProposalContext): Promise<number>;
25
+ /**
26
+ * `tslaws promote <proposal> [--to PATH]`: a person moves a proposal out of `.tslaws/proposals/` into the tree. Refused
27
+ * without a terminal, under CI, as an agent and with TSLAWS_AGENT set; a delegation does not cover it. Never writes the
28
+ * lock. In-tree `*.proposed.laws.ts` files promote, per law, into the file of the same kind.
29
+ */
30
+ export declare function promoteCommand(cwd: string, flags: Map<string, string | true>, files: string[], ctx: ProposalContext): Promise<number>;
13
31
  export declare function main(args: string[]): Promise<number>;