tslaws 0.9.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/README.md +8 -2
  2. package/bin/tslaws.js +8 -2
  3. package/dist/browser.d.ts +1 -1
  4. package/dist/browser.js +36 -7
  5. package/dist/bundled.js +2 -2
  6. package/dist/bundlerPlugins.d.ts +2 -0
  7. package/dist/bundlerPlugins.js +7 -0
  8. package/dist/certificates.d.ts +139 -0
  9. package/dist/certificates.js +433 -0
  10. package/dist/chc.d.ts +85 -0
  11. package/dist/chc.js +298 -0
  12. package/dist/check.d.ts +13 -1
  13. package/dist/check.js +215 -28
  14. package/dist/cli.d.ts +4 -0
  15. package/dist/cli.js +324 -41
  16. package/dist/compile.d.ts +17 -1
  17. package/dist/compile.js +244 -25
  18. package/dist/coverage.d.ts +55 -3
  19. package/dist/coverage.js +231 -12
  20. package/dist/e2eApi.js +3 -1
  21. package/dist/generators.js +12 -2
  22. package/dist/github.d.ts +49 -5
  23. package/dist/github.js +107 -24
  24. package/dist/githubCli.d.ts +28 -0
  25. package/dist/githubCli.js +1039 -211
  26. package/dist/hints.js +2 -1
  27. package/dist/init.js +42 -0
  28. package/dist/isolate.d.ts +28 -0
  29. package/dist/isolate.js +262 -0
  30. package/dist/isolatedCheck.d.ts +1 -0
  31. package/dist/isolatedCheck.js +16 -0
  32. package/dist/lawHost.d.ts +50 -0
  33. package/dist/lawHost.js +199 -0
  34. package/dist/lawRuntime.d.ts +39 -0
  35. package/dist/lawRuntime.js +242 -0
  36. package/dist/lock.d.ts +49 -9
  37. package/dist/lock.js +132 -21
  38. package/dist/mcp.js +28 -7
  39. package/dist/mutate.d.ts +4 -0
  40. package/dist/mutate.js +7 -1
  41. package/dist/plan.d.ts +1 -0
  42. package/dist/plan.js +4 -0
  43. package/dist/pluginHooks.d.ts +16 -0
  44. package/dist/pluginHooks.js +48 -0
  45. package/dist/pluginHost.d.ts +5 -0
  46. package/dist/pluginHost.js +43 -0
  47. package/dist/pluginWorker.d.ts +1 -0
  48. package/dist/pluginWorker.js +40 -0
  49. package/dist/plural.d.ts +2 -0
  50. package/dist/plural.js +4 -0
  51. package/dist/pool.d.ts +80 -7
  52. package/dist/pool.js +222 -11
  53. package/dist/projects.d.ts +70 -0
  54. package/dist/projects.js +457 -0
  55. package/dist/promote.d.ts +56 -2
  56. package/dist/promote.js +429 -13
  57. package/dist/property.js +13 -2
  58. package/dist/propertyWorker.js +11 -1
  59. package/dist/proposals.d.ts +52 -4
  60. package/dist/proposals.js +484 -21
  61. package/dist/reporters.js +5 -1
  62. package/dist/runtimeEnv.d.ts +32 -0
  63. package/dist/runtimeEnv.js +146 -0
  64. package/dist/sandbox.d.ts +98 -0
  65. package/dist/sandbox.js +673 -0
  66. package/dist/sandboxGuard.d.ts +56 -0
  67. package/dist/sandboxGuard.js +249 -0
  68. package/dist/seal.d.ts +9 -0
  69. package/dist/seal.js +426 -0
  70. package/dist/security/cli.d.ts +6 -0
  71. package/dist/security/cli.js +39 -0
  72. package/dist/security/cwe.d.ts +14 -0
  73. package/dist/security/cwe.js +40 -0
  74. package/dist/security/deps/cache.d.ts +28 -0
  75. package/dist/security/deps/cache.js +107 -0
  76. package/dist/security/deps/config.d.ts +16 -0
  77. package/dist/security/deps/config.js +43 -0
  78. package/dist/security/deps/imports.d.ts +4 -0
  79. package/dist/security/deps/imports.js +33 -0
  80. package/dist/security/deps/lockfiles.d.ts +23 -0
  81. package/dist/security/deps/lockfiles.js +153 -0
  82. package/dist/security/deps/osv.d.ts +66 -0
  83. package/dist/security/deps/osv.js +137 -0
  84. package/dist/security/deps/run.d.ts +54 -0
  85. package/dist/security/deps/run.js +135 -0
  86. package/dist/security/deps/severity.d.ts +26 -0
  87. package/dist/security/deps/severity.js +78 -0
  88. package/dist/security/generators.d.ts +9 -0
  89. package/dist/security/generators.js +36 -0
  90. package/dist/security/index.d.ts +27 -0
  91. package/dist/security/index.js +18 -0
  92. package/dist/security/integers.d.ts +31 -0
  93. package/dist/security/integers.js +105 -0
  94. package/dist/security/law.d.ts +54 -0
  95. package/dist/security/law.js +54 -0
  96. package/dist/security/pathTraversal.d.ts +29 -0
  97. package/dist/security/pathTraversal.js +146 -0
  98. package/dist/security/prototypePollution.d.ts +30 -0
  99. package/dist/security/prototypePollution.js +142 -0
  100. package/dist/security/redirect.d.ts +21 -0
  101. package/dist/security/redirect.js +154 -0
  102. package/dist/security/redos.d.ts +21 -0
  103. package/dist/security/redos.js +93 -0
  104. package/dist/security/validation.d.ts +25 -0
  105. package/dist/security/validation.js +89 -0
  106. package/dist/security/xss.d.ts +21 -0
  107. package/dist/security/xss.js +90 -0
  108. package/dist/settings.d.ts +20 -0
  109. package/dist/settings.js +32 -0
  110. package/dist/smt.d.ts +29 -1
  111. package/dist/smt.js +239 -107
  112. package/dist/smtWorker.d.ts +1 -0
  113. package/dist/smtWorker.js +26 -0
  114. package/dist/solvers.d.ts +9 -0
  115. package/dist/solvers.js +11 -5
  116. package/dist/symbolic.d.ts +54 -1
  117. package/dist/symbolic.js +239 -13
  118. package/dist/tsconfigResolve.d.ts +28 -0
  119. package/dist/tsconfigResolve.js +141 -0
  120. package/dist/types.d.ts +28 -0
  121. package/env.d.ts +17 -0
  122. package/hooks/claude-hook.mjs +2 -0
  123. package/package.json +22 -6
