tslaws 1.0.0 → 1.2.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 (51) hide show
  1. package/README.md +183 -187
  2. package/dist/api.d.ts +86 -0
  3. package/dist/api.js +78 -0
  4. package/dist/badge.d.ts +111 -0
  5. package/dist/badge.js +288 -0
  6. package/dist/browser.d.ts +5 -2
  7. package/dist/browser.js +403 -173
  8. package/dist/browserApi.d.ts +305 -0
  9. package/dist/browserApi.js +456 -0
  10. package/dist/browserServer.d.ts +13 -0
  11. package/dist/browserServer.js +406 -0
  12. package/dist/certificates.js +50 -28
  13. package/dist/chc.d.ts +13 -1
  14. package/dist/chc.js +40 -8
  15. package/dist/check.js +64 -36
  16. package/dist/cli.d.ts +16 -0
  17. package/dist/cli.js +78 -1
  18. package/dist/compile.js +46 -5
  19. package/dist/coverage.d.ts +17 -0
  20. package/dist/coverage.js +297 -24
  21. package/dist/derived.d.ts +2 -0
  22. package/dist/derived.js +9 -4
  23. package/dist/generators.d.ts +5 -1
  24. package/dist/generators.js +50 -4
  25. package/dist/githubCli.js +88 -15
  26. package/dist/isolate.d.ts +5 -0
  27. package/dist/isolate.js +1 -1
  28. package/dist/lawHost.d.ts +2 -0
  29. package/dist/lawHost.js +32 -21
  30. package/dist/lawRuntime.d.ts +6 -0
  31. package/dist/lawRuntime.js +86 -7
  32. package/dist/nativeZ3.d.ts +11 -0
  33. package/dist/nativeZ3.js +162 -0
  34. package/dist/plan.d.ts +7 -0
  35. package/dist/plan.js +11 -0
  36. package/dist/pluginHooks.d.ts +4 -0
  37. package/dist/pluginHooks.js +13 -4
  38. package/dist/proofCache.d.ts +24 -0
  39. package/dist/proofCache.js +135 -0
  40. package/dist/property.d.ts +2 -2
  41. package/dist/property.js +33 -8
  42. package/dist/propertyWorker.js +14 -8
  43. package/dist/sandbox.d.ts +1 -1
  44. package/dist/sandbox.js +48 -8
  45. package/dist/seal.js +47 -8
  46. package/dist/smt.d.ts +16 -2
  47. package/dist/smt.js +241 -31
  48. package/dist/symbolic.d.ts +38 -3
  49. package/dist/symbolic.js +504 -47
  50. package/dist/types.d.ts +9 -0
  51. package/package.json +7 -7
@@ -7,6 +7,10 @@ export interface PluginHookHost {
7
7
  beside(request: string, parent: {
8
8
  filename: string;
9
9
  }): string | undefined;
10
+ /** The build's compiled copy of a project `.ts` file that a file in a project format imports, if it has one. */
11
+ twin(file: string, importer: string | undefined): string | undefined;
12
+ /** The same for a `./x.js` specifier that stands for `x.ts` (what Node cannot resolve beside the source). */
13
+ twinOfSpecifier(request: string, importer: string | undefined): string | undefined;
10
14
  /** The source Node can run for a file in a project format (see `transformPluginFile` in pluginHost.ts). */
11
15
  transform(file: string, cwd: string, plugins: readonly string[], format: 'cjs' | 'esm'): string;
12
16
  }
