lawspec 0.25.0 → 0.27.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 (156) hide show
  1. package/CHANGELOG.md +109 -1
  2. package/NORMALIZATION-LICENSES.txt +296 -0
  3. package/README.md +13 -4
  4. package/api.mjs +0 -8
  5. package/bin/lawspec.mjs +114 -79
  6. package/build.json +99 -117
  7. package/core.wasm +2 -2
  8. package/core_jsffi.js +5 -0
  9. package/doctor.mjs +14 -4
  10. package/examples/native-payments/clojure/lawspec.json +1 -1
  11. package/examples/native-payments/csharp/lawspec.json +1 -1
  12. package/examples/native-payments/elixir/lawspec.json +1 -1
  13. package/examples/native-payments/erlang/lawspec.json +1 -1
  14. package/examples/native-payments/fsharp/lawspec.json +1 -1
  15. package/examples/native-payments/gleam/lawspec.json +1 -1
  16. package/examples/native-payments/go/lawspec.json +1 -1
  17. package/examples/native-payments/groovy/lawspec.json +1 -1
  18. package/examples/native-payments/haskell/lawspec.json +1 -1
  19. package/examples/native-payments/java/lawspec.json +1 -1
  20. package/examples/native-payments/javascript/lawspec.json +1 -1
  21. package/examples/native-payments/kotlin/lawspec.json +1 -1
  22. package/examples/native-payments/prolog/lawspec.json +20 -0
  23. package/examples/native-payments/prolog/src/domain/payments.pl +23 -0
  24. package/examples/native-payments/prolog/tests/domain/payment_generators.pl +17 -0
  25. package/examples/native-payments/python/lawspec.json +1 -1
  26. package/examples/native-payments/rust/lawspec.json +1 -1
  27. package/examples/native-payments/scala/lawspec.json +1 -1
  28. package/examples/native-payments/swift/lawspec.json +1 -1
  29. package/examples/native-payments/typescript/lawspec.json +1 -1
  30. package/examples/packages/orders/lawspec.json +1 -1
  31. package/examples/packages/orders/orders.lawspec +27 -25
  32. package/examples/packages/shop-domain/src/domain.lawspec +15 -14
  33. package/examples/packages/shop-tax-1/src/api.lawspec +1 -0
  34. package/examples/packages/shop-tax-1/src/rates.lawspec +1 -0
  35. package/examples/packages/shop-tax-2/src/api.lawspec +1 -0
  36. package/examples/packages/shop-tax-2/src/rates.lawspec +1 -0
  37. package/examples/rc1/authorization-snapshots.lawspec +24 -23
  38. package/examples/rc1/banner-filenames.lawspec +7 -6
  39. package/examples/rc1/bit-codec.lawspec +12 -11
  40. package/examples/rc1/bounded-witness-search.lawspec +52 -45
  41. package/examples/rc1/conflicting-requirements.lawspec +8 -7
  42. package/examples/rc1/constructive-witnesses.lawspec +40 -33
  43. package/examples/rc1/documentary-review.lawspec +9 -8
  44. package/examples/rc1/empty-domains.lawspec +16 -15
  45. package/examples/rc1/finite-integer-domains.lawspec +24 -23
  46. package/examples/rc1/law-metadata.lawspec +6 -5
  47. package/examples/rc1/native-payments.lawspec +17 -16
  48. package/examples/rc1/nesting/rrr.lawspec +4 -3
  49. package/examples/rc1/nesting/rru.lawspec +7 -6
  50. package/examples/rc1/nesting/rur.lawspec +7 -6
  51. package/examples/rc1/nesting/ruu.lawspec +10 -9
  52. package/examples/rc1/nesting/urr.lawspec +7 -6
  53. package/examples/rc1/nesting/uru.lawspec +10 -9
  54. package/examples/rc1/nesting/uur.lawspec +10 -9
  55. package/examples/rc1/nesting/uuu.lawspec +13 -12
  56. package/examples/rc1/order-workflow.lawspec +18 -17
  57. package/examples/rc1/parcel-measurements.lawspec +14 -13
  58. package/examples/rc1/picture-records.lawspec +6 -5
  59. package/examples/rc1/picture-tuples.lawspec +6 -5
  60. package/examples/rc1/record-payloads.lawspec +12 -11
  61. package/examples/rc1/recursive-records.lawspec +11 -10
  62. package/examples/rc1/refund-conformance.lawspec +7 -6
  63. package/examples/rc1/refund-policy.lawspec +15 -14
  64. package/examples/rc1/requirement-composition.lawspec +26 -25
  65. package/examples/rc1/structural-records.lawspec +13 -12
  66. package/examples/rc1-authoring.lawspec +6 -5
  67. package/examples/specs/abilities.lawspec +67 -65
  68. package/examples/specs/ability_imports.lawspec +58 -57
  69. package/examples/specs/actors.lawspec +23 -22
  70. package/examples/specs/algebra.lawspec +142 -141
  71. package/examples/specs/approvals.lawspec +19 -18
  72. package/examples/specs/async_bindings.lawspec +10 -9
  73. package/examples/specs/async_fetch.lawspec +12 -11
  74. package/examples/specs/atoi_codec.lawspec +16 -15
  75. package/examples/specs/boolean_flags.lawspec +10 -9
  76. package/examples/specs/builtins.lawspec +73 -72
  77. package/examples/specs/canonical_url.lawspec +14 -13
  78. package/examples/specs/collections.lawspec +153 -154
  79. package/examples/specs/composition.lawspec +70 -66
  80. package/examples/specs/concurrent_collections.lawspec +8 -7
  81. package/examples/specs/consistency.lawspec +4 -3
  82. package/examples/specs/contracts.lawspec +80 -79
  83. package/examples/specs/crypto.lawspec +26 -25
  84. package/examples/specs/ctc.lawspec +148 -0
  85. package/examples/specs/currying.lawspec +32 -31
  86. package/examples/specs/data_types.lawspec +50 -49
  87. package/examples/specs/distribution.lawspec +57 -56
  88. package/examples/specs/domain_modeling.lawspec +68 -47
  89. package/examples/specs/durations.lawspec +39 -38
  90. package/examples/specs/equivalent.lawspec +25 -24
  91. package/examples/specs/failures.lawspec +64 -63
  92. package/examples/specs/finite_data.lawspec +32 -31
  93. package/examples/specs/flow_stack.lawspec +64 -63
  94. package/examples/specs/gadt_expressions.lawspec +50 -49
  95. package/examples/specs/generation.lawspec +115 -114
  96. package/examples/specs/handler_bindings.lawspec +42 -40
  97. package/examples/specs/handles.lawspec +2 -1
  98. package/examples/specs/harness.lawspec +45 -43
  99. package/examples/specs/harness_testing.lawspec +18 -13
  100. package/examples/specs/indexed_arithmetic.lawspec +401 -126
  101. package/examples/specs/indexed_families.lawspec +182 -66
  102. package/examples/specs/keywords.lawspec +22 -21
  103. package/examples/specs/limits.lawspec +7 -6
  104. package/examples/specs/list_contracts.lawspec +121 -120
  105. package/examples/specs/list_refinements.lawspec +43 -42
  106. package/examples/specs/lists.lawspec +45 -44
  107. package/examples/specs/matchers.lawspec +79 -78
  108. package/examples/specs/matching.lawspec +43 -42
  109. package/examples/specs/mixed_inputs.lawspec +25 -24
  110. package/examples/specs/models.lawspec +44 -43
  111. package/examples/specs/parse_port.lawspec +28 -27
  112. package/examples/specs/payments.lawspec +55 -54
  113. package/examples/specs/railway.lawspec +59 -58
  114. package/examples/specs/records.lawspec +149 -148
  115. package/examples/specs/records_inner.lawspec +5 -4
  116. package/examples/specs/recursive_refinements.lawspec +30 -29
  117. package/examples/specs/refined_definitions.lawspec +24 -23
  118. package/examples/specs/refinements.lawspec +58 -57
  119. package/examples/specs/resilience.lawspec +161 -160
  120. package/examples/specs/resources.lawspec +61 -60
  121. package/examples/specs/scalar_adapters.lawspec +60 -59
  122. package/examples/specs/scalar_catalog.lawspec +165 -164
  123. package/examples/specs/scalars.lawspec +78 -77
  124. package/examples/specs/scheduling_order.lawspec +8 -7
  125. package/examples/specs/scheduling_overlap.lawspec +5 -4
  126. package/examples/specs/sequences.lawspec +66 -65
  127. package/examples/specs/sessions.lawspec +13 -12
  128. package/examples/specs/slug.lawspec +16 -15
  129. package/examples/specs/sum_refinements.lawspec +42 -41
  130. package/examples/specs/tables.lawspec +29 -28
  131. package/examples/specs/total_functions.lawspec +71 -70
  132. package/examples/specs/workflows.lawspec +101 -100
  133. package/examples-command.mjs +7 -7
  134. package/explain.mjs +6 -4
  135. package/expression-presentation.mjs +8 -8
  136. package/files.mjs +1 -1
  137. package/index.d.ts +10 -528
  138. package/launcher.mjs +9 -2
  139. package/lsp.mjs +10 -6
  140. package/native-evidence.mjs +25 -12
  141. package/native-examples.mjs +3 -3
  142. package/package.json +2 -1
  143. package/starter-rc1.lawspec +6 -5
  144. package/starter.lawspec +16 -15
  145. package/templates.mjs +88 -5
  146. package/test-command.mjs +40 -4
  147. package/migrate.mjs +0 -135
  148. package/migration-bindings.mjs +0 -86
  149. package/migration-cases.mjs +0 -45
  150. package/migration-collections.mjs +0 -54
  151. package/migration-correspondence.mjs +0 -275
  152. package/migration-generation.mjs +0 -99
  153. package/migration-laws.mjs +0 -102
  154. package/migration-records.mjs +0 -166
  155. package/migration-source.mjs +0 -247
  156. package/migration-write.mjs +0 -156
