lawspec 0.24.0 → 0.25.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 (87) hide show
  1. package/CHANGELOG.md +67 -1
  2. package/README.md +29 -22
  3. package/UNICODE-LICENSE.txt +39 -0
  4. package/api.mjs +14 -23
  5. package/bin/lawspec.mjs +186 -65
  6. package/build.json +255 -159
  7. package/builtin-data-names.mjs +73 -0
  8. package/core.wasm +2 -2
  9. package/examples/native-payments/clojure/lawspec.json +13 -2
  10. package/examples/native-payments/csharp/lawspec.json +13 -2
  11. package/examples/native-payments/elixir/lawspec.json +14 -3
  12. package/examples/native-payments/erlang/lawspec.json +14 -3
  13. package/examples/native-payments/fsharp/lawspec.json +14 -3
  14. package/examples/native-payments/gleam/lawspec.json +14 -3
  15. package/examples/native-payments/go/lawspec.json +14 -3
  16. package/examples/native-payments/groovy/lawspec.json +14 -3
  17. package/examples/native-payments/haskell/lawspec.json +14 -3
  18. package/examples/native-payments/java/lawspec.json +14 -3
  19. package/examples/native-payments/javascript/lawspec.json +14 -3
  20. package/examples/native-payments/kotlin/lawspec.json +14 -3
  21. package/examples/native-payments/python/lawspec.json +14 -3
  22. package/examples/native-payments/rust/lawspec.json +14 -3
  23. package/examples/native-payments/scala/lawspec.json +14 -3
  24. package/examples/native-payments/swift/lawspec.json +14 -3
  25. package/examples/native-payments/typescript/lawspec.json +14 -3
  26. package/examples/packages/orders/lawspec.json +25 -5
  27. package/examples/packages/orders/orders.lawspec +36 -34
  28. package/examples/packages/shop-domain/src/domain.lawspec +23 -21
  29. package/examples/packages/shop-tax-1/src/rates.lawspec +4 -4
  30. package/examples/packages/shop-tax-2/src/rates.lawspec +5 -4
  31. package/examples/rc1/authorization-snapshots.lawspec +112 -0
  32. package/examples/rc1/banner-filenames.lawspec +63 -0
  33. package/examples/rc1/bit-codec.lawspec +56 -0
  34. package/examples/rc1/bounded-witness-search.lawspec +144 -0
  35. package/examples/rc1/conflicting-requirements.lawspec +30 -0
  36. package/examples/rc1/constructive-witnesses.lawspec +113 -0
  37. package/examples/rc1/documentary-review.lawspec +42 -0
  38. package/examples/rc1/empty-domains.lawspec +46 -0
  39. package/examples/rc1/finite-integer-domains.lawspec +75 -0
  40. package/examples/rc1/law-metadata.lawspec +29 -0
  41. package/examples/rc1/native-payments.lawspec +107 -0
  42. package/examples/rc1/nesting/rrr.lawspec +33 -0
  43. package/examples/rc1/nesting/rru.lawspec +56 -0
  44. package/examples/rc1/nesting/rur.lawspec +57 -0
  45. package/examples/rc1/nesting/ruu.lawspec +77 -0
  46. package/examples/rc1/nesting/urr.lawspec +52 -0
  47. package/examples/rc1/nesting/uru.lawspec +72 -0
  48. package/examples/rc1/nesting/uur.lawspec +73 -0
  49. package/examples/rc1/nesting/uuu.lawspec +95 -0
  50. package/examples/rc1/order-workflow.lawspec +126 -0
  51. package/examples/rc1/parcel-measurements.lawspec +92 -0
  52. package/examples/rc1/picture-records.lawspec +51 -0
  53. package/examples/rc1/picture-tuples.lawspec +47 -0
  54. package/examples/rc1/record-payloads.lawspec +56 -0
  55. package/examples/rc1/recursive-records.lawspec +64 -0
  56. package/examples/rc1/refund-conformance.lawspec +44 -0
  57. package/examples/rc1/refund-policy.lawspec +88 -0
  58. package/examples/rc1/requirement-composition.lawspec +89 -0
  59. package/examples/rc1/structural-records.lawspec +53 -0
  60. package/examples/rc1-authoring.lawspec +56 -0
  61. package/examples-command.mjs +11 -5
  62. package/explain.mjs +112 -0
  63. package/expression-presentation.mjs +333 -0
  64. package/files.mjs +16 -0
  65. package/index.d.ts +929 -11
  66. package/lsp.mjs +231 -0
  67. package/migrate.mjs +135 -0
  68. package/migration-bindings.mjs +86 -0
  69. package/migration-cases.mjs +45 -0
  70. package/migration-collections.mjs +54 -0
  71. package/migration-correspondence.mjs +275 -0
  72. package/migration-generation.mjs +99 -0
  73. package/migration-laws.mjs +102 -0
  74. package/migration-records.mjs +166 -0
  75. package/migration-source.mjs +247 -0
  76. package/migration-write.mjs +156 -0
  77. package/native-evidence.mjs +187 -0
  78. package/native-examples.mjs +8 -1
  79. package/node-events-reporter.mjs +23 -0
  80. package/package.json +8 -1
  81. package/positional-fields.mjs +13 -0
  82. package/proof.d.ts +35 -0
  83. package/proof.mjs +174 -0
  84. package/starter-rc1.lawspec +25 -0
  85. package/templates.mjs +2 -2
  86. package/test-command.mjs +107 -35
  87. package/typed-presentation.mjs +165 -0
