lawspec 0.27.0 → 0.29.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 (40) hide show
  1. package/CHANGELOG.md +124 -1
  2. package/bin/lawspec.mjs +39 -14
  3. package/build.json +139 -121
  4. package/builtin-data-names.mjs +4 -4
  5. package/core.wasm +2 -2
  6. package/core_jsffi.js +5 -5
  7. package/examples/native-payments/elixir/lib/payments_domain.ex +1 -1
  8. package/examples/native-payments/erlang/src/payments_domain.erl +1 -1
  9. package/examples/rc1/bit-codec.lawspec +6 -6
  10. package/examples/rc1/native-payments.lawspec +6 -6
  11. package/examples/rc1/nesting/rrr.lawspec +2 -2
  12. package/examples/rc1/nesting/rru.lawspec +4 -4
  13. package/examples/rc1/nesting/rur.lawspec +4 -4
  14. package/examples/rc1/nesting/ruu.lawspec +5 -5
  15. package/examples/rc1/nesting/urr.lawspec +4 -4
  16. package/examples/rc1/nesting/uru.lawspec +5 -5
  17. package/examples/rc1/nesting/uur.lawspec +5 -5
  18. package/examples/rc1/nesting/uuu.lawspec +6 -6
  19. package/examples/rc1/recursive-records.lawspec +5 -5
  20. package/examples/rc1/refund-policy.lawspec +4 -0
  21. package/examples/specs/builtins.lawspec +2 -2
  22. package/examples/specs/collections.lawspec +8 -8
  23. package/examples/specs/composition.lawspec +10 -10
  24. package/examples/specs/contracts.lawspec +2 -2
  25. package/examples/specs/crypto.lawspec +2 -2
  26. package/examples/specs/flow_stack.lawspec +4 -4
  27. package/examples/specs/generation.lawspec +2 -2
  28. package/examples/specs/list_contracts.lawspec +3 -3
  29. package/examples/specs/lists.lawspec +6 -6
  30. package/examples/specs/matching.lawspec +8 -8
  31. package/examples/specs/payments.lawspec +5 -5
  32. package/examples/specs/records.lawspec +4 -4
  33. package/examples/specs/refinements.lawspec +4 -0
  34. package/examples/specs/resources.lawspec +5 -5
  35. package/examples/specs/sequences.lawspec +1 -1
  36. package/examples/specs/sum_refinements.lawspec +11 -11
  37. package/index.d.ts +159 -4
  38. package/package.json +1 -1
  39. package/proof.d.ts +57 -12
  40. package/proof.mjs +277 -13
