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.
- package/README.md +8 -2
- package/bin/tslaws.js +8 -2
- package/dist/browser.d.ts +1 -1
- package/dist/browser.js +36 -7
- package/dist/bundled.js +2 -2
- package/dist/bundlerPlugins.d.ts +2 -0
- package/dist/bundlerPlugins.js +7 -0
- package/dist/certificates.d.ts +139 -0
- package/dist/certificates.js +433 -0
- package/dist/chc.d.ts +85 -0
- package/dist/chc.js +298 -0
- package/dist/check.d.ts +13 -1
- package/dist/check.js +215 -28
- package/dist/cli.d.ts +4 -0
- package/dist/cli.js +324 -41
- package/dist/compile.d.ts +17 -1
- package/dist/compile.js +244 -25
- package/dist/coverage.d.ts +55 -3
- package/dist/coverage.js +231 -12
- package/dist/e2eApi.js +3 -1
- package/dist/generators.js +12 -2
- package/dist/github.d.ts +49 -5
- package/dist/github.js +107 -24
- package/dist/githubCli.d.ts +28 -0
- package/dist/githubCli.js +1039 -211
- package/dist/hints.js +2 -1
- package/dist/init.js +42 -0
- package/dist/isolate.d.ts +28 -0
- package/dist/isolate.js +262 -0
- package/dist/isolatedCheck.d.ts +1 -0
- package/dist/isolatedCheck.js +16 -0
- package/dist/lawHost.d.ts +50 -0
- package/dist/lawHost.js +199 -0
- package/dist/lawRuntime.d.ts +39 -0
- package/dist/lawRuntime.js +242 -0
- package/dist/lock.d.ts +49 -9
- package/dist/lock.js +132 -21
- package/dist/mcp.js +28 -7
- package/dist/mutate.d.ts +4 -0
- package/dist/mutate.js +7 -1
- package/dist/plan.d.ts +1 -0
- package/dist/plan.js +4 -0
- package/dist/pluginHooks.d.ts +16 -0
- package/dist/pluginHooks.js +48 -0
- package/dist/pluginHost.d.ts +5 -0
- package/dist/pluginHost.js +43 -0
- package/dist/pluginWorker.d.ts +1 -0
- package/dist/pluginWorker.js +40 -0
- package/dist/plural.d.ts +2 -0
- package/dist/plural.js +4 -0
- package/dist/pool.d.ts +80 -7
- package/dist/pool.js +222 -11
- package/dist/projects.d.ts +70 -0
- package/dist/projects.js +457 -0
- package/dist/promote.d.ts +56 -2
- package/dist/promote.js +429 -13
- package/dist/property.js +13 -2
- package/dist/propertyWorker.js +11 -1
- package/dist/proposals.d.ts +52 -4
- package/dist/proposals.js +484 -21
- package/dist/reporters.js +5 -1
- package/dist/runtimeEnv.d.ts +32 -0
- package/dist/runtimeEnv.js +146 -0
- package/dist/sandbox.d.ts +98 -0
- package/dist/sandbox.js +673 -0
- package/dist/sandboxGuard.d.ts +56 -0
- package/dist/sandboxGuard.js +249 -0
- package/dist/seal.d.ts +9 -0
- package/dist/seal.js +426 -0
- package/dist/security/cli.d.ts +6 -0
- package/dist/security/cli.js +39 -0
- package/dist/security/cwe.d.ts +14 -0
- package/dist/security/cwe.js +40 -0
- package/dist/security/deps/cache.d.ts +28 -0
- package/dist/security/deps/cache.js +107 -0
- package/dist/security/deps/config.d.ts +16 -0
- package/dist/security/deps/config.js +43 -0
- package/dist/security/deps/imports.d.ts +4 -0
- package/dist/security/deps/imports.js +33 -0
- package/dist/security/deps/lockfiles.d.ts +23 -0
- package/dist/security/deps/lockfiles.js +153 -0
- package/dist/security/deps/osv.d.ts +66 -0
- package/dist/security/deps/osv.js +137 -0
- package/dist/security/deps/run.d.ts +54 -0
- package/dist/security/deps/run.js +135 -0
- package/dist/security/deps/severity.d.ts +26 -0
- package/dist/security/deps/severity.js +78 -0
- package/dist/security/generators.d.ts +9 -0
- package/dist/security/generators.js +36 -0
- package/dist/security/index.d.ts +27 -0
- package/dist/security/index.js +18 -0
- package/dist/security/integers.d.ts +31 -0
- package/dist/security/integers.js +105 -0
- package/dist/security/law.d.ts +54 -0
- package/dist/security/law.js +54 -0
- package/dist/security/pathTraversal.d.ts +29 -0
- package/dist/security/pathTraversal.js +146 -0
- package/dist/security/prototypePollution.d.ts +30 -0
- package/dist/security/prototypePollution.js +142 -0
- package/dist/security/redirect.d.ts +21 -0
- package/dist/security/redirect.js +154 -0
- package/dist/security/redos.d.ts +21 -0
- package/dist/security/redos.js +93 -0
- package/dist/security/validation.d.ts +25 -0
- package/dist/security/validation.js +89 -0
- package/dist/security/xss.d.ts +21 -0
- package/dist/security/xss.js +90 -0
- package/dist/settings.d.ts +20 -0
- package/dist/settings.js +32 -0
- package/dist/smt.d.ts +29 -1
- package/dist/smt.js +239 -107
- package/dist/smtWorker.d.ts +1 -0
- package/dist/smtWorker.js +26 -0
- package/dist/solvers.d.ts +9 -0
- package/dist/solvers.js +11 -5
- package/dist/symbolic.d.ts +54 -1
- package/dist/symbolic.js +239 -13
- package/dist/tsconfigResolve.d.ts +28 -0
- package/dist/tsconfigResolve.js +141 -0
- package/dist/types.d.ts +28 -0
- package/env.d.ts +17 -0
- package/hooks/claude-hook.mjs +2 -0
- package/package.json +22 -6
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
// Checkable proof certificates. Z3 answers `unsat` to a law's query, but its answer is a claim. With `"certify": true` in
|
|
2
|
+
// tslaws.json (or `--certify`), the same query goes to cvc5, which writes an Alethe proof of the `unsat`, and Carcara
|
|
3
|
+
// checks that proof independently. A law whose proof Carcara accepts is `certified`; the hashes of the problem, the
|
|
4
|
+
// proof and the checker's verdict are what the lock records beside the law.
|
|
5
|
+
//
|
|
6
|
+
// The tools are never required unless asked: when cvc5 or Carcara is missing the certificate is `unavailable` and the law
|
|
7
|
+
// keeps the status it had. `"certify": "require"` turns anything short of `certified` into an error.
|
|
8
|
+
import { spawn } from 'node:child_process';
|
|
9
|
+
import { createHash } from 'node:crypto';
|
|
10
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
11
|
+
import { tmpdir } from 'node:os';
|
|
12
|
+
import { dirname, join } from 'node:path';
|
|
13
|
+
import { certificationProblem } from "./chc.js";
|
|
14
|
+
import { budget as slots, lowerPriority } from "./pool.js";
|
|
15
|
+
import { cvc5Text, toolCommand } from "./solvers.js";
|
|
16
|
+
/** What is wrong with a `certify` value from tslaws.json, or undefined when it is valid. */
|
|
17
|
+
export function certifyProblem(value) {
|
|
18
|
+
if (typeof value === 'boolean' || value === 'require')
|
|
19
|
+
return undefined;
|
|
20
|
+
return `"certify" must be true, false or "require", got ${JSON.stringify(value)}`;
|
|
21
|
+
}
|
|
22
|
+
/** `certified`, or `uncertified (reason)` or `unavailable (reason)`: the line a report shows for a law. */
|
|
23
|
+
export function certificateLabel(certificate) {
|
|
24
|
+
return certificate.status === 'certified' || certificate.reason === undefined
|
|
25
|
+
? certificate.status
|
|
26
|
+
: `${certificate.status} (${certificate.reason})`;
|
|
27
|
+
}
|
|
28
|
+
/** Whether a certificate satisfies the mode: with `require`, only a certified proof does. */
|
|
29
|
+
export function certificateFailure(mode, certificate) {
|
|
30
|
+
if (mode !== 'require' || certificate.status === 'certified')
|
|
31
|
+
return undefined;
|
|
32
|
+
return `"certify": "require" is set but the proof is ${certificateLabel(certificate)}`;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* What cvc5's Alethe proofs cannot cover. Alethe has no rules for floating point or for strings and regular
|
|
36
|
+
* expressions, so a query that uses them has no proof Carcara could check. Returns the reason, or undefined when the
|
|
37
|
+
* query is in the fragment cvc5 can prove in Alethe.
|
|
38
|
+
*/
|
|
39
|
+
export function uncertifiable(query) {
|
|
40
|
+
const text = query.replace(/\|[^|]*\|/g, ' ');
|
|
41
|
+
if (/\b(?:FloatingPoint|Float(?:16|32|64|128)|RoundingMode)\b|\(\s*fp\.|\(\s*_\s+(?:to_fp|NaN|\+oo|-oo|\+zero|-zero)\b|\bR(?:NE|NA|TP|TN|TZ)\b/.test(text))
|
|
42
|
+
return 'the law uses floating-point numbers, which Alethe proofs do not cover (use int or bigint)';
|
|
43
|
+
if (/\bString\b|\(\s*(?:str|re)\.|\bRegLan\b/.test(text))
|
|
44
|
+
return 'the law uses strings, which Alethe proofs do not cover';
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The problem cvc5 and Carcara both read: the query as `cvc5Text` renders it (no Z3 timeout, no `(get-model)`, a logic
|
|
49
|
+
* set), so the proof is checked against exactly the text cvc5 proved.
|
|
50
|
+
*/
|
|
51
|
+
export const problemText = cvc5Text;
|
|
52
|
+
/**
|
|
53
|
+
* Options that make cvc5 print an Alethe proof Carcara can check.
|
|
54
|
+
*
|
|
55
|
+
* `--no-proof-alethe-res-pivots` matters: with pivots on, cvc5 names the pivot of each `resolution` step, and for a clause
|
|
56
|
+
* that repeats a literal (every integer range obligation does: `a` is bounded once per use) the named pivot is not found
|
|
57
|
+
* in the clause, so Carcara fails with "pivot was not found" on a proof that is sound. Without them Carcara finds each
|
|
58
|
+
* pivot itself. cvc5's own regression tests check Alethe proofs with this option off.
|
|
59
|
+
*/
|
|
60
|
+
export const cvc5ProofArgs = [
|
|
61
|
+
'--lang',
|
|
62
|
+
'smt2',
|
|
63
|
+
'--dump-proofs',
|
|
64
|
+
'--proof-format-mode=alethe',
|
|
65
|
+
'--proof-granularity=dsl-rewrite',
|
|
66
|
+
'--no-proof-alethe-res-pivots',
|
|
67
|
+
'--dag-thresh=0',
|
|
68
|
+
'--simplification=none',
|
|
69
|
+
'--enum-inst-interleave',
|
|
70
|
+
'--cegqi-all',
|
|
71
|
+
];
|
|
72
|
+
/** Carcara's arguments after `check <proof> <problem>`: the options cvc5's proofs need. */
|
|
73
|
+
export const carcaraArgs = ['--allow-int-real-subtyping', '--expand-let-bindings'];
|
|
74
|
+
export const hashOf = (text) => createHash('sha256').update(text).digest('hex');
|
|
75
|
+
/** Runs a tool to the end; resolves `undefined` when the binary cannot be started and `'timeout'` when it overran. */
|
|
76
|
+
function run(file, args, timeoutMs) {
|
|
77
|
+
return slots.run(() => spawnTool(file, args, timeoutMs));
|
|
78
|
+
}
|
|
79
|
+
function spawnTool(file, args, timeoutMs) {
|
|
80
|
+
return new Promise((resolve) => {
|
|
81
|
+
const child = spawn(file, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
|
|
82
|
+
lowerPriority(child.pid);
|
|
83
|
+
let stdout = '';
|
|
84
|
+
let stderr = '';
|
|
85
|
+
let finished = false;
|
|
86
|
+
const done = (value) => {
|
|
87
|
+
if (finished)
|
|
88
|
+
return;
|
|
89
|
+
finished = true;
|
|
90
|
+
clearTimeout(timer);
|
|
91
|
+
resolve(value);
|
|
92
|
+
};
|
|
93
|
+
const timer = setTimeout(() => {
|
|
94
|
+
child.kill();
|
|
95
|
+
done('timeout');
|
|
96
|
+
}, timeoutMs);
|
|
97
|
+
child.stdout.setEncoding('utf8').on('data', (chunk) => (stdout += chunk));
|
|
98
|
+
child.stderr.setEncoding('utf8').on('data', (chunk) => (stderr += chunk));
|
|
99
|
+
child.on('error', (error) => {
|
|
100
|
+
if (error.code === 'ENOENT' || error.code === 'EACCES')
|
|
101
|
+
done(undefined);
|
|
102
|
+
else
|
|
103
|
+
done({ stdout, stderr: error.message, code: null });
|
|
104
|
+
});
|
|
105
|
+
child.on('close', (code) => done({ stdout, stderr, code }));
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
const firstLine = (text) => text.trim().split('\n')[0]?.trim() ?? '';
|
|
109
|
+
const cvc5Missing = 'the cvc5 binary was not found: install cvc5 (https://cvc5.github.io) so that cvc5 is on the PATH, or set TSLAWS_CVC5 to its path';
|
|
110
|
+
const carcaraMissing = 'the carcara binary was not found: install Carcara (https://github.com/ufmg-smite/carcara) so that carcara is on the PATH, or set TSLAWS_CARCARA to its path';
|
|
111
|
+
/** The hash that binds a checker's verdict to the problem and the proof it checked. */
|
|
112
|
+
const checkerHashOf = (verdict, problemHash, proofHash) => hashOf(JSON.stringify({ verdict, problem: problemHash, proof: proofHash }));
|
|
113
|
+
/** The names of the RARE rewrite rules an Alethe proof applies. */
|
|
114
|
+
export function rareRulesOf(proof) {
|
|
115
|
+
const names = new Set();
|
|
116
|
+
for (const match of proof.matchAll(/:rule rare_rewrite\s+(?::premises\s+\([^)]*\)\s+)?:args\s+\(\s*"([^"]+)"/g))
|
|
117
|
+
names.add(match[1]);
|
|
118
|
+
return [...names];
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Rewrite rules that cvc5 1.4.2 cites in Alethe proofs but whose declarations Carcara cannot use from `-o rare-db`: it
|
|
122
|
+
* omits `ite-eq` (cvc5 issue 12801) and declares the integer `div` rule with `div_total`, which Carcara does not know.
|
|
123
|
+
* cvc5 keeps the Alethe form of these in proofs/alethe/rewrites.eo, and these are copied from there. Each states an
|
|
124
|
+
* identity that holds for every argument: `ite-eq` is the case split on `C`, and the `div` rule only restates a term
|
|
125
|
+
* under the premise that the divisor is not 0. (`ite-eq` has one sort variable for both branches: upstream writes `@T1`
|
|
126
|
+
* for the second and Carcara 1.1.0 does not accept that.) The integer `mod` rules are not here: a `mod` proof also needs
|
|
127
|
+
* `mod-elim`, which cvc5 1.4.2 does not declare either, and `tslaws` does not add a rule it cannot show to be sound, so
|
|
128
|
+
* a law with `mod` stays `uncertified` and the reason names the rule.
|
|
129
|
+
*/
|
|
130
|
+
const aletheRareRules = {
|
|
131
|
+
'ite-eq': [
|
|
132
|
+
'(declare-rare-rule ite-eq ((@T0 Type) (C Bool) (t1 @T0) (t2 @T0))',
|
|
133
|
+
' :args (C t1 t2)',
|
|
134
|
+
' :conclusion (= (ite C (= (ite C t1 t2) t1) (= (ite C t1 t2) t2)) true)',
|
|
135
|
+
')',
|
|
136
|
+
].join('\n'),
|
|
137
|
+
'arith-int-div-total': [
|
|
138
|
+
'(declare-rare-rule arith-int-div-total ((t1 Int) (s1 Int))',
|
|
139
|
+
' :premises ((= (= s1 0) false))',
|
|
140
|
+
' :args (t1 s1)',
|
|
141
|
+
' :conclusion (= (div t1 s1) (div t1 s1))',
|
|
142
|
+
')',
|
|
143
|
+
].join('\n'),
|
|
144
|
+
};
|
|
145
|
+
/**
|
|
146
|
+
* The RARE rule declarations for `names`, in the form Carcara reads. cvc5 itself prints its database of rewrite rules, so
|
|
147
|
+
* the rules a proof may lean on come from the same binary that wrote the proof and never from a file beside the proof;
|
|
148
|
+
* the few rules in `aletheRareRules` are the exception, because the binary's own text for them cannot be checked.
|
|
149
|
+
*/
|
|
150
|
+
export async function rareDeclarations(names, work, budget) {
|
|
151
|
+
const cvc5 = toolCommand('TSLAWS_CVC5', 'cvc5');
|
|
152
|
+
const input = join(work, 'rare.smt2');
|
|
153
|
+
writeFileSync(input, '(check-sat)\n');
|
|
154
|
+
const printed = await run(cvc5.file, [
|
|
155
|
+
...cvc5.args,
|
|
156
|
+
'-o',
|
|
157
|
+
'rare-db',
|
|
158
|
+
'--force-logic=ALL',
|
|
159
|
+
'--produce-proofs',
|
|
160
|
+
'--proof-granularity=dsl-rewrite',
|
|
161
|
+
'--proof-format-mode=alethe',
|
|
162
|
+
input,
|
|
163
|
+
], budget);
|
|
164
|
+
if (printed === undefined)
|
|
165
|
+
return { status: 'unavailable', reason: cvc5Missing };
|
|
166
|
+
if (printed === 'timeout')
|
|
167
|
+
return { status: 'uncertified', reason: `cvc5 did not print its rewrite rules within ${budget} ms` };
|
|
168
|
+
const blocks = new Map();
|
|
169
|
+
let current;
|
|
170
|
+
for (const line of printed.stdout.split(/\r?\n/)) {
|
|
171
|
+
const start = /^\(declare-rule\s+(\S+)/.exec(line);
|
|
172
|
+
if (start !== null)
|
|
173
|
+
current = { name: start[1], lines: [] };
|
|
174
|
+
if (current !== undefined)
|
|
175
|
+
current.lines.push(line);
|
|
176
|
+
if (current !== undefined && line === ')') {
|
|
177
|
+
blocks.set(current.name, current.lines.join('\n').replace('(declare-rule ', '(declare-rare-rule '));
|
|
178
|
+
current = undefined;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
const missing = names.filter((name) => !blocks.has(name) && aletheRareRules[name] === undefined);
|
|
182
|
+
if (missing.length > 0)
|
|
183
|
+
return {
|
|
184
|
+
status: 'uncertified',
|
|
185
|
+
reason: `cvc5 does not define the rewrite rules the proof uses: ${missing.join(', ')}`,
|
|
186
|
+
};
|
|
187
|
+
return { text: `${names.map((name) => aletheRareRules[name] ?? blocks.get(name)).join('\n')}\n` };
|
|
188
|
+
}
|
|
189
|
+
/** Runs Carcara on a saved proof and problem: `certified` (with its verdict) only when Carcara says `valid`. */
|
|
190
|
+
async function recheck(problemFile, proofFile, budget) {
|
|
191
|
+
const carcara = toolCommand('TSLAWS_CARCARA', 'carcara');
|
|
192
|
+
const rare = rareRulesOf(readFileSync(proofFile, 'utf8'));
|
|
193
|
+
const work = mkdtempSync(join(tmpdir(), 'tslaws-rare-'));
|
|
194
|
+
try {
|
|
195
|
+
const extra = [];
|
|
196
|
+
if (rare.length > 0) {
|
|
197
|
+
const declared = await rareDeclarations(rare, work, budget);
|
|
198
|
+
if (!('text' in declared))
|
|
199
|
+
return declared;
|
|
200
|
+
const rareFile = join(work, 'rules.rare');
|
|
201
|
+
writeFileSync(rareFile, declared.text);
|
|
202
|
+
extra.push('--rare-file', rareFile);
|
|
203
|
+
}
|
|
204
|
+
return await runCarcara(carcara, proofFile, problemFile, extra, budget);
|
|
205
|
+
}
|
|
206
|
+
finally {
|
|
207
|
+
rmSync(work, { recursive: true, force: true });
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
const terminalColours = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, 'g');
|
|
211
|
+
/** Carcara's first `error:` line, and the file it points at, from what it printed (without terminal colours). */
|
|
212
|
+
function carcaraError(output) {
|
|
213
|
+
const lines = output.replace(terminalColours, '').split(/\r?\n/);
|
|
214
|
+
const at = lines.findIndex((line) => line.startsWith('error:'));
|
|
215
|
+
if (at < 0)
|
|
216
|
+
return { error: '', file: undefined };
|
|
217
|
+
const located = lines.slice(at + 1, at + 4).find((line) => /\bin file\s/.test(line));
|
|
218
|
+
const file = located === undefined ? undefined : /\bin file\s+(\S+?)(?::\d+:\d+)?\s*$/.exec(located)?.[1];
|
|
219
|
+
return { error: lines[at].trim(), file };
|
|
220
|
+
}
|
|
221
|
+
async function runCarcara(carcara, proofFile, problemFile, extra, budget) {
|
|
222
|
+
const checked = await run(carcara.file, [...carcara.args, 'check', proofFile, problemFile, ...carcaraArgs, ...extra], budget);
|
|
223
|
+
if (checked === undefined)
|
|
224
|
+
return { status: 'unavailable', reason: carcaraMissing };
|
|
225
|
+
if (checked === 'timeout')
|
|
226
|
+
return { status: 'uncertified', reason: `Carcara did not finish within ${budget} ms` };
|
|
227
|
+
const verdict = firstLine(checked.stdout);
|
|
228
|
+
if (checked.code !== 0 || verdict !== 'valid') {
|
|
229
|
+
const { error, file } = carcaraError(`${checked.stdout}\n${checked.stderr}`);
|
|
230
|
+
// An error in the rules file is Carcara not reading what cvc5 declared; the proof was never checked, so it was not rejected.
|
|
231
|
+
if (file?.endsWith('.rare') === true)
|
|
232
|
+
return { status: 'uncertified', reason: `Carcara could not read the rewrite rules cvc5 declared (${error})` };
|
|
233
|
+
const why = verdict === 'holey'
|
|
234
|
+
? 'the proof has steps Carcara could not check'
|
|
235
|
+
: (verdict !== '' ? verdict : firstLine(checked.stderr)) || `exited with code ${checked.code}`;
|
|
236
|
+
return {
|
|
237
|
+
status: 'uncertified',
|
|
238
|
+
reason: `Carcara did not accept the proof (${error === '' ? why : `${why}: ${error}`})`,
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
return { status: 'certified', verdict };
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Certifies the `unsat` answer of a query: cvc5 proves it again in Alethe, Carcara checks the proof. Never throws for a
|
|
245
|
+
* missing or failing tool; the outcome is in the certificate's status.
|
|
246
|
+
*/
|
|
247
|
+
export async function certify(query, options) {
|
|
248
|
+
const reason = uncertifiable(query);
|
|
249
|
+
if (reason !== undefined)
|
|
250
|
+
return { status: 'uncertified', reason };
|
|
251
|
+
const problem = problemText(query);
|
|
252
|
+
const work = mkdtempSync(join(tmpdir(), 'tslaws-cert-'));
|
|
253
|
+
try {
|
|
254
|
+
const problemFile = join(work, 'problem.smt2');
|
|
255
|
+
const proofFile = join(work, 'proof.alethe');
|
|
256
|
+
writeFileSync(problemFile, problem);
|
|
257
|
+
// Alethe proofs are large; the budget covers cvc5's search and its printing.
|
|
258
|
+
const budget = Math.max(options.timeoutMs, 1000) + 3000;
|
|
259
|
+
const cvc5 = toolCommand('TSLAWS_CVC5', 'cvc5');
|
|
260
|
+
const proved = await run(cvc5.file, [...cvc5.args, ...cvc5ProofArgs, '--tlimit', String(options.timeoutMs), problemFile], budget);
|
|
261
|
+
if (proved === undefined)
|
|
262
|
+
return { status: 'unavailable', reason: cvc5Missing };
|
|
263
|
+
if (proved === 'timeout')
|
|
264
|
+
return { status: 'uncertified', reason: `cvc5 gave no proof within ${budget} ms` };
|
|
265
|
+
const answer = firstLine(proved.stdout);
|
|
266
|
+
if (proved.code !== 0 || answer !== 'unsat') {
|
|
267
|
+
const why = answer !== '' ? answer : firstLine(proved.stderr) || `exited with code ${proved.code}`;
|
|
268
|
+
return { status: 'uncertified', reason: `cvc5 gave no Alethe proof (${why})` };
|
|
269
|
+
}
|
|
270
|
+
const proof = proved.stdout.slice(proved.stdout.indexOf('\n') + 1).trim();
|
|
271
|
+
if (proof === '')
|
|
272
|
+
return { status: 'uncertified', reason: 'cvc5 answered unsat but printed no proof' };
|
|
273
|
+
writeFileSync(proofFile, `${proof}\n`);
|
|
274
|
+
const checked = await recheck(problemFile, proofFile, budget);
|
|
275
|
+
if (checked.status !== 'certified')
|
|
276
|
+
return checked;
|
|
277
|
+
const verdict = checked.verdict;
|
|
278
|
+
const problemHash = hashOf(problem);
|
|
279
|
+
const proofHash = hashOf(`${proof}\n`);
|
|
280
|
+
const certificate = {
|
|
281
|
+
status: 'certified',
|
|
282
|
+
problemHash,
|
|
283
|
+
proofHash,
|
|
284
|
+
checkerHash: checkerHashOf(verdict, problemHash, proofHash),
|
|
285
|
+
...(options.horn === undefined ? {} : { systemHash: hashOf(options.horn.horn) }),
|
|
286
|
+
};
|
|
287
|
+
if (options.keep !== undefined) {
|
|
288
|
+
const { dir, name, root } = options.keep;
|
|
289
|
+
mkdirSync(dir, { recursive: true });
|
|
290
|
+
writeFileSync(join(dir, `${name}.smt2`), problem);
|
|
291
|
+
writeFileSync(join(dir, `${name}.alethe`), `${proof}\n`);
|
|
292
|
+
if (options.horn !== undefined) {
|
|
293
|
+
writeFileSync(join(dir, `${name}.horn`), options.horn.horn);
|
|
294
|
+
writeFileSync(join(dir, `${name}.inv`), options.horn.invariants);
|
|
295
|
+
}
|
|
296
|
+
certificate.proofFile = join(dir, `${name}.alethe`)
|
|
297
|
+
.slice(root.length + 1)
|
|
298
|
+
.replaceAll('\\', '/');
|
|
299
|
+
}
|
|
300
|
+
return certificate;
|
|
301
|
+
}
|
|
302
|
+
finally {
|
|
303
|
+
rmSync(work, { recursive: true, force: true });
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Certifies a proof by loop invariants. The invariants Z3's Spacer found are put back into the clauses
|
|
308
|
+
* (`certificationProblem`), and the problem that results is an ordinary query, refuted by cvc5 and checked by Carcara
|
|
309
|
+
* like any other: a certificate says that the invariants hold at entry, are kept by every pass of the body, and imply the
|
|
310
|
+
* law, and Spacer needs no more trust than a guess does.
|
|
311
|
+
*/
|
|
312
|
+
export async function certifyHorn(certification, options) {
|
|
313
|
+
const query = certificationProblem(certification.horn, certification.invariants);
|
|
314
|
+
if (query === undefined)
|
|
315
|
+
return {
|
|
316
|
+
status: 'uncertified',
|
|
317
|
+
reason: 'the loop invariants could not be put back into the clauses to be checked',
|
|
318
|
+
};
|
|
319
|
+
return certify(query, { ...options, horn: certification });
|
|
320
|
+
}
|
|
321
|
+
/** What binds a record to the code: the Horn text for a loop proof, the problem itself for any other. */
|
|
322
|
+
export const bindingOf = (hashes) => hashes.systemHash ?? hashes.problemHash;
|
|
323
|
+
/** The file name a law's problem and proof are kept under, beside `.tslaws/certificates/`. */
|
|
324
|
+
export function certificateName(key) {
|
|
325
|
+
const slug = key
|
|
326
|
+
.slice(key.indexOf('::') + 2)
|
|
327
|
+
.replace(/[^A-Za-z0-9]+/g, '-')
|
|
328
|
+
.slice(0, 40);
|
|
329
|
+
return `${slug}-${hashOf(key).slice(0, 8)}`;
|
|
330
|
+
}
|
|
331
|
+
/** Where `tslaws check` keeps the problems and proofs of the laws it certified. */
|
|
332
|
+
export const certificatesDir = (cwd) => join(cwd, '.tslaws', 'certificates');
|
|
333
|
+
/**
|
|
334
|
+
* Where `tslaws check` leaves the records of the laws it certified, for `tslaws accept` to consider. Anyone can write this
|
|
335
|
+
* file, so accept trusts none of it: see `verifyRecord`.
|
|
336
|
+
*/
|
|
337
|
+
export const recordsPath = (cwd) => join(cwd, '.tslaws', 'certificates.json');
|
|
338
|
+
export function readRecords(cwd) {
|
|
339
|
+
const path = recordsPath(cwd);
|
|
340
|
+
if (!existsSync(path))
|
|
341
|
+
return {};
|
|
342
|
+
try {
|
|
343
|
+
const value = JSON.parse(readFileSync(path, 'utf8'));
|
|
344
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : {};
|
|
345
|
+
}
|
|
346
|
+
catch {
|
|
347
|
+
return {};
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Updates the records after a check: each law that was proved or bounded has its record replaced by the new one when it
|
|
352
|
+
* is certified and removed when it is not (a law that did not run keeps what it had).
|
|
353
|
+
*/
|
|
354
|
+
export function writeRecords(cwd, updates) {
|
|
355
|
+
const records = readRecords(cwd);
|
|
356
|
+
for (const [key, record] of updates) {
|
|
357
|
+
if (record === undefined)
|
|
358
|
+
delete records[key];
|
|
359
|
+
else
|
|
360
|
+
records[key] = record;
|
|
361
|
+
}
|
|
362
|
+
const path = recordsPath(cwd);
|
|
363
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
364
|
+
writeFileSync(path, JSON.stringify(records, null, 2) + '\n');
|
|
365
|
+
}
|
|
366
|
+
const isHash = (value) => typeof value === 'string' && /^[0-9a-f]{64}$/.test(value);
|
|
367
|
+
/**
|
|
368
|
+
* Whether a record from the sidecar may enter the lock, or why not. Nothing in the sidecar is trusted. The record must
|
|
369
|
+
* be for the law as it is now (`lawNow`) and for a problem the law still yields (`problems`, the hashes of the problems
|
|
370
|
+
* `tslaws accept` rebuilt from the code); the saved problem and proof must exist and hash as the record says; and
|
|
371
|
+
* Carcara must accept them again, here and now. With Carcara missing nothing is kept.
|
|
372
|
+
*/
|
|
373
|
+
export async function verifyRecord(cwd, key, record, lawNow, problems, timeoutMs = 20000) {
|
|
374
|
+
const r = record;
|
|
375
|
+
if (typeof r !== 'object' || r === null || !isHash(r.problemHash) || !isHash(r.proofHash) || !isHash(r.checkerHash))
|
|
376
|
+
return 'the record is malformed';
|
|
377
|
+
if (r.law !== lawNow)
|
|
378
|
+
return 'the law changed since it was certified';
|
|
379
|
+
if (r.systemHash !== undefined && !isHash(r.systemHash))
|
|
380
|
+
return 'the record is malformed';
|
|
381
|
+
if (!problems.has(bindingOf(r)))
|
|
382
|
+
return 'the record is for a different proof problem than the law yields now';
|
|
383
|
+
const name = certificateName(key);
|
|
384
|
+
const problemFile = join(certificatesDir(cwd), `${name}.smt2`);
|
|
385
|
+
const proofFile = join(certificatesDir(cwd), `${name}.alethe`);
|
|
386
|
+
if (!existsSync(problemFile) || !existsSync(proofFile))
|
|
387
|
+
return 'the saved problem or proof is missing';
|
|
388
|
+
const savedProblem = readFileSync(problemFile, 'utf8');
|
|
389
|
+
if (hashOf(savedProblem) !== r.problemHash)
|
|
390
|
+
return 'the saved problem does not match the record';
|
|
391
|
+
if (r.systemHash !== undefined) {
|
|
392
|
+
// A loop proof: the saved problem must be what the invariants make of the Horn text the code yields, and nothing else.
|
|
393
|
+
const hornFile = join(certificatesDir(cwd), `${name}.horn`);
|
|
394
|
+
const invariantFile = join(certificatesDir(cwd), `${name}.inv`);
|
|
395
|
+
if (!existsSync(hornFile) || !existsSync(invariantFile))
|
|
396
|
+
return 'the saved clauses or invariants are missing';
|
|
397
|
+
const horn = readFileSync(hornFile, 'utf8');
|
|
398
|
+
if (hashOf(horn) !== r.systemHash)
|
|
399
|
+
return 'the saved clauses do not match the record';
|
|
400
|
+
const query = certificationProblem(horn, readFileSync(invariantFile, 'utf8'));
|
|
401
|
+
if (query === undefined || problemText(query) !== savedProblem)
|
|
402
|
+
return 'the saved invariants do not turn the clauses into the saved problem';
|
|
403
|
+
}
|
|
404
|
+
if (hashOf(readFileSync(proofFile, 'utf8')) !== r.proofHash)
|
|
405
|
+
return 'the saved proof does not match the record';
|
|
406
|
+
const checked = await recheck(problemFile, proofFile, timeoutMs);
|
|
407
|
+
if (checked.status !== 'certified')
|
|
408
|
+
return checked.reason;
|
|
409
|
+
if (checkerHashOf(checked.verdict, r.problemHash, r.proofHash) !== r.checkerHash)
|
|
410
|
+
return 'the checker verdict does not match the record';
|
|
411
|
+
return undefined;
|
|
412
|
+
}
|
|
413
|
+
/** The record for a certified certificate, or undefined for any other. */
|
|
414
|
+
export function recordOf(lawHash, certificate) {
|
|
415
|
+
if (certificate.status !== 'certified')
|
|
416
|
+
return undefined;
|
|
417
|
+
return {
|
|
418
|
+
law: lawHash,
|
|
419
|
+
problemHash: certificate.problemHash,
|
|
420
|
+
...(certificate.systemHash === undefined ? {} : { systemHash: certificate.systemHash }),
|
|
421
|
+
proofHash: certificate.proofHash,
|
|
422
|
+
checkerHash: certificate.checkerHash,
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
/** The certificate a proved or bounded law gets when certifying is on but no proof was checked. */
|
|
426
|
+
export const noCertificate = { status: 'uncertified', reason: 'no certificate produced' };
|
|
427
|
+
/**
|
|
428
|
+
* Whether a lock record still describes what a run just proved: the same problem. A law with no record, or a run
|
|
429
|
+
* that did not certify it, has nothing to compare.
|
|
430
|
+
*/
|
|
431
|
+
export function staleRecord(record, certificate) {
|
|
432
|
+
return record !== undefined && (certificate.status !== 'certified' || bindingOf(certificate) !== bindingOf(record));
|
|
433
|
+
}
|
package/dist/chc.d.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/** One unknown predicate: the invariant of one loop, over the variables live at the loop. */
|
|
2
|
+
export interface Predicate {
|
|
3
|
+
name: string;
|
|
4
|
+
/** The SMT sort of each argument. */
|
|
5
|
+
sorts: string[];
|
|
6
|
+
/** What each argument is called in the source, for showing the invariant. */
|
|
7
|
+
names: string[];
|
|
8
|
+
}
|
|
9
|
+
/** A clause set with every free constant universally quantified, as Spacer needs. */
|
|
10
|
+
export interface HornSystem {
|
|
11
|
+
predicates: Predicate[];
|
|
12
|
+
/** Every constant a clause mentions; each clause is closed over all of them. */
|
|
13
|
+
constants: {
|
|
14
|
+
name: string;
|
|
15
|
+
sort: string;
|
|
16
|
+
}[];
|
|
17
|
+
/** `(=> body head)` clauses, with constants free. */
|
|
18
|
+
clauses: string[];
|
|
19
|
+
/** Terms the executor named to keep its formulas short (`_s3`); expanded in place, since a clause is closed. */
|
|
20
|
+
shared: Map<string, string>;
|
|
21
|
+
}
|
|
22
|
+
export type ExternalAnswer = {
|
|
23
|
+
solver: string;
|
|
24
|
+
answer: 'sat' | 'unsat' | 'unknown' | 'timeout' | 'error';
|
|
25
|
+
detail?: string;
|
|
26
|
+
};
|
|
27
|
+
export interface Engine {
|
|
28
|
+
/** Z3: runs a script, and `values` after a `sat`. */
|
|
29
|
+
z3: (query: string, values: string, timeoutMs: number) => Promise<{
|
|
30
|
+
out: string;
|
|
31
|
+
vals: string;
|
|
32
|
+
}>;
|
|
33
|
+
/** The other CHC solvers that are installed, on the same system. */
|
|
34
|
+
external: (query: string, timeoutMs: number) => Promise<ExternalAnswer[]>;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* What a proof certificate for a loop proof is made from: the Horn system as `hornText` prints it (no timeout, so it is
|
|
38
|
+
* the same text every run) and the `define-fun` of each invariant as Z3 printed it. The invariants are guesses that need
|
|
39
|
+
* no trust: `certificationProblem` puts them back into the clauses, and the problem it makes is unsatisfiable only when
|
|
40
|
+
* each clause holds with them.
|
|
41
|
+
*/
|
|
42
|
+
export interface HornCertification {
|
|
43
|
+
horn: string;
|
|
44
|
+
invariants: string;
|
|
45
|
+
}
|
|
46
|
+
export type ChcVerdict =
|
|
47
|
+
/** A verified invariant for every loop; `notes` says which other solvers confirmed it or could not. */
|
|
48
|
+
{
|
|
49
|
+
kind: 'safe';
|
|
50
|
+
invariants: string[];
|
|
51
|
+
notes: string[];
|
|
52
|
+
certification: HornCertification;
|
|
53
|
+
}
|
|
54
|
+
/** Spacer found the clauses contradictory: the law may fail (the unrolled proof looks for the input). */
|
|
55
|
+
| {
|
|
56
|
+
kind: 'unsafe';
|
|
57
|
+
}
|
|
58
|
+
/** No answer, or an answer that did not verify. */
|
|
59
|
+
| {
|
|
60
|
+
kind: 'unknown';
|
|
61
|
+
reason: string;
|
|
62
|
+
}
|
|
63
|
+
/** Spacer and another solver gave opposite answers. */
|
|
64
|
+
| {
|
|
65
|
+
kind: 'disagree';
|
|
66
|
+
reason: string;
|
|
67
|
+
};
|
|
68
|
+
/** The SMT-LIB script Spacer (and any other CHC solver) reads. */
|
|
69
|
+
export declare function hornText(system: HornSystem, timeoutMs?: number): string;
|
|
70
|
+
/**
|
|
71
|
+
* The SMT-LIB problem that proves a loop proof, from the Horn text and the invariants of a `HornCertification`: every
|
|
72
|
+
* constant of the clauses declared, each invariant put in place of its predicate, and one assertion that some clause
|
|
73
|
+
* fails. It has no quantifiers and no unknown predicate, so cvc5 can refute it with an Alethe proof and Carcara can check
|
|
74
|
+
* that proof. Because some constant can break one clause exactly when some constant breaks a clause, the problem is
|
|
75
|
+
* unsatisfiable exactly when every clause holds for every value, that is, when the invariants are inductive and make the
|
|
76
|
+
* law hold. Undefined when the invariants do not match the predicates the text declares.
|
|
77
|
+
*/
|
|
78
|
+
export declare function certificationProblem(horn: string, invariants: string): string | undefined;
|
|
79
|
+
/**
|
|
80
|
+
* Looks for an invariant for every loop in `system`, verifies it, and has the installed CHC solvers confirm it.
|
|
81
|
+
* Never throws: anything that goes wrong is an `unknown` verdict, and the caller falls back to unrolling.
|
|
82
|
+
*/
|
|
83
|
+
export declare function solveHorn(system: HornSystem, engine: Engine, timeoutMs: number): Promise<ChcVerdict>;
|
|
84
|
+
/** Runs each installed solver (`TSLAWS_ELDARICA` and `TSLAWS_GOLEM`, else `eld` and `golem` on the PATH) on the system. */
|
|
85
|
+
export declare function runExternalSolvers(query: string, timeoutMs: number): Promise<ExternalAnswer[]>;
|