package/dist/check.js CHANGED
@@ -1,14 +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
- import { analyzeCoverage, coverFiles, readConfig } from "./coverage.js";
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
- import { proveLaw } from "./smt.js";
15
+ import { prepareRuntime } from "./runtimeEnv.js";
16
+ import { problemTexts, proveLaw } from "./smt.js";
12
17
  import { decodeExample, loadExamples, regressionMessage, saveExample } from "./regressions.js";
13
18
  import { closeBrowser, runBrowserLaw } from "./browser.js";
14
19
  import { ensureServer, runE2eLaw, stopServer } from "./e2e.js";
@@ -16,7 +21,7 @@ import { inProposals } from "./lawFiles.js";
16
21
  import { classifyLawFile } from "./lawKinds.js";
17
22
  import { normaliseProposal } from "./proposals.js";
18
23
  import { declarationOf, exercisesOf, markFailing, Sources } from "./exercises.js";
19
- /** 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. */
20
25
  class Semaphore {
21
26
  free;
22
27
  queue = [];
@@ -45,7 +50,7 @@ export function exemptionsOf(options) {
45
50
  const covered = coverFiles(options.cwd, readConfig(options.cwd).cover ?? []);
46
51
  const compiled = [...new Set([...options.files, ...covered])];
47
52
  const built = build(options.compiler, compiled, options.cwd);
48
- const program = ts.createProgram(declarationFiles(built.outDir), compilerOptions);
53
+ const program = ts.createProgram(declarationFiles(built.outDir), withResolution(built.outDir, compilerOptions));
49
54
  return analyzeCoverage({
50
55
  cwd: options.cwd,
51
56
  outDir: built.outDir,
@@ -54,6 +59,80 @@ export function exemptionsOf(options) {
54
59
  program,
55
60
  }).exempt;
56
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
+ }
57
136
  export async function check(options, enforceLock) {
58
137
  // A proposal placed in .tslaws/proposals by hand may write its imports from the project root; store them where they resolve.
59
138
  for (const file of options.files)
@@ -65,11 +144,19 @@ export async function check(options, enforceLock) {
65
144
  const notices = [];
66
145
  // The level of a laws file comes from its name (the default) or its imports (`levels: "imports"`); looked at once per file.
67
146
  const config = readConfig(options.cwd);
147
+ configureJobs({ config: config.jobs });
68
148
  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`';
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';
73
160
  const verdicts = new Map();
74
161
  const verdictOf = (file) => {
75
162
  let verdict = verdicts.get(file);
@@ -123,6 +210,7 @@ export async function check(options, enforceLock) {
123
210
  method,
124
211
  ...(extra.counterexample === undefined ? {} : { counterexample: extra.counterexample }),
125
212
  ...(extra.message === undefined ? {} : { message: extra.message }),
213
+ ...(extra.certificate === undefined ? {} : { certificate: extra.certificate }),
126
214
  },
127
215
  ...(exercises.length > 0 ? { exercises } : {}),
128
216
  };
@@ -137,14 +225,21 @@ export async function check(options, enforceLock) {
137
225
  lock = readLock(options.lockFile);
138
226
  lockMissing = lock === undefined;
139
227
  const byKey = new Map(laws.map((l) => [lawKey(l.file, l.name), l]));
140
- // With levels from imports (or a lock that recorded levels), the resolved level of each laws file is part of the lock.
228
+ // With levels from imports, the resolved level of each laws file is part of the lock. A lock that recorded levels
229
+ // while the project no longer resolves any (levels went back to names) is tampered until accepted again.
141
230
  const levels = levelsMode === 'imports' || lock?.levels !== undefined
142
231
  ? {
143
232
  locked: lock?.levels,
144
- now: Object.fromEntries([...new Set(laws.map((l) => l.file.replaceAll('\\', '/')))].map((f) => [f, verdictOf(f).kind])),
233
+ now: levelsMode === 'imports'
234
+ ? Object.fromEntries([...new Set(laws.map((l) => l.file.replaceAll('\\', '/')))].map((f) => [f, verdictOf(f).kind]))
235
+ : undefined,
145
236
  }
146
237
  : undefined;
147
- for (const violation of compareLock(lock?.laws, laws, levels)) {
238
+ // A lock from before the hashes covered helpers, imports and run settings: every law differs from it by the format.
239
+ const outdated = (lock?.version ?? lockFormat) < lockFormat;
240
+ if (outdated)
241
+ 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`);
242
+ for (const violation of compareLock(lock?.laws, laws, levels, options.partial === true ? scopeOf(options.files) : undefined)) {
148
243
  const law = byKey.get(violation.key);
149
244
  if (law === undefined) {
150
245
  const [file, name] = violation.key.split('::');
@@ -165,7 +260,9 @@ export async function check(options, enforceLock) {
165
260
  ? `law is not in the lock; ${acceptor}`
166
261
  : violation.reason === 'level'
167
262
  ? `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',
263
+ : outdated
264
+ ? `lock format upgraded: this lock hashes only the law's own text; ${acceptor} to record it in the new format`
265
+ : 'law changed since the lock was accepted',
169
266
  });
170
267
  }
171
268
  }
@@ -176,14 +273,32 @@ export async function check(options, enforceLock) {
176
273
  }
177
274
  const covered = coverFiles(options.cwd, readConfig(options.cwd).cover ?? []);
178
275
  const compiled = [...new Set([...options.files, ...covered])];
179
- warmWorkers(laws.filter((law) => law.problems.length === 0 && verdictOf(law.file).kind === 'node').length);
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;
278
+ // The sandbox is on unless the person turned it off with `sandbox: false` (`--no-sandbox`), and a Node that cannot
279
+ // enforce it is an error here, never a quiet fallback. End-to-end laws are no exception: see `allowE2e`.
280
+ const sandboxed = runsHere > 0 && useSandbox(options);
281
+ if (sandboxed)
282
+ warmSandbox(options.cwd, nodeLaws);
283
+ else
284
+ warmWorkers(nodeLaws);
180
285
  const built = build(options.compiler, compiled, options.cwd);
286
+ // What the sandbox may load: the build's output, what the seals of the laws cover (the lock digests the same files), and
287
+ // the packages the manifests declare. Reviewed once, after the build.
288
+ const sandbox = sandboxed
289
+ ? new Sandbox(options.cwd, hostConfig(options.cwd, compiled, built.outDir, laws.filter((law) => law.problems.length === 0)))
290
+ : undefined;
181
291
  // What the type checker works out is kept with the build it came from, so an unchanged project skips the checker.
182
292
  const derived = derivedStore(options.cwd, built.key);
183
293
  let programOf;
184
- const program = () => (programOf ??= built.program ?? ts.createProgram(declarationFiles(built.outDir), compilerOptions));
294
+ const program = () => (programOf ??=
295
+ built.program ?? ts.createProgram(declarationFiles(built.outDir), withResolution(built.outDir, compilerOptions)));
185
296
  const sourceCwd = built.program === undefined ? undefined : options.cwd;
297
+ // Compiled laws are CommonJS (see `build` in compile.ts): the one place a law is loaded, so `require` is unavoidable here
298
+ // (`import()` would cache the module for good, and a recompiled law must load again).
186
299
  const require = createRequire(import.meta.url);
300
+ // Laws that run here (end to end) and the code they load read `import.meta.env` and extensionless imports as bundled.
301
+ prepareRuntime(lawEnv(options.cwd, 'node'));
187
302
  const runOne = async (law, index) => {
188
303
  const buffered = [];
189
304
  try {
@@ -217,10 +332,25 @@ export async function check(options, enforceLock) {
217
332
  }
218
333
  const browser = verdict.kind === 'browser';
219
334
  const e2e = verdict.kind === 'e2e';
335
+ // An end-to-end law needs processes (a browser, the app's server) that the sandbox refuses, so it would run in this
336
+ // process with every permission it has. A law says for itself that it is end to end, so that is never taken as leave
337
+ // to do so: the person must ask for it.
338
+ if (e2e && sandboxed && options.allowE2e !== true) {
339
+ add(law, 'error', 'e2e', {
340
+ message: 'end-to-end laws run outside the sandbox, with full access to this machine; run them with --allow-e2e (allowE2e) ' +
341
+ 'once you have reviewed them, or with --no-sandbox to turn the sandbox off',
342
+ });
343
+ return;
344
+ }
345
+ if (e2e && sandboxed)
346
+ warnE2e();
220
347
  const method = browser ? 'browser' : e2e ? 'e2e' : 'property';
221
348
  let fn;
222
- // A browser law touches the DOM when it loads, so only the browser loads it.
223
- if (!browser) {
349
+ // A browser law touches the DOM when it loads, so only the browser loads it. A node law loads in its sandbox, not here
350
+ // (an end-to-end law runs in this process once `allowE2e` lets it: it drives a browser, which needs processes the
351
+ // sandbox refuses).
352
+ let isAsync = false;
353
+ if (!browser && (!sandboxed || e2e)) {
224
354
  try {
225
355
  fn = require(jsPath(built.outDir, law.file))[law.symbol ?? law.name];
226
356
  }
@@ -232,7 +362,20 @@ export async function check(options, enforceLock) {
232
362
  add(law, 'error', 'load', { message: 'compiled module does not export the law' });
233
363
  return;
234
364
  }
365
+ isAsync = fn.constructor.name === 'AsyncFunction';
235
366
  }
367
+ // 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.
368
+ const execute = async (runOptions) => {
369
+ if (!sandboxed || e2e)
370
+ return runLawGuarded(built.outDir, law, runOptions, types.plans);
371
+ if (sandbox === undefined)
372
+ throw new Error('the law sandbox is on but was not set up');
373
+ const ran = await sandbox.run(built.outDir, law, runOptions, types.plans);
374
+ if (ran === 'timeout')
375
+ return ran;
376
+ isAsync = ran.async;
377
+ return ran.outcome;
378
+ };
236
379
  let details;
237
380
  // Counterexamples found before are tried first.
238
381
  let lawOptions = options.noRegressions
@@ -258,10 +401,13 @@ export async function check(options, enforceLock) {
258
401
  jsFile: jsPath(built.outDir, law.file),
259
402
  generators: types.generators,
260
403
  }, lawOptions)
261
- : await runLawGuarded(built.outDir, law, lawOptions, types.plans);
404
+ : await execute(lawOptions);
262
405
  }
263
406
  catch (error) {
264
- add(law, 'error', method, { message: error.message });
407
+ if (error instanceof LawLoadError)
408
+ add(law, 'error', 'load', { message: `cannot load compiled law: ${error.message}` });
409
+ else
410
+ add(law, 'error', method, { message: error.message });
265
411
  return;
266
412
  }
267
413
  if (details === 'timeout') {
@@ -296,7 +442,7 @@ export async function check(options, enforceLock) {
296
442
  return;
297
443
  }
298
444
  // Browser and async laws are tested, never proved: the prover cannot model a DOM or an await.
299
- const unprovable = browser || e2e ? 'runs in a browser' : fn.constructor.name === 'AsyncFunction' ? 'is async' : undefined;
445
+ const unprovable = browser || e2e ? 'runs in a browser' : isAsync ? 'is async' : undefined;
300
446
  if (options.noProve || unprovable !== undefined) {
301
447
  add(law, law.proved ? 'open' : 'tested', method, {
302
448
  runs: details.numRuns,
@@ -310,6 +456,10 @@ export async function check(options, enforceLock) {
310
456
  return;
311
457
  }
312
458
  const holds = (inputs) => {
459
+ if (sandboxed && sandbox === undefined)
460
+ return false;
461
+ if (sandbox !== undefined)
462
+ return sandbox.holds(built.outDir, law, inputs, limitMs);
313
463
  try {
314
464
  return fn(...inputs) !== false;
315
465
  }
@@ -325,12 +475,33 @@ export async function check(options, enforceLock) {
325
475
  timeoutMs: options.proofTimeoutMs,
326
476
  holds,
327
477
  solvers: config.solvers,
478
+ certify: certifyMode === false
479
+ ? undefined
480
+ : { mode: certifyMode, dir: join(options.cwd, '.tslaws', 'certificates'), root: options.cwd },
328
481
  });
482
+ const certified = (certificate) => certificate === undefined ? {} : { certificate };
329
483
  const assumed = (list) => (list.length > 0 ? { assumptions: list } : {});
484
+ if (proof.kind === 'proved' || proof.kind === 'bounded') {
485
+ // With certifying on, every proof has a certificate; one that is missing counts as uncertified, so `require`
486
+ // cannot pass a proof nobody checked.
487
+ if (certifyMode !== false)
488
+ proof.certificate ??= noCertificate;
489
+ if (proof.certificate !== undefined) {
490
+ records.set(lawKey(law.file, law.name), recordOf(lawHash(law), proof.certificate));
491
+ const required = certificateFailure(certifyMode, proof.certificate);
492
+ if (required !== undefined) {
493
+ add(law, 'error', 'smt', { certificate: proof.certificate, message: required });
494
+ return;
495
+ }
496
+ // A lock certificate for a different problem than the one proved now no longer vouches for the law.
497
+ if (lock !== undefined && staleRecord(lock.certificates?.[lawKey(law.file, law.name)], proof.certificate))
498
+ 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`);
499
+ }
500
+ }
330
501
  if (proof.kind === 'proved') {
331
502
  // The property run above used generators inside the proved domain; a short one is topped up before the proof stands.
332
503
  const passed = details;
333
- const rerun = (runs) => runLawGuarded(built.outDir, law, { ...lawOptions, runs, seed: passed.seed }, types.plans);
504
+ const rerun = (runs) => execute({ ...lawOptions, runs, seed: passed.seed });
334
505
  let disagrees;
335
506
  try {
336
507
  disagrees = await crossCheck(details, types.plans.length, rerun);
@@ -355,7 +526,12 @@ export async function check(options, enforceLock) {
355
526
  });
356
527
  }
357
528
  else
358
- add(law, 'proved', 'smt', { runs: details.numRuns, seed: details.seed, ...assumed(proof.assumptions) });
529
+ add(law, 'proved', 'smt', {
530
+ runs: details.numRuns,
531
+ seed: details.seed,
532
+ ...assumed(proof.assumptions),
533
+ ...certified(proof.certificate),
534
+ });
359
535
  }
360
536
  else if (proof.kind === 'bounded') {
361
537
  // `law proved` promises every input; a bounded proof is the most Z3 could show.
@@ -372,6 +548,7 @@ export async function check(options, enforceLock) {
372
548
  seed: details.seed,
373
549
  message,
374
550
  ...assumed(proof.assumptions),
551
+ ...certified(proof.certificate),
375
552
  });
376
553
  }
377
554
  else if (proof.kind === 'error')
@@ -397,8 +574,9 @@ export async function check(options, enforceLock) {
397
574
  nextToFlush += 1;
398
575
  }
399
576
  };
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) };
577
+ // Every law takes a slot of the process-wide CPU budget, and what it starts (a proof, a solver, a law process) runs on
578
+ // that slot. Browser and end-to-end laws also share one page and one server, so they queue for it first.
579
+ const page = new Semaphore(1);
402
580
  await Promise.all(laws.map(async (law, index) => {
403
581
  const skipped = (options.only !== undefined && !options.only.includes(law.name)) || blocked.has(lawKey(law.file, law.name));
404
582
  if (skipped) {
@@ -406,8 +584,8 @@ export async function check(options, enforceLock) {
406
584
  flush();
407
585
  return;
408
586
  }
409
- const lane = verdictOf(law.file).kind !== 'node' ? lanes.page : lanes.cpu;
410
- await lane.run(() => runOne(law, index));
587
+ const inSlot = () => budget.run(() => runOne(law, index));
588
+ await (verdictOf(law.file).kind !== 'node' ? page.run(inSlot) : inSlot());
411
589
  }));
412
590
  if (enforceLock) {
413
591
  const coverage = derived.coverage(() => analyzeCoverage({
@@ -445,6 +623,15 @@ export async function check(options, enforceLock) {
445
623
  }
446
624
  await closeBrowser();
447
625
  await stopServer();
626
+ // Records for `tslaws accept` to consider; a law that did not end proved or bounded keeps no certificate.
627
+ if (certifyMode !== false && enforceLock && records.size > 0) {
628
+ // A law the lock does not record yet is reported `tampered`; its proof counts through the proposal it carries.
629
+ const held = new Set(results.filter((r) => proofStatus(r) !== undefined).map((r) => lawKey(r.file, r.name)));
630
+ for (const key of records.keys())
631
+ if (!held.has(key))
632
+ records.set(key, undefined);
633
+ writeRecords(options.cwd, records);
634
+ }
448
635
  const ok = built.ok &&
449
636
  !lockMissing &&
450
637
  results.every((r) => r.status === 'proved' || r.status === 'bounded' || r.status === 'tested');
package/dist/cli.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { CheckReport } from './check.ts';
2
+ export declare function totals(report: CheckReport): string;
1
3
  export declare function watched(filename: string | null): boolean;
2
4
  /** What a command needs from its caller. `home` is for unit tests; the CLI never sets it. */
3
5
  export interface CommandContext {
@@ -7,6 +9,8 @@ export interface CommandContext {
7
9
  now?: Date;
8
10
  out?: (text: string) => void;
9
11
  err?: (text: string) => void;
12
+ /** Projects nested below `cwd`, project-relative: their laws are not this project's (set by a root run). */
13
+ skip?: string[];
10
14
  }
11
15
  export declare function acceptCommand(cwd: string, flags: Map<string, string | true>, files: string[], ctx: CommandContext): Promise<number>;
12
16
  /** `tslaws delegate <action> [--for D] [--root DIR]`; `argv` is everything after `delegate`. */