package/bin/lawspec.mjs CHANGED
@@ -4,10 +4,8 @@ import { readFile, mkdir, readdir, rm, stat, writeFile } from "node:fs/promises"
4
4
  import { createHash } from "node:crypto";
5
5
  import path from "node:path";
6
6
  import { createCompiler } from "../api.mjs";
7
- import { targets, templates, commands, setup } from "../templates.mjs";
7
+ import { targets, artifactTargets, templates, commands, setup } from "../templates.mjs";
8
8
  import { generateExamples } from "../examples-command.mjs";
9
- import { migrationReport } from "../migrate.mjs";
10
- import { writeMigration } from "../migration-write.mjs";
11
9
  import { proveWithZ3 } from "../proof.mjs";
12
10
  import { serveLanguage } from "../lsp.mjs";
13
11
  import { explainLaw, explanationViews } from "../explain.mjs";
@@ -28,14 +26,14 @@ import {
28
26
  safePath,
29
27
  collectSources,
30
28
  } from "../files.mjs";
31
- const VERSION = "0.25.0";
29
+ const VERSION = "0.27.0";
32
30
  const args = process.argv.slice(2);
33
31
  const verb = args.shift();
34
32
  const options = {};
35
33
  const positional = [];
36
34
  for (let i = 0; i < args.length; i++) {
37
35
  const arg = args[i];
38
- if (["--target", "--project", "--config", "--output", "--machine-bits", "--example", "--seed", "--report", "--attestation", "--view", "--from", "--solver", "--proof-timeout", "--proof-memory", "--proof-rlimit", "--proof-seed"].includes(arg)) {
36
+ if (["--target", "--project", "--config", "--output", "--machine-bits", "--example", "--seed", "--report", "--attestation", "--view", "--solver", "--proof-timeout", "--proof-memory", "--proof-rlimit", "--proof-seed"].includes(arg)) {
39
37
  if (!args[i + 1] || args[i + 1].startsWith("--"))
40
38
  throw new Error(`Missing value for ${arg}`);
41
39
  options[arg.slice(2)] = args[++i];
@@ -44,7 +42,7 @@ for (let i = 0; i < args.length; i++) {
44
42
  if (!args[i + 1] || args[i + 1].startsWith("--"))
45
43
  throw new Error(`Missing value for ${arg}`);
46
44
  options[arg.slice(2)] = [...(options[arg.slice(2)] ?? []), ...args[++i].split(",").filter(Boolean)];
47
- } else if (["--dry-run", "--check", "--json", "--minify", "--no-cache", "--fresh", "--coverage", "--update-recorded", "--benchmarks", "--write", "--stdio", "--warn-matches"].includes(arg))
45
+ } else if (["--dry-run", "--check", "--json", "--minify", "--no-cache", "--fresh", "--coverage", "--update-recorded", "--benchmarks", "--stdio", "--warn-matches"].includes(arg))
48
46
  options[arg.slice(2)] = true;
49
47
  else if (arg.startsWith("--")) throw new Error(`Unknown option: ${arg}`);
50
48
  else positional.push(arg);
@@ -58,10 +56,13 @@ const output = (value) =>
58
56
  const shellQuote = (value) =>
59
57
  "'" + String(value).replaceAll("'", "'\\''") + "'";
60
58
  function testCommand(target, root) {
59
+ if (artifactTargets.includes(target.language)) return null;
61
60
  const testDir = target.testDir || "test";
62
61
  let command = commands[target.language];
63
62
  if (target.language === "python")
64
63
  command = `${shellQuote(target.python || "python3")} -m pytest`;
64
+ if (target.language === "prolog")
65
+ command = `${shellQuote(target.python || "python3")} lawspec_test.py`;
65
66
  if (target.language === "java")
66
67
  command = `${shellQuote(target.maven || "mvn")} test`;
67
68
  if (target.language === "kotlin")
@@ -126,49 +127,16 @@ async function packageInput(owner, root) {
126
127
  ...(owner.dependencies !== undefined ? { dependencies: owner.dependencies } : {}),
127
128
  };
128
129
  }
129
- async function migrateCommand() {
130
- if(options.write&&options["dry-run"])throw new Error("--write and --dry-run cannot be combined");
131
- if (options.from !== "0.24") throw new Error("migrate requires --from 0.24");
132
- const configurationText=await readFile(configFile,"utf8");
133
- const config = JSON.parse(configurationText);
134
- if (config.version !== 1) throw new Error("migrate --from 0.24 requires configuration version 1");
135
- const compiler = await createCompiler();
136
- const input={
137
- sources: await sources(config), ...(await packageInput(config, configRoot)),
138
- generation: config.generation, machineBits: config.machineBits ?? 64, minify: options.minify === true,
139
- };
140
- const recheck=async()=>{
141
- const current={sources:await sources(config),...(await packageInput(config,configRoot))};
142
- const original={sources:input.sources,...Object.fromEntries(['packages','dependencies']
143
- .filter(key=>input[key]!==undefined).map(key=>[key,input[key]]))};
144
- if(JSON.stringify(current)!==JSON.stringify(original))throw new Error('Project sources or package dependencies changed during migration.');
145
- };
146
- const report=options.write?await writeMigration(compiler,configRoot,path.basename(configFile),configurationText,input,{recheck}):
147
- await migrationReport(compiler,config,input);
148
- diagnostics(report);
149
- const bindingChanges=report.bindingPreview.targets.flatMap(target=>target.evidence?.changes??[]).length;
150
- const bindingChecked=report.bindingPreview.targets.filter(target=>target.evidence?.beforeValidated===true).length;
151
- const bindingMatched=report.bindingPreview.targets.filter(target=>target.status==='matched').length;
152
- const bindingSummary=`Native binding preview: ${bindingChecked} of ${report.bindingPreview.configurationCount} original configurations checked; ${bindingMatched} proposals match; ${bindingChanges} field changes.\n`;
153
- const generationAccepted=report.generationPreview.targets.filter(target=>target.status==='accepted').length;
154
- const generationSummary=`Target generation preview: ${generationAccepted} of ${report.generationPreview.configurationCount} configurations accepted. Native implementation conformance remains unestablished.\n`;
155
- const boundaryMatched=report.generationPreview.targets.filter(target=>target.nativeBoundary.status==='matched').length;
156
- const boundarySummary=`Native boundary comparison: ${boundaryMatched} of ${report.generationPreview.configurationCount} configurations match under their existing native implementation assumptions.\n`;
157
- output(options.json ? report : `${options.write?"Written":"Read-only"} migration report: ${report.baseline.laws.length} laws, ${report.baseline.definitions.length} definitions, ${report.constructorChanges.length} constructor payload changes.\n` + bindingSummary + generationSummary + boundarySummary +
158
- report.blockers.join("\n") + (options.write?`\n${report.filesWritten.length} files written. Existing native implementation assumptions are retained; no law verification is claimed.`:
159
- `\nNo files were written. ${report.validated?'The migration is validated under its existing compiler and native implementation assumptions. Use --write to apply it.':'Migration remains incomplete.'} Use --json to inspect the complete report.`));
160
- }
161
-
162
130
  async function formatCommand() {
163
131
  const config = positional.length ? null : JSON.parse(await readFile(configFile, "utf8"));
164
- if(config&&(config.version!==2||config.languageProfile!=="1.0-rc.1"))
165
- throw new Error("Formatting a project requires configuration version 2 and languageProfile 1.0-rc.1; run lawspec migrate --from 0.24 first.");
132
+ if(config&&(config.version!==2||config.languageProfile!=="1.0-rc.2"))
133
+ throw new Error("Formatting a project requires configuration version 2 and languageProfile 1.0-rc.2");
166
134
  const root = positional.length ? process.cwd() : configRoot;
167
135
  const files = await collectSources(root, positional.length ? positional : config.sources);
168
136
  const compiler = await createCompiler();
169
137
  const result = diagnostics(await compiler.format({
170
138
  sources: files, ...(config ? await packageInput(config, configRoot) : {}),
171
- languageProfile: "1.0-rc.1", verification: { layers: [] },
139
+ languageProfile: "1.0-rc.2", verification: { layers: [] },
172
140
  }));
173
141
  const changed = result.formattedSources.filter((file, index) => file.content !== files[index].content);
174
142
  if (!options.check) for (const file of changed) await atomicWrite(path.resolve(root, file.path), file.content);
@@ -183,7 +151,7 @@ async function packageCommand() {
183
151
  const compiler = await createCompiler();
184
152
  const result = diagnostics(
185
153
  await compiler.check({
186
- languageProfile: '1.0-rc.1', verification: {layers: []},
154
+ languageProfile: '1.0-rc.2', verification: {layers: []},
187
155
  sources: own.sources,
188
156
  package: { name: own.name, version: own.version },
189
157
  ...(await packageInput(manifest, directory)),
@@ -223,10 +191,10 @@ async function init() {
223
191
  const current = await readOptional(configFile);
224
192
  const config =
225
193
  current === null
226
- ? { version: 2, languageProfile: "1.0-rc.1", verification: { layers: [] }, sources: ["laws"], targets: [] }
194
+ ? { version: 2, languageProfile: "1.0-rc.2", verification: { layers: [] }, sources: ["laws"], targets: [] }
227
195
  : JSON.parse(current);
228
- if(config.version!==2||config.languageProfile!=='1.0-rc.1')
229
- throw new Error('Existing projects require configuration version 2 and languageProfile 1.0-rc.1; run lawspec migrate --from 0.24 first.');
196
+ if(config.version!==2||config.languageProfile!=='1.0-rc.2')
197
+ throw new Error('Existing projects require configuration version 2 and languageProfile 1.0-rc.2');
230
198
  if (
231
199
  config.targets.some(
232
200
  (t) =>
@@ -272,7 +240,9 @@ async function init() {
272
240
  if (current === null)
273
241
  await atomicWrite(
274
242
  starter,
275
- await readFile(new URL("../starter-rc1.lawspec", import.meta.url), "utf8"),
243
+ artifactTargets.includes(language) && language !== "make"
244
+ ? "unit configuration\ntype Settings is a record{port :: UInt16 enabled :: Bool} end type\nfunction settings (unused :: Unit) -> Settings is Settings record{port = 8080, enabled = true} end function\nend unit\n"
245
+ : await readFile(new URL("../starter-rc1.lawspec", import.meta.url), "utf8"),
276
246
  true,
277
247
  );
278
248
  if (options.machineBits !== undefined) config.machineBits = options.machineBits;
@@ -326,10 +296,23 @@ async function lastRuns() {
326
296
  const folder = path.join(configRoot, ".lawspec", "results");
327
297
  const runs = new Map();
328
298
  const attestations = new Map();
299
+ // The outcome each law last had in each attested run, by run id; across
300
+ // targets a failure outweighs a pass.
301
+ const outcomes = new Map();
302
+ const rank = (o) => ["passed", "known-failing", "skipped", "incomplete", "failed"].indexOf(o);
329
303
  for (const name of (await readOptionalDirectory(folder)) ?? []) {
330
304
  if (!name.endsWith(".json")) continue;
331
305
  const recorded = JSON.parse((await readOptional(path.join(folder, name))) ?? "{}");
332
306
  for (const [id, attestation] of Object.entries(recorded.attestations ?? {})) attestations.set(id, attestation);
307
+ const outcome = (id, law, value) => {
308
+ const known = outcomes.get(id) ?? {};
309
+ if (known[law] === undefined || rank(value) > rank(known[law])) known[law] = value;
310
+ outcomes.set(id, known);
311
+ };
312
+ for (const [law, attempt] of Object.entries(recorded.attempts ?? {}))
313
+ if (attempt.environment) outcome(attempt.environment, law, attempt.outcome);
314
+ for (const [law, run] of Object.entries(recorded.laws ?? {}))
315
+ if (run.environment && recorded.attempts?.[law]?.environment !== run.environment) outcome(run.environment, law, "passed");
333
316
  for (const [law, run] of Object.entries(recorded.laws ?? {})) {
334
317
  const known = runs.get(law) ?? {};
335
318
  const latest = (known.passed ?? "") > (run.passed ?? "") ? known : run;
@@ -337,7 +320,7 @@ async function lastRuns() {
337
320
  passed: latest.passed, seed: latest.seed, environment: latest.environment });
338
321
  }
339
322
  }
340
- return { runs, attestations };
323
+ return { runs, attestations, outcomes };
341
324
  }
342
325
  // An environment attestation: a versioned JSON document any tool may write,
343
326
  // recording for one run where each dependency was wired and whether it was
@@ -358,10 +341,29 @@ async function readAttestation(config) {
358
341
  // One attested dependency, as lawspec evidence shows it.
359
342
  function dependencyText(d) {
360
343
  const level = (c) => /^[0-9]+$/.test(c) ? `conformance level ${c}` : `conformance ${c}`;
344
+ const ran = d.ranAgainst ?? {};
345
+ const history = ran.historyDigest ?? d.standIn?.historyDigest;
361
346
  return `${d.dependency}: ` + (d.standIn
362
347
  ? `stand-in ${d.standIn.identity} ${d.standIn.version} (${level(d.standIn.conformance)}` +
363
- (d.standIn.historyDigest ? `, history ${d.standIn.historyDigest}` : "") + ")"
364
- : "real") + ` at ${d.endpoint}` + (d.reached ? "" : " (not reached when recorded)");
348
+ (history ? `, history ${history}${ran.historyFrom === "completed" ? " when completed" : ""}` : "") + ")"
349
+ : "real") + ` at ${d.endpoint}` + (d.reached ? "" : " (not reached when recorded)") +
350
+ (d.implementation ? `; ${d.implementation.kind} ${d.implementation.product} ${d.implementation.version}` : "") +
351
+ (d.contract ? `; contract ${d.contract.package} ${d.contract.version}` : "") +
352
+ (d.node ? `; node ${d.node}` + (d.edge ? ` via ${d.edge}` : "") : "") +
353
+ (d.completed && !d.completed.reached ? " (not reached when completed)" : "");
354
+ }
355
+ // What an attested run's document records, as lawspec evidence shows it.
356
+ function executionText(run) {
357
+ const e = run?.execution;
358
+ if (!e) return "";
359
+ return e.status === "completed" ? `, completed with exit code ${e.exitCode}` :
360
+ e.status === "running" ? ", in progress" : ", wiring only";
361
+ }
362
+ // Why a law relying on an attested dependency has no completed run linked.
363
+ function unlinkedText(run) {
364
+ const status = run?.execution?.status;
365
+ return status === "wired" ? "wiring only; nothing ran" :
366
+ status === "running" ? "run in progress; no completed run linked" : "no completed run linked";
365
367
  }
366
368
  // One law's harness, as lawspec evidence shows it.
367
369
  function harnessText(item) {
@@ -380,9 +382,7 @@ function harnessText(item) {
380
382
  if (h.skip) parts.push(`skip "${h.skip}"`);
381
383
  if (h.knownFailing) parts.push(`known failing "${h.knownFailing}"`);
382
384
  if (h.orderRandom) parts.push("order random");
383
- // Python runs a parallel unit's tests at the same time only with
384
- // pytest-xdist; without it, parallel changes nothing there.
385
- if (h.parallel) parts.push("parallel (on Python only with pytest-xdist; otherwise one after another)");
385
+ if (h.parallel) parts.push("parallel");
386
386
  const lines = [` ${item.declaration.replace("::law::", "::")}: ${parts.join("; ") || "no harness settings"}`];
387
387
  for (const run of item.adequacy ?? []) {
388
388
  lines.push(` last run: ${run.cases} generated case(s)` +
@@ -522,12 +522,11 @@ async function runTests(compiler, input, selected, roots, config) {
522
522
  if (beam || target.language === "scala") await rm(coverage, {recursive: true, force: true});
523
523
  await mkdir(beam ? path.join(coverage, "runs") : coverage, { recursive: true });
524
524
  }
525
- // parallel on Python needs pytest-xdist; without it the tests run one
526
- // after another, and lawspec test says so.
525
+ // Python may use xdist processes; the host harness otherwise supplies
526
+ // its existing thread scheduler, which Prolog also uses through Janus.
527
527
  let xdist = false;
528
528
  if (target.language === "python" && stale.some((entry) => entry.parallel)) {
529
529
  xdist = spawnSync(target.python || "python3", ["-c", "import xdist"], { cwd: root, stdio: "ignore" }).status === 0;
530
- if (!xdist) console.error("python: `parallel` runs tests at the same time only with pytest-xdist (pip install pytest-xdist); without it they run one after another.");
531
530
  }
532
531
  // A skipped law runs nothing. BEAM known-failing checks finish as native
533
532
  // passing tests, so their completion must appear in the native report.
@@ -614,10 +613,14 @@ async function runTests(compiler, input, selected, roots, config) {
614
613
  await writeFile(databaseFile, JSON.stringify(database, null, 2) + "\n");
615
614
  await mkdir(path.dirname(resultsFile), { recursive: true });
616
615
  await writeFile(path.join(path.dirname(resultsFile), ".gitignore"), "*\n");
616
+ // Each attempt at a law the attestation touches names the run it was
617
+ // made in, whatever its outcome.
618
+ if (attestation) for (const entry of stale)
619
+ if (attested.has(entry.law) && attempts[entry.law]) attempts[entry.law] = { ...attempts[entry.law], environment: attestation.run.id };
617
620
  // Each attestation a recorded law ran under is kept with the results.
618
621
  const attestations = Object.fromEntries(Object.entries({ ...(previous.attestations ?? {}),
619
622
  ...(attestation ? { [attestation.run.id]: attestation } : {}) })
620
- .filter(([id]) => Object.values(laws).some((run) => run.environment === id)));
623
+ .filter(([id]) => [...Object.values(laws), ...Object.values(attempts)].some((run) => run.environment === id)));
621
624
  await atomicWrite(resultsFile, JSON.stringify({ version: 1, laws, attempts,
622
625
  ...(Object.keys(attestations).length ? { attestations } : {}) }, null, 2) + "\n");
623
626
  const flaky = statistics.filter((s) => s.outcome === "flaky").map((s) => s.law);
@@ -745,7 +748,7 @@ async function main() {
745
748
  }
746
749
  if (!verb || ["help", "--help", "-h"].includes(verb)) {
747
750
  output(
748
- "LawSpec " + VERSION + "\nUsage: lawspec init --target <language> [--project <directory>] [--minify]\n lawspec fmt [paths...] [--check]\n lawspec migrate --from 0.24 [--write]\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: " +
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: " +
749
752
  targets.join(", "),
750
753
  );
751
754
  return;
@@ -799,11 +802,8 @@ async function main() {
799
802
  throw new Error("--attestation applies to evidence and test");
800
803
  if (options.seed !== undefined && !/^[0-9]+$/.test(options.seed))
801
804
  throw new Error("--seed must be a whole number");
802
- if (options.from && verb !== "migrate") throw new Error("--from applies to migrate");
803
- if (options.write && verb !== "migrate") throw new Error("--write applies to migrate");
804
805
  if (options["warn-matches"] && verb !== "check") throw new Error("--warn-matches applies to check");
805
806
  if (options.stdio && verb !== "lsp") throw new Error("--stdio applies to lsp");
806
- if (verb === "migrate") return migrateCommand();
807
807
  if (verb === "lsp") {
808
808
  if (!options.stdio) throw new Error("lsp requires --stdio");
809
809
  return serveLanguage();
@@ -820,11 +820,14 @@ async function main() {
820
820
  !Array.isArray(config.targets)
821
821
  )
822
822
  throw new Error(
823
- "Expected lawspec.json version 2 with languageProfile 1.0-rc.1, sources and targets arrays; run lawspec migrate --from 0.24 for version 1 projects",
823
+ "Expected lawspec.json version 2 with languageProfile 1.0-rc.2, sources and targets arrays",
824
824
  );
825
- if (config.languageProfile !== "1.0-rc.1") throw new Error("Configuration version 2 requires languageProfile 1.0-rc.1");
825
+ if (config.languageProfile !== "1.0-rc.2") throw new Error("Configuration version 2 requires languageProfile 1.0-rc.2");
826
+ if (verb === "test" && artifactTargets.includes(options.target))
827
+ throw new Error(`${options.target} is an artifact target and cannot execute application laws`);
826
828
  const selected = config.targets.filter(
827
- (t) => !options.target || t.language === options.target,
829
+ (t) => (!options.target || t.language === options.target) &&
830
+ (verb !== "test" || !artifactTargets.includes(t.language)),
828
831
  );
829
832
  if (["doctor", "generate", "test"].includes(verb) && !selected.length &&
830
833
  !(verb === "test" && !options.benchmarks && config.version === 2 && !(config.verification?.layers ?? []).some(layer => ["exhaustive", "property", "examples", "model"].includes(layer))))
@@ -842,7 +845,7 @@ async function main() {
842
845
  : reports
843
846
  .map(
844
847
  (r) =>
845
- `${r.target}: ${r.ok ? "ready" : `${r.message}\n${r.instructions}`}`,
848
+ `${r.target}: ${r.ok ? (r.kind === "artifact" ? "generation ready" : "ready") : `${r.message}\n${r.instructions}`}`,
846
849
  )
847
850
  .join("\n"),
848
851
  );
@@ -864,7 +867,7 @@ async function main() {
864
867
  };
865
868
  const compiler = await createCompiler();
866
869
  if (verb === "prove") {
867
- if (config.version !== 2) throw new Error("prove requires configuration version 2 and languageProfile 1.0-rc.1");
870
+ if (config.version !== 2) throw new Error("prove requires configuration version 2 and languageProfile 1.0-rc.2");
868
871
  const result = diagnostics(await proveWithZ3(compiler, input, {
869
872
  ...(options.solver !== undefined ? {binary: options.solver} : {}),
870
873
  ...Object.fromEntries([["proof-timeout","timeoutMs"],["proof-memory","memoryMb"],
@@ -928,22 +931,40 @@ async function main() {
928
931
  if (verb === "evidence") {
929
932
  // An attestation named here, or in lawspec.json, says where the tests
930
933
  // ran; otherwise each law shows the attested run it last passed in.
934
+ // A named attestation of a run lawspec test recorded links each law to
935
+ // that run, with the outcome recorded for it, unless the document says
936
+ // the run has not completed.
931
937
  const named = await readAttestation(config);
932
- const result = diagnostics(await compiler.check({ ...input, ...(named ? { attestation: named } : {}) }));
938
+ const { runs, attestations, outcomes } = await lastRuns();
939
+ 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 } : {}) } : {}) }));
933
942
  let evidence = attachNativeEvidence(result.evidence,await readNativeObservations({compiler,input,selected,roots,
934
943
  configRoot,build:await buildDigest(),evidence:result.evidence,attestation:named}));
935
- const { runs, attestations } = await lastRuns();
936
944
  const environments = named ? [result.attestation] : [];
937
945
  if (!named) for (const [id, attestation] of attestations) {
938
946
  const laws = new Set([...runs].filter(([, run]) => run.environment === id).map(([law]) => law));
939
947
  if (!laws.size) continue;
940
- const attested = diagnostics(await compiler.check({ ...input, attestation }));
948
+ const attested = diagnostics(await compiler.check({ ...input, attestation, attestedOutcomes: outcomes.get(id) ?? {} }));
941
949
  const fields = new Map(attested.evidence.filter((item) => (item.against || item.plannedAgainst) && laws.has(item.declaration))
942
- .map(item => [item.declaration, {environment: item.environment ?? item.plannedEnvironment,
943
- environmentRun: item.environmentRun ?? item.plannedEnvironmentRun, against: item.against ?? item.plannedAgainst}]));
950
+ .map(item => {
951
+ // Receipts predating execution states keep their historical meaning.
952
+ // An explicit running/wired state must retain the compiler's planned
953
+ // fields; a cached passing law does not complete its environment run.
954
+ const legacy = !attestation.execution && !item.against;
955
+ return [item.declaration, legacy ? {
956
+ environment: item.plannedEnvironment, environmentRun: item.plannedEnvironmentRun,
957
+ against: item.plannedAgainst, environmentProviders: item.plannedEnvironmentProviders,
958
+ } : Object.fromEntries(["environment", "environmentRun", "against", "environmentProviders", "environmentOutcome",
959
+ "plannedEnvironment", "plannedEnvironmentRun", "plannedAgainst", "plannedEnvironmentProviders"]
960
+ .filter(key => item[key] !== undefined).map(key => [key, item[key]]))];
961
+ }));
944
962
  evidence = evidence.map((item) => item.stage === "law" && fields.has(item.declaration) ? { ...item, ...fields.get(item.declaration) } : item);
945
963
  environments.push({ ...attested.attestation, dependencies: attested.attestation.dependencies
946
- .map((d) => ({ ...d, obligations: [...new Set([...d.obligations, ...(d.plannedObligations ?? [])])].filter((law) => laws.has(law)), plannedObligations: [] })) });
964
+ .map((d) => ({ ...d,
965
+ obligations: (attestation.execution ? d.obligations : [...new Set([...d.obligations, ...(d.plannedObligations ?? [])])])
966
+ .filter((law) => laws.has(law)),
967
+ plannedObligations: attestation.execution ? (d.plannedObligations ?? []).filter((law) => laws.has(law)) : [] })) });
947
968
  }
948
969
  // Native bindings are configured per target; their obligations are added.
949
970
  for (const target of selected) {
@@ -979,18 +1000,32 @@ async function main() {
979
1000
  (item.claim ? `: ${item.claim.text}` : "") + `\n ${item.reason}` +
980
1001
  (item.nativeEvidence ? `\n ${nativeEvidenceText(item).replaceAll("\n","\n ")}` : "") +
981
1002
  (item.lastNativeRun ? `\n last native run passed at ${item.lastNativeRun.passed} (seed ${item.lastNativeRun.seed})` : "") +
982
- (item.against ? `\n last recorded passing run in environment ${item.environment} (run ${item.environmentRun.id}) against ` +
983
- item.against.map(dependencyText).join("; ") : "")).join("\n");
1003
+ (item.against ? (item.environmentOutcome
1004
+ ? `\n ${item.environmentOutcome} in completed run ${item.environmentRun.id} in environment ${item.environment}${executionText(item.environmentRun)} against `
1005
+ : `\n last recorded passing run in environment ${item.environment} (run ${item.environmentRun.id}) against `) +
1006
+ item.against.map(dependencyText).join("; ") : "") +
1007
+ (item.plannedAgainst ? `\n planned in environment ${item.plannedEnvironment} (run ${item.plannedEnvironmentRun.id}` +
1008
+ `${executionText(item.plannedEnvironmentRun)}; ${unlinkedText(item.plannedEnvironmentRun)}) against ` +
1009
+ item.plannedAgainst.map(dependencyText).join("; ") : "")).join("\n");
984
1010
  })
985
1011
  .filter((section) => section !== null),
986
1012
  // How each law is discharged: the harness plane, apart from what
987
1013
  // the laws say.
988
1014
  ...(harnessed.length ? [`HARNESS (${harnessed.length})\n` + harnessed.map(harnessText).join("\n")] : []),
989
1015
  // Where the tests ran: reporting only, so no status above changes.
990
- ...environments.map((e) => `ENVIRONMENT ${e.environment} (run ${e.run.id}, recorded ${e.run.recordedAt})\n` +
991
- e.dependencies.map((d) => ` ${dependencyText(d)}; ` + (d.obligations.length
992
- ? `${d.obligations.length} tested obligation(s)` :
993
- d.plannedObligations?.length ? `${d.plannedObligations.length} planned obligation(s); no completed run linked` : "no tested obligation relies on it")).join("\n"))]
1016
+ ...environments.map((e) => `ENVIRONMENT ${e.environment} (run ${e.run.id}, recorded ${e.run.recordedAt}${executionText(e.run)})\n` +
1017
+ (e.architecture ? ` architecture ${e.architecture.document} ${e.architecture.digest}` +
1018
+ (e.architecture.topologyDigest ? `, topology ${e.architecture.topologyDigest}` : "") + "\n" : "") +
1019
+ (e.application ? ` application ${e.application.node}: contract ${e.application.contract.package} ${e.application.contract.version}; ` +
1020
+ `${e.application.implementation.kind} ${e.application.implementation.product} ${e.application.implementation.version}` +
1021
+ (e.application.implementation.commit ? ` (commit ${e.application.implementation.commit})` : "") + "\n" : "") +
1022
+ e.dependencies.map((d) => {
1023
+ const outcome = (o) => evidence.find((item) => item.declaration === o && item.environmentOutcome)?.environmentOutcome;
1024
+ const failed = d.obligations.filter((o) => ["failed", "incomplete"].includes(outcome(o))).length;
1025
+ return ` ${dependencyText(d)}; ` + (d.obligations.length
1026
+ ? `${d.obligations.length} tested obligation(s)` + (failed ? `, ${failed} failed` : "") :
1027
+ d.plannedObligations?.length ? `${d.plannedObligations.length} planned obligation(s); ${unlinkedText(e.run)}` : "no tested obligation relies on it");
1028
+ }).join("\n"))]
994
1029
  .join("\n\n"),
995
1030
  );
996
1031
  return;
@@ -1062,7 +1097,7 @@ async function main() {
1062
1097
  : summary
1063
1098
  .map(
1064
1099
  (r) =>
1065
- `${r.target}: ${r.changes.length} ${options["dry-run"] || options.check ? "planned" : "applied"} change(s), ${r.preservedAdapters.length} user adapter(s) preserved.${r.adapterUpdates.length ? "\nReview required adapter signatures:\n" + r.adapterUpdates.map((a) => a.path + "\n" + a.requiredAdapter).join("\n") : ""}\nTest: ${r.test}`,
1100
+ `${r.target}: ${r.changes.length} ${options["dry-run"] || options.check ? "planned" : "applied"} change(s), ${r.preservedAdapters.length} user adapter(s) preserved.${r.adapterUpdates.length ? "\nReview required adapter signatures:\n" + r.adapterUpdates.map((a) => a.path + "\n" + a.requiredAdapter).join("\n") : ""}\n${r.test === null ? "Artifact generation complete." : "Test: " + r.test}`,
1066
1101
  )
1067
1102
  .join("\n"),
1068
1103
  );