lemmascript 0.6.4 → 0.6.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # LemmaScript (Tech Preview)
2
2
 
3
- A verification toolchain for TypeScript. Write ordinary TypeScript with `//@ ` specification annotations. The toolchain generates verifiable code from your TypeScript — either in Dafny or Lean 4 (with Velvet/Loom).
3
+ A verification toolchain for TypeScript. Write ordinary TypeScript with `//@ ` specification annotations. The toolchain generates verifiable code from your TypeScript — either in Dafny or Lean 4 (with Velvet 2).
4
4
 
5
5
  See [SPEC.md](SPEC.md), [DESIGN.md](DESIGN.md), and [GETTING_STARTED.md](GETTING_STARTED.md).
6
6
 
@@ -29,7 +29,7 @@ See the external [case studies](https://github.com/search?q=topic%3Alemmascript+
29
29
  - **[xyflow-lemmascript](https://github.com/midspiral/xyflow-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield verification of [xyflow](https://github.com/xyflow/xyflow)'s core edge and geometry utilities. 9 functions verified: `addEdge` (dedup — never loses edges, adds at most one), `reconnectEdge` (semantic: under a unique-id precondition, the result is in-place — `|result| ≤ |edges|`, no insertion — *and* when a matching edge existed with non-empty new endpoints, the output contains an edge with those endpoints. Uses `//@ assume` to characterize destructuring, `find`, and the constructed edge), `connectionExists`, `getEdgeCenter` (midpoint correctness), `clamp` (bounds), `rectToBox`/`boxToRect` (field arithmetic), `getBoundsOfBoxes` (enclosure), `getOverlappingArea` (non-negative), `areSetsEqual` (subset + same size). 14 Dafny proof obligations. Also adds a new verified feature — a **DAG connection gate**: `canReach` decides reachability soundly *and* completely, and `wouldCreateCycle` gates both new connections and edge reconnections so the graph is proven to stay acyclic, with `isAcyclic` (sound + complete) establishing the base case and a topological-rank witness giving a safe evaluation order (+29 obligations), shown live in a React Flow demo that refuses cycle-closing edges — extending the case study from verifying existing code to adding a verified feature. Dafny only.
30
30
  - **[rallly-lemmascript](https://github.com/midspiral/rallly-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield verification of [rallly](https://github.com/lukevella/rallly)'s meeting-poll Next.js app. 2 functions: `validateRedirectUrl` (in-place — open-redirect predicate; non-`undefined` outputs start with `/` but not `//`) and `scorePoll` (extracted ranking core — length preservation, score bounds, top-choice characterization, score-formula equality, within-poll monotonicity, tiebreaker injectivity). The injectivity proof surfaced a real spec-level constraint on the existing `(yes + ifNeedBe) * 1000 + yes` encoding: it overflows when an option has ≥ 1000 yes votes. 10 Dafny VCs, 0 errors. Drove four toolchain additions: `s.startsWith()`, `T | null` nullability, `\result` narrowing under `==>`, `Math.max(...arr)` spread. Dafny only.
31
31
  - **[opencode-lemmascript](https://github.com/midspiral/opencode-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield verification of [opencode](https://github.com/anomalyco/opencode)'s permission system and unified-diff patch parser. Highlights: (1) `Patch.parsePatch` carries conservation loop invariants over local ghost state — a parser bug here would silently corrupt user files when an AI applies a patch, and (2) the permission-engine work mechanically closes opencode bug #26514 (subagents bypassing Plan Mode's file-edit restrictions). 9 functions verified in-place, 0 errors. Dafny only.
32
- - **[pi-lemmascript](https://github.com/midspiral/pi-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield, **in-place** verification of the context-compaction cut-point selector in **pi** (the [earendil-works](https://pi.dev) agent harness). When the context window fills, pi discards history before a chosen cut; a provider API rejects a retained prefix containing an orphaned `toolResult` (a tool result whose tool call was cut away). Both selector functions proven: the cut never lets the kept suffix *start with* — nor *split a tool-use/tool-result run* into — an orphaned tool result, even across the backward metadata snap. The no-orphan result forced the session tree's tool-pairing ordering into an explicit `requires`. 4 VCs, 0 errors. Drove five toolchain additions, headlined by an **opaque fall-through type**: a union LemmaScript can't discriminate (here an array-element union of unreachable imports) becomes a single opaque `type` — the field stays present so distinct values stay distinct, and with no constructor or tag predicate it can only be passed through, never unsoundly observed. **Dafny + Lean**: the no-orphan theorem, the changelog semver core, and both tool-output truncators also carry Lean 4 (Velvet/Loom) proofs from the same annotated source, zero `sorry`; the Lean port drove the backend's brownfield batch (cross-file externs, union destructor lowering, Bool-vs-Prop contexts, `return`-in-loop elimination).
32
+ - **[pi-lemmascript](https://github.com/midspiral/pi-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield, **in-place** verification of the context-compaction cut-point selector in **pi** (the [earendil-works](https://pi.dev) agent harness). When the context window fills, pi discards history before a chosen cut; a provider API rejects a retained prefix containing an orphaned `toolResult` (a tool result whose tool call was cut away). Both selector functions proven: the cut never lets the kept suffix *start with* — nor *split a tool-use/tool-result run* into — an orphaned tool result, even across the backward metadata snap. The no-orphan result forced the session tree's tool-pairing ordering into an explicit `requires`. 4 VCs, 0 errors. Drove five toolchain additions, headlined by an **opaque fall-through type**: a union LemmaScript can't discriminate (here an array-element union of unreachable imports) becomes a single opaque `type` — the field stays present so distinct values stay distinct, and with no constructor or tag predicate it can only be passed through, never unsoundly observed. **Dafny + Lean**: the no-orphan theorem, the changelog semver core, and both tool-output truncators also carry Lean 4 (Velvet 2) proofs from the same annotated source, zero `sorry`; the Lean port drove the backend's brownfield batch (cross-file externs, union destructor lowering, Bool-vs-Prop contexts, `return`-in-loop elimination).
33
33
  - **[flue-lemmascript](https://github.com/midspiral/flue-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield, **in-place** verification of pure logic in **Flue** ([withastro/flue](https://github.com/withastro/flue)), Astro's agent harness — crash-recovery and context-compaction functions proven byte-identical. What it drove into the toolchain: native Dafny `continue`, bounds-guarded `noUncheckedIndexedAccess` optional indexing, optional narrowing past an `opt?.disc` guard composing with discriminated-union matching, and object truthiness. Dafny only.
34
34
  - **[balanced-match-lemmascript](https://github.com/midspiral/balanced-match-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield, **in-place** verification of [balanced-match](https://github.com/juliangruber/balanced-match), the ~70-line balanced-bracket finder pulled in by `npm`, `webpack`, and most of the JS tooling stack (1B+ downloads/month). The stack-based `range` core is verified by **refinement**: a pure recursive spec `range_spec` mirrors the loop one branch per recursive case, so the single equivalence `range == range_spec` transfers every property automatically — including an unconditional Dyck body-balance theorem for the interior of every returned pair. 2233 VCs, 0 errors under `--isolate-assertions` (registered on the `dafny-slow` track). Dafny only.
35
35
  - **[guardians-lemmascript](https://github.com/midspiral/guardians-lemmascript)** — greenfield verification of the core safety argument behind [Guardians](https://github.com/metareflection/guardians) (Erik Meijer, "Guardians of the Agents", CACM Jan 2026), a generate-verify-execute checker for AI-agent workflows. Instead of verifying an app, it proves the agent *guardrail itself sound* — that a static taint/automaton check over the real recursive workflow AST can never admit an unsafe plan. Highlights: taint over **nested conditionals** as a sound branch-union over-approximation; per-source **provenance** with a join (a multi-input tool is tainted if *any* input was); **unbounded loops** discharged by a one-step pre-fixpoint (`sat = t0 ‖ bodyTaint(t0)`) that bounds taint over any iteration count without iterating to a fixpoint; and a **unified capstone** (`verifyWfSound`) — one clean verdict rules out, on *every* path, both a tainted-data-to-sink leak and a security-automaton error. 54 Dafny obligations, 0 errors. The verified cores are reached from a Guardians-style `Workflow`/`Policy` through a thin *unverified* adapter, differentially tested against the real Python Guardians (used as the oracle, not a porting target). Dafny only.
@@ -56,13 +56,22 @@ git clone https://github.com/midspiral/LemmaScript.git
56
56
  cd LemmaScript && npm install && npm run build
57
57
  ```
58
58
 
59
- **Lean backend** additionally requires the Loom and Velvet forks:
59
+ **Lean backend:** from the LemmaScript source checkout, clone Velvet 2 as a sibling on the **`lemma2` branch**:
60
60
 
61
61
  ```sh
62
- git clone https://github.com/namin/loom.git -b lemma ../loom
63
- git clone https://github.com/namin/velvet.git -b lemma ../velvet
62
+ git clone --branch lemma2 https://github.com/namin/velvet.git ../velvet
63
+ lake build
64
+ ```
65
+
66
+ For an existing Velvet checkout, select the branch with:
67
+
68
+ ```sh
69
+ git -C ../velvet fetch origin
70
+ git -C ../velvet checkout lemma2
64
71
  ```
65
72
 
73
+ The `lemma` branch is for the previous Velvet version. Use the Lean version pinned in `lean-toolchain` (currently 4.34.0); Lake resolves the Mathlib dependency. Velvet 2 does not require a Loom checkout or external Z3/cvc5 binaries. See [SPEC_LEAN.md](SPEC_LEAN.md) for the project layout and proof workflow.
74
+
66
75
  ## Usage
67
76
 
68
77
  ### Dafny backend
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lemmascript",
3
- "version": "0.6.4",
3
+ "version": "0.6.6",
4
4
  "description": "A verification toolchain for TypeScript — generates Lean 4 or Dafny from annotated TS",
5
5
  "type": "module",
6
6
  "engines": {
@@ -19,15 +19,27 @@
19
19
  * State is explicit (§6.1): detection that mints binders or consults type
20
20
  * declarations takes a `CondCtx`; nothing module-level.
21
21
  */
22
- import { freshName } from "./names.js";
22
+ import { freshName, freshNameWhere, isUserName } from "./names.js";
23
23
  import { unionDeclOfTy, discriminantOf } from "./typedecls.js";
24
+ /** Allocate within this context, retaining a path's name on repeated
25
+ * detection. Semantic-only callers need no registry. */
26
+ function freshBinder(ctx, hint, key) {
27
+ const names = ctx.binders ??= { names: new Map(), used: new Set() };
28
+ const existing = key === undefined ? undefined : names.names.get(key);
29
+ if (existing !== undefined)
30
+ return existing;
31
+ const binder = freshNameWhere(hint, name => isUserName(name) || names.used.has(name));
32
+ names.used.add(binder);
33
+ if (key !== undefined)
34
+ names.names.set(key, binder);
35
+ return binder;
36
+ }
24
37
  export function freshOcBinder(ctx) {
25
- return freshName(`_oc${ctx.oc.n++}_val`);
38
+ return freshBinder(ctx, `_oc${ctx.oc.n++}_val`);
26
39
  }
27
- /** Pure access paths: var(x) or field(purePath, name). Walks down to the
28
- * var root, collecting field names. Returns `_root_field1..._val` (or
29
- * `_root_val` for a bare var); null for non-path shapes. */
30
- export function binderHintFor(e) {
40
+ /** Pure access paths: the raw var root followed by its field names;
41
+ * null for non-path shapes. */
42
+ function pathParts(e) {
31
43
  const fields = [];
32
44
  let cur = e;
33
45
  while (cur.kind === "field") {
@@ -36,9 +48,24 @@ export function binderHintFor(e) {
36
48
  }
37
49
  if (cur.kind !== "var")
38
50
  return null;
51
+ return [cur.name, ...fields];
52
+ }
53
+ export function binderHintFor(e) {
54
+ const parts = pathParts(e);
55
+ if (!parts)
56
+ return null;
39
57
  // \result is stored as the IR var name "\\result"; sanitize for a valid identifier.
40
- const root = cur.name === "\\result" ? "result" : cur.name;
41
- return fields.length === 0 ? `_${root}_val` : `_${root}_${fields.join("_")}_val`;
58
+ const root = parts[0] === "\\result" ? "result" : parts[0];
59
+ return `_${[root, ...parts.slice(1)].join("_")}_val`;
60
+ }
61
+ /** The hint is deliberately readable, not a path identity: `a_b` and `a.b`
62
+ * share it. Key the allocation by the complete path instead. */
63
+ export function freshPathBinder(e, ctx) {
64
+ const hint = binderHintFor(e);
65
+ return hint === null ? null : freshBinder(ctx, hint, JSON.stringify(["path", ...pathParts(e)]));
66
+ }
67
+ export function bindPresentFact(f, ctx) {
68
+ return { ...f, binder: freshPathBinder(f.scrutinee, ctx) };
42
69
  }
43
70
  /** Detect optional checks: `e !== undefined`, `e === undefined`, `!e`, or a
44
71
  * bare optional `e` — for a pure-access-path optional-typed `e`. `!e` and
@@ -95,29 +122,24 @@ export const bound = (f) => ({ kind: "var", name: f.binder, ty: f.innerTy });
95
122
  * the tree with that conjunct removed:
96
123
  * `(x !== undefined && b) && c` → { check, restCond: b && c }.
97
124
  *
98
- * Search order is shallowest-first, left-biased — both immediate operands
99
- * before either nested chain — so the conjunct found is not necessarily the
100
- * source-leftmost one. That is sound because every `parse` passed here
101
- * (`leadingPresent`, `leadingIsArray`) matches only pure, total checks on an
102
- * already-typed path, so hoisting one above the others is observationally
103
- * neutral. The one thing it does change: the residual now sits inside the
104
- * match arm, so a conjunct that would have run before a failing check no
105
- * longer runs at all.
106
- * Harmless while conditions stay pure — revisit if that ever stops holding. */
125
+ * Search matching conjuncts in source order. A later check may read a field
126
+ * whose root an earlier check unwraps, so the left subtree must be searched
127
+ * before the right operand. Keep the remaining conjuncts in their original
128
+ * relative order. */
107
129
  export function extractConjunct(cond, parse) {
108
130
  if (cond.kind !== "binop" || cond.op !== "&&")
109
131
  return null;
110
132
  const left = parse(cond.left);
111
133
  if (left)
112
134
  return { check: left, restCond: cond.right };
113
- const right = parse(cond.right);
114
- if (right)
115
- return { check: right, restCond: cond.left };
116
135
  if (cond.left.kind === "binop" && cond.left.op === "&&") {
117
136
  const inner = extractConjunct(cond.left, parse);
118
137
  if (inner)
119
138
  return { check: inner.check, restCond: { ...cond, left: inner.restCond } };
120
139
  }
140
+ const right = parse(cond.right);
141
+ if (right)
142
+ return { check: right, restCond: cond.left };
121
143
  if (cond.right.kind === "binop" && cond.right.op === "&&") {
122
144
  const inner = extractConjunct(cond.right, parse);
123
145
  if (inner)
@@ -125,9 +147,8 @@ export function extractConjunct(cond, parse) {
125
147
  }
126
148
  return null;
127
149
  }
128
- /** The positive presence fact an `&&` chain contributes, plus the residual.
129
- * "Leading" describes the rewrite, not the source: this fact becomes the
130
- * outermost match, wherever in the chain it was written. */
150
+ /** The first positive presence fact in source order, plus the residual.
151
+ * It becomes the outermost match, keeping later path checks in its arm. */
131
152
  export function leadingPresent(cond) {
132
153
  return extractConjunct(cond, e => {
133
154
  const f = presentFact(e);
@@ -146,10 +167,9 @@ export function noneDetector(leaf, ctx) {
146
167
  if (leaf.kind === "binop" && leaf.op === "!==") {
147
168
  const oc = leaf.left.kind === "optChain" ? leaf.left : leaf.right.kind === "optChain" ? leaf.right : null;
148
169
  if (oc && oc.kind === "optChain" && oc.obj.ty.kind === "optional") {
149
- const hint = binderHintFor(oc.obj);
150
- if (hint === null)
170
+ const binder = freshPathBinder(oc.obj, ctx);
171
+ if (binder === null)
151
172
  return null;
152
- const binder = freshName(hint);
153
173
  const unwrapped = applyChain({ kind: "var", name: binder, ty: oc.obj.ty.inner }, oc.chain);
154
174
  restoreDiscriminantFlag(unwrapped, ctx.decls);
155
175
  const lit = leaf.left === oc ? leaf.right : leaf.left;
@@ -157,8 +177,9 @@ export function noneDetector(leaf, ctx) {
157
177
  }
158
178
  }
159
179
  // `!x` / `x === undefined`.
160
- const f = presentFact(leaf);
161
- if (f && f.negated) {
180
+ const detected = presentFact(leaf);
181
+ if (detected && detected.negated) {
182
+ const f = bindPresentFact(detected, ctx);
162
183
  const residual = canBeFalsy(f)
163
184
  ? { kind: "unop", op: "!", expr: { kind: "var", name: f.binder, ty: f.innerTy }, ty: { kind: "bool" } }
164
185
  : null;
@@ -222,7 +243,7 @@ export function binderHintForMapAccess(m, k, ctx) {
222
243
  // mHint is `_m_val`, kHint is `_k_val` — stitch into `_m_k_val`.
223
244
  const mStem = mHint.replace(/_val$/, "");
224
245
  const kStem = kHint.replace(/^_/, "").replace(/_val$/, "");
225
- return freshName(`${mStem}_${kStem}_val`);
246
+ return freshBinder(ctx, `${mStem}_${kStem}_val`, JSON.stringify(["map", pathParts(m), pathParts(k)]));
226
247
  }
227
248
  return freshOcBinder(ctx);
228
249
  }
@@ -342,7 +363,8 @@ export function negVariantFact(cond, ctx) {
342
363
  /** Reify a presence fact in statement position: the falsy gate (for
343
364
  * truthiness checks over falsy-capable inners) tests the bound value inside
344
365
  * the Some arm, routing falsy inners to `none`. */
345
- export function presentMatchStmts(f, some, none) {
366
+ export function presentMatchStmts(f, some, none, ctx) {
367
+ f = bindPresentFact(f, ctx);
346
368
  return {
347
369
  kind: "someMatch",
348
370
  scrutinee: f.scrutinee, binderTy: f.innerTy,
@@ -352,7 +374,8 @@ export function presentMatchStmts(f, some, none) {
352
374
  };
353
375
  }
354
376
  /** Reify a presence fact in expression position; same falsy gate. */
355
- export function presentMatchExpr(f, some, none, ty) {
377
+ export function presentMatchExpr(f, some, none, ty, ctx) {
378
+ f = bindPresentFact(f, ctx);
356
379
  return {
357
380
  kind: "someMatch",
358
381
  scrutinee: f.scrutinee, binderTy: f.innerTy,
@@ -29,6 +29,26 @@ export const OPTION_SPECS = {
29
29
  fileOverride: false,
30
30
  description: "Directory for Dafny artifacts, relative to lemmascript.json.",
31
31
  },
32
+ "string-semantics": {
33
+ type: "enum",
34
+ values: ["unicode-scalar", "javascript-utf16"],
35
+ default: "unicode-scalar",
36
+ fileOverride: true,
37
+ description: "Which model of JavaScript strings a Dafny proof is made under.",
38
+ },
39
+ "dafny-library": {
40
+ type: "enum",
41
+ values: ["stdlib", "local"],
42
+ default: "stdlib",
43
+ fileOverride: true,
44
+ description: "Use Dafny's standard library or generated local helpers for collection operations.",
45
+ },
46
+ "run-log": {
47
+ type: "boolean",
48
+ default: true,
49
+ fileOverride: false,
50
+ description: "Record lsc check and regen runs in .lemmascript/.",
51
+ },
32
52
  };
33
53
  export const DEFAULT_OPTIONS = Object.freeze(Object.fromEntries(Object.entries(OPTION_SPECS).map(([key, spec]) => [key, spec.default])));
34
54
  const KNOWN_KEYS = Object.keys(OPTION_SPECS);
@@ -39,7 +59,8 @@ function fail(source, message) {
39
59
  function isKnownKey(key) {
40
60
  return Object.hasOwn(OPTION_SPECS, key);
41
61
  }
42
- function parseValue(key, raw, source) {
62
+ /** Validate one option against the registry and return its typed value. */
63
+ export function parseOptionValue(key, raw, source) {
43
64
  const spec = OPTION_SPECS[key];
44
65
  if (spec.type === "boolean") {
45
66
  if (typeof raw !== "boolean")
@@ -71,7 +92,7 @@ export function validateOptions(raw, source) {
71
92
  if (!isKnownKey(key)) {
72
93
  fail(source, `unknown option '${key}' (known options: ${KNOWN_KEYS.join(", ")})`);
73
94
  }
74
- out[key] = parseValue(key, value, source);
95
+ out[key] = parseOptionValue(key, value, source);
75
96
  }
76
97
  return out;
77
98
  }
@@ -83,10 +104,10 @@ function parseDirectiveValue(key, text, source) {
83
104
  return (text === "true");
84
105
  }
85
106
  if (spec.type === "enum")
86
- return parseValue(key, text, source);
107
+ return parseOptionValue(key, text, source);
87
108
  // Config-only today, but keep the diagnostic precise if a future path is
88
109
  // made file-overridable.
89
- return parseValue(key, text, source);
110
+ return parseOptionValue(key, text, source);
90
111
  }
91
112
  /**
92
113
  * Find comment lines, marking those that occur before any code.
@@ -183,13 +204,14 @@ export function parseFileOptions(sourceText, source) {
183
204
  }
184
205
  return out;
185
206
  }
186
- /** Apply defaults and all cross-option rules after explicit layers are merged. */
207
+ /** Apply defaults, check option compatibility, and freeze the resolved configuration. */
187
208
  export function resolveOptions(explicit, source) {
188
- // There are no cross-option constraints in the initial registry. Keep this
189
- // as the single resolution gate: future dependent defaults (UTF-16 → local
190
- // Dafny library) and incompatibilities belong here, before any consumer runs.
191
- void source;
192
- return Object.freeze({ ...DEFAULT_OPTIONS, ...explicit });
209
+ const options = { ...DEFAULT_OPTIONS, ...explicit };
210
+ // Dafny's precompiled standard library uses Unicode-scalar characters.
211
+ if (options["string-semantics"] === "javascript-utf16" && options["dafny-library"] === "stdlib") {
212
+ fail(source, '"string-semantics": "javascript-utf16" is incompatible with "dafny-library": "stdlib"; set "dafny-library": "local" explicitly');
213
+ }
214
+ return Object.freeze(options);
193
215
  }
194
216
  /** Find `fileName` at or above `fromPath`. */
195
217
  export function findUp(fileName, fromPath, fromIsDirectory = false) {
@@ -4,6 +4,7 @@
4
4
  import { existsSync, readFileSync, writeFileSync, copyFileSync, unlinkSync } from "fs";
5
5
  import { execFileSync } from "child_process";
6
6
  import path from "path";
7
+ import { DEFAULT_OPTIONS, parseOptionValue } from "./config.js";
7
8
  function writeGen(genPath, text) {
8
9
  writeFileSync(genPath, text);
9
10
  console.log(`Generated: ${genPath}`);
@@ -15,13 +16,31 @@ export function dafnyGen(genPath, dfyPath, text) {
15
16
  console.log(`Created: ${dfyPath}`);
16
17
  }
17
18
  }
18
- export function dafnyCheckDiff(genPath, dfyPath) {
19
+ export function dafnyCheckDiff(genPath, dfyPath, log) {
20
+ const ok = additionsOnly(genPath, dfyPath);
21
+ if (!ok)
22
+ log?.finish({ stage: "diff", exit: 1, dfyPath });
23
+ return ok;
24
+ }
25
+ function additionsOnly(genPath, dfyPath) {
19
26
  for (const filePath of [genPath, dfyPath]) {
20
27
  if (!existsSync(filePath)) {
21
28
  console.error(`ERROR: cannot verify additions-only diff; file does not exist: ${filePath}`);
22
29
  return false;
23
30
  }
24
31
  }
32
+ // Proof additions must retain the model chosen by the generated companion.
33
+ try {
34
+ const generated = readStringSemantics(readFileSync(genPath, "utf-8"));
35
+ const proof = readStringSemantics(readFileSync(dfyPath, "utf-8"));
36
+ if (proof !== generated) {
37
+ throw new Error(`proof string-semantics=${proof} differs from generated string-semantics=${generated}`);
38
+ }
39
+ }
40
+ catch (error) {
41
+ console.error(`ERROR: ${path.basename(dfyPath)}: ${error instanceof Error ? error.message : String(error)}`);
42
+ return false;
43
+ }
25
44
  let diff = "";
26
45
  try {
27
46
  diff = execFileSync("git", ["diff", "--no-index", "--minimal", "--no-color", "--no-ext-diff", "--no-textconv", "--text", "--", genPath, dfyPath], { encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] });
@@ -61,32 +80,94 @@ export function dafnyCheckDiff(genPath, dfyPath) {
61
80
  }
62
81
  return true;
63
82
  }
64
- export function dafnyVerify(dfyPath, dir, timeLimit, extraFlags) {
83
+ /** Read the saved model, rejecting ambiguous headers before verification. */
84
+ function readStringSemantics(content) {
85
+ const headers = [...content.matchAll(/^\/\/ lsc options:(.*)$/gm)];
86
+ if (headers.length > 1)
87
+ throw new Error("generated header: duplicate lsc options header (string-semantics must be unambiguous)");
88
+ let model = DEFAULT_OPTIONS["string-semantics"];
89
+ let seen = false;
90
+ for (const token of (headers[0]?.[1] ?? "").trim().split(/\s+/).filter(Boolean)) {
91
+ const eq = token.indexOf("=");
92
+ const key = eq < 0 ? token : token.slice(0, eq);
93
+ if (key !== "string-semantics")
94
+ continue;
95
+ if (seen)
96
+ throw new Error("generated header: duplicate string-semantics option");
97
+ seen = true;
98
+ model = parseOptionValue(key, eq < 0 ? "" : token.slice(eq + 1), "generated header");
99
+ }
100
+ return model;
101
+ }
102
+ /**
103
+ * Build verifier arguments from the generated file's `// lsc options:` header.
104
+ * Reading the saved string model instead of the current project config keeps
105
+ * verification consistent with generation, even if the config later changes.
106
+ * Always pass `--unicode-char` explicitly. UTF-16 mode also needs
107
+ * `--allow-deprecation` because Dafny 4.11 deprecates `--unicode-char:false`.
108
+ * Other warning categories remain fatal.
109
+ */
110
+ export function dafnyVerifyArgs(content, timeLimit, extraFlags) {
111
+ let stringSemantics;
112
+ try {
113
+ stringSemantics = readStringSemantics(content);
114
+ }
115
+ catch (error) {
116
+ return { args: [], error: `ERROR: ${error instanceof Error ? error.message : String(error)}` };
117
+ }
118
+ const utf16 = stringSemantics === "javascript-utf16";
119
+ const usesStandardLibrary = content.includes("Std.");
120
+ if (utf16 && usesStandardLibrary) {
121
+ return { args: [], error: "ERROR: this proof combines \"string-semantics\": \"javascript-utf16\" with Dafny's standard library. " +
122
+ "Dafny 4.11 cannot load its Unicode-scalar standard library under --unicode-char:false. " +
123
+ "Set \"dafny-library\": \"local\" in lemmascript.json or add //@ option dafny-library local, " +
124
+ "then run lsc regen to regenerate collection helpers. " +
125
+ "This does not rewrite handwritten Std.* imports or calls; replace those with local proofs or helpers separately." };
126
+ }
127
+ const args = ["verify"];
128
+ if (usesStandardLibrary)
129
+ args.push("--standard-libraries");
130
+ if (timeLimit)
131
+ args.push("--verification-time-limit", String(timeLimit));
132
+ if (extraFlags) {
133
+ for (const tok of extraFlags.split(/\s+/))
134
+ if (tok)
135
+ args.push(tok);
136
+ }
137
+ args.push(utf16 ? "--unicode-char:false" : "--unicode-char:true");
138
+ if (utf16)
139
+ args.push("--allow-deprecation");
140
+ return { args };
141
+ }
142
+ export function dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log) {
65
143
  console.log("Running dafny verify...");
66
144
  try {
67
- const content = readFileSync(dfyPath, "utf-8");
68
- const args = ["verify"];
69
- if (content.includes("Std."))
70
- args.push("--standard-libraries");
71
- if (timeLimit)
72
- args.push("--verification-time-limit", String(timeLimit));
73
- if (extraFlags) {
74
- for (const tok of extraFlags.split(/\s+/))
75
- if (tok)
76
- args.push(tok);
145
+ const { args, error } = dafnyVerifyArgs(readFileSync(dfyPath, "utf-8"), timeLimit, extraFlags);
146
+ if (error) {
147
+ console.error(error);
148
+ log?.finish({ stage: "resolve", exit: 1, dfyPath });
149
+ return false;
77
150
  }
151
+ if (log)
152
+ args.push(...log.dafnyArgs());
78
153
  args.push(dfyPath);
79
154
  execFileSync("dafny", args, { cwd: dir, stdio: "inherit" });
155
+ log?.finish({ stage: "ok", exit: 0, dfyPath, results: log.readResults() });
80
156
  return true;
81
157
  }
82
158
  catch (e) {
83
159
  if (e?.code === "ENOENT") {
84
160
  console.error("ERROR: `dafny` not found on PATH — verification never ran. Install Dafny 4.x: https://dafny.org/");
161
+ log?.discard();
162
+ return false;
85
163
  }
164
+ // Dafny writes no results when it stops at parsing or resolution.
165
+ const results = log?.readResults() ?? null;
166
+ log?.finish({ stage: results ? "verify" : "resolve", exit: 1, dfyPath, results });
86
167
  return false;
87
168
  }
88
169
  }
89
- export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, extraFlags, noVerify = false) {
170
+ export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, extraFlags, noVerify = false, log) {
90
171
  // 1. Read old gen before overwriting (needed for base seeding)
91
172
  const oldGen = existsSync(genPath) ? readFileSync(genPath, "utf-8") : "";
92
173
  // 2. Always write new gen so user can inspect latest output
@@ -95,10 +176,11 @@ export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, ext
95
176
  if (!existsSync(dfyPath)) {
96
177
  writeFileSync(dfyPath, text);
97
178
  console.log(`Created: ${path.basename(dfyPath)}`);
98
- if (!noVerify && !dafnyVerify(dfyPath, dir, timeLimit, extraFlags)) {
179
+ if (!noVerify && !dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log)) {
99
180
  console.error(`FAILED: ${path.basename(dfyPath)} verification failed on first run.`);
100
181
  process.exit(1);
101
182
  }
183
+ log?.finish({ stage: "ok", exit: 0, dfyPath });
102
184
  return;
103
185
  }
104
186
  // 4. Determine anchor: base file if it exists (dirty state), otherwise old gen
@@ -119,18 +201,19 @@ export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, ext
119
201
  copyFileSync(dfyPath, mergedPath);
120
202
  writeFileSync(dfyPath, savedDfy);
121
203
  console.error(`CONFLICT: ${path.basename(dfyPath)} — merge had conflicts, dfy restored. See ${path.basename(mergedPath)}`);
204
+ log?.finish({ stage: "conflict", exit: 1, dfyPath });
122
205
  process.exit(1);
123
206
  }
124
207
  throw e;
125
208
  }
126
209
  }
127
210
  // 6. Check gen invariant (unconditional)
128
- if (!dafnyCheckDiff(genPath, dfyPath)) {
211
+ if (!dafnyCheckDiff(genPath, dfyPath, log)) {
129
212
  console.error(`FAILED: ${path.basename(dfyPath)} has modifications to generated lines.`);
130
213
  process.exit(1);
131
214
  }
132
215
  // 7. Verify (skipped under --no-verify: caller verifies separately)
133
- if (!noVerify && !dafnyVerify(dfyPath, dir, timeLimit, extraFlags)) {
216
+ if (!noVerify && !dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log)) {
134
217
  // The clean merge already incorporated this generation into the proof
135
218
  // file. Keep that generation as the next merge anchor even though the
136
219
  // verifier rejected the current proof state; otherwise the next regen
@@ -139,7 +222,9 @@ export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, ext
139
222
  console.error(`FAILED: ${path.basename(dfyPath)} verification failed.`);
140
223
  process.exit(1);
141
224
  }
142
- // 8. Success — delete base (gen is now the anchor)
225
+ // 8. Success — delete base (gen is now the anchor). After a verified run
226
+ // dafnyVerify has already recorded the outcome; this records --no-verify.
143
227
  if (existsSync(basePath))
144
228
  unlinkSync(basePath);
229
+ log?.finish({ stage: "ok", exit: 0, dfyPath });
145
230
  }