tslaws 0.10.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.
Files changed (124) hide show
  1. package/README.md +13 -2
  2. package/bin/tslaws.js +8 -2
  3. package/dist/badge.d.ts +64 -0
  4. package/dist/badge.js +121 -0
  5. package/dist/browser.d.ts +1 -1
  6. package/dist/browser.js +25 -5
  7. package/dist/bundled.js +2 -2
  8. package/dist/bundlerPlugins.d.ts +2 -0
  9. package/dist/bundlerPlugins.js +7 -0
  10. package/dist/certificates.d.ts +139 -0
  11. package/dist/certificates.js +433 -0
  12. package/dist/chc.d.ts +97 -0
  13. package/dist/chc.js +307 -0
  14. package/dist/check.d.ts +13 -1
  15. package/dist/check.js +218 -31
  16. package/dist/cli.d.ts +18 -0
  17. package/dist/cli.js +242 -34
  18. package/dist/compile.d.ts +15 -5
  19. package/dist/compile.js +203 -70
  20. package/dist/coverage.d.ts +38 -1
  21. package/dist/coverage.js +123 -19
  22. package/dist/e2eApi.js +3 -1
  23. package/dist/generators.js +12 -2
  24. package/dist/github.d.ts +49 -5
  25. package/dist/github.js +107 -24
  26. package/dist/githubCli.d.ts +28 -0
  27. package/dist/githubCli.js +1113 -212
  28. package/dist/hints.js +2 -1
  29. package/dist/init.js +42 -0
  30. package/dist/isolate.d.ts +33 -0
  31. package/dist/isolate.js +262 -0
  32. package/dist/isolatedCheck.d.ts +1 -0
  33. package/dist/isolatedCheck.js +16 -0
  34. package/dist/lawHost.d.ts +50 -0
  35. package/dist/lawHost.js +197 -0
  36. package/dist/lawRuntime.d.ts +45 -0
  37. package/dist/lawRuntime.js +321 -0
  38. package/dist/lock.d.ts +49 -9
  39. package/dist/lock.js +132 -21
  40. package/dist/mcp.js +28 -7
  41. package/dist/mutate.d.ts +4 -0
  42. package/dist/mutate.js +7 -1
  43. package/dist/plan.d.ts +1 -0
  44. package/dist/plan.js +4 -0
  45. package/dist/pluginHooks.d.ts +20 -0
  46. package/dist/pluginHooks.js +57 -0
  47. package/dist/pluginHost.d.ts +5 -0
  48. package/dist/pluginHost.js +43 -0
  49. package/dist/pluginWorker.d.ts +1 -0
  50. package/dist/pluginWorker.js +40 -0
  51. package/dist/plural.d.ts +2 -0
  52. package/dist/plural.js +4 -0
  53. package/dist/pool.d.ts +80 -7
  54. package/dist/pool.js +222 -11
  55. package/dist/projects.d.ts +43 -1
  56. package/dist/projects.js +283 -11
  57. package/dist/promote.d.ts +56 -2
  58. package/dist/promote.js +429 -13
  59. package/dist/property.js +5 -1
  60. package/dist/propertyWorker.js +9 -4
  61. package/dist/proposals.d.ts +52 -4
  62. package/dist/proposals.js +484 -21
  63. package/dist/reporters.js +5 -1
  64. package/dist/runtimeEnv.d.ts +13 -5
  65. package/dist/runtimeEnv.js +48 -10
  66. package/dist/sandbox.d.ts +98 -0
  67. package/dist/sandbox.js +673 -0
  68. package/dist/sandboxGuard.d.ts +56 -0
  69. package/dist/sandboxGuard.js +249 -0
  70. package/dist/seal.d.ts +9 -0
  71. package/dist/seal.js +426 -0
  72. package/dist/security/cli.d.ts +6 -0
  73. package/dist/security/cli.js +39 -0
  74. package/dist/security/cwe.d.ts +14 -0
  75. package/dist/security/cwe.js +40 -0
  76. package/dist/security/deps/cache.d.ts +28 -0
  77. package/dist/security/deps/cache.js +107 -0
  78. package/dist/security/deps/config.d.ts +16 -0
  79. package/dist/security/deps/config.js +43 -0
  80. package/dist/security/deps/imports.d.ts +4 -0
  81. package/dist/security/deps/imports.js +33 -0
  82. package/dist/security/deps/lockfiles.d.ts +23 -0
  83. package/dist/security/deps/lockfiles.js +153 -0
  84. package/dist/security/deps/osv.d.ts +66 -0
  85. package/dist/security/deps/osv.js +137 -0
  86. package/dist/security/deps/run.d.ts +54 -0
  87. package/dist/security/deps/run.js +135 -0
  88. package/dist/security/deps/severity.d.ts +26 -0
  89. package/dist/security/deps/severity.js +78 -0
  90. package/dist/security/generators.d.ts +9 -0
  91. package/dist/security/generators.js +36 -0
  92. package/dist/security/index.d.ts +27 -0
  93. package/dist/security/index.js +18 -0
  94. package/dist/security/integers.d.ts +31 -0
  95. package/dist/security/integers.js +105 -0
  96. package/dist/security/law.d.ts +54 -0
  97. package/dist/security/law.js +54 -0
  98. package/dist/security/pathTraversal.d.ts +29 -0
  99. package/dist/security/pathTraversal.js +146 -0
  100. package/dist/security/prototypePollution.d.ts +30 -0
  101. package/dist/security/prototypePollution.js +142 -0
  102. package/dist/security/redirect.d.ts +21 -0
  103. package/dist/security/redirect.js +154 -0
  104. package/dist/security/redos.d.ts +21 -0
  105. package/dist/security/redos.js +93 -0
  106. package/dist/security/validation.d.ts +25 -0
  107. package/dist/security/validation.js +89 -0
  108. package/dist/security/xss.d.ts +21 -0
  109. package/dist/security/xss.js +90 -0
  110. package/dist/settings.d.ts +20 -0
  111. package/dist/settings.js +32 -0
  112. package/dist/smt.d.ts +37 -1
  113. package/dist/smt.js +277 -111
  114. package/dist/smtWorker.d.ts +1 -0
  115. package/dist/smtWorker.js +26 -0
  116. package/dist/solvers.d.ts +9 -0
  117. package/dist/solvers.js +11 -5
  118. package/dist/symbolic.d.ts +54 -1
  119. package/dist/symbolic.js +239 -13
  120. package/dist/tsconfigResolve.d.ts +28 -0
  121. package/dist/tsconfigResolve.js +141 -0
  122. package/dist/types.d.ts +33 -0
  123. package/hooks/claude-hook.mjs +2 -0
  124. package/package.json +19 -7