@@ -20,16 +20,21 @@ export function installPluginHooks(host) {
20
20
  return installed;
21
21
  registerHooks({
22
22
  resolve(specifier, context, nextResolve) {
23
+ const parent = context.parentURL?.startsWith('file:') ? fileURLToPath(context.parentURL) : undefined;
24
+ let resolved;
23
25
  try {
24
- return nextResolve(specifier, context);
26
+ resolved = nextResolve(specifier, context);
25
27
  }
26
28
  catch (error) {
27
- const parent = context.parentURL?.startsWith('file:') ? fileURLToPath(context.parentURL) : undefined;
28
- const file = parent === undefined ? undefined : host.beside(specifier, { filename: parent });
29
+ const file = parent === undefined
30
+ ? undefined
31
+ : (host.beside(specifier, { filename: parent }) ?? host.twinOfSpecifier(specifier, parent));
29
32
  if (file === undefined)
30
33
  throw error;
31
34
  return { url: pathToFileURL(file).href, shortCircuit: true };
32
35
  }
36
+ const twin = resolved.url.startsWith('file:') ? host.twin(fileURLToPath(resolved.url), parent) : undefined;
37
+ return twin === undefined ? resolved : { ...resolved, url: pathToFileURL(twin).href, format: 'commonjs' };
33
38
  },
34
39
  load(url, context, nextLoad) {
35
40
  if (!url.startsWith('file:'))
@@ -40,7 +45,11 @@ export function installPluginHooks(host) {
40
45
  const owner = host.ownerOf(file);
41
46
  const commonjs = context.conditions.includes('require');
42
47
  const source = host.transform(file, owner?.cwd ?? process.cwd(), owner?.bundlerPlugins ?? [], commonjs ? 'cjs' : 'esm');
43
- return { format: commonjs ? 'commonjs' : 'module', source, shortCircuit: true };
48
+ return {
49
+ format: commonjs ? 'commonjs' : 'module',
50
+ source,
51
+ shortCircuit: true,
52
+ };
44
53
  },
45
54
  });
46
55
  installed = true;
@@ -0,0 +1,24 @@
1
+ import type { CertifyMode } from './certificates.ts';
2
+ import { type SolverName } from './solvers.ts';
3
+ import type { ProofResult } from './smt.ts';
4
+ /** Fingerprint of the solver + certificate toolchain relevant to a proof query. */
5
+ export declare function toolchainFingerprint(solvers: readonly SolverName[] | undefined, certify: CertifyMode | undefined): string;
6
+ export interface ProofCache {
7
+ get(key: string, keep?: {
8
+ dir: string;
9
+ name: string;
10
+ root: string;
11
+ }): ProofResult | undefined;
12
+ set(key: string, result: ProofResult): void;
13
+ flush(): void;
14
+ }
15
+ /** Computes the cache key for an exact SMT-LIB query (or Horn system) under the given solver/certify configuration. */
16
+ export declare function proofCacheKey(input: {
17
+ query: string;
18
+ bounded: readonly string[];
19
+ assumptions: readonly string[];
20
+ solvers: readonly SolverName[] | undefined;
21
+ certify: CertifyMode | undefined;
22
+ }): string;
23
+ /** Opens the project's proof cache (`.tslaws/proof-cache.json`). Deferred write: call `flush()` once at end of check. */
24
+ export declare function openProofCache(cwd: string): ProofCache;
@@ -0,0 +1,135 @@
1
+ // On-disk proof & certificate verdict cache keyed by exact SMT-LIB query hash and solver/tool fingerprints.
2
+ // Unchanged laws skip Z3, cvc5 and Carcara on incremental/watch/CI runs; any change to the law, its called code,
3
+ // solver config, or tool binary invalidates the entry.
4
+ import { createHash } from 'node:crypto';
5
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
6
+ import { dirname, join } from 'node:path';
7
+ import { hashOf } from "./certificates.js";
8
+ import { z3Fingerprint } from "./nativeZ3.js";
9
+ import { toolCommand } from "./solvers.js";
10
+ const cacheVersion = 1;
11
+ const maxEntries = 2000;
12
+ function toolStamp(env, binary) {
13
+ const cmd = toolCommand(env, binary);
14
+ const target = cmd.args[0] ?? cmd.file;
15
+ try {
16
+ const st = statSync(target);
17
+ return `${cmd.file}:${cmd.args.join(',')}:${st.size}:${st.mtimeMs}`;
18
+ }
19
+ catch {
20
+ return `${cmd.file}:${cmd.args.join(',')}`;
21
+ }
22
+ }
23
+ /** Fingerprint of the solver + certificate toolchain relevant to a proof query. */
24
+ export function toolchainFingerprint(solvers, certify) {
25
+ const parts = [z3Fingerprint()];
26
+ const usesCvc5 = (solvers?.includes('cvc5') ?? false) || (certify !== undefined && certify !== false);
27
+ if (usesCvc5)
28
+ parts.push(`cvc5=${toolStamp('TSLAWS_CVC5', 'cvc5')}`);
29
+ if (certify !== undefined && certify !== false)
30
+ parts.push(`carcara=${toolStamp('TSLAWS_CARCARA', 'carcara')}`);
31
+ return parts.join('|');
32
+ }
33
+ const noopCache = {
34
+ get: () => undefined,
35
+ set: () => undefined,
36
+ flush: () => undefined,
37
+ };
38
+ /** Computes the cache key for an exact SMT-LIB query (or Horn system) under the given solver/certify configuration. */
39
+ export function proofCacheKey(input) {
40
+ const hash = createHash('sha256');
41
+ hash.update(JSON.stringify([
42
+ cacheVersion,
43
+ input.query,
44
+ input.bounded,
45
+ input.assumptions,
46
+ input.solvers ?? ['z3'],
47
+ input.certify ?? false,
48
+ toolchainFingerprint(input.solvers, input.certify),
49
+ ]));
50
+ return hash.digest('hex');
51
+ }
52
+ /** Verifies that a cached certified result still has intact saved proof files on disk when `keep` is requested. */
53
+ function keptFilesIntact(certificate, keep) {
54
+ if (certificate === undefined || certificate.status !== 'certified' || keep === undefined)
55
+ return true;
56
+ const smtFile = join(keep.dir, `${keep.name}.smt2`);
57
+ const proofFile = join(keep.dir, `${keep.name}.alethe`);
58
+ if (!existsSync(smtFile) || !existsSync(proofFile))
59
+ return false;
60
+ try {
61
+ if (certificate.problemHash !== undefined && hashOf(readFileSync(smtFile, 'utf8')) !== certificate.problemHash)
62
+ return false;
63
+ if (certificate.proofHash !== undefined && hashOf(readFileSync(proofFile, 'utf8')) !== certificate.proofHash)
64
+ return false;
65
+ if (certificate.systemHash !== undefined) {
66
+ const hornFile = join(keep.dir, `${keep.name}.horn`);
67
+ const invFile = join(keep.dir, `${keep.name}.inv`);
68
+ if (!existsSync(hornFile) || !existsSync(invFile))
69
+ return false;
70
+ if (hashOf(readFileSync(hornFile, 'utf8')) !== certificate.systemHash)
71
+ return false;
72
+ }
73
+ return true;
74
+ }
75
+ catch {
76
+ return false;
77
+ }
78
+ }
79
+ /** Opens the project's proof cache (`.tslaws/proof-cache.json`). Deferred write: call `flush()` once at end of check. */
80
+ export function openProofCache(cwd) {
81
+ if (process.env.TSLAWS_NO_PROOF_CACHE === '1')
82
+ return noopCache;
83
+ const path = join(cwd, '.tslaws', 'proof-cache.json');
84
+ let stored = { version: cacheVersion, entries: {} };
85
+ try {
86
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
87
+ if (parsed?.version === cacheVersion && typeof parsed.entries === 'object' && parsed.entries !== null)
88
+ stored = parsed;
89
+ }
90
+ catch {
91
+ // No cache yet.
92
+ }
93
+ let dirty = false;
94
+ return {
95
+ get(key, keep) {
96
+ const entry = stored.entries[key];
97
+ if (entry === undefined)
98
+ return undefined;
99
+ // Never serve an unavailable/uncertified certificate from cache so newly installed tools are picked up immediately.
100
+ if (entry.result.certificate !== undefined && entry.result.certificate.status !== 'certified')
101
+ return undefined;
102
+ if (!keptFilesIntact(entry.result.certificate, keep))
103
+ return undefined;
104
+ entry.at = Date.now();
105
+ return entry.result;
106
+ },
107
+ set(key, result) {
108
+ if (result.kind !== 'proved' && result.kind !== 'bounded')
109
+ return;
110
+ if (result.certificate !== undefined && result.certificate.status !== 'certified')
111
+ return;
112
+ stored.entries[key] = { result, at: Date.now() };
113
+ dirty = true;
114
+ },
115
+ flush() {
116
+ if (!dirty)
117
+ return;
118
+ dirty = false;
119
+ try {
120
+ const keys = Object.keys(stored.entries);
121
+ if (keys.length > maxEntries) {
122
+ keys
123
+ .sort((a, b) => (stored.entries[a]?.at ?? 0) - (stored.entries[b]?.at ?? 0))
124
+ .slice(0, keys.length - maxEntries)
125
+ .forEach((k) => delete stored.entries[k]);
126
+ }
127
+ mkdirSync(dirname(path), { recursive: true });
128
+ writeFileSync(path, JSON.stringify(stored));
129
+ }
130
+ catch {
131
+ // Not caching is only slower.
132
+ }
133
+ },
134
+ };
135
+ }
@@ -14,7 +14,7 @@ export interface LawTypes {
14
14
  /** Every declaration file the compiler emitted: the laws' own do not import the code they are about. */
15
15
  export declare function declarationFiles(outDir: string): string[];
16
16
  export declare function dtsPath(outDir: string, file: string): string;
17
- /** What the prover models of `type`: numbers, `int`s, bigints, strings, booleans, arrays and records of them. */
17
+ /** What the prover models of `type`: numbers, `int`s (and refinements), bigints, strings, booleans, arrays and records. */
18
18
  export declare function shapeOf(checker: ts.TypeChecker, type: ts.Type): Shape;
19
19
  /** `cwd` is given when `program` is the one that compiled the laws, whose source files hold the types the declarations would. */
20
20
  export declare function typesOf(program: ts.Program, outDir: string, law: ManifestLaw, cwd?: string): LawTypes;
@@ -22,4 +22,4 @@ export declare const compilerOptions: ts.CompilerOptions;
22
22
  /** Starts `n` property workers ahead of the first law, so they load while the code compiles. */
23
23
  export declare function warmWorkers(n: number): void;
24
24
  /** Runs the property test of `law` in a pooled worker, giving up on it after `options.propertyTimeoutMs`. */
25
- export declare function runLawGuarded(outDir: string, law: ManifestLaw, options: CheckOptions, plans: Plan[]): Promise<PropertyOutcome | 'timeout'>;
25
+ export declare function runLawGuarded(outDir: string, law: ManifestLaw, options: CheckOptions, plans: Plan[], buildKey?: string): Promise<PropertyOutcome | 'timeout'>;
package/dist/property.js CHANGED
@@ -2,7 +2,7 @@ import { Worker } from 'node:worker_threads';
2
2
  import { readdirSync, statSync } from 'node:fs';
3
3
  import { join, resolve } from 'node:path';
4
4
  import ts from 'typescript';
5
- import { GeneratorFactory } from "./generators.js";
5
+ import { GeneratorFactory, readIntRangeBounds, readNonEmptyElement } from "./generators.js";
6
6
  import { lawEnv } from "./coverage.js";
7
7
  import { arbitraryOf, UnsupportedType } from "./plan.js";
8
8
  import { budget, WorkerPool } from "./pool.js";
@@ -27,11 +27,35 @@ export function declarationFiles(outDir) {
27
27
  export function dtsPath(outDir, file) {
28
28
  return join(outDir, file.replace(/\.(ts|tsx|mts|cts)$/, '.d.ts'));
29
29
  }
30
- /** What the prover models of `type`: numbers, `int`s, bigints, strings, booleans, arrays and records of them. */
30
+ /** What the prover models of `type`: numbers, `int`s (and refinements), bigints, strings, booleans, arrays and records. */
31
31
  export function shapeOf(checker, type) {
32
- if ((type.aliasSymbol ?? type.getSymbol())?.getName() === 'int' &&
33
- type.flags & (ts.TypeFlags.Intersection | ts.TypeFlags.Number))
34
- return 'int';
32
+ const aliasName = (type.aliasSymbol ?? type.getSymbol())?.getName();
33
+ if (type.flags & (ts.TypeFlags.Intersection | ts.TypeFlags.Number)) {
34
+ const bounds = readIntRangeBounds(checker, type);
35
+ if (bounds !== undefined)
36
+ return { intRange: bounds };
37
+ if (aliasName === 'int')
38
+ return 'int';
39
+ if (aliasName === 'nat')
40
+ return 'nat';
41
+ if (aliasName === 'posInt')
42
+ return 'posInt';
43
+ if (aliasName === 'nonZeroInt')
44
+ return 'nonZeroInt';
45
+ if (aliasName === 'finite')
46
+ return 'number';
47
+ }
48
+ if (type.flags & (ts.TypeFlags.Intersection | ts.TypeFlags.String)) {
49
+ if (aliasName === 'asciiString')
50
+ return 'asciiString';
51
+ if (aliasName === 'nonEmptyString')
52
+ return 'nonEmptyString';
53
+ }
54
+ if (aliasName === 'nonEmpty') {
55
+ const elemType = readNonEmptyElement(checker, type);
56
+ const element = elemType === undefined ? undefined : shapeOf(checker, elemType);
57
+ return element === undefined ? undefined : { array: element, minLength: 1 };
58
+ }
35
59
  if (type.flags & ts.TypeFlags.Number)
36
60
  return 'number';
37
61
  if (type.flags & ts.TypeFlags.BigInt)
@@ -110,11 +134,11 @@ export function warmWorkers(n) {
110
134
  workers.warm(n);
111
135
  }
112
136
  /** Runs the property test of `law` in a pooled worker, giving up on it after `options.propertyTimeoutMs`. */
113
- export async function runLawGuarded(outDir, law, options, plans) {
137
+ export async function runLawGuarded(outDir, law, options, plans, buildKey) {
114
138
  // The worker task is a slot of the budget (the law's own, when it runs under one).
115
- return budget.run(() => runInWorker(outDir, law, options, plans));
139
+ return budget.run(() => runInWorker(outDir, law, options, plans, buildKey));
116
140
  }
117
- async function runInWorker(outDir, law, options, plans) {
141
+ async function runInWorker(outDir, law, options, plans, buildKey) {
118
142
  const current = await workers.acquire();
119
143
  return new Promise((resolve, reject) => {
120
144
  const timer = setTimeout(() => {
@@ -138,6 +162,7 @@ async function runInWorker(outDir, law, options, plans) {
138
162
  plans,
139
163
  options: { ...options, onEvent: undefined },
140
164
  env: lawEnv(options.cwd, 'node'),
165
+ buildKey,
141
166
  });
142
167
  });
143
168
  }
@@ -2,7 +2,7 @@ import { readFileSync } from 'node:fs';
2
2
  import { createRequire } from 'node:module';
3
3
  import { join } from 'node:path';
4
4
  import { parentPort } from 'node:worker_threads';
5
- import { installLawRuntime, runtimeFile } from "./lawRuntime.js";
5
+ import { evictLoaded, installLawRuntime, runtimeFile } from "./lawRuntime.js";
6
6
  import { arbitraryOf } from "./plan.js";
7
7
  import { jsPath, runLaw, summarise } from "./propertyRun.js";
8
8
  import { installLoaderHooks, setImportMetaEnv } from "./runtimeEnv.js";
@@ -12,17 +12,23 @@ import { installLoaderHooks, setImportMetaEnv } from "./runtimeEnv.js";
12
12
  // from `require.cache` and loaded again; an `import()` of it could not be forgotten.
13
13
  const require = createRequire(import.meta.url);
14
14
  installLoaderHooks();
15
+ const loadedBuildKeys = new Map();
15
16
  parentPort.on('message', async (request) => {
16
17
  try {
17
- const { outDir, law, plans, options, env } = request;
18
+ const { outDir, law, plans, options, env, buildKey } = request;
18
19
  setImportMetaEnv(env);
19
20
  const generators = plans.map(arbitraryOf);
20
- // The build left the project's module resolution beside the output (aliases from its tsconfig, TypeScript sources).
21
- installLawRuntime(JSON.parse(readFileSync(join(outDir, runtimeFile), 'utf8')));
22
- // The worker outlives a check, and the code may have been recompiled since the last one.
23
- for (const loaded of Object.keys(require.cache))
24
- if (loaded.startsWith(outDir))
25
- delete require.cache[loaded];
21
+ const sameBuild = buildKey !== undefined && loadedBuildKeys.get(outDir) === buildKey;
22
+ if (!sameBuild) {
23
+ // The build left the project's module resolution beside the output (aliases from its tsconfig, TypeScript sources).
24
+ installLawRuntime(JSON.parse(readFileSync(join(outDir, runtimeFile), 'utf8')));
25
+ // The worker outlives a check, and the code may have been recompiled since the last one. Files a plugin loaded go too.
26
+ evictLoaded(require.cache, outDir);
27
+ if (buildKey !== undefined)
28
+ loadedBuildKeys.set(outDir, buildKey);
29
+ else
30
+ loadedBuildKeys.delete(outDir);
31
+ }
26
32
  const fn = require(jsPath(outDir, law.file))[law.symbol ?? law.name];
27
33
  parentPort.postMessage({ ok: summarise(await runLaw(fn, generators, options), options) });
28
34
  }
package/dist/sandbox.d.ts CHANGED
@@ -89,7 +89,7 @@ export declare class Sandbox {
89
89
  private ask;
90
90
  private askOnce;
91
91
  /** The property test of `law`, `'timeout'` when it does not finish; throws `LawLoadError` when it cannot be loaded. */
92
- run(outDir: string, law: ManifestLaw, options: CheckOptions, plans: Plan[]): Promise<SandboxedRun | 'timeout'>;
92
+ run(outDir: string, law: ManifestLaw, options: CheckOptions, plans: Plan[], buildKey?: string): Promise<SandboxedRun | 'timeout'>;
93
93
  /**
94
94
  * Whether the law holds on `inputs` (a model the prover found), as the prover's replay needs it. A law that hangs or
95
95
  * cannot be loaded counts as holding: the model is then not confirmed, and nothing is reported as refuted.
package/dist/sandbox.js CHANGED
@@ -12,7 +12,7 @@
12
12
  // them (`--allow-e2e`). `--no-sandbox` turns it all off, with a warning.
13
13
  import { fork } from 'node:child_process';
14
14
  import { createHash, randomBytes } from 'node:crypto';
15
- import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs';
15
+ import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
16
16
  import { homedir } from 'node:os';
17
17
  import { dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
18
18
  import { fileURLToPath } from 'node:url';
@@ -316,6 +316,35 @@ const namesOf = (manifest, fields) => fields.flatMap((field) => {
316
316
  const value = manifest?.[field];
317
317
  return typeof value === 'object' && value !== null ? Object.keys(value) : [];
318
318
  });
319
+ const trustedPackagesCache = new Map();
320
+ function manifestStamp(dir) {
321
+ const out = [];
322
+ for (const name of ['package.json', 'package-lock.json', 'pnpm-lock.yaml']) {
323
+ const p = join(dir, name);
324
+ try {
325
+ const st = statSync(p);
326
+ out.push([p, st.size, st.mtimeMs]);
327
+ }
328
+ catch {
329
+ out.push([p, -1, -1]);
330
+ }
331
+ }
332
+ return out;
333
+ }
334
+ function stampsMatch(stamps) {
335
+ for (const [p, size, mtimeMs] of stamps) {
336
+ try {
337
+ const st = statSync(p);
338
+ if (st.size !== size || st.mtimeMs !== mtimeMs)
339
+ return false;
340
+ }
341
+ catch {
342
+ if (size !== -1 || mtimeMs !== -1)
343
+ return false;
344
+ }
345
+ }
346
+ return true;
347
+ }
319
348
  /**
320
349
  * The packages the code may load: those the manifests declare (the project's `package.json` with its dev dependencies,
321
350
  * and tslaws's own) and, from each one's manifest, what it declares in turn. Anything else in a `node_modules` was put
@@ -324,6 +353,10 @@ const namesOf = (manifest, fields) => fields.flatMap((field) => {
324
353
  */
325
354
  export function trustedPackages(cwd) {
326
355
  const project = realOf(resolve(cwd));
356
+ const cached = trustedPackagesCache.get(project);
357
+ if (cached !== undefined && stampsMatch(cached.stamps))
358
+ return cached.value;
359
+ const stamps = [...manifestStamp(project), ...manifestStamp(tslawsRoot)];
327
360
  const modules = new Set();
328
361
  const linked = new Set();
329
362
  const seen = new Set();
@@ -358,7 +391,11 @@ export function trustedPackages(cwd) {
358
391
  for (const [dir, fields] of manifests)
359
392
  for (const name of namesOf(readManifest(join(dir, 'package.json')), fields))
360
393
  visit(name, dir);
361
- return { modules: [...modules], linked: [...linked] };
394
+ const value = { modules: [...modules], linked: [...linked] };
395
+ if (trustedPackagesCache.size > 256)
396
+ trustedPackagesCache.clear();
397
+ trustedPackagesCache.set(project, { stamps, value });
398
+ return value;
362
399
  }
363
400
  /**
364
401
  * The reviewed set of a project after a build: the build's output, the files its laws reach, the packages, and the
@@ -476,11 +513,11 @@ class LawProcess {
476
513
  configKey;
477
514
  /** Answers only requests that carry it. The process learns it from `configure` and no law can read it. */
478
515
  token = randomBytes(24).toString('hex');
479
- constructor(cwd, extra) {
516
+ constructor(flags) {
480
517
  this.child = fork(hostFile, [], {
481
518
  // The allowlisted environment the token-free check process gets (see isolate.ts): no credential, no code loader.
482
519
  env: scrubbedEnv(process.env),
483
- execArgv: sandboxFlags(cwd, extra),
520
+ execArgv: flags,
484
521
  serialization: 'advanced',
485
522
  stdio: ['ignore', 'inherit', 'inherit', 'ipc'],
486
523
  windowsHide: true,
@@ -551,7 +588,7 @@ export function liveSandboxProcesses() {
551
588
  * Makes room for a process about to start: the cap is shared by every project, not held by each, so an idle process of
552
589
  * another project (or configuration) ends when the budget is already spent. The pool counts the new one before it starts.
553
590
  */
554
- function startProcess(cwd, extra) {
591
+ function startProcess(flags) {
555
592
  const cap = jobs();
556
593
  for (const { pool } of pools.values()) {
557
594
  if (liveSandboxProcesses() <= cap)
@@ -559,15 +596,17 @@ function startProcess(cwd, extra) {
559
596
  while (liveSandboxProcesses() > cap && pool.evictOne())
560
597
  ;
561
598
  }
562
- return new LawProcess(cwd, extra);
599
+ return new LawProcess(flags);
563
600
  }
564
601
  function poolFor(cwd, extra) {
565
602
  const key = JSON.stringify([resolve(cwd), extra]);
566
603
  let entry = pools.get(key);
567
604
  if (entry === undefined) {
605
+ // Compute permission flags once per pool instead of re-walking node_modules for every forked process.
606
+ const flags = sandboxFlags(cwd, extra);
568
607
  entry = {
569
608
  cwd: resolve(cwd),
570
- pool: new WorkerPool(() => startProcess(cwd, extra), jobs, idleMs),
609
+ pool: new WorkerPool(() => startProcess(flags), jobs, idleMs),
571
610
  };
572
611
  pools.set(key, entry);
573
612
  }
@@ -633,7 +672,7 @@ export class Sandbox {
633
672
  }
634
673
  }
635
674
  /** The property test of `law`, `'timeout'` when it does not finish; throws `LawLoadError` when it cannot be loaded. */
636
- async run(outDir, law, options, plans) {
675
+ async run(outDir, law, options, plans, buildKey) {
637
676
  const reply = await this.ask(options.propertyTimeoutMs ?? 30000, (id) => ({
638
677
  type: 'run',
639
678
  id,
@@ -643,6 +682,7 @@ export class Sandbox {
643
682
  // Functions cannot cross to the process; it needs only the numbers.
644
683
  options: { ...options, onEvent: undefined },
645
684
  env: lawEnv(options.cwd, 'node'),
685
+ buildKey,
646
686
  }));
647
687
  if (reply === 'timeout')
648
688
  return reply;
package/dist/seal.js CHANGED
@@ -30,7 +30,7 @@ import { readResolution, resolutionCompilerOptions } from "./tsconfigResolve.js"
30
30
  const digest = (data) => createHash('sha256').update(data).digest('hex');
31
31
  /** The code as its tokens joined by one space: no comments or layout, every literal exact. */
32
32
  function tokensOf(text, fileName) {
33
- const source = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true);
33
+ const source = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, false);
34
34
  const tokens = [];
35
35
  const visit = (node) => {
36
36
  if (node.kind >= ts.SyntaxKind.FirstJSDocNode && node.kind <= ts.SyntaxKind.LastJSDocNode)
@@ -45,14 +45,55 @@ function tokensOf(text, fileName) {
45
45
  return tokens.join(' ');
46
46
  }
47
47
  const scripts = /\.(?:[cm]?[jt]sx?)$/;
48
+ /** Stat-validated cache for file digests and module specifiers so unchanged files aren't re-parsed across checks. */
49
+ const digestCache = new Map();
50
+ const specifierCache = new Map();
48
51
  /** The line endings of a checkout must not matter, so text is read with `\n`. */
49
52
  const readText = (path) => readFileSync(path, 'utf8').replaceAll('\r\n', '\n');
50
53
  /** A file's digest: the tokens of a script, the text of any other text file, the bytes of a binary one. */
51
54
  function digestOf(path) {
55
+ let st;
56
+ try {
57
+ st = statSync(path);
58
+ const cached = digestCache.get(path);
59
+ if (cached !== undefined && cached.size === st.size && cached.mtimeMs === st.mtimeMs)
60
+ return cached.digest;
61
+ }
62
+ catch {
63
+ // Fall through to readFileSync which throws if unreadable.
64
+ }
65
+ let result;
52
66
  if (scripts.test(path))
53
- return digest(tokensOf(readText(path), path));
54
- const bytes = readFileSync(path);
55
- return digest(bytes.includes(0) ? bytes : bytes.toString('utf8').replaceAll('\r\n', '\n'));
67
+ result = digest(tokensOf(readText(path), path));
68
+ else {
69
+ const bytes = readFileSync(path);
70
+ result = digest(bytes.includes(0) ? bytes : bytes.toString('utf8').replaceAll('\r\n', '\n'));
71
+ }
72
+ if (st !== undefined) {
73
+ if (digestCache.size > 4000)
74
+ digestCache.clear();
75
+ digestCache.set(path, { size: st.size, mtimeMs: st.mtimeMs, digest: result });
76
+ }
77
+ return result;
78
+ }
79
+ function cachedSpecifiers(path) {
80
+ let st;
81
+ try {
82
+ st = statSync(path);
83
+ const cached = specifierCache.get(path);
84
+ if (cached !== undefined && cached.size === st.size && cached.mtimeMs === st.mtimeMs)
85
+ return cached.specifiers;
86
+ }
87
+ catch {
88
+ // Fall through.
89
+ }
90
+ const specifiers = moduleSpecifiers(readText(path), path).map((s) => s.value);
91
+ if (st !== undefined) {
92
+ if (specifierCache.size > 4000)
93
+ specifierCache.clear();
94
+ specifierCache.set(path, { size: st.size, mtimeMs: st.mtimeMs, specifiers });
95
+ }
96
+ return specifiers;
56
97
  }
57
98
  const builtins = new Set(builtinModules);
58
99
  const underNodeModules = /(?:^|[\\/])node_modules[\\/]/;
@@ -137,7 +178,7 @@ class Linker {
137
178
  if (installed !== undefined && installed !== 'linked')
138
179
  externals.push(registry(installed, specifier));
139
180
  const found = ts.resolveModuleName(specifier, from, this.options, ts.sys).resolvedModule;
140
- const typesOnly = builtin && found !== undefined && /[\/]node_modules[\/]@types[\/]/.test(realOf(found.resolvedFileName));
181
+ const typesOnly = builtin && found !== undefined && /[/]node_modules[/]@types[/]/.test(realOf(found.resolvedFileName));
141
182
  if (found !== undefined && existsSync(found.resolvedFileName) && !typesOnly) {
142
183
  const real = realOf(found.resolvedFileName);
143
184
  if (underNodeModules.test(real)) {
@@ -299,9 +340,7 @@ class Sealer {
299
340
  try {
300
341
  found = {
301
342
  digest: digestOf(path),
302
- links: scripts.test(path)
303
- ? moduleSpecifiers(readText(path), path).map((s) => this.linker.link(s.value, path))
304
- : [],
343
+ links: scripts.test(path) ? cachedSpecifiers(path).map((s) => this.linker.link(s, path)) : [],
305
344
  };
306
345
  }
307
346
  catch {
package/dist/smt.d.ts CHANGED
@@ -1,8 +1,13 @@
1
+ import { Worker } from 'node:worker_threads';
1
2
  import { type Certificate, type CertifyMode } from './certificates.ts';
3
+ import { type ProofCache } from './proofCache.ts';
2
4
  import { type SolverName } from './solvers.ts';
3
5
  import type { ManifestLaw } from './types.ts';
4
- export type Shape = 'number' | 'int' | 'bigint' | 'boolean' | 'string' | {
6
+ export type Shape = 'number' | 'int' | 'nat' | 'posInt' | 'nonZeroInt' | {
7
+ intRange: [number, number];
8
+ } | 'bigint' | 'boolean' | 'string' | 'asciiString' | 'nonEmptyString' | {
5
9
  array: Shape;
10
+ minLength?: number;
6
11
  } | {
7
12
  fields: Record<string, Shape>;
8
13
  } | undefined;
@@ -50,10 +55,19 @@ export interface ProveInput {
50
55
  dir: string;
51
56
  root: string;
52
57
  };
58
+ /** Optional proof & certificate result cache keyed by exact SMT-LIB problem hash. */
59
+ cache?: ProofCache;
53
60
  }
61
+ /**
62
+ * Starts the Z3 workers with `start` from now on and ends the idle ones, which were started the old way; the returned
63
+ * function puts the first way back. For tests that make a worker crash.
64
+ */
65
+ export declare function startSolverWorkersWith(start: () => Worker): () => void;
54
66
  /**
55
67
  * Runs the query, and runs it again in a fresh worker when the solver itself fell over (a WebAssembly allocation that
56
- * fails on a machine short of memory). A query that merely ran too long is not retried: it would only run long again.
68
+ * fails on a machine short of memory). Idle workers are ended first, so the retry has their memory. A query that merely
69
+ * ran too long is not retried: it would only run long again. A crash that outlasts the retries throws `SolverCrash`,
70
+ * never `Unsupported`, so a proof cannot take it for a solver that gave up.
57
71
  */
58
72
  export declare function solve(query: string, values: string, timeoutMs: number): Promise<{
59
73
  out: string;