qleisli 0.2.1

Experimental quantum language with linear ownership, exact contracts and independent finite IR verification
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
# Selected M1 machine interfaces

Status: **X1 retained; X2–X6 implemented in the 0.2.0 finite profile**
(updated 2026-09-29). See the executed checks and publication evidence in the
[release record](releases/v0.2.0.md). These are independently
shippable slices of [M1](next-minor-spec.md), versioned by
[compatibility](versioning.md), with X1 first implemented in 0.1.7. Formats below
have their own versions; product/package versions never change their meaning.
Current `check`/`run`, Rust IR and exhaustive reference simulation stay intact.

The later [interoperability direction](interoperability-roadmap.md) adds future
Python, OpenQASM 3 and QIR entry points. The bounded OpenQASM input/output
and QIR output now have a separate [M1.1-A contract and implementation](interop-m1.1.md);
Python, QIR input and adaptive extensions remain pending. They do not change X1–X6 below. In particular, this document's **QIRF**
is Qleisli's JSON interchange, not QIR Alliance LLVM IR.

The [Lean migration](lean-kernel-migration.md) adds a separate experimental
[phase-word protocol](lean-kernel-migration.md#first-executable-slice): canonical
LF text `.qpk` artifacts and independently supplied `.qpr` requirements, with
a fixed JSON result. It is not QIRF1/2, a new QIRF tag, or a production evidence
receipt. Existing QIRF import and `check`/`run` remain Rust-authoritative.
Later migration must reconstruct evidence from data, bind the same immutable
artifact and requested contract, and fail explicitly when a required Lean
checker is unavailable or rejects; a Rust seal or supplied digest is no proof.

For these adapters, **[desugaring](terminology.md#desugaring-layer)** means
meaning-preserving translation of convenient representations to already
specified core operations, emitting untrusted IR/evidence without new primitive
meanings or checker rules. Parsing and approximate synthesis are separate.
The [coefficient-domain recommendation](coefficient-domains.md) requires future
domain/approximation extensions to bind their domain version, interpretation
and error claims explicitly. It does not add fields or tags to X1–X6 or permit
arbitrary-domain arithmetic in the current finite format.

The 0.1.8 authoring continuation enriches explanatory `message` text with
expected/actual exact types and a restricted-cleanup repair hint. It changes
neither JSON v1 fields nor category, location or exit-code contracts. Consumers
should use the structured category rather than matching full message prose.
[Repair tests](../tests/repair_diagnostics.rs) exercise text and JSON paths.

The 0.1.9 compatible review update also locates effect failures at a causal
expression and names derived/declared effects; import/provider and snapshot-limit
messages explain repairs or causes. Truncated static arguments produce a located
`parse` error at EOF, exit 1 and one JSON envelope instead of panicking.
Fields, categories, coordinate conventions and success results are unchanged.
Multiple-error recovery remains future work even though the envelope contains
a diagnostics array.

## Diagnostics

**Implemented scope:** `check`, `run`, `sample`, `emit-ir` and `verify-ir`.
`doc` remains Markdown-only and rejects `--format=json` as usage.

Add the opt-in flag `--format=json` to `check`, `run`, `sample`, `emit-ir` and
`verify-ir`. Flags may precede/follow positional arguments; duplicates, unknown
flags and missing values are usage errors. With this flag, stdout is exactly
one UTF-8 JSON object plus LF, also on failure. Diagnostic prose is never mixed
into stdout. Stderr is empty for handled results; an OS-level failure to write
the JSON document may use stderr and exits 1. No NDJSON/progress stream is used.
Human mode for the two existing commands preserves existing output/exit rules.
The supported spelling is exactly `--format=json`, once, anywhere in the argument
list (including before the command). `--format`, `--format=`, separate format
values and other formats are usage errors. If the exact JSON flag appears,
handled usage errors also use JSON. Otherwise usage stays on stderr. A path
starting with `-` must be written with a `./` prefix so it is not a flag.
The envelope's `command` is the first argument remaining after removing exact
JSON flags; use the empty string if absent or non-UTF-8. Unknown UTF-8 command
names are preserved as JSON strings, never executed.

```json
{"format":"qleisli.result","version":1,"command":"check","outcome":"error",
 "diagnostics":[{"code":"ownership","severity":"error","message":"owner already consumed",
 "primary":{"path":"main.qli","start":27,"end":28,"line":2,"column":5},
 "related":[]}],"result":null}
```

All displayed fields are required. `outcome` is `ok` or `error`; success has
no error diagnostic, failure has at least one and a null result. Severity is
`error` or `warning`. `message` is explanatory text, not a stable API. A primary
location may be null for usage, I/O or artifact-wide errors. Related entries
are `{message,location}` with the same location schema. Spans are half-open
UTF-8 byte offsets into the original unnormalized source; empty EOF spans are
allowed. Line/column are one-based Unicode scalar positions, matching the
current frontend. Paths are project-relative with `/`, or `std://` for bundled
sources. Non-UTF-8 filesystem paths produce `project` with null location;
never lossy-encode an identity. Artifact errors use `json_pointer` in a related
entry's message when no source location exists; they do not invent source spans.

Version 1 codes are `usage`, `project`, `parse`, `unknown_name`, `recursive_call`,
`type_mismatch`, `arity`, `ownership`, `effect`, `invalid_entry`, `unsupported`,
`limit`, `invalid_ir`, `contract`, `capability`, `format`, `simulation`,
`random_source`, and `numerical`. Existing CompileError codes map to their
snake_case spellings; parser/load, new access/contract and runtime errors map
to the corresponding additional codes. CLI exit is 0 for successful command
execution, 2 for usage and 1 for other failure. Retry exhaustion is a successful
trial-run result, not a simulator error; clients inspect its typed outcome.
Version/tag/code additions require a new format version for this closed schema.

Success result schemas: `check` is `{verified:true}`; `run` is
`{distribution:[{bits:[bool,...],probability:number},...]}` in lexicographic
bit-vector order; `emit-ir` is `{path:string}`; `verify-ir` is
`{verified:true,request_checked:bool}`; `sample` is specified below. Probabilities
are finite numbers in [0,1]; reference floating output is not an exact proof.
The envelope only reports the check actually performed.

The JSON adapter clamps reference probabilities to [0,1] only when endpoint
roundoff is at most 2^-40, inclusive. Nonfinite values or larger excursions
produce `numerical`, exit 1 and no partial distribution. It does not renormalize
the distribution, change the underlying simulator or weaken exact evidence.
Both text and JSON `run` retain every positive computed weight: ideal-zero
outcomes may appear as roundoff residues (for example about `6.16e-33` for
`H; T^8; H` on zero). Listing an outcome does not prove it has nonzero ideal
probability. No automatic display cutoff hides genuinely rare outcomes;
[A020-13](v0.2.0-backlog.md#a020-13--numerical-zero-outcomes-obscure-ideal-deterministic-examples)
tracks a separately specified, optional display summary.
Simulation capacity errors map to `limit`; other current runtime failures map
to `simulation`. Existing compiler codes, including contract failures currently
classified as `InvalidIr`, retain their specified snake_case category. Future
`contract`/`capability` codes are reserved for their corresponding new checks.

The additive Rust functions `check_project_diagnostic` and
`compile_project_diagnostic` use the same checker as the legacy entry points,
returning `frontend::diagnostic::Diagnostic` (`code`, `message`, optional
`primary`). `SourceLocation` retains a `PathBuf`, `Span`, line and column;
portable relative/`std://` rendering belongs to the CLI. Parser provenance and
coordinates are retained from the loaded source rather than inferred from
message text or a later file read. Load failures with source spans retain them;
I/O/path failures and a missing entry point have null locations. Source errors
still produce no related locations or warnings; artifact errors attach their
JSON pointer with a null location. Legacy `CompileError`, `ErrorCode` and `ProjectError`
shapes/categories remain unchanged, including parser failures as `Project`.

## Portable finite IR and evidence

Select **QIRF version 1**, a UTF-8 JSON interchange for the existing finite
RawProgram and its retained function-evidence DAG. CLI:

```text
qleisli emit-ir <project> --output=<new-file>
qleisli verify-ir <artifact> [--against=<request-file>]
```

Output uses exclusive creation and writes a complete temporary sibling before
atomic installation; an existing destination is an error. Verification never
loads source paths, accesses the network, runs a compiler/plugin, or executes
embedded code. An optional request is an independently chosen expected contract;
without it `request_checked` is false even when internal validity succeeds.
Artifact-supplied expectations cannot certify that the user asked for them.

The artifact has exactly `{format:"qleisli.finite-ir",version:1,profile:"finite-v0",
sources,programs,evidence,root,root_interface}`. Arrays are indexed by zero-based references.
`root` is a program index. Object key order/whitespace have no significance;
duplicate/unknown/missing keys, unknown tags, nonintegers in integer fields,
negative IDs, nonfinite numbers and ill-formed UTF-8 are rejected. Numbers used
for IDs/counts are decimal JSON integer tokens, not floats/exponents. IDs and
indices fit u32; gate/table values fit the narrower ranges below. No unchecked
conversion to host `usize` is allowed. String equality is exact Unicode scalar
equality without normalization; embedded sources preserve their UTF-8 bytes.

`sources` entries are `{path,text}`, with unique nonempty path labels, at most
4,096 bytes per path, no NUL, and at most 128 entries. Labels are identities,
never filesystem instructions. `programs` contains raw program objects.
`evidence` entries have `{signature,implementation,specification,identity}`:
the two programs are indices, `signature` is the full basis tree, and identity
is `{implementation:string,specification:string,sources:[source-index,...]}`.
Its source indices are unique and preserve the original identity snapshot order. Names obey the existing 4,096-byte
limit. Identity snapshots are checked binding metadata, not proof that source
lowering was correct.

`root_interface` is null or exactly `{input:BasisType,output:BasisType}`. A
non-null value describes the sole quantum input and sole quantum output of
`programs[root]`, which must have declared effect `unitary` and no classical
inputs/outputs. Import first verifies the raw program, then checks each tree's
bit count against its corresponding verified port, including the output token's
resolved shape and wire order. Bit leaves map left to right to the port's
ordered wires, first leaf least significant; retain every Unit node, tuple arity and nested
association. Both trees obey the existing depth-64 and 4,096-node type limits
as well as the transport limits. Invalid port/effect/width binding rejects the
artifact as `invalid_ir`; resource exhaustion is `limit`.

Export retains both exact trees from the type-checked frontend boundary or a
checked function contract for that same root implementation. Never reconstruct
them from bit counts, an unrelated nested evidence signature, or a request-file.
Use null for other root interfaces or when exporting legacy raw IR without
retained type information. Null permits ordinary IR verification but cannot
satisfy `--against`. The root index, both trees, ordered ports and complete
IR/evidence form one checked binding; any change requires revalidation. This
metadata is an untrusted declaration checked against the IR and, separately,
the user's request; it does not prove which source type was originally written.
The existing public RawProgram/QuantumPort records are unchanged: the new
transport envelope carries the root types.

The following encoding completely determines the finite payload. All named
record fields in [ir.rs](../src/ir.rs) are required with their current names.
This specification freezes their version-1 field set, recorded below; later
Rust fields are not silently added to the wire format.

| Type | Version-1 JSON representation |
| --- | --- |
| BasisType | `{"tag":"unit"}`, `{"tag":"bit"}`, `{"tag":"pair","left":T,"right":T}`, or `{"tag":"tuple","fields":[T,...]}` with at least three immediate fields; retain Unit nodes, exact arity and nesting. Two fields use `pair`; smaller `tuple` arrays reject. See the [0.2.0 type migration]tuple-shapes.md. |
| ID/index/bit count | Nonnegative integer; token/wire/classical IDs are distinct namespaces; a shape is `{"bits":n}` with n≤12 |
| QuantumPort | `{token,wires,shape}`; `wires` is an ordered array of wire IDs |
| RawProgram | `{quantum_inputs,classical_inputs,operations,quantum_outputs,classical_outputs,declared_effect}`; quantum inputs are ports, quantum outputs are token IDs, classical inputs/outputs are classical IDs |
| Effect / SingleGate / ScalarPhase | Strings `unitary/iso/observe`, `h/x/z/t`, `minus_one/eighth_turn` respectively |
| UnitaryStep | Tagged objects: `gate` with gate,target_index; `cnot` with control_index,target_index; `toffoli` with control_a_index,control_b_index,target_index; `scalar_phase` with phase |
| CircuitStep / BitControl | `{controls,action}` / `{index,when_one}` with boolean when_one |
| CircuitAction | `contract` with indices,evidence,adjoint; `hadamard` with target; `monomial` with indices,permutation,phases. Evidence is an evidence-array index, adjoint boolean; permutations use u16 and phases integers 0–7 |
| ProtectedBit / Control | `{region,index}` with region `source/ancilla`, index u8 / `{bit,when_one}` |
| ProtectedUse | `protected_gate` with bit,gate; `controlled_target_gate` with controls,target_index,gate; `controlled_phase` with controls,phase |
| TargetTransition | `{input,output}` token IDs |
| QuantumPhi | `{then_token,else_token,output,output_wires}` |
| ClassicalPhi | `{then_id,else_id,output}` |

Every tagged object above/below has a `tag` string in addition to its listed
fields. Arrays encode all Vec fields; booleans are JSON booleans. RawOp tags
and complete payload fields are:

| Tag | Fields |
| --- | --- |
| `certified_compute` | source,source_out,ancilla_wires,function,use_steps,logical_steps |
| `apply_unitary` | input,output,steps |
| `init0` | output,wire |
| `gate` | gate,input,output |
| `cnot` | control,target,control_out,target_out |
| `toffoli` | control_a,control_b,target,control_a_out,control_b_out,target_out |
| `quantum_if` | control,target,control_out,target_out,zero_ops,one_ops |
| `split` | input,left,right,left_bits |
| `join` | left,right,output |
| `lift_basis` | input,output,output_wires,table |
| `measure_z` | input,output |
| `reset` | input,output,fresh_wire |
| `discard` | input |
| `classical_const` | value,output |
| `classical_not` | input,output |
| `classical_xor` | left,right,output |
| `classical_and` | left,right,output |
| `classical_branch` | condition,then_ops,else_ops,quantum_phis,classical_phis |
| `compute_use_uncompute` | source,source_out,targets,ancilla_wires,function,use_ops |

`function`/`table` entries are u16. `use_steps`/`logical_steps`/`steps` are circuit
steps, `zero_ops`/`one_ops` are unitary steps, and branch arrays are RawOps.
Index ranges, arity, token freshness, shape compatibility, effect, table
totality/injectivity, axis order, exact phase and cleanup are checked by the
independent finite verifier, not inferred from successful JSON parsing.

Import performs bounded tokenization, schema/range preflight, graph validation,
then semantic checking. Construct edges program→referenced evidence and
evidence→implementation/specification programs; reject every cycle, invalid
reference and unused object/source. Share each checked evidence result once,
in topological order; do not recursively expand shared dependencies. Reconstruct
each FunctionEvidence with its ordinary exact checker, then independently
verify all referring raw programs and the root. Standalone CheckedContract
objects are not transported in QIRF1: retained SC claims are reconstructed
from their complete raw computed operation and rechecked. Nothing serializes
private checked fields, `Arc` identity, verified flags or a dense result as
authority. Export/import round trips may issue new evidence identities while
preserving complete structural binding and denotation.

The fixed transport limits are 16 MiB raw bytes, JSON nesting 128, 1,000,000
JSON values, 65,536 program/evidence objects combined, 1,000,000 total raw/step
nodes, graph depth 32 and 1 MiB total embedded source text. Bound each array
incrementally before allocation; reject deep inputs without recursive drop.
The stricter current semantic limits (six-bit evidence, 1,024 circuit steps,
1,000,000 expanded steps and 10,000,000 aggregate exact work per import) still
apply. The current 1 MiB identity budget counts implementation/specification
names for each distinct evidence entry, plus each referenced source path and
its exact text once per artifact. Repeated references to the same source index
spend no additional source-byte budget; duplicate indices within an identity
still reject. One path cannot label conflicting text. Import retains shared
immutable snapshots for identical ordered source-index sequences; changing
order or membership changes the snapshot. The ordinary evidence checker
revalidates every receipt, and its aggregate exact-work/storage budget still
applies. Export borrows metadata without materializing per-receipt source copies.
Counts are aggregate, not reset by each evidence entry. Exhaustion is
`limit`, not `invalid_ir`; both reject the artifact. These are limits on a new
format, not capacity changes to existing Rust constructors.

### Reconstructed finite unitary leaves

The additive Rust API [interchange::finite_leaf](../src/interchange/finite_leaf.rs)
reuses the finite verifier and exact checker for an explicit transitional
leaf premise. `UnitaryBoundary::new` requires a complete legacy `BasisType`
tree and one input/output `QuantumPort`, including each owner ID, shape and
ordered wire list. Both endpoints have that exact type; zero-width `Unit`
still has an owner. Equal widths do not identify distinct type trees or
authorize an implicit Bit/Bits conversion.

`check_unitary(payload, boundary, meaning, budget)` freshly imports all QIRF1/2
programs and embedded evidence. It requires declared and derived `Unitary`,
no external classical ports, the exact retained root type trees, the requested
input port and the verifier's actual final output port. It extracts the exact
whole-space matrix in those ordered axes, checks equality to the independently
required matrix including global phase, and checks its isometry. Internal
closed classical control is allowed by the existing finite contract. The
six-bit/64-dimensional, arithmetic and circuit limits remain unchanged.

The caller supplies the same `Budget` for all leaves of one artifact. Imports,
embedded receipts, matrix extraction/comparison and isometry checks consume
that allowance; the adapter neither resets it nor accepts an allowance above
the existing 10,000,000-unit ceiling. QIRF byte/graph limits still apply to each
packet; the future hierarchy host must also enforce its aggregate transport
limits and reconstruct each bound packet. Capacity exhaustion returns `limit`;
malformed QIRF and failed equations retain the existing `format`/`contract`
diagnostics.

`CheckedUnitaryLeaf` has private fields and retains immutable complete bytes,
the required boundary, checked program and exact matrix. Its `matches` method
compares complete bytes and structural values, never addresses or digests.
Different whitespace can encode the same program, but constitutes a distinct
byte binding. This result has no serialized authority form. It is not a Lean
theorem, a hierarchy seal or a proof of the Rust implementation. The
[migration plan](lean-kernel-migration.md) retains that Rust correspondence
premise until K1/K2. The pure [hierarchical request projection](hierarchical-ir-spec.md#finite-reconstruction-requests)
now retains actual indexed program/meaning bytes and identity-encoded endpoints.
The [fresh hierarchy host](hierarchical-ir-spec.md#external-field-encoding-and-reconstruction-host)
now reconstructs the actual returned indices from the same immutable artifact.
Its additive [independent request API](hierarchical-ir-spec.md#independently-requested-roots)
also checks the supported conditional root against a separate meaning graph.
Its [singleton Fourier path](hierarchical-ir-spec.md#fourier-request-host) now
uses the same API and request envelope for a closed single-`Bits<n>` QFT. A fresh
composite Lean check binds the actual circuit to the independent Fourier
contract, and Rust reconstructs both ordinary finite proofs and the additional
phase-fixed H obligations on the same bytes and exact budget. Private `QLF1`
framing and pending output are transport data, not producer evidence.
Complete production integration, rectangular isometries, instruments and
multi-owner leaves remain pending.

### Exact finite matrix descriptions

The additive `interchange::finite_matrix` transport encodes a mathematical
matrix independently of its implementation. Its version-one envelope is
exactly `{format:"qleisli.finite-matrix",version:1,domain:"zeta8-dyadic-v1",
rows,cols,entries}`. Rows and columns are unsigned integers in 1–64; `entries`
is a row-major array with exactly `rows*cols` scalars. Rectangular matrices are
valid descriptions, but the unitary-leaf adapter requires the square dimension
specified by its independently required type. A description is not evidence.

Each scalar is an array of four dyadics in the fixed order `a,b,c,d`, denoting
`a + b*sqrt(2) + i*(c + d*sqrt(2))`. A dyadic is exactly
`{numerator:string,denominator_bits:integer}`, denoting `numerator/2^denominator_bits`.
The numerator is canonical signed decimal i128 text: `0`, a nonzero positive
decimal without leading zeros, or `-` followed by such a positive decimal.
No plus sign, negative zero, whitespace or floating-point number is allowed.
The exponent is 0–126. Zero requires exponent zero; a nonzero numerator must be
odd when the exponent is positive. The four exponents are independent; an
encoder must not rescale all coefficients to a common denominator. The complete
existing exact scalar capacity is retained. Out-of-range numerators/exponents
or dimensions return `limit`; malformed/noncanonical representations return
`format`. Unknown fields, domains, versions and duplicate keys are rejected.

`finite_matrix::encode(matrix)` produces deterministic JSON and a trailing LF.
`decode(description, budget)` uses the existing bounded strict JSON reader
(16 MiB, depth 128, one million values), checks dimensions and entry count,
then charges four units per entry before constructing scalars. Failed scalar
decoding does not refund that charge. The same caller budget is shared with
leaf reconstruction and cannot exceed 10,000,000 units. Tokenization has its
separate existing transport limits. Decoding performs no equation/isometry
check and does not establish that a matrix is a supported program meaning.

`finite_leaf::check_serialized_unitary(payload, boundary, description, budget)`
first requires the combined payload and description size to be at most 16 MiB,
decodes the description and invokes `check_unitary` with that exact matrix.
`CheckedSerializedUnitaryLeaf` privately retains the checked leaf and the
complete description bytes. `matches` compares both complete byte strings and
the required boundary; altered whitespace changes the binding even if decoding
is equal. Its work count includes decoding and reconstruction. All equation,
phase, ownership and embedded-evidence checks of `check_unitary` still apply.
This is a transitional finite Rust result, not a serialized authority token or
a whole-hierarchy result. The reconstruction host now binds it to actual Lean
request indices and shares aggregate work and payload accounting. Independent
production root contracts and decoder correspondence remain separate obligations.

### Independently supplied finite requests

A request-file is exactly `{format:"qleisli.request",version:1,signature,
meaning:{tag,table},source_snapshot}`. The signature is a basis tree; meaning
tag is `permutation` or `phase8`; table is the complete ordered u16 permutation
or 0–7 phase table. `source_snapshot` is null (no provenance requirement) or
the exact ordered array of `{path,text}`. `--against` requires a non-null,
validated `root_interface` whose input and output trees both equal the request
signature structurally, including Unit nodes, tuple arity and nested association. Missing
type information or either tree mismatch is `contract`, even if the bit counts
and operators agree; never fill in or replace root types from the request.
It also requires a closed unary unitary root (no classical inputs/outputs), exact
operator equality to the requested meaning and, if supplied, identical source
snapshots. Here “closed unary” means no free inputs beyond the one declared
quantum port, not a zero-input simulator entry point. It does not recompile
source or establish source adequacy. A valid but different contract is rejected.

For example, a one-bit identity root declared with input/output `Bit` satisfies
an identity request on `Bit`, but rejects identity requests on `(Unit,Bit)` or
`(Bit,Unit)`. An identity root declared with `(Unit,Bit)` at both ports instead
satisfies the matching `(Unit,Bit)` request. Changing only its output tree to
`Bit` rejects that request; replacing the interface with null also rejects it.
A declared two-bit tree on that one-bit root is internally invalid even without
`--against`. Equal matrix dimensions never establish equality of type trees.

M1's new meaning/evidence action uses **QIRF version 2**, with a distinct
profile `finite-meaning-v1`. It inherits all version-1 fields/rules and extends
evidence entries with a tag: `circuit` has the v1 fields; `meaning` has signature,
implementation,meaning,identity, where meaning is the request meaning above
and identity uses the declared meaning name as specification. All entries in
v2 require a tag. Import checks the meaning table and equality independently.
The checked v1→v2 adapter adds `circuit` tags and preserves `root_interface`
exactly, including null; v2→v1 rejects `meaning` entries
instead of disguising them as an unchecked circuit. Unknown versions fail.
Hierarchy requires another profile/version; it is never squeezed into v1/v2.

## Sampling and typed trials

Add `sample_closed(program, random, limits) -> Result<Sample, SampleError>`
as a **host Rust API**, taking a VerifiedProgram, a mutable fallible random
source returning uniform u64 words, and explicit limits. Sample owns
`bits: Vec<bool>` in the same output order as `run_closed` and
`execution_steps: u64`. It returns no live quantum owner. The input program
must have no external quantum/classical inputs and no quantum outputs.
Errors distinguish not-closed, limit, random-source failure, numerical failure
and inconsistent verified IR. No error is returned as an ordinary outcome bit.
Keep the existing exhaustive simulator/API unchanged.

Use one normalized pure-state trajectory, starting from empty state on every
call. At measurement, compute p0 by ascending basis index, draw
`u=(word>>11)*2^-53`, select zero iff u<p0, collapse and renormalize the chosen
branch. Clamp a probability outside [0,1] only within 2^-40; otherwise return
numerical failure. After each deterministic IR operation, require finite
amplitudes, positive finite norm² and
`|norm²−1| ≤ 2^-40 + 16 × f64::EPSILON × executed_steps`, then renormalize.
Here `executed_steps` is work charged by that operation since the previous
normalization, including nested circuit/contract steps; unused configured
capacity contributes nothing. Before each observation, after collapse and at
completion, use the base `2^-40` norm guard and renormalize within tolerance.
Never continue from a zero-norm selected branch. Renormalization consumes no
random word or extra IR execution step. This empirical roundoff guard is not
a certified forward-error bound and does not authorize evidence. Deterministic observations still consume a
word. Reset/discard use a hidden computational-basis measurement, then remove
the old wire and optionally allocate fresh zero; this reproduces the ensemble
partial trace, including entangled inputs. Consume hidden draws in program and
ascending wire order. Runtime classical branches execute only the selected arm.
This sampling algorithm is approximate reference execution, not a proof of
exact semantics or a guarantee of hardware distributions.

Defaults: max live qubits 16 (hard maximum 20), amplitude cells 1,048,576,
execution steps 1,000,000 per sample. Charge each executed primitive/branch
dispatch and each repeated/called step, including hidden observations; symbolic
counts never make execution free. No ensemble-component limit is needed for
one trajectory. Aggregate CLI work is at most 10,000,000 executed steps across
all shots; error atomically with no partial success document if exceeded.

CLI syntax is `qleisli sample <project> --shots=N --seed=S [--format=json]`.
Both are required: 1≤N≤1,000,000 and 0≤S<2^64, decimal canonical integers.
Use a single sequential generator stream across fresh shots. Generator profile
`splitmix64-v1` is specified by this exact unsigned-64 wrapping algorithm:

```text
state = state + 0x9e3779b97f4a7c15
z = state
z = (z xor (z >> 30)) * 0xbf58476d1ce4e5b9
z = (z xor (z >> 27)) * 0x94d049bb133111eb
word = z xor (z >> 31)
```

Seed initializes state directly. The host API may supply a different uniform
source; the CLI has no implicit time-based seed. Same seed/profile/program and
numeric backend reproduce a trace; cross-platform floating rounding can change
a boundary decision and is not promised bit-for-bit. JSON result is
`{rng:"splitmix64-v1",seed:string,shots:[{bits,execution_steps},...],
execution_steps:integer}`; seed is decimal text to avoid JSON-client precision
loss. Human output is one bitstring (or `()`) per shot. This is an actual draw,
not returning every branch of `run_closed`.

Provide the independent host combinator `run_trials(max_attempts, trial)`.
The callback receives a one-based attempt index and returns
`Result<TrialDecision<T,R>, E>`, where TrialDecision is `Accepted(T)` or
`Retry(R)`. R is the caller's typed retry reason. Result is
`Result<TrialRun<T,R>, TrialFailure<R,E>>`; TrialRun is
`Accepted{value,attempts,retries}` or `Exhausted{attempts,retries}`.
TrialFailure is `InvalidLimit{requested,max}` or
`Execution{attempts_started,error:E,retries}`. InvalidLimit invokes no callback.
`retries` is an ordered
list of `{attempt,reason}`. A callback error aborts immediately and is never
counted as a retry; acceptance stops immediately. Zero attempts yields
Exhausted with zero attempts without invoking the callback. Maximum accepted
bound is 1,000,000. Each quantum callback must invoke fresh preparation/sampling;
the combinator does not reuse a collapsed state or secretly choose a new seed.

The first Shor host integration keeps `invalid_candidate`, `odd_period`, and
`trivial_factor` as distinct retry reasons. Before reporting a period, check
r>0, a^r mod N=1 and minimality by prime-divisor reduction of r. Before reporting
factors check 1<p,q<N and p*q=N with checked arithmetic; an unverified continued
fraction denominator is only a candidate. Select the bounded reference host
profile 2≤N<2^32, 1<a<N, gcd(a,N)=1 and 1≤m≤32. Enumerate convergents of y/2^m
in order, test denominators 1≤r<N, reduce successful r by trial-dividing its
prime factors in increasing order, then apply the standard even-r gcd tests.
No successful denominator yields invalid_candidate; no fabricated period.
Arithmetic uses checked u128, Euclidean gcd and square-and-multiply modular
power. At most 1,000,000 arithmetic loop iterations per trial; exhaustion is
an execution limit error. Classical prechecks (even N/nontrivial gcd) report
validated classical factors separately, without claiming a quantum trial.
This specifies integration behavior; general efficient number theory is M4.

## Source input capacities and migration

The 0.2.0 CLI loader defaults to 1 MiB per UTF-8 `.qli` file and 16 MiB aggregate
across distinct canonical project files plus bundled modules, counting bytes
before decoding/normalization. Stream at most limit+1 bytes per file, rejecting
at the first excess; account files in existing deterministic path order.
I/O/UTF-8 errors remain project errors; size errors are `limit` and identify the
path and limit with no invented character span. Symlinks/canonical paths keep
the current project rules. Per-function source evidence retains its stricter
current 1 MiB snapshot limit, even if loading succeeds.

Add `--source-bytes=N --project-bytes=N` positive u64 overrides and a mutually
exclusive `--legacy-source-limits` restoring the current unbounded byte loader.
Host loading gains the analogous explicit policy object; retain the old loader
through an adapter selecting legacy policy. Arithmetic overflow is a limit
error. Overrides alter byte limits only, not parser/evidence/work limits.
The new default/restricted acceptance is MINOR; migration for old large
projects is explicit opt-in legacy loading or larger bounds. 0.1.5 adds no cap.

## Required conformance before shipping

| Gate | Positive and adversarial evidence required |
| --- | --- |
| X1 diagnostics | Golden success/usage/type/runtime JSON; Unicode and EOF spans; no mixed stdout; unchanged human check/run and exits; reject unknown/duplicate flags. |
| X2 interchange | Round-trip every RawOp/action, shared evidence DAG and exact root input/output trees (including Unit, tuple arity and nested association) through v1/v2; check requested meaning/provenance; reject cycles, dangling/unused entries, malformed tags/IDs, invalid root port/type binding, phase/output/source mutation and all limits, including deep-rejection destruction. |
| X3 independent trust | Import in a fresh process with no frontend/cache; mutate the root or requested target; accept matching typed identity requests, reject equal-width tree substitutions at either root port and null interfaces under `--against`; never infer types from requests; reject invalid contracts even when names/hashes match; document source-adequacy boundary. |
| X4 sampling | Deterministic basis states; seeded known generator words; Bell correlation, reset/discard marginal and feedback; independent statistical tests against finite exhaustive distributions with stated confidence/tolerance. No golden lucky random frequency. |
| X5 trials | Accept on first/later attempt, all retries, zero bound, injected RNG/runtime/numerical failure, invalid/odd periods, trivial gcds and checked factors; count preparation/attempts precisely. |
| X6 migration/capacity | Boundary byte sizes, multibyte UTF-8, many small files, bundle accounting, overflow and legacy override; old source/IR behavior preserved through explicit adapters. |

The original documentation release did not execute these tests. X1 check/run
now has [Rust CLI regressions](../tests/cli_json.rs),
[structured location checks](../tests/diagnostics.rs) and an
[independent JSON decoder suite](../scripts/test_cli_json.py); execution results
belong in the [0.1.7 record](releases/v0.1.7.md). X2–X6's implementation and
validation are recorded separately in the [0.2.0 record](releases/v0.2.0.md).

## 0.2.0 host API mapping

[`interchange::export`](../src/interchange/mod.rs) accepts a `VerifiedProgram`,
optional retained `RootInterface`, and `Version::V1`/`V2`.
`export_with_meanings` retains explicitly supplied sealed `MeaningEvidence`
receipts as v2 meaning entries; ordinary export retains their already checked
canonical target circuits. `convert` checks the input and preserves source
ordering and exact root types; it rejects a v2 meaning entry when targeting v1.
`import(bytes, request)` reconstructs all receipts and returns the verified
root, retained interface, `request_checked`, and charged exact work.

The CLI emitter currently exports the closed observation entry as QIRF2, with
a null root interface. Such an entry cannot satisfy a unary unitary request;
typed unitary producers use the Rust exporter and retain their exact trees.
`verify-ir` accepts both specified versions and has no frontend dependency in
its execution path. No source-adequacy theorem is claimed by either adapter.

[`sample_closed`](../src/sim/sampling.rs), `RandomSource`, `SampleLimits`,
`SampleError` and `SplitMix64` implement X4; [`run_trials`](../src/host.rs) and
the [bounded factoring helpers](../src/host/factoring.rs) implement X5.
[`SourcePolicy`](../src/frontend/project.rs) and policy-bearing project/check/
compile functions implement X6. Existing host entry points select `Legacy`.
These are host APIs, not new sealed `.qli` operations or bundled definitions.
Their future shipping still requires the remaining release validation and a
compatibility-based release decision; reduced acceptance in X6 requires MINOR.
X1 diagnostic transport alone is not portable IR or evidence.