package/dist/check.js CHANGED
@@ -1,15 +1,19 @@
1
1
  import { createRequire } from 'node:module';
2
- import { resolve } from 'node:path';
2
+ import { join, resolve } from 'node:path';
3
3
  import ts from 'typescript';
4
4
  import { build, readManifest } from "./compile.js";
5
+ import { withResolution } from "./lawRuntime.js";
5
6
  import { compilerOptions, declarationFiles, isDiscard, jsPath, runLawGuarded, warmWorkers, typesOf, } from "./property.js";
6
7
  import { analyzeCoverage, coverFiles, lawEnv, readConfig } from "./coverage.js";
8
+ import { parseGithubConfig } from "./github.js";
7
9
  import { derivedStore } from "./derived.js";
8
- import { jobs } from "./pool.js";
9
- import { compareLock, lawKey, readLock } from "./lock.js";
10
+ import { budget, configureJobs } from "./pool.js";
11
+ import { hostConfig, LawLoadError, Sandbox, useSandbox, warnE2e, warmSandbox } from "./sandbox.js";
12
+ import { bindingOf, certificateFailure, hashOf, noCertificate, recordOf, staleRecord, verifyRecord, writeRecords, readRecords, } from "./certificates.js";
13
+ import { compareLock, lawHash, lawKey, lockFormat, proofStatus, readLock, scopeOf } from "./lock.js";
10
14
  import { crossCheck, disagreement } from "./propertyRun.js";