@@ -0,0 +1,187 @@
1
+ // Generated from templates/npm/native-evidence.mjs by lawspec-dev generate. Do not edit.
2
+ import {readFile} from 'node:fs/promises';
3
+ import {isDeepStrictEqual} from 'node:util';
4
+ import path from 'node:path';
5
+ import {doctor} from './doctor.mjs';
6
+ import {planWrites} from './files.mjs';
7
+ import {projectKey} from './failure-database.mjs';
8
+ import {lawKeys,environmentDigest,recordedDigest,projectDigest,invocations} from './test-command.mjs';
9
+
10
+ // Native execution observations are scoped to actual completed test slots.
11
+ // They never establish a universal model proof or a witness-search completeness claim.
12
+ export const obligationTargets = entry => entry.obligations ?? [{declaration:entry.law,stage:'law'}];
13
+
14
+ export function nativeSeed(value){
15
+ const text=String(value),number=Number(text);
16
+ if(!/^[0-9]+$/.test(text))throw new Error('A native seed must be a whole number');
17
+ if(typeof value==='number'&&!Number.isSafeInteger(value))
18
+ throw new Error('The recorded numeric seed lost precision; rerun with an explicit exact seed');
19
+ return Number.isSafeInteger(number)?number:text;
20
+ }
21
+
22
+ export function recordNativeAttempts(run, tests, {keys,seed,ok,profile,output,allEntries=run.laws,at=new Date().toISOString()}) {
23
+ return Object.fromEntries((run.laws??[]).map(entry=>{
24
+ const matched=tests.filter(test=>(run.matches?.(test)??[]).includes(entry));
25
+ const model=(entry.obligations?.length??0)>0;
26
+ const complete=matched.length>0&&matched.every(test=>test.status==='passed')&&(ok||model);
27
+ const outcome=matched.some(test=>test.status==='failed')?'failed':
28
+ entry.skip?'skipped':complete?(entry.knownFailing?'known-failing':'passed'):
29
+ matched.length&&matched.every(test=>test.status==='skipped')?'skipped':'incomplete';
30
+ return [entry.law,{key:keys.get(entry.law),planKey:entry.key,seed:nativeSeed(seed),at,outcome,
31
+ profile,coverage:entry.coverage??{kind:'sampled',scopedQuantifiers:true},check:{id:entry.law,unit:entry.unit,file:entry.file,name:entry.name,label:entry.label,
32
+ ...(entry.scope?{scope:entry.scope}:{}),obligations:obligationTargets(entry),
33
+ nativeGroup:(allEntries??[]).filter(other=>other.file===entry.file&&other.name===entry.name&&other.scope===entry.scope)
34
+ .map(other=>other.law)},
35
+ // A passed combined method covers all its logical model aliases. A failed
36
+ // combined method completes none successfully, even if another method passed.
37
+ tests:matched,invocation:{ok,command:run.command,
38
+ ...(!ok&&['failed','incomplete'].includes(outcome)&&output&&
39
+ !matched.some(test=>test.status==='failed'&&(test.failure||test.reason||test.message))?{output}: {})},
40
+ verification:'native-execution',searchCompleteness:'not-established'}];
41
+ }));
42
+ }
43
+
44
+ export function attestedKeys(result) {
45
+ return new Map((result.evidence??[]).filter(item=>item.against||item.plannedAgainst)
46
+ .map(item=>[item.declaration,JSON.stringify([
47
+ item.environment??item.plannedEnvironment,item.against??item.plannedAgainst])]));
48
+ }
49
+
50
+ const subject = (entry,item) => obligationTargets(entry).some(target=>
51
+ target.declaration===item.declaration&&target.stage===item.stage);
52
+ const runtimeStages=new Set(['law','model','linearizable','sequentially consistent','causally consistent',
53
+ 'eventually consistent','restart','scenario','supervision']);
54
+
55
+ // Only observations with matching current compiler/configuration/source/native
56
+ // inputs are eligible for completed evidence. A stored timestamp alone is not.
57
+ export async function readNativeObservations({compiler,input,selected,roots,configRoot,build,evidence,attestation}) {
58
+ const records=await Promise.all(selected.map(async(target,index)=>{
59
+ const root=roots[index],file=path.join(configRoot,'.lawspec/results',`${target.language}-${projectKey(root)}.json`);
60
+ const record=JSON.parse(await readFile(file,'utf8').catch(error=>{
61
+ if(error.code==='ENOENT')return '{}';throw error;
62
+ }));
63
+ return {target,root,attempts:record.attempts??{},runs:record.laws??{}};
64
+ }));
65
+ if(!records.some(record=>Object.keys(record.attempts).length))return [];
66
+ const observations=[];
67
+ for(const {target,root,attempts,runs}of records){
68
+ const plans=new Map(),contexts=new Map();
69
+ async function plan(minify){
70
+ if(!plans.has(minify))plans.set(minify,await compiler.planGeneration({...input,target:target.language,
71
+ sourceDir:target.sourceDir,testDir:target.testDir,nativeBindings:target.nativeBindings,minify,
72
+ ...(attestation?{attestation}:{})}));
73
+ return plans.get(minify);
74
+ }
75
+ const modes=[...new Set(Object.values(attempts).map(attempt=>attempt.profile?.minify)
76
+ .filter(mode=>typeof mode==='boolean'))];
77
+ if(!modes.length)modes.push(false);
78
+ const base=await plan(modes[0]);
79
+ if(base.diagnostics.length){
80
+ observations.push({target:target.language,root,freshness:'unavailable',outcome:'incomplete',
81
+ obligations:evidence.filter(item=>runtimeStages.has(item.stage)).map(({declaration,stage})=>({declaration,stage})),
82
+ reason:'Native generation is unavailable: '+base.diagnostics.map(diagnostic=>diagnostic.message).join('; ')});
83
+ continue;
84
+ }
85
+ const expected=new Map(base.tests.map(entry=>[entry.law,entry]));
86
+ async function context(minify){
87
+ if(contexts.has(minify))return contexts.get(minify);
88
+ const generated=await plan(minify);
89
+ let result;
90
+ if(generated.diagnostics.length)result={reason:'Native generation is unavailable for the recorded layout'};
91
+ else {
92
+ const pending=await planWrites(root,generated.files);
93
+ if(pending.changes.length)result={stale:true,reason:'Generated files differ from the recorded/current plan'};
94
+ else {
95
+ const report=await doctor(target,root,generated.files);
96
+ if(!report.ok)result={reason:'The current native environment could not be checked: '+report.message};
97
+ else {
98
+ const owned=new Set(generated.files.filter(file=>file.ownership==='generated').map(file=>file.path));
99
+ const keys=lawKeys({build,target,machineBits:input.machineBits,minify,tests:generated.tests,files:generated.files,
100
+ environment:await environmentDigest(root,report)+await recordedDigest(path.join(configRoot,'recorded')),
101
+ project:await projectDigest(root,owned),attested:attestedKeys(generated)});
102
+ result={generated,keys};
103
+ }
104
+ }
105
+ }
106
+ contexts.set(minify,result);return result;
107
+ }
108
+ for(const [id,baseline]of expected){
109
+ const attempt=attempts[id];
110
+ const row={target:target.language,root,check:{id,obligations:obligationTargets(baseline)},
111
+ outcome:attempt?.outcome??'not-run',coverage:baseline.coverage,attempt};
112
+ if(!attempt){observations.push({...row,freshness:'not-run',reason:'No completed native observation was recorded'});continue;}
113
+ const profile=attempt.profile??{};
114
+ if(profile.target!==target.language||profile.root!==root||profile.machineBits!==input.machineBits||profile.build!==build||
115
+ typeof profile.minify!=='boolean'){
116
+ observations.push({...row,freshness:'stale',reason:'Compiler, target or machine profile differs'});continue;
117
+ }
118
+ const current=await context(profile.minify);
119
+ if(current.reason){observations.push({...row,freshness:current.stale?'stale':'unavailable',reason:current.reason});continue;}
120
+ const entry=current.generated.tests.find(entry=>entry.law===id);
121
+ if(!entry||attempt.key!==current.keys.get(id)||attempt.planKey!==entry.key||
122
+ !isDeepStrictEqual(attempt.check?.obligations,obligationTargets(entry))||
123
+ !isDeepStrictEqual(attempt.coverage,entry.coverage)){
124
+ observations.push({...row,freshness:'stale',reason:'Specification, selection, bindings, native source or toolchain inputs differ'});continue;
125
+ }
126
+ const invocation=invocations(target,[entry],{root}).find(run=>run.laws?.includes(entry));
127
+ const validSeed=(typeof attempt.seed==='number'&&Number.isSafeInteger(attempt.seed)&&attempt.seed>=0)||
128
+ (typeof attempt.seed==='string'&&/^[0-9]+$/.test(attempt.seed));
129
+ const recomputed=validSeed&&Number.isFinite(Date.parse(attempt.at))&&invocation&&Array.isArray(attempt.tests)&&recordNativeAttempts(invocation,attempt.tests,
130
+ {keys:current.keys,seed:attempt.seed,ok:attempt.invocation?.ok===true,profile,at:attempt.at,
131
+ allEntries:current.generated.tests})[id];
132
+ if(!recomputed||recomputed.outcome!==attempt.outcome||
133
+ !isDeepStrictEqual(recomputed.check.nativeGroup,attempt.check?.nativeGroup)){
134
+ observations.push({...row,freshness:'unavailable',reason:'The stored observation does not establish the current native completion'});continue;
135
+ }
136
+ const run=runs[id];
137
+ observations.push({...row,freshness:'matching-inputs',
138
+ ...(attempt.outcome==='passed'&&run?.key===attempt.key&&(run.flaky||run.adequacy)?
139
+ {harness:{...(run.flaky?{flaky:true}:{}),...(run.adequacy?{adequacy:run.adequacy}:{})}}:{}),
140
+ reason:attempt.outcome==='passed'?'Recorded native completion matches the current inputs':'Recorded native attempt matches the current inputs'});
141
+ }
142
+ for(const [id,attempt]of Object.entries(attempts))if(!expected.has(id)&&Array.isArray(attempt.check?.obligations))
143
+ observations.push({target:target.language,root,check:attempt.check,attempt,outcome:attempt.outcome,
144
+ coverage:attempt.coverage,freshness:'not-selected',reason:'This native check is not selected by the current configuration'});
145
+ }
146
+ return observations;
147
+ }
148
+
149
+ export function attachNativeEvidence(evidence,observations){
150
+ return evidence.map(item=>{
151
+ const rows=observations.filter(row=>row.check?subject({obligations:row.check.obligations},item):
152
+ row.obligations?.some(target=>target.declaration===item.declaration&&target.stage===item.stage));
153
+ if(!rows.length)return item;
154
+ const current=rows.filter(row=>row.freshness==='matching-inputs');
155
+ const failed=current.filter(row=>row.outcome==='failed');
156
+ const combinedFailure=failed.some(row=>(row.attempt?.check.nativeGroup?.length??0)>1);
157
+ const status=failed.length?(combinedFailure?'incomplete':'failed'):
158
+ current.length===rows.length&&current.every(row=>row.outcome==='passed')?'passed':
159
+ current.length===rows.length&&current.every(row=>row.outcome==='skipped')?'skipped':
160
+ current.length===rows.length&&current.every(row=>row.outcome==='known-failing')?'known-failing':
161
+ current.some(row=>row.outcome==='passed')?'partial':
162
+ current.some(row=>['incomplete','not-run'].includes(row.outcome))?'incomplete':
163
+ rows.every(row=>row.freshness==='not-selected')?'not-selected':
164
+ rows.some(row=>row.freshness==='stale')?'stale':'unavailable';
165
+ const completeFinite=status==='passed'&&rows.every(row=>row.coverage?.kind==='finite-inputs'&&
166
+ row.coverage.scopedQuantifiers===false);
167
+ const nativeEvidence={kind:'native-conformance',status,
168
+ searchCompleteness:completeFinite?'complete-finite-inputs':'not-established',observations:rows};
169
+ const adequacy=current.flatMap(row=>row.harness?.adequacy??[]);
170
+ const enriched={...item,nativeEvidence,...(adequacy.length?{adequacy}:{})};
171
+ if(item.status!=='planned')return enriched;
172
+ const flaky=current.some(row=>row.harness?.flaky);
173
+ if(status==='passed')return {...enriched,plannedEvidence:{status:item.status,reason:item.reason},
174
+ status:flaky?'flaky':completeFinite?'exhaustively-checked':'property-tested',
175
+ reason:`Recorded native checks completed for ${new Set(rows.map(row=>row.target+'\0'+row.root)).size} requested target(s); `+
176
+ (completeFinite?'every finite input was checked.':'this is scoped native execution evidence, not a universal model or search proof.')+
177
+ (flaky?' Its last run failed, then passed on a retry.':'')};
178
+ if(['failed','incomplete'].includes(status))return {...enriched,
179
+ plannedEvidence:{status:item.status,reason:item.reason},status:'incomplete',
180
+ reason:combinedFailure?'A combined native method failed; the specific included logical check is not identified, and no successful conformance result is established.':
181
+ status==='failed'?'A recorded native implementation check failed; no successful conformance result is established.':
182
+ 'Native execution did not complete all selected checks; no successful conformance result is established.'};
183
+ return enriched;
184
+ });
185
+ }
186
+
187
+ export {nativeEvidenceText} from './explain.mjs';
@@ -19,7 +19,7 @@ async function projectFiles(directory, prefix = '') {
19
19
  export async function exportNativePayments(options, selected) {
20
20
  const root = await safePath(process.cwd(), options.output || 'native_payments');
21
21
  await mkdir(root, {recursive: true});
22
- const law = await readFile(new URL('./examples/specs/payments.lawspec', import.meta.url), 'utf8');
22
+ const law = await readFile(new URL('./examples/rc1/native-payments.lawspec', import.meta.url), 'utf8');
23
23
  const plans = [];
24
24
  const results = [];
25
25
  for (const target of selected) {
@@ -31,6 +31,8 @@ export async function exportNativePayments(options, selected) {
31
31
  'laws/payments.lawspec': law,
32
32
  };
33
33
  const config = JSON.parse(files['lawspec.json']);
34
+ if(config.version!==2||config.languageProfile!=='1.0-rc.1')
35
+ throw new Error(`Bundled native payments configuration for ${target} must use version 2 and languageProfile 1.0-rc.1`);
34
36
  config.machineBits = options.machineBits ?? 64;
35
37
  files['lawspec.json'] = JSON.stringify(config, null, options.minify ? undefined : 2) + '\n';
36
38
  const instructions = target === 'gleam' ? setup[target].replace(
@@ -42,6 +44,11 @@ This project checks application-owned payment types against the shared LawSpec
42
44
  model. Money maps to Price, currency variants have application names, and the
43
45
  archive preserves distinct present and absent payments.
44
46
 
47
+ The specification uses the canonical language profile. The version 2 project
48
+ configuration selects its verification layers explicitly. Most targets bind
49
+ application-owned domain types; C# and Clojure use the generated model data
50
+ and bind the application's functions and generators.
51
+
45
52
  ## Run
46
53
 
47
54
  Install LawSpec and the native dependencies described below, then run:
@@ -0,0 +1,23 @@
1
+ // Generated from templates/npm/node-events-reporter.mjs by lawspec-dev generate. Do not edit.
2
+ // Node's structured reporter stream preserves names without XML encoding.
3
+ // A nonce and final seal tie execution evidence to this invocation only.
4
+ export default async function* report(source) {
5
+ const run=process.env.LAWSPEC_NODE_RUN;
6
+ if(!run) throw new Error('LawSpec Node reporting requires an invocation identity');
7
+ const row=value=>JSON.stringify({version:1,run,...value})+'\n';
8
+ let count=0;
9
+ yield row({event:'start'});
10
+ for await(const event of source) {
11
+ if(!['test:pass','test:fail'].includes(event.type)||event.data?.details?.type==='suite') continue;
12
+ const data=event.data;
13
+ const skipped=[data.skip,data.todo].some(value=>value!==undefined&&value!==false);
14
+ const duration=data.details?.duration_ms;
15
+ const failure=data.details?.error?.message;
16
+ yield row({event:'test',name:data.name,classname:data.file??'',
17
+ status:skipped?'skipped':event.type==='test:pass'?'passed':'failed',
18
+ ...(Number.isFinite(duration)&&duration>=0?{time:duration/1000}:{}),
19
+ ...(event.type==='test:fail'?{failure:typeof failure==='string'?failure:'native test failed'}:{})});
20
+ count++;
21
+ }
22
+ yield row({event:'end',count});
23
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lawspec",
3
- "version": "0.24.0",
3
+ "version": "0.25.0",
4
4
  "description": "State the law once. Check it everywhere.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -18,6 +18,10 @@
18
18
  ".": {
19
19
  "types": "./index.d.ts",
20
20
  "import": "./api.mjs"
21
+ },
22
+ "./proof": {
23
+ "types": "./proof.d.ts",
24
+ "import": "./proof.mjs"
21
25
  }
22
26
  },
23
27
  "types": "index.d.ts",
@@ -25,13 +29,16 @@
25
29
  "*.mjs",
26
30
  "*.json",
27
31
  "index.d.ts",
32
+ "proof.d.ts",
28
33
  "bin",
29
34
  "core.wasm",
30
35
  "core_jsffi.js",
31
36
  "README.md",
32
37
  "CHANGELOG.md",
33
38
  "LICENSE",
39
+ "UNICODE-LICENSE.txt",
34
40
  "starter.lawspec",
41
+ "starter-rc1.lawspec",
35
42
  "examples"
36
43
  ],
37
44
  "scripts": {
@@ -0,0 +1,13 @@
1
+ // Generated from templates/npm/positional-fields.mjs by lawspec-dev generate. Do not edit.
2
+ // Positions come from checked compiler metadata, never from guessing labels.
3
+ export function positionalFields(declaration) {
4
+ const structure = declaration?.structure, constructors = declaration?.constructors;
5
+ const positions = structure?.positions;
6
+ if (structure?.kind !== 'record' || !Array.isArray(positions) || positions.length < 2
7
+ || constructors?.length !== 1 || new Set(positions).size !== positions.length) return undefined;
8
+ const fields = constructors[0].fields;
9
+ if (fields.length !== positions.length) return undefined;
10
+ const byName = new Map(fields.map(field => [field.name, field]));
11
+ if (byName.size !== positions.length || !positions.every(label => byName.has(label))) return undefined;
12
+ return positions.map(label => byName.get(label));
13
+ }
package/proof.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ // Generated from templates/npm/proof.d.ts by lawspec-dev generate. Do not edit.
2
+ import type {CheckRequest,Compiler,Location,Result} from './index.d.ts';
3
+
4
+ export interface Z3Options {
5
+ binary?: string;
6
+ timeoutMs?: number;
7
+ memoryMb?: number;
8
+ resourceLimit?: number;
9
+ seed?: number;
10
+ maxOutputBytes?: number;
11
+ }
12
+ export interface SolverEvidence {
13
+ owner: string;
14
+ declaration: string;
15
+ at: Location;
16
+ encoding: 'lawspec-smtlib-v1';
17
+ machineBits: 32 | 64;
18
+ programFingerprint: string;
19
+ taskFingerprint?: string;
20
+ status: 'proved' | 'incomplete' | 'unsupported';
21
+ outcome: 'unsat' | 'sat' | 'unknown' | 'timeout' | 'resource-limit' | 'out-of-memory' | 'unavailable' | 'failed' | 'unsupported';
22
+ reason: string;
23
+ model?: string;
24
+ modelValidated?: false;
25
+ stdout?: string;
26
+ stderr?: string;
27
+ elapsedMs?: number;
28
+ exitCode?: number | null;
29
+ signal?: string | null;
30
+ runFingerprint?: string;
31
+ prover?: {name:'z3'; version:string; binary:string; binaryFingerprint:string; fingerprint:string; arguments:string[]};
32
+ configuration?: Required<Z3Options>;
33
+ }
34
+ export function proofTaskFingerprint(task: {encoding:string;programFingerprint:string;machineBits:number;owner:string;declaration:string;script:string}):string;
35
+ export function proveWithZ3(compiler:Compiler,request:CheckRequest,options?:Z3Options):Promise<Result & {solverEvidence:SolverEvidence[]}>;
package/proof.mjs ADDED
@@ -0,0 +1,174 @@
1
+ // Generated from templates/npm/proof.mjs by lawspec-dev generate. Do not edit.
2
+ // Host execution of compiler-produced tasks. The browser/WASM compiler stays
3
+ // pure; this Node host invokes Z3's SMT-LIB interface without a shell.
4
+ import {spawn} from 'node:child_process';
5
+ import {createHash} from 'node:crypto';
6
+ import {access,readFile,realpath} from 'node:fs/promises';
7
+ import {constants} from 'node:fs';
8
+ import path from 'node:path';
9
+
10
+ const hash=value=>createHash('sha256').update(value).digest('hex');
11
+ const frame=value=>Buffer.byteLength(value,'utf8')+':'+value;
12
+ const fingerprint=values=>hash(values.map(frame).join(''));
13
+ const encoding='lawspec-smtlib-v1';
14
+
15
+ export function proofTaskFingerprint(task) {
16
+ return fingerprint([task.encoding,task.programFingerprint,String(task.machineBits),
17
+ task.owner,task.declaration,task.script]);
18
+ }
19
+
20
+ function optionsWithDefaults(options) {
21
+ const config={binary:options.binary??'z3',timeoutMs:options.timeoutMs??5000,
22
+ memoryMb:options.memoryMb??512,resourceLimit:options.resourceLimit??0,
23
+ seed:options.seed??0,maxOutputBytes:options.maxOutputBytes??1048576};
24
+ for(const [key,maximum] of [['timeoutMs',600000],['memoryMb',65536],
25
+ ['resourceLimit',2147483647],['seed',2147483647],['maxOutputBytes',16777216]]) {
26
+ const minimum=['resourceLimit','seed'].includes(key)?0:1;
27
+ if(!Number.isSafeInteger(config[key])||config[key]<minimum||config[key]>maximum)
28
+ throw new TypeError(`Invalid Z3 ${key}`);
29
+ }
30
+ if(typeof config.binary!=='string'||!config.binary||config.binary.includes('\0'))
31
+ throw new TypeError('Invalid Z3 executable');
32
+ return config;
33
+ }
34
+
35
+ async function executable(binary) {
36
+ const candidates=path.isAbsolute(binary)||binary.includes('/')||binary.includes('\\')
37
+ ?[path.resolve(binary)]
38
+ :(process.env.PATH??'').split(path.delimiter).map(folder=>path.resolve(folder,binary));
39
+ for(const candidate of candidates) {
40
+ try {await access(candidate,constants.X_OK);return await realpath(candidate);}
41
+ catch(error) {if(!['ENOENT','EACCES','ENOTDIR'].includes(error.code))throw error;}
42
+ }
43
+ throw Object.assign(new Error(`Z3 executable is unavailable: ${binary}`),{code:'ENOENT'});
44
+ }
45
+
46
+ // Only the first response line is a protocol token. Models and unknown reasons
47
+ // remain raw prover output; this host does not implement another SMT parser.
48
+ function execute(binary,args,initial,config,interactive=false) {
49
+ return new Promise(resolve=>{
50
+ const started=performance.now();
51
+ const child=spawn(binary,args,{stdio:['pipe','pipe','pipe'],shell:false});
52
+ child.stdout.setEncoding('utf8');child.stderr.setEncoding('utf8');
53
+ let stdout='',stderr='',input=initial,bytes=0,outcome=null,error=null;
54
+ let timeout=false,outputLimit=false,answered=false,closed=false;
55
+ const timer=setTimeout(()=>{timeout=true;child.kill('SIGKILL');},config.timeoutMs);
56
+ const append=(which,chunk)=>{
57
+ bytes+=Buffer.byteLength(chunk,'utf8');
58
+ if(bytes>config.maxOutputBytes){outputLimit=true;child.kill('SIGKILL');return;}
59
+ if(which==='stdout')stdout+=chunk;else stderr+=chunk;
60
+ if(interactive&&!answered&&stdout.includes('\n')) {
61
+ answered=true;
62
+ const token=stdout.slice(0,stdout.indexOf('\n')).trim();
63
+ if(['sat','unsat','unknown'].includes(token))outcome=token;
64
+ else error='unexpected Z3 protocol response';
65
+ const finish=token==='sat'?'(get-model)\n(exit)\n':
66
+ token==='unknown'?'(get-info :reason-unknown)\n(exit)\n':'(exit)\n';
67
+ input+=finish;
68
+ child.stdin.end(finish);
69
+ }
70
+ };
71
+ child.stdout.on('data',chunk=>append('stdout',chunk));
72
+ child.stderr.on('data',chunk=>append('stderr',chunk));
73
+ child.stdin.on('error',problem=>{if(problem.code!=='EPIPE')error=problem.message;});
74
+ child.on('error',problem=>{error=problem.message;});
75
+ child.on('close',(exitCode,signal)=>{
76
+ if(closed)return;
77
+ closed=true;clearTimeout(timer);
78
+ resolve({stdout,stderr,input,outcome,error,timeout,outputLimit,exitCode,signal,
79
+ elapsedMs:performance.now()-started});
80
+ });
81
+ if(interactive)child.stdin.write(initial);else child.stdin.end(initial);
82
+ });
83
+ }
84
+
85
+ async function prover(config) {
86
+ const binary=await executable(config.binary);
87
+ const binaryFingerprint=hash(await readFile(binary));
88
+ const versionRun=await execute(binary,['-version'],'',config);
89
+ const version=versionRun.stdout.trim();
90
+ if(versionRun.exitCode!==0||versionRun.error||versionRun.timeout||versionRun.outputLimit||
91
+ !/^Z3 version [0-9]+\.[0-9]+/.test(version))
92
+ throw Object.assign(new Error('The selected executable did not return a successful Z3 version response'),
93
+ {outcome:versionRun.timeout?'timeout':'failed'});
94
+ const args=['-in','-smt2',`-t:${config.timeoutMs}`,`-memory:${config.memoryMb}`];
95
+ const identity=fingerprint([binaryFingerprint,version,JSON.stringify(args),JSON.stringify(config)]);
96
+ return {binary,binaryFingerprint,version,args,fingerprint:identity};
97
+ }
98
+
99
+ function validTask(task) {
100
+ return task.encoding===encoding&&[32,64].includes(task.machineBits)&&
101
+ ['owner','declaration','programFingerprint','script','taskFingerprint'].every(key=>typeof task[key]==='string')&&
102
+ /^[0-9a-f]{64}$/.test(task.programFingerprint)&&
103
+ proofTaskFingerprint(task)===task.taskFingerprint;
104
+ }
105
+
106
+ async function solve(task,selected,config) {
107
+ const common={owner:task.owner,declaration:task.declaration,at:task.at,
108
+ programFingerprint:task.programFingerprint,taskFingerprint:task.taskFingerprint,
109
+ encoding:task.encoding,machineBits:task.machineBits,configuration:config};
110
+ if(task.status==='unsupported')return {...common,status:'unsupported',outcome:'unsupported',reason:task.reason};
111
+ if(task.status!=='ready'||!validTask(task))
112
+ return {...common,status:'incomplete',outcome:'failed',reason:'Compiler proof task binding is invalid'};
113
+ if(selected.error)return {...common,status:'incomplete',outcome:selected.outcome,reason:selected.error};
114
+ const input=`(set-option :print-success false)\n(set-option :produce-models true)\n`+
115
+ `(set-option :random-seed ${config.seed})\n(set-option :rlimit ${config.resourceLimit})\n`+
116
+ task.script+'(check-sat)\n';
117
+ const run=await execute(selected.binary,selected.args,input,config,true);
118
+ let unchanged=false;
119
+ try {unchanged=hash(await readFile(selected.binary))===selected.binaryFingerprint;} catch {}
120
+ const metadata={...common,prover:{name:'z3',version:selected.version,
121
+ binary:selected.binary,binaryFingerprint:selected.binaryFingerprint,
122
+ fingerprint:selected.fingerprint,arguments:selected.args},configuration:config,
123
+ runFingerprint:fingerprint([task.taskFingerprint,selected.fingerprint,run.input]),
124
+ elapsedMs:run.elapsedMs,exitCode:run.exitCode,signal:run.signal,
125
+ stdout:run.stdout,stderr:run.stderr};
126
+ let outcome=run.outcome,reason;
127
+ if(!unchanged){outcome='failed';reason='Z3 executable changed during execution';}
128
+ else if(run.timeout){outcome='timeout';reason='Z3 exceeded the host wall-clock limit';}
129
+ else if(run.outputLimit){outcome='failed';reason='Z3 exceeded the output limit';}
130
+ else if(run.exitCode!==0&&/out of memory|out_of_memory/i.test(run.stdout+'\n'+run.stderr)) {
131
+ outcome='out-of-memory';reason='Z3 reported memory exhaustion';
132
+ } else if(run.error||run.exitCode!==0||!outcome||run.stdout.includes('(error ')) {
133
+ outcome='failed';reason=run.error??'Z3 did not complete the task protocol successfully';
134
+ } else if(outcome==='unsat')reason='Z3 established this law, including required definedness; trusts the typed translation and selected solver, without a kernel-checked certificate';
135
+ else if(outcome==='sat')reason='Z3 returned a satisfying model for the negated proof task; it has not been validated as a LawSpec counterexample';
136
+ else {
137
+ reason='Z3 could not decide this task: '+run.stdout.slice(run.stdout.indexOf('\n')+1).trim();
138
+ if(/:reason-unknown\s+"timeout"/.test(run.stdout))outcome='timeout';
139
+ else if(/:reason-unknown\s+"max\. resource limit exceeded"/.test(run.stdout))outcome='resource-limit';
140
+ }
141
+ return {...metadata,status:outcome==='unsat'?'proved':'incomplete',outcome,reason,
142
+ ...(run.outcome==='sat'?{model:run.stdout.slice(run.stdout.indexOf('\n')+1).trim(),modelValidated:false}:{})};
143
+ }
144
+
145
+ // Tasks always come freshly from the compiler for the supplied source request.
146
+ // An imported JSON solver report cannot upgrade a law's evidence through here.
147
+ export async function proveWithZ3(compiler,request,options={}) {
148
+ const config=optionsWithDefaults(options);
149
+ const result=await compiler.proofTasks(request);
150
+ if(result.diagnostics?.length)return {...result,solverEvidence:[]};
151
+ const tasks=result.proofTasks??[];
152
+ let selected={};
153
+ if(tasks.some(task=>task.status==='ready')) {
154
+ try {selected=await prover(config);}
155
+ catch(error){selected={error:error.message,outcome:error.code==='ENOENT'?'unavailable':error.outcome??'failed'};}
156
+ }
157
+ const solverEvidence=[];
158
+ for(const task of tasks)solverEvidence.push(await solve(task,selected,config));
159
+ const diagnostics=[...(result.diagnostics??[])];
160
+ const evidence=(result.evidence??[]).map(row=>{
161
+ const found=solverEvidence.find(item=>item.owner===row.owner&&item.declaration===row.declaration);
162
+ if(row.stage!=='law'||!found)return row;
163
+ if(found.status!=='proved') {
164
+ if(['proved','exhaustively-checked','known-failing','skipped','flaky'].includes(row.status))return row;
165
+ return {...row,status:found.status==='unsupported'?'unsupported':'incomplete',reason:found.reason};
166
+ }
167
+ if(row.status==='known-failing') {
168
+ diagnostics.push({code:'harness',message:`Z3 proved ${row.declaration}; its harness cannot mark it known failing`,at:found.at});
169
+ return row;
170
+ }
171
+ return {...row,status:'proved',reason:found.reason+`; task ${found.taskFingerprint}`};
172
+ });
173
+ return {...result,diagnostics,evidence,solverEvidence};
174
+ }
@@ -0,0 +1,25 @@
1
+ -- Generated from templates/npm/starter-rc1.lawspec by lawspec-dev generate. Do not edit.
2
+ unit example.codec
3
+
4
+ itoa of type Int32 -> Text
5
+ atoi of type Text -> Int32
6
+
7
+ law codec is
8
+ description:
9
+ "Converting an integer to decimal text and reading it back preserves it."
10
+ end
11
+
12
+ definition:
13
+ for all (x of type Int32) =>
14
+ atoi (itoa x) must be x
15
+ end
16
+ end
17
+
18
+ expect itoa x = encoded
19
+ expect atoi encoded = x
20
+ in table (x, encoded):
21
+ row -42, "-42"
22
+ row 0, "0"
23
+ row 42, "42"
24
+ end
25
+ end
package/templates.mjs CHANGED
@@ -280,11 +280,11 @@ const scaffolds = {
280
280
  "groovy": {
281
281
  "readable": {
282
282
  "settings.gradle": "rootProject.name = 'lawspec-example'\n",
283
- "build.gradle": "plugins {\n id 'groovy'\n}\n\nrepositories {\n mavenCentral()\n}\n\njava {\n toolchain { languageVersion = JavaLanguageVersion.of(25) }\n}\n\nsourceSets {\n main { java { srcDirs = [] }; groovy { srcDirs = ['src/main/groovy', 'src/main/java'] } }\n test { java { srcDirs = [] }; groovy { srcDirs = ['src/test/groovy', 'src/test/java'] } }\n}\n\ndependencies {\n implementation 'org.apache.groovy:groovy:5.0.8'\n testImplementation platform('org.spockframework:spock-bom:2.5-groovy-5.0')\n testImplementation 'org.spockframework:spock-core'\n testImplementation 'org.jetbrains:jetCheck:0.3.0'\n testImplementation 'org.junit.jupiter:junit-jupiter-api:5.14.0'\n testRuntimeOnly 'org.junit.platform:junit-platform-launcher'\n}\n\ntest {\n useJUnitPlatform()\n}\n"
283
+ "build.gradle": "plugins {\n id 'groovy'\n}\n\nrepositories {\n mavenCentral()\n}\n\njava {\n toolchain { languageVersion = JavaLanguageVersion.of(25) }\n}\n\nsourceSets {\n main { java { srcDirs = [] }; groovy { srcDirs = ['src/main/groovy', 'src/main/java'] } }\n test { java { srcDirs = [] }; groovy { srcDirs = ['src/test/groovy', 'src/test/java'] } }\n}\n\ntasks.withType(org.gradle.api.tasks.compile.GroovyCompile).configureEach {\n groovyOptions.forkOptions.memoryMaximumSize = '2g'\n}\n\ndependencies {\n implementation 'org.apache.groovy:groovy:5.0.8'\n testImplementation platform('org.spockframework:spock-bom:2.5-groovy-5.0')\n testImplementation 'org.spockframework:spock-core'\n testImplementation 'org.jetbrains:jetCheck:0.3.0'\n testImplementation 'org.junit.jupiter:junit-jupiter-api:5.14.0'\n testRuntimeOnly 'org.junit.platform:junit-platform-launcher'\n}\n\ntest {\n useJUnitPlatform()\n}\n"
284
284
  },
285
285
  "compact": {
286
286
  "settings.gradle": "rootProject.name = 'lawspec-example'\n",
287
- "build.gradle": "plugins { id 'groovy' }\nrepositories { mavenCentral() }\njava { toolchain { languageVersion = JavaLanguageVersion.of(25) } }\nsourceSets { main { java { srcDirs = [] }; groovy { srcDirs = ['src/main/groovy', 'src/main/java'] } }; test { java { srcDirs = [] }; groovy { srcDirs = ['src/test/groovy', 'src/test/java'] } } }\ndependencies { implementation 'org.apache.groovy:groovy:5.0.8'; testImplementation platform('org.spockframework:spock-bom:2.5-groovy-5.0'); testImplementation 'org.spockframework:spock-core'; testImplementation 'org.jetbrains:jetCheck:0.3.0'; testImplementation 'org.junit.jupiter:junit-jupiter-api:5.14.0'; testRuntimeOnly 'org.junit.platform:junit-platform-launcher' }\ntest { useJUnitPlatform() }\n"
287
+ "build.gradle": "plugins { id 'groovy' }\nrepositories { mavenCentral() }\njava { toolchain { languageVersion = JavaLanguageVersion.of(25) } }\nsourceSets { main { java { srcDirs = [] }; groovy { srcDirs = ['src/main/groovy', 'src/main/java'] } }; test { java { srcDirs = [] }; groovy { srcDirs = ['src/test/groovy', 'src/test/java'] } } }\ntasks.withType(org.gradle.api.tasks.compile.GroovyCompile).configureEach { groovyOptions.forkOptions.memoryMaximumSize = '2g' }\ndependencies { implementation 'org.apache.groovy:groovy:5.0.8'; testImplementation platform('org.spockframework:spock-bom:2.5-groovy-5.0'); testImplementation 'org.spockframework:spock-core'; testImplementation 'org.jetbrains:jetCheck:0.3.0'; testImplementation 'org.junit.jupiter:junit-jupiter-api:5.14.0'; testRuntimeOnly 'org.junit.platform:junit-platform-launcher' }\ntest { useJUnitPlatform() }\n"
288
288
  }
289
289
  },
290
290
  "clojure": {