package/CHANGELOG.md CHANGED
@@ -6,6 +6,127 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.29.0] - 2026-10-22
10
+
11
+ ### Changed
12
+
13
+ - `lawspec fmt` parses syntax without compiling by default, including sources
14
+ whose definitions or imports are unfinished. `--compile` opts into checked
15
+ formatting before any write; `--check` works with either mode. SDK formatting
16
+ remains checked by default and accepts `compile: false` for parsing alone.
17
+ - Source formatting uses separate brace lines and two-space fields for record
18
+ types, including one-field and nested records, with one field per line.
19
+
20
+ ## [0.28.0] - 2026-10-22
21
+
22
+ ### Added
23
+
24
+ - Laws about observed histories: `law n in history h is definition: the
25
+ complete history holds P` (closed: proved or refuted) or `the history so far
26
+ holds P` (open: proved, refuted, or the new status `pending` while what
27
+ comes next decides). A deadline is refuted as soon as an entry is observed
28
+ past it.
29
+ - Model laws with deadlines (`whenever P, Q within 24h`) in whole
30
+ microsecond ticks, only through the model's `wait` command; a
31
+ missed deadline is refuted with the run and the time waited. For models
32
+ the explicit search cannot finish, `lawspec prove` proves an invariant by
33
+ induction, or by an invariant Z3's Spacer proposes and plain queries
34
+ re-check, and refutes one with a bounded run the evaluator replays.
35
+ - Laws about a model's runs: `property` declares a claim in plain words
36
+ (`always`, `eventually`, `whenever P, Q`, `never P before Q`, `until`),
37
+ and `law n in model m [assuming [strong] fairness for c] is definition:
38
+ every run holds P end definition end law` (or `some run holds P`) checks it
39
+ over the model's reference by an in-house explicit-state search, shared by
40
+ the native and WASM compilers. A law is proved with the number of states
41
+ explored, refuted with the run that breaks it, or incomplete past the
42
+ search's bound; native conformance keeps its own evidence.
43
+ - `lawspec prove` quantifies `Rational` inputs exactly (never an irrational
44
+ witness), handles `Decimal`, and reasons about `Float32` and `Float64` with
45
+ IEEE equality: NaN differs from itself and the zeros are equal. A law true
46
+ for reals but not floats is refuted with a float the evaluator confirms.
47
+ - `lawspec prove` reasons about `Text`: joining, length, slices, decimal
48
+ text, ordering, `starts with`, `ends with`, `contains` and
49
+ `matches regex`, using UTF-32BE to preserve the complete Unicode scalar
50
+ domain through U+10FFFF despite Z3's smaller alphabet. List length and joining are
51
+ supported too, and the codec portfolio and unbounded laws of the
52
+ Chapter 6 reference models are proved.
53
+ - `lawspec prove` proves laws by induction. A law's harness says
54
+ `prove by induction on xs`, citing other laws with `using "|a|`; with no
55
+ setting, a law with one list-like input gets one try. Each case is its own
56
+ task with its own receipt, a law rests on the laws it cites, and a case
57
+ whose model the law survives reports that the induction hypothesis is too
58
+ weak. The harness can also choose how recursion is unfolded:
59
+ `prove by unfolding step by step [up to n times]`,
60
+ `prove by solver recursion`, or both in turn (the default). Unproved laws
61
+ over recursive definitions get a counterexample search, so obviously false
62
+ ones are refuted.
63
+ - `lawspec prove` handles laws over recursive definitions. Each task gives Z3
64
+ the definitions unfolded step by step (guarded axioms with fuel, as Why3
65
+ and Dafny do) and by solver recursion (`define-fun-rec`); the host tries
66
+ them in turn, and the evidence records which one proved the law and every
67
+ attempt.
68
+ - The laws about a function are checked together: completeness, overlap,
69
+ conflict and vacuity, on by default. A `laws for f are ... end laws` block
70
+ states claims (`complete over`, `without overlap`, `without conflict`) and
71
+ excuses checks with a reason (`partial`, `overlap allowed`,
72
+ `conflict allowed until`, `vacuity allowed for`), until a project version
73
+ or a UTC date-time. An excused failure is `exempted`, a new status weaker
74
+ than `assumed`, and keeps its counterexample; an expired exemption is
75
+ `refuted` and fails the build. The `exhaustive` layer decides finite
76
+ domains; `lawspec prove` sends the rest to Z3, and the evaluator confirms
77
+ every input Z3 gives. `lawspec.json` gains `projectVersion`.
78
+ - A new evidence status, `refuted`: a law a confirmed counterexample shows
79
+ false (the compiler's exhaustive check, or a Z3 model the reference
80
+ evaluator confirms). The build still fails with a `refuted` diagnostic, and
81
+ `lawspec evidence` lists the law under `REFUTED` and exits with status 1.
82
+ - Z3 proof tasks cover data (`lawspec-smtlib-v2`): enums, records,
83
+ alternatives, structural records, `Maybe`, `List` and `Either` become SMT
84
+ datatypes whose field refinements are part of their well-formedness. The
85
+ refund policy and order lifecycle laws in `examples/rc1` are proved, and a
86
+ counterexample over data is read back and confirmed by the evaluator.
87
+ - `lawspec prove` validates counterexamples. When Z3 finds a law's negation
88
+ satisfiable, it gives values for the law's outer inputs, and the compiler
89
+ re-checks the law at them with its reference evaluator. A confirmed law is
90
+ `refuted` with its inputs, and `prove` exits with status 1. Unconfirmed
91
+ values are a `proof-translation` diagnostic, never a refutation.
92
+ - `lawspec-smtlib-v1` proof tasks are frozen byte for byte, checked against
93
+ a corpus of every current task. The compiler can name a later encoding,
94
+ `lawspec-smtlib-v2`, for tasks that need new features.
95
+ - A definition may rely on an ability operation's refined result. The
96
+ generated code checks each such result where the definition performs the
97
+ operation, and stops the definition if a handler broke the type.
98
+ `lawspec evidence` reports each check as `runtime-checked`.
99
+ ### Changed
100
+
101
+ - **Breaking:** `Maybe`'s values are now `Present x` and `Absent`. They were
102
+ `Just x` and `Nothing`. The type is still `Maybe a`. The old names are not
103
+ aliases: a source that uses them is refused, and the error names the new
104
+ constructor. Generated code follows the new names wherever LawSpec's
105
+ constructors appear: data tags (`Maybe::Present`, `Maybe::Absent`), the
106
+ Python, JavaScript, TypeScript and JVM `Present` and `Absent` classes, the
107
+ Go `LawSpecPresent` and `LawSpecAbsent` helpers, the C# `Maybe.Absent`
108
+ helper, the typed Java `Maybe.present`, `absent` and `isPresent`, the
109
+ Erlang and Elixir `present` and `absent` atoms, rendered values, the
110
+ editor grammar and the npm names. Native mappings are unchanged: Rust,
111
+ Swift, Scala, F# and Gleam keep their options, and Haskell keeps `Maybe`.
112
+
113
+ ### Fixed
114
+
115
+ - Proof execution discards imported settlement answers, checks the complete
116
+ solver protocol for law-set and model tasks, and records model solver
117
+ identities and raw output. An unavailable model solver stays explicit.
118
+ - Model induction keeps an unencodable command obligation incomplete rather
119
+ than proving only the remaining steps. Reachability counts obey the search
120
+ bound, and unfinished history searches cannot refute a law. Open history
121
+ deadlines stay pending, late responses fail, and backwards times are refused.
122
+ - Go harness statistics belong to each test run, so a law's boundary tests no
123
+ longer reset its property test's counts while they run in parallel. Python,
124
+ JavaScript, Rust, Haskell and Java (with Kotlin, Scala, Groovy and Clojure)
125
+ keep statistics per run too.
126
+ - The workflows example's `|an all group's checks run at the same time|` law
127
+ checks that the two slow checks overlapped in time, on every target,
128
+ instead of timing the call against 550 ms, which failed on a loaded machine.
129
+
9
130
  ## [0.27.0] - 2026-10-21
10
131
 
11
132
  ### Added
@@ -1805,7 +1926,9 @@ A maintenance release. The language, generated code and API are unchanged from
1805
1926
  machine-sized bindings reject an architecture mismatch. Rust adapters take
1806
1927
  owned values.
1807
1928
 
1808
- [Unreleased]: https://github.com/brain-fuel/lawspec/compare/v0.27.0...HEAD
1929
+ [Unreleased]: https://github.com/brain-fuel/lawspec/compare/v0.29.0...HEAD
1930
+ [0.29.0]: https://github.com/brain-fuel/lawspec/compare/v0.28.0...v0.29.0
1931
+ [0.28.0]: https://github.com/brain-fuel/lawspec/compare/v0.27.0...v0.28.0
1809
1932
  [0.27.0]: https://github.com/brain-fuel/lawspec/compare/v0.26.0...v0.27.0
1810
1933
  [0.26.0]: https://github.com/brain-fuel/lawspec/compare/v0.25.0...v0.26.0
1811
1934
  [0.25.0]: https://github.com/brain-fuel/lawspec/compare/v0.24.0...v0.25.0
package/bin/lawspec.mjs CHANGED
@@ -26,7 +26,7 @@ import {
26
26
  safePath,
27
27
  collectSources,
28
28
  } from "../files.mjs";
29
- const VERSION = "0.27.0";
29
+ const VERSION = "0.29.0";
30
30
  const args = process.argv.slice(2);
31
31
  const verb = args.shift();
32
32
  const options = {};
@@ -42,7 +42,7 @@ for (let i = 0; i < args.length; i++) {
42
42
  if (!args[i + 1] || args[i + 1].startsWith("--"))
43
43
  throw new Error(`Missing value for ${arg}`);
44
44
  options[arg.slice(2)] = [...(options[arg.slice(2)] ?? []), ...args[++i].split(",").filter(Boolean)];
45
- } else if (["--dry-run", "--check", "--json", "--minify", "--no-cache", "--fresh", "--coverage", "--update-recorded", "--benchmarks", "--stdio", "--warn-matches"].includes(arg))
45
+ } else if (["--dry-run", "--check", "--json", "--minify", "--no-cache", "--fresh", "--coverage", "--update-recorded", "--benchmarks", "--stdio", "--warn-matches", "--compile"].includes(arg))
46
46
  options[arg.slice(2)] = true;
47
47
  else if (arg.startsWith("--")) throw new Error(`Unknown option: ${arg}`);
48
48
  else positional.push(arg);
@@ -75,6 +75,13 @@ function testCommand(target, root) {
75
75
  command = `npm exec -- tsc -p tsconfig.json && node --test ${shellQuote("dist/" + testDir)}/*.test.js`;
76
76
  return `(cd ${shellQuote(root)} && ${command})`;
77
77
  }
78
+ // A refuted law fails the command, but evidence still lists it: the
79
+ // diagnostics then only say which laws are refuted.
80
+ function refutedOnly(result) {
81
+ return result.diagnostics?.length && result.diagnostics.every((d) => d.code === "refuted") && result.evidence
82
+ ? { ...result, refuted: result.diagnostics, diagnostics: [] } : result;
83
+ }
84
+
78
85
  function diagnostics(result) {
79
86
  if (result.diagnostics?.length)
80
87
  throw Object.assign(
@@ -116,14 +123,17 @@ async function loadPackage(directory) {
116
123
  },
117
124
  };
118
125
  }
119
- async function packageInput(owner, root) {
126
+ async function packageInput(owner, root, optional = false) {
120
127
  if (owner.packages !== undefined && !Array.isArray(owner.packages))
121
128
  throw new Error("packages must be an array of package directories");
122
129
  const packages = await Promise.all(
123
- (owner.packages ?? []).map(async (p) => (await loadPackage(path.resolve(root, p))).package),
130
+ (owner.packages ?? []).map(async (p) => {
131
+ try { return (await loadPackage(path.resolve(root, p))).package; }
132
+ catch (error) { if (optional && error.code === "ENOENT") return null; throw error; }
133
+ }),
124
134
  );
125
135
  return {
126
- ...(packages.length ? { packages } : {}),
136
+ ...(packages.some(Boolean) ? { packages: packages.filter(Boolean) } : {}),
127
137
  ...(owner.dependencies !== undefined ? { dependencies: owner.dependencies } : {}),
128
138
  };
129
139
  }
@@ -135,7 +145,8 @@ async function formatCommand() {
135
145
  const files = await collectSources(root, positional.length ? positional : config.sources);
136
146
  const compiler = await createCompiler();
137
147
  const result = diagnostics(await compiler.format({
138
- sources: files, ...(config ? await packageInput(config, configRoot) : {}),
148
+ sources: files, compile: !!options.compile, machineBits: options.machineBits ?? 64,
149
+ ...(config ? await packageInput(config, configRoot, !options.compile) : {}),
139
150
  languageProfile: "1.0-rc.2", verification: { layers: [] },
140
151
  }));
141
152
  const changed = result.formattedSources.filter((file, index) => file.content !== files[index].content);
@@ -748,7 +759,7 @@ async function main() {
748
759
  }
749
760
  if (!verb || ["help", "--help", "-h"].includes(verb)) {
750
761
  output(
751
- "LawSpec " + VERSION + "\nUsage: lawspec init --target <language> [--project <directory>] [--minify]\n lawspec fmt [paths...] [--check]\n lawspec lsp --stdio\n lawspec prove [--solver <z3-executable>] [--proof-timeout <ms>] [--json]\n lawspec check [--warn-matches] | doctor | explain [<unit>::<law>] [--view developer|business|formal|evidence] | generate\n lawspec evidence [<unit> | <unit>::<declaration>] [--attestation <file>]\n lawspec test [--target <language>] [--fresh] [--seed <n>] [--attestation <file>] [--update-recorded] [--tag <t>] [--exclude-tag <t>] [--report junit=<path>] [--coverage] [--benchmarks]\n lawspec package [--project <package directory>]\n lawspec examples [--example payments] [--target <language>] [--output <directory>]\nOptions: --config <path>, --target <language>, --machine-bits <32|64>, --json, --no-cache\nGeneration: --dry-run, --check, --minify\nTargets: " +
762
+ "LawSpec " + VERSION + "\nUsage: lawspec init --target <language> [--project <directory>] [--minify]\n lawspec fmt [paths...] [--check] [--compile]\n lawspec lsp --stdio\n lawspec prove [--solver <z3-executable>] [--proof-timeout <ms>] [--json]\n lawspec check [--warn-matches] | doctor | explain [<unit>::<law>] [--view developer|business|formal|evidence] | generate\n lawspec evidence [<unit> | <unit>::<declaration>] [--attestation <file>]\n lawspec test [--target <language>] [--fresh] [--seed <n>] [--attestation <file>] [--update-recorded] [--tag <t>] [--exclude-tag <t>] [--report junit=<path>] [--coverage] [--benchmarks]\n lawspec package [--project <package directory>]\n lawspec examples [--example payments] [--target <language>] [--output <directory>]\nOptions: --config <path>, --target <language>, --machine-bits <32|64>, --json, --no-cache\nGeneration: --dry-run, --check, --minify\nTargets: " +
752
763
  targets.join(", "),
753
764
  );
754
765
  return;
@@ -757,6 +768,7 @@ async function main() {
757
768
  output(VERSION);
758
769
  return;
759
770
  }
771
+ if (options.compile && verb !== "fmt") throw new Error("--compile applies to fmt");
760
772
  if (verb !== "fmt" && positional.length > (["explain", "evidence"].includes(verb) ? 1 : 0))
761
773
  throw new Error(`Unexpected argument: ${positional.join(" ")}`);
762
774
  if (verb === "examples") {
@@ -864,6 +876,10 @@ async function main() {
864
876
  ...(await packageInput(config, configRoot)),
865
877
  generation: config.generation,
866
878
  machineBits: options.machineBits ?? config.machineBits ?? 64,
879
+ // What a law-set exemption's until is compared with: the project's
880
+ // version and the current UTC time.
881
+ ...(typeof config.projectVersion === "string" ? { projectVersion: config.projectVersion } : {}),
882
+ now: new Date().toISOString(),
867
883
  };
868
884
  const compiler = await createCompiler();
869
885
  if (verb === "prove") {
@@ -875,11 +891,13 @@ async function main() {
875
891
  .filter(([name]) => options[name] !== undefined).map(([name,key]) => [key,Number(options[name])])),
876
892
  }));
877
893
  output(options.json ? result : result.solverEvidence.length
878
- ? result.solverEvidence.map(row => `${row.declaration}: ${row.status} (${row.outcome}). ${row.reason}`).join("\n")
894
+ ? result.solverEvidence.map(row => `${row.declaration}${row.kind === "analysis" ? ` ${row.stage}` : ""}: ${row.status} (${row.outcome}). ${row.reason}`).join("\n")
879
895
  : (input.verification?.layers.includes("proof")
880
896
  ? "No source law obligations are available. No solver was invoked."
881
897
  : "No proof layer selected. Intrinsic definition checks passed; no solver was invoked."));
882
- if (result.solverEvidence.some(row => row.status !== "proved")) process.exitCode = 2;
898
+ // A refuted law is a definite failure; anything else not proved is incomplete.
899
+ if (result.solverEvidence.some(row => row.status === "refuted")) process.exitCode = 1;
900
+ else if (result.solverEvidence.some(row => !["proved", "exempted"].includes(row.status))) process.exitCode = 2;
883
901
  return;
884
902
  }
885
903
  // Each obligation reports how it is discharged, strongest first.
@@ -891,11 +909,17 @@ async function main() {
891
909
  ["runtime-checked", "RUNTIME CHECKED"],
892
910
  ["default-handler", "DEFAULT HANDLER"],
893
911
  ["assumed", "ASSUMED / EXTERNAL"],
912
+ // A law-set check a laws-for block excuses, with its reason and expiry.
913
+ ["exempted", "EXEMPTED"],
914
+ // A law a confirmed counterexample shows false; the build fails.
915
+ ["refuted", "REFUTED"],
894
916
  // The harness plane: a law it marks as known to fail, a law whose last
895
917
  // run was flaky, and a law whose tests it skips.
896
918
  ["known-failing", "KNOWN FAILING"],
897
919
  ["flaky", "FLAKY"],
898
920
  ["skipped", "SKIPPED"],
921
+ // A law about an open history that the entries so far do not decide.
922
+ ["pending", "PENDING"],
899
923
  ["planned", "PLANNED"],
900
924
  ["not-verified", "NOT VERIFIED"],
901
925
  ["incomplete", "INCOMPLETE"],
@@ -904,9 +928,9 @@ async function main() {
904
928
  const evidenceSummary = (evidence) => {
905
929
  if (!evidence.length) return "";
906
930
  const count = (status) => evidence.filter((item) => item.status === status).length;
907
- // The harness statuses (after assumed) are counted only when a harness
908
- // gives some.
909
- const harnessFrom = statuses.findIndex(([status]) => status === "known-failing");
931
+ // Exempted, refuted and the harness statuses (after assumed) are counted only when
932
+ // some obligation has them.
933
+ const harnessFrom = statuses.findIndex(([status]) => status === "exempted");
910
934
  const shown = statuses.filter(([status], i) => i < harnessFrom || count(status));
911
935
  return ` Evidence: ${shown.map(([status, label]) => `${count(status)} ${label.toLowerCase()}`).join(", ")}.`;
912
936
  };
@@ -937,8 +961,9 @@ async function main() {
937
961
  const named = await readAttestation(config);
938
962
  const { runs, attestations, outcomes } = await lastRuns();
939
963
  const recorded = named && typeof named.run?.id === "string" ? outcomes.get(named.run.id) : undefined;
940
- const result = diagnostics(await compiler.check({ ...input,
941
- ...(named ? { attestation: named, ...(recorded ? { attestedOutcomes: recorded } : {}) } : {}) }));
964
+ const result = diagnostics(refutedOnly(await compiler.check({ ...input,
965
+ ...(named ? { attestation: named, ...(recorded ? { attestedOutcomes: recorded } : {}) } : {}) })));
966
+ if (result.refuted) process.exitCode = 1;
942
967
  let evidence = attachNativeEvidence(result.evidence,await readNativeObservations({compiler,input,selected,roots,
943
968
  configRoot,build:await buildDigest(),evidence:result.evidence,attestation:named}));
944
969
  const environments = named ? [result.attestation] : [];