11
15
  import { prepareRuntime } from "./runtimeEnv.js";
12
- import { proveLaw } from "./smt.js";
16
+ import { problemTexts, proveLaw } from "./smt.js";
13
17
  import { decodeExample, loadExamples, regressionMessage, saveExample } from "./regressions.js";
14
18
  import { closeBrowser, runBrowserLaw } from "./browser.js";
15
19
  import { ensureServer, runE2eLaw, stopServer } from "./e2e.js";
@@ -17,7 +21,7 @@ import { inProposals } from "./lawFiles.js";
17
21
  import { classifyLawFile } from "./lawKinds.js";
18
22
  import { normaliseProposal } from "./proposals.js";
19
23
  import { declarationOf, exercisesOf, markFailing, Sources } from "./exercises.js";
20
- /** Runs at most `limit` tasks at once. */
24
+ /** Runs at most `limit` tasks at once. The CPU limit is the process-wide budget (pool.ts); this holds the single page. */
21
25
  class Semaphore {
22
26
  free;
23
27
  queue = [];
@@ -46,7 +50,7 @@ export function exemptionsOf(options) {
46
50
  const covered = coverFiles(options.cwd, readConfig(options.cwd).cover ?? []);
47
51
  const compiled = [...new Set([...options.files, ...covered])];
48
52
  const built = build(options.compiler, compiled, options.cwd);
49
- const program = ts.createProgram(declarationFiles(built.outDir), compilerOptions);
53
+ const program = ts.createProgram(declarationFiles(built.outDir), withResolution(built.outDir, compilerOptions));
50
54
  return analyzeCoverage({
51
55
  cwd: options.cwd,
52
56
  outDir: built.outDir,
@@ -55,6 +59,80 @@ export function exemptionsOf(options) {
55
59
  program,
56
60
  }).exempt;
57
61
  }
62
+ /**
63
+ * The hash of each SMT-LIB problem the prover would send for each law now, rebuilt from the compiled code without
64
+ * running a solver. A certificate is for a law only while its problem hash is one of these.
65
+ */
66
+ export function problemHashesOf(options, laws) {
67
+ const covered = coverFiles(options.cwd, readConfig(options.cwd).cover ?? []);
68
+ const built = build(options.compiler, [...new Set([...options.files, ...covered])], options.cwd);
69
+ const program = built.program ?? ts.createProgram(declarationFiles(built.outDir), withResolution(built.outDir, compilerOptions));
70
+ const sourceCwd = built.program === undefined ? undefined : options.cwd;
71
+ const hashes = new Map();
72
+ for (const law of laws) {
73
+ if (law.problems.length > 0)
74
+ continue;
75
+ try {
76
+ const types = typesOf(program, built.outDir, law, sourceCwd);
77
+ const texts = problemTexts({
78
+ law,
79
+ shapes: types.shapes,
80
+ jsFile: jsPath(built.outDir, law.file),
81
+ bound: options.bound,
82
+ timeoutMs: options.proofTimeoutMs,
83
+ holds: () => true,
84
+ });
85
+ hashes.set(lawKey(law.file, law.name), new Set(texts.map(hashOf)));
86
+ }
87
+ catch {
88
+ // A law whose types cannot be read has no problem to match.
89
+ }
90
+ }
91
+ return hashes;
92
+ }
93
+ /**
94
+ * The certificates `tslaws accept` writes into the lock. The ones in the old lock stay only while their law and their
95
+ * problem are unchanged. The ones `tslaws check --certify` left in the sidecar file enter only after `verifyRecord`
96
+ * passes: the file is not trusted. Every record turned away is reported through `say`.
97
+ */
98
+ export async function certificatesToAccept(options, laws, held, say) {
99
+ const fresh = readRecords(options.cwd);
100
+ const accepted = {};
101
+ if (Object.keys(held ?? {}).length === 0 && Object.keys(fresh).length === 0)
102
+ return accepted;
103
+ const now = new Map(laws.map((law) => [lawKey(law.file, law.name), lawHash(law)]));
104
+ const problems = problemHashesOf(options, laws);
105
+ const drop = (key, why) => say(`certificate dropped for ${key}: ${why}
106
+ `);
107
+ let toolsMissing = false;
108
+ // The sidecar file is only a candidate: its records enter after `verifyRecord` passes.
109
+ for (const [key, record] of Object.entries(fresh)) {
110
+ const hash = now.get(key);
111
+ if (hash === undefined)
112
+ continue;
113
+ const why = await verifyRecord(options.cwd, key, record, hash, problems.get(key) ?? new Set());
114
+ if (why === undefined)
115
+ accepted[key] = record;
116
+ else {
117
+ drop(key, why);
118
+ if (why.includes('binary was not found'))
119
+ toolsMissing = true;
120
+ }
121
+ }
122
+ // A record the lock holds stays while its law and problem match, unless a verified fresh record replaced it, so a
123
+ // failed candidate never costs the lock a certificate that is still current.
124
+ for (const [key, record] of Object.entries(held ?? {})) {
125
+ if (accepted[key] !== undefined)
126
+ continue;
127
+ if (now.get(key) === record?.law && problems.get(key)?.has(bindingOf(record)))
128
+ accepted[key] = record;
129
+ else
130
+ drop(key, 'the law or its proof problem changed since it was certified');
131
+ }
132
+ if (toolsMissing)
133
+ say('no new certificates were recorded: cvc5 and Carcara are needed to check them again when accepting\n');
134
+ return accepted;
135
+ }
58
136
  export async function check(options, enforceLock) {
59
137
  // A proposal placed in .tslaws/proposals by hand may write its imports from the project root; store them where they resolve.
60
138
  for (const file of options.files)
@@ -66,11 +144,19 @@ export async function check(options, enforceLock) {
66
144
  const notices = [];
67
145
  // The level of a laws file comes from its name (the default) or its imports (`levels: "imports"`); looked at once per file.
68
146
  const config = readConfig(options.cwd);
147
+ configureJobs({ config: config.jobs });
69
148
  const levelsMode = config.levels ?? 'names';
70
- // Who records a law in the lock: a person locally, or the tslaws workflow on merge when "github" is configured.
71
- const acceptor = readConfig(options.cwd).github !== undefined
72
- ? 'it is accepted by the tslaws workflow when the pull request merges'
73
- : 'a person must run `tslaws accept`';
149
+ const certifyMode = options.certify ?? config.certify ?? false;
150
+ // The certificate each law proved this run got, or undefined when its proof was not certified.
151
+ const records = new Map();
152
+ // Who records a law in the lock: a person locally, or the tslaws workflow on merge when "github" is configured. A
153
+ // project that leaves "github.local" on lets a person accept by hand as well.
154
+ const github = readConfig(options.cwd).github;
155
+ const acceptor = github === undefined
156
+ ? 'a person must run `tslaws accept`'
157
+ : parseGithubConfig(github).local
158
+ ? 'a person can run `tslaws accept`, or the tslaws workflow accepts it when the pull request merges'
159
+ : 'it is accepted by the tslaws workflow when the pull request merges';
74
160
  const verdicts = new Map();
75
161
  const verdictOf = (file) => {
76
162
  let verdict = verdicts.get(file);
@@ -82,6 +168,9 @@ export async function check(options, enforceLock) {
82
168
  }
83
169
  return verdict;
84
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);
85
174
  const sources = new Sources(options.cwd);
86
175
  // What a law reaches is syntactic and cheap; a project that cannot be read this way just has no locations.
87
176
  const exercisesFor = (law) => {
@@ -124,6 +213,7 @@ export async function check(options, enforceLock) {
124
213
  method,
125
214
  ...(extra.counterexample === undefined ? {} : { counterexample: extra.counterexample }),
126
215
  ...(extra.message === undefined ? {} : { message: extra.message }),
216
+ ...(extra.certificate === undefined ? {} : { certificate: extra.certificate }),
127
217
  },
128
218
  ...(exercises.length > 0 ? { exercises } : {}),
129
219
  };
@@ -138,14 +228,21 @@ export async function check(options, enforceLock) {
138
228
  lock = readLock(options.lockFile);
139
229
  lockMissing = lock === undefined;
140
230
  const byKey = new Map(laws.map((l) => [lawKey(l.file, l.name), l]));
141
- // With levels from imports (or a lock that recorded levels), the resolved level of each laws file is part of the lock.
231
+ // With levels from imports, the resolved level of each laws file is part of the lock. A lock that recorded levels
232
+ // while the project no longer resolves any (levels went back to names) is tampered until accepted again.
142
233
  const levels = levelsMode === 'imports' || lock?.levels !== undefined
143
234
  ? {
144
235
  locked: lock?.levels,
145
- now: Object.fromEntries([...new Set(laws.map((l) => l.file.replaceAll('\\', '/')))].map((f) => [f, verdictOf(f).kind])),
236
+ now: levelsMode === 'imports'
237
+ ? Object.fromEntries([...new Set(laws.map((l) => l.file.replaceAll('\\', '/')))].map((f) => [f, verdictOf(f).kind]))
238
+ : undefined,
146
239
  }
147
240
  : undefined;
148
- for (const violation of compareLock(lock?.laws, laws, levels)) {
241
+ // A lock from before the hashes covered helpers, imports and run settings: every law differs from it by the format.
242
+ const outdated = (lock?.version ?? lockFormat) < lockFormat;
243
+ if (outdated)
244
+ notices.push(`lock format upgraded: the lock was written in format ${lock?.version ?? 0} and tslaws now hashes helpers, imported code and run settings too (format ${lockFormat}); run \`tslaws accept\` to record the laws again`);
245
+ for (const violation of compareLock(lock?.laws, laws, levels, options.partial === true ? scopeOf(options.files) : undefined)) {
149
246
  const law = byKey.get(violation.key);
150
247
  if (law === undefined) {
151
248
  const [file, name] = violation.key.split('::');
@@ -166,24 +263,42 @@ export async function check(options, enforceLock) {
166
263
  ? `law is not in the lock; ${acceptor}`
167
264
  : violation.reason === 'level'
168
265
  ? `the level this laws file runs at (node, browser or e2e) changed since the lock was accepted; ${acceptor}`
169
- : 'law changed since the lock was accepted',
266
+ : outdated
267
+ ? `lock format upgraded: this lock hashes only the law's own text; ${acceptor} to record it in the new format`
268
+ : 'law changed since the lock was accepted',
170
269
  });
171
270
  }
172
271
  }
173
272
  }
174
273
  for (const law of laws) {
175
- 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)))
176
275
  add(law, 'error', 'manifest', { message: law.problems.join('; ') });
177
276
  }
178
277
  const covered = coverFiles(options.cwd, readConfig(options.cwd).cover ?? []);
179
278
  const compiled = [...new Set([...options.files, ...covered])];
180
- warmWorkers(laws.filter((law) => law.problems.length === 0 && verdictOf(law.file).kind === 'node').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;
281
+ // The sandbox is on unless the person turned it off with `sandbox: false` (`--no-sandbox`), and a Node that cannot
282
+ // enforce it is an error here, never a quiet fallback. End-to-end laws are no exception: see `allowE2e`.
283
+ const sandboxed = runsHere > 0 && useSandbox(options);
284
+ if (sandboxed)
285
+ warmSandbox(options.cwd, nodeLaws);
286
+ else
287
+ warmWorkers(nodeLaws);
181
288
  const built = build(options.compiler, compiled, options.cwd);
289
+ // What the sandbox may load: the build's output, what the seals of the laws cover (the lock digests the same files), and
290
+ // the packages the manifests declare. Reviewed once, after the build.
291
+ const sandbox = sandboxed
292
+ ? new Sandbox(options.cwd, hostConfig(options.cwd, compiled, built.outDir, laws.filter((law) => law.problems.length === 0)))
293
+ : undefined;
182
294
  // What the type checker works out is kept with the build it came from, so an unchanged project skips the checker.
183
295
  const derived = derivedStore(options.cwd, built.key);
184
296
  let programOf;
185
- const program = () => (programOf ??= built.program ?? ts.createProgram(declarationFiles(built.outDir), compilerOptions));
297
+ const program = () => (programOf ??=
298
+ built.program ?? ts.createProgram(declarationFiles(built.outDir), withResolution(built.outDir, compilerOptions)));
186
299
  const sourceCwd = built.program === undefined ? undefined : options.cwd;
300
+ // Compiled laws are CommonJS (see `build` in compile.ts): the one place a law is loaded, so `require` is unavoidable here
301
+ // (`import()` would cache the module for good, and a recompiled law must load again).
187
302
  const require = createRequire(import.meta.url);
188
303
  // Laws that run here (end to end) and the code they load read `import.meta.env` and extensionless imports as bundled.
189
304
  prepareRuntime(lawEnv(options.cwd, 'node'));
@@ -200,7 +315,7 @@ export async function check(options, enforceLock) {
200
315
  }
201
316
  };
202
317
  const runBody = async (law, add) => {
203
- if (options.only !== undefined && !options.only.includes(law.name))
318
+ if (!selected(law))
204
319
  return;
205
320
  if (blocked.has(lawKey(law.file, law.name)))
206
321
  return;
@@ -220,10 +335,25 @@ export async function check(options, enforceLock) {
220
335
  }
221
336
  const browser = verdict.kind === 'browser';
222
337
  const e2e = verdict.kind === 'e2e';
338
+ // An end-to-end law needs processes (a browser, the app's server) that the sandbox refuses, so it would run in this
339
+ // process with every permission it has. A law says for itself that it is end to end, so that is never taken as leave
340
+ // to do so: the person must ask for it.
341
+ if (e2e && sandboxed && options.allowE2e !== true) {
342
+ add(law, 'error', 'e2e', {
343
+ message: 'end-to-end laws run outside the sandbox, with full access to this machine; run them with --allow-e2e (allowE2e) ' +
344
+ 'once you have reviewed them, or with --no-sandbox to turn the sandbox off',
345
+ });
346
+ return;
347
+ }
348
+ if (e2e && sandboxed)
349
+ warnE2e();
223
350
  const method = browser ? 'browser' : e2e ? 'e2e' : 'property';
224
351
  let fn;
225
- // A browser law touches the DOM when it loads, so only the browser loads it.
226
- if (!browser) {
352
+ // A browser law touches the DOM when it loads, so only the browser loads it. A node law loads in its sandbox, not here
353
+ // (an end-to-end law runs in this process once `allowE2e` lets it: it drives a browser, which needs processes the
354
+ // sandbox refuses).
355
+ let isAsync = false;
356
+ if (!browser && (!sandboxed || e2e)) {
227
357
  try {
228
358
  fn = require(jsPath(built.outDir, law.file))[law.symbol ?? law.name];
229
359
  }
@@ -235,7 +365,20 @@ export async function check(options, enforceLock) {
235
365
  add(law, 'error', 'load', { message: 'compiled module does not export the law' });
236
366
  return;
237
367
  }
368
+ isAsync = fn.constructor.name === 'AsyncFunction';
238
369
  }
370
+ // One property run of the law: in the sandbox, or in a worker of this process when it is off or the law is end to end.
371
+ const execute = async (runOptions) => {
372
+ if (!sandboxed || e2e)
373
+ return runLawGuarded(built.outDir, law, runOptions, types.plans);
374
+ if (sandbox === undefined)
375
+ throw new Error('the law sandbox is on but was not set up');
376
+ const ran = await sandbox.run(built.outDir, law, runOptions, types.plans);
377
+ if (ran === 'timeout')
378
+ return ran;
379
+ isAsync = ran.async;
380
+ return ran.outcome;
381
+ };
239
382
  let details;
240
383
  // Counterexamples found before are tried first.
241
384
  let lawOptions = options.noRegressions
@@ -261,10 +404,13 @@ export async function check(options, enforceLock) {
261
404
  jsFile: jsPath(built.outDir, law.file),
262
405
  generators: types.generators,
263
406
  }, lawOptions)
264
- : await runLawGuarded(built.outDir, law, lawOptions, types.plans);
407
+ : await execute(lawOptions);
265
408
  }
266
409
  catch (error) {
267
- add(law, 'error', method, { message: error.message });
410
+ if (error instanceof LawLoadError)
411
+ add(law, 'error', 'load', { message: `cannot load compiled law: ${error.message}` });
412
+ else
413
+ add(law, 'error', method, { message: error.message });
268
414
  return;
269
415
  }
270
416
  if (details === 'timeout') {
@@ -299,7 +445,7 @@ export async function check(options, enforceLock) {
299
445
  return;
300
446
  }
301
447
  // Browser and async laws are tested, never proved: the prover cannot model a DOM or an await.
302
- const unprovable = browser || e2e ? 'runs in a browser' : fn.constructor.name === 'AsyncFunction' ? 'is async' : undefined;
448
+ const unprovable = browser || e2e ? 'runs in a browser' : isAsync ? 'is async' : undefined;
303
449
  if (options.noProve || unprovable !== undefined) {
304
450
  add(law, law.proved ? 'open' : 'tested', method, {
305
451
  runs: details.numRuns,
@@ -313,6 +459,10 @@ export async function check(options, enforceLock) {
313
459
  return;
314
460
  }
315
461
  const holds = (inputs) => {
462
+ if (sandboxed && sandbox === undefined)
463
+ return false;
464
+ if (sandbox !== undefined)
465
+ return sandbox.holds(built.outDir, law, inputs, limitMs);
316
466
  try {
317
467
  return fn(...inputs) !== false;
318
468
  }
@@ -328,12 +478,33 @@ export async function check(options, enforceLock) {
328
478
  timeoutMs: options.proofTimeoutMs,
329
479
  holds,
330
480
  solvers: config.solvers,
481
+ certify: certifyMode === false
482
+ ? undefined
483
+ : { mode: certifyMode, dir: join(options.cwd, '.tslaws', 'certificates'), root: options.cwd },
331
484
  });
485
+ const certified = (certificate) => certificate === undefined ? {} : { certificate };
332
486
  const assumed = (list) => (list.length > 0 ? { assumptions: list } : {});
487
+ if (proof.kind === 'proved' || proof.kind === 'bounded') {
488
+ // With certifying on, every proof has a certificate; one that is missing counts as uncertified, so `require`
489
+ // cannot pass a proof nobody checked.
490
+ if (certifyMode !== false)
491
+ proof.certificate ??= noCertificate;
492
+ if (proof.certificate !== undefined) {
493
+ records.set(lawKey(law.file, law.name), recordOf(lawHash(law), proof.certificate));
494
+ const required = certificateFailure(certifyMode, proof.certificate);
495
+ if (required !== undefined) {
496
+ add(law, 'error', 'smt', { certificate: proof.certificate, message: required });
497
+ return;
498
+ }
499
+ // A lock certificate for a different problem than the one proved now no longer vouches for the law.
500
+ if (lock !== undefined && staleRecord(lock.certificates?.[lawKey(law.file, law.name)], proof.certificate))
501
+ notices.push(`${lawKey(law.file, law.name)}: the certificate in the lock is for a different proof problem; run \`tslaws accept --certify\` to record the new one`);
502
+ }
503
+ }
333
504
  if (proof.kind === 'proved') {
334
505
  // The property run above used generators inside the proved domain; a short one is topped up before the proof stands.
335
506
  const passed = details;
336
- const rerun = (runs) => runLawGuarded(built.outDir, law, { ...lawOptions, runs, seed: passed.seed }, types.plans);
507
+ const rerun = (runs) => execute({ ...lawOptions, runs, seed: passed.seed });
337
508
  let disagrees;
338
509
  try {
339
510
  disagrees = await crossCheck(details, types.plans.length, rerun);
@@ -358,7 +529,12 @@ export async function check(options, enforceLock) {
358
529
  });
359
530
  }
360
531
  else
361
- add(law, 'proved', 'smt', { runs: details.numRuns, seed: details.seed, ...assumed(proof.assumptions) });
532
+ add(law, 'proved', 'smt', {
533
+ runs: details.numRuns,
534
+ seed: details.seed,
535
+ ...assumed(proof.assumptions),
536
+ ...certified(proof.certificate),
537
+ });
362
538
  }
363
539
  else if (proof.kind === 'bounded') {
364
540
  // `law proved` promises every input; a bounded proof is the most Z3 could show.
@@ -375,6 +551,7 @@ export async function check(options, enforceLock) {
375
551
  seed: details.seed,
376
552
  message,
377
553
  ...assumed(proof.assumptions),
554
+ ...certified(proof.certificate),
378
555
  });
379
556
  }
380
557
  else if (proof.kind === 'error')
@@ -400,19 +577,20 @@ export async function check(options, enforceLock) {
400
577
  nextToFlush += 1;
401
578
  }
402
579
  };
403
- // Property laws and proofs share the cores; browser and end-to-end laws share one page and one server, so they queue.
404
- const lanes = { cpu: new Semaphore(jobs()), page: new Semaphore(1) };
580
+ // Every law takes a slot of the process-wide CPU budget, and what it starts (a proof, a solver, a law process) runs on
581
+ // that slot. Browser and end-to-end laws also share one page and one server, so they queue for it first.
582
+ const page = new Semaphore(1);
405
583
  await Promise.all(laws.map(async (law, index) => {
406
- 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));
407
585
  if (skipped) {
408
586
  finished.set(index, []);
409
587
  flush();
410
588
  return;
411
589
  }
412
- const lane = verdictOf(law.file).kind !== 'node' ? lanes.page : lanes.cpu;
413
- await lane.run(() => runOne(law, index));
590
+ const inSlot = () => budget.run(() => runOne(law, index));
591
+ await (verdictOf(law.file).kind !== 'node' ? page.run(inSlot) : inSlot());
414
592
  }));
415
- if (enforceLock) {
593
+ if (enforceLock && options.onlyKeys === undefined) {
416
594
  const coverage = derived.coverage(() => analyzeCoverage({
417
595
  cwd: options.cwd,
418
596
  outDir: built.outDir,
@@ -448,6 +626,15 @@ export async function check(options, enforceLock) {
448
626
  }
449
627
  await closeBrowser();
450
628
  await stopServer();
629
+ // Records for `tslaws accept` to consider; a law that did not end proved or bounded keeps no certificate.
630
+ if (certifyMode !== false && enforceLock && records.size > 0) {
631
+ // A law the lock does not record yet is reported `tampered`; its proof counts through the proposal it carries.
632
+ const held = new Set(results.filter((r) => proofStatus(r) !== undefined).map((r) => lawKey(r.file, r.name)));
633
+ for (const key of records.keys())
634
+ if (!held.has(key))
635
+ records.set(key, undefined);
636
+ writeRecords(options.cwd, records);
637
+ }
451
638
  const ok = built.ok &&
452
639
  !lockMissing &&
453
640
  results.every((r) => r.status === 'proved' || r.status === 'bounded' || r.status === 'tested');
package/dist/cli.d.ts CHANGED
@@ -1,3 +1,15 @@
1
+ import type { CheckReport } from './check.ts';
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
+ }
1
13
  export declare function watched(filename: string | null): boolean;
2
14
  /** What a command needs from its caller. `home` is for unit tests; the CLI never sets it. */
3
15
  export interface CommandContext {
@@ -13,6 +25,11 @@ export interface CommandContext {
13
25
  export declare function acceptCommand(cwd: string, flags: Map<string, string | true>, files: string[], ctx: CommandContext): Promise<number>;
14
26
  /** `tslaws delegate <action> [--for D] [--root DIR]`; `argv` is everything after `delegate`. */
15
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>;
16
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. */
17
34
  export interface ProposalContext extends CommandContext {
18
35
  ask?: (question: string) => Promise<string>;
@@ -31,3 +48,4 @@ export declare function proposeCommand(cwd: string, flags: Map<string, string |
31
48
  */
32
49
  export declare function promoteCommand(cwd: string, flags: Map<string, string | true>, files: string[], ctx: ProposalContext): Promise<number>;
33
50
  export declare function main(args: string[]): Promise<number>;
51
+ export {};