qleisli 0.2.2

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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
import QleisliKernel.Hierarchy
import QleisliKernel.Layout
import QleisliKernel.LayoutDag
import QleisliKernel.PhaseLayout
import QleisliKernel.Hierarchical.Root
import QleisliKernel.Hierarchical.FourierRoot
import QleisliKernel.Hierarchical.Readout
import QleisliKernel.Hierarchical.Preparation
import QleisliKernel.Hierarchical.Instrument
import QleisliKernel.Hierarchical.QpeInstrument

/-
Copyright 2026 Masahiko G. Yamada.
Licensed under the Apache License, Version 2.0; see the repository LICENSE.

This deliberately small experimental wire protocol is not QIRF or a general
IR decoder. Parsing is an unproved adapter; the corresponding pure checker
determines acceptance of each experimental profile.
-/

namespace QleisliKernel.Protocol

def maxInputBytes : Nat := 65536

def header : String := "qleisli.phase-word 1 phase256-word-v1"

def interfaceLine : String := "Bit->Bit"

inductive Error where
  | syntax
  | limit
  deriving BEq, Repr

structure Artifact where
  word : Word
  claimed : Summary

private def decimal (text : String) (bound : Nat) : Except Error Nat := do
  if text.isEmpty || !(text.toList.all Char.isDigit) then
    throw .syntax
  if text.length > 1 && text.startsWith "0" then
    throw .syntax
  -- Every protocol integer is at most 4096. Refuse long decimal strings
  -- before allocating arbitrary-precision values for their numeric contents.
  if text.length > 4 then
    throw .limit
  match text.toNat? with
  | none => throw .syntax
  | some value =>
    if value > bound then throw .limit
    return value

private def summary (tag line : String) : Except Error Summary := do
  match line.splitOn " " with
  | [actualTag, flip, phase0, phase1] =>
    if actualTag != tag then throw .syntax
    let bit ← decimal flip 1
    let p0 ← decimal phase0 255
    let p1 ← decimal phase1 255
    return { flip := bit == 1, phase0 := p0, phase1 := p1 }
  | _ => throw .syntax

private def gate (line : String) : Except Error Gate := do
  match line.splitOn " " with
  | ["x"] => return .x
  | ["phase", ticks] => return .phase (← decimal ticks 255)
  | _ => throw .syntax

private def gates (lines : List String) : Except Error Word := do
  -- The final empty split component requires a trailing LF. Folding the
  -- remaining reversed lines reconstructs execution order without a project
  -- recursive declaration or a compiler-generated partial replacement.
  match lines.reverse with
  | "" :: rest =>
    rest.foldlM (fun result line => do return (← gate line) :: result) []
  | _ => throw .syntax

private def envelope (text : String) : Except Error (List String) := do
  if text.utf8ByteSize > maxInputBytes then throw .limit
  -- LF and printable ASCII are the entire alphabet. In particular CR, NUL,
  -- tabs, Unicode separators, and a byte-order mark are never normalized.
  if !(text.toList.all (fun c => c == '\n' || (' ' ≤ c && c ≤ '~'))) then
    throw .syntax
  match text.splitOn "\n" with
  | h :: interface :: rest =>
    if h != header || interface != interfaceLine then throw .syntax
    return rest
  | _ => throw .syntax

/-- Parse an exact LF-terminated `.qpk` artifact, with no ignored fields. -/
def parseArtifact (text : String) : Except Error Artifact := do
  match ← envelope text with
  | claim :: count :: lines =>
    let claimed ← summary "claim" claim
    let expectedLength ← decimal count 4096
    if lines.length != expectedLength + 1 then throw .syntax
    let word ← gates lines
    return { word, claimed }
  | _ => throw .syntax

/-- Parse the client's independent, exact LF-terminated `.qpr` requirement. -/
def parseRequirement (text : String) : Except Error Summary := do
  match ← envelope text with
  | [expected, ""] => summary "expect" expected
  | _ => throw .syntax

end QleisliKernel.Protocol

namespace QleisliKernel.Protocol.Dag
open QleisliKernel.Dag QleisliKernel.Hierarchy

def header : String := "qleisli.phase-dag 1 phase256-dag-v1"

structure Artifact where
  definitions : List Definition
  entry : Nat

private def envelope (text : String) : Except Error (List String) := do
  if text.utf8ByteSize > maxInputBytes then throw .limit
  if !(text.toList.all (fun c => c == '\n' || (' ' ≤ c && c ≤ '~'))) then
    throw .syntax
  match text.splitOn "\n" with
  | h :: rest =>
    if h != header then throw .syntax
    match rest.reverse with
    | "" :: lines => return lines.reverse
    | _ => throw .syntax
  | _ => throw .syntax

private def shape : String → Except Error Shape
  | "Unit" => .ok .unit
  | "Bit" => .ok .bit
  | "Bits0" => .ok .bits0
  | "Bits1" => .ok .bits1
  | _ => .error .syntax

private def naturalList (texts : List String) : Except Error (List Nat) :=
  texts.mapM (fun text => decimal text 4096)

private def leafGate (text : String) : Except Error Gate := do
  if text == "x" then return .x
  if text.startsWith "p" then
    return .phase (← decimal (text.drop 1).toString 255)
  throw .syntax

private def instruction : List String → Except Error Instruction
  | "leaf" :: length :: gates => do
    let count ← decimal length 4096
    if gates.length != count then throw .syntax
    return .leaf (← gates.mapM leafGate)
  | ["repeat", count, body] => do
    return .repeatOp (← decimal count 4096) (← decimal body 255)
  | "sequence" :: length :: children => do
    let count ← decimal length 4096
    if children.length != count then throw .syntax
    return .sequence (← naturalList children)
  | "call" :: body :: inputs :: rest => do
    let definition ← decimal body 255
    let inputCount ← decimal inputs 4096
    if rest.length < inputCount then throw .syntax
    let (input, remaining) := rest.splitAt inputCount
    match remaining with
    | outputs :: output =>
      let outputCount ← decimal outputs 4096
      if output.length != outputCount then throw .syntax
      return .call definition (← naturalList input) (← naturalList output)
    | _ => throw .syntax
  | _ => .error .syntax

private def definition (line : String) : Except Error Definition := do
  match line.splitOn " " with
  | type :: flip :: phase0 :: phase1 :: body =>
    let interface ← shape type
    let claimed ← summary "claim" ("claim " ++ flip ++ " " ++ phase0 ++ " " ++ phase1)
    return ⟨interface, ← instruction body, claimed⟩
  | _ => throw .syntax

/-- Strict transport for the bounded composition slice; no unknown rule is enabled. -/
def parseArtifact (text : String) : Except Error Artifact := do
  match ← envelope text with
  | entryLine :: countLine :: definitions =>
    match entryLine.splitOn " ", countLine.splitOn " " with
    | ["entry", entry], ["nodes", count] =>
      let root ← decimal entry 255
      let count ← decimal count 256
      if definitions.length != count then throw .syntax
      return ⟨← definitions.mapM definition, root⟩
    | _, _ => throw .syntax
  | _ => throw .syntax

def parseRequirement (text : String) : Except Error Request := do
  match ← envelope text with
  | [interface, expected] =>
    return ⟨← shape interface, ← summary "expect" expected⟩
  | _ => throw .syntax

end QleisliKernel.Protocol.Dag

namespace QleisliKernel.Protocol.Layout
open QleisliKernel.Layout

structure Artifact where
  layout : Rewire
  witness : Witness

private def envelope (expected text : String) : Except Error (List String) := do
  if text.utf8ByteSize > maxInputBytes then throw .limit
  if !(text.toList.all (fun c => c == '\n' || (' ' ≤ c && c ≤ '~'))) then
    throw .syntax
  match text.splitOn "\n" with
  | h :: rest =>
    if h != expected then throw .syntax
    match rest.reverse with
    | "" :: lines => return lines.reverse
    | _ => throw .syntax
  | _ => throw .syntax

private def countLine (tag : String) (limit : Nat) (line : String) : Except Error Nat := do
  match line.splitOn " " with
  | [actual, count] =>
    if actual != tag then throw .syntax
    decimal count limit
  | _ => throw .syntax

private def indices (tag : String) (limit : Nat) (line : String) : Except Error (List Nat) := do
  match line.splitOn " " with
  | actual :: length :: items =>
    if actual != tag then throw .syntax
    let count ← decimal length limit
    if items.length != count then throw .syntax
    items.mapM (fun text => decimal text 4096)
  | _ => throw .syntax

private def atom (text : String) : Except Error TypeAtom := do
  if text == "Unit" then return .unit
  if text == "Bit" then return .bit
  if text.startsWith "Bits" then return .bits (← decimal (text.drop 4).toString 4096)
  if text.startsWith "t" then return .tuple (← decimal (text.drop 1).toString 4096)
  throw .syntax

private def port (line : String) : Except Error Port := do
  match line.splitOn " " with
  | "port" :: length :: rest =>
    let count ← decimal length 128
    if rest.length ≤ count then throw .syntax
    let basis ← (rest.take count).mapM atom
    let width :: axes := rest.drop count | throw .syntax
    let bits ← decimal width 16
    if axes.length != bits then throw .syntax
    return ⟨basis, ← axes.mapM (fun text => decimal text 4096)⟩
  | _ => throw .syntax

private def interface (tag : String) (lines : List String) :
    Except Error (Interface × List String) := do
  let first :: rest := lines | throw .syntax
  let count ← countLine tag 64 first
  if rest.length < count then throw .syntax
  return (← (rest.take count).mapM port, rest.drop count)

private def rewire (lines : List String) : Except Error (Rewire × List String) := do
  let (inputs, rest) ← interface "inputs" lines
  let (outputs, rest) ← interface "outputs" rest
  let owners :: axes :: rest := rest | throw .syntax
  return (⟨inputs, outputs, ← indices "owners" 64 owners, ← indices "axes" 16 axes⟩, rest)

def parseArtifact (text : String) : Except Error Artifact := do
  let lines ← envelope "qleisli.layout 1 typed-layout-v1" text
  let (layout, rest) ← rewire lines
  match rest with
  | [owners, axes] =>
    return ⟨layout, ⟨← indices "inverse_owners" 64 owners, ← indices "inverse_axes" 16 axes⟩⟩
  | _ => throw .syntax

def parseRequirement (text : String) : Except Error Rewire := do
  let lines ← envelope "qleisli.layout-request 1 typed-layout-v1" text
  let (layout, rest) ← rewire lines
  if !rest.isEmpty then throw .syntax
  return layout

end QleisliKernel.Protocol.Layout

namespace QleisliKernel.Protocol.LayoutDag
open QleisliKernel.LayoutDag

structure Artifact where
  entry : Nat
  definitions : List Definition

private def certified (lines : List String) : Except Error (Certified × List String) := do
  let (layout, rest) ← Layout.rewire lines
  let owners :: axes :: rest := rest | throw .syntax
  return (⟨layout, ⟨← Layout.indices "inverse_owners" 64 owners,
    ← Layout.indices "inverse_axes" 16 axes⟩⟩, rest)

private def definition (lines : List String) : Except Error (Definition × List String) := do
  let first :: rest := lines | throw .syntax
  match first.splitOn " " with
  | ["leaf"] =>
    let (result, rest) ← certified rest
    return (⟨.leaf result.layout, result⟩, rest)
  | ["call", child] =>
    let child ← decimal child 255
    let (input, rest) ← certified rest
    let (output, rest) ← certified rest
    let (result, rest) ← certified rest
    return (⟨.call child input output, result⟩, rest)
  | ["then", first, second] =>
    let first ← decimal first 255
    let second ← decimal second 255
    let (result, rest) ← certified rest
    return (⟨.then first second, result⟩, rest)
  | _ => throw .syntax

def parseArtifact (text : String) : Except Error Artifact := do
  let lines ← Layout.envelope "qleisli.layout-dag 1 typed-layout-dag-v1" text
  let entry :: count :: rest := lines | throw .syntax
  let entry ← Layout.countLine "entry" 255 entry
  let count ← Layout.countLine "definitions" 256 count
  let mut remaining := rest
  let mut definitions := #[]
  for _ in List.range count do
    let (next, rest) ← definition remaining
    definitions := definitions.push next
    remaining := rest
  if !remaining.isEmpty then throw .syntax
  return ⟨entry, definitions.toList⟩

end QleisliKernel.Protocol.LayoutDag

namespace QleisliKernel.Protocol.PhaseLayout
open QleisliKernel.PhaseLayout QleisliKernel.PhasePolynomial

structure Artifact where
  entry : Nat
  definitions : List Definition

private def term (line : String) : Except Error Term := do
  match line.splitOn " " with
  | "term" :: ticks :: count :: axes =>
    let ticks ← decimal ticks 255
    let count ← decimal count 16
    if axes.length != count then throw .syntax
    return ⟨← axes.mapM (fun axis => decimal axis 15), ticks⟩
  | _ => throw .syntax

private def polynomial (tag : String) (lines : List String) :
    Except Error (Polynomial × List String) := do
  let first :: rest := lines | throw .syntax
  let count ← Layout.countLine tag 128 first
  if rest.length < count then throw .syntax
  return (← (rest.take count).mapM term, rest.drop count)

def parseArtifact (text : String) : Except Error Artifact := do
  let lines ← Layout.envelope "qleisli.phase-layout 1 typed-phase256-dag-v1" text
  let entry :: count :: rest := lines | throw .syntax
  let entry ← Layout.countLine "entry" 255 entry
  let count ← Layout.countLine "definitions" 256 count
  let mut remaining := rest
  let mut definitions := #[]
  for _ in List.range count do
    let (wiring, rest) ← LayoutDag.definition remaining
    let (source, rest) ← polynomial "source_phases" rest
    let (claim, rest) ← polynomial "claim_phases" rest
    definitions := definitions.push ⟨wiring, source, claim⟩
    remaining := rest
  if !remaining.isEmpty then throw .syntax
  return ⟨entry, definitions.toList⟩

def parseRequirement (text : String) : Except Error QleisliKernel.PhaseLayout.Summary := do
  let lines ← Layout.envelope "qleisli.phase-layout-request 1 typed-phase256-dag-v1" text
  let (layout, rest) ← Layout.rewire lines
  let (phases, rest) ← polynomial "expect_phases" rest
  if !rest.isEmpty then throw .syntax
  return ⟨layout, phases⟩

end QleisliKernel.Protocol.PhaseLayout

namespace QleisliKernel.Protocol.Hierarchical
open QleisliKernel.Hierarchical.Artifact

/-! Private bounded framing for the strict Rust external decoder. This total
transport decoder is outside the pure acceptance core. Its output is untrusted
until the actual whole-artifact checker runs; finite bytes remain obligations. -/

def maxBridgeBytes : Nat := 67108864

private structure Cursor where
  bytes : ByteArray
  position : Nat := 4
  remaining : Nat := 1000000

private abbrev DecodeM := StateT Cursor (Except Protocol.Error)

private def word : DecodeM Nat := do
  let s ← get
  if s.remaining == 0 then throw .limit
  if s.position + 4 > s.bytes.size then throw .syntax
  let n := s.bytes[s.position]!.toNat + 256 * s.bytes[s.position+1]!.toNat +
    65536 * s.bytes[s.position+2]!.toNat + 16777216 * s.bytes[s.position+3]!.toNat
  set { s with position := s.position + 4, remaining := s.remaining - 1 }
  return n

private def boolean : DecodeM Bool := do
  match ← word with
  | 0 => return false
  | 1 => return true
  | _ => throw .syntax

private def block (limit : Nat) : DecodeM ByteArray := do
  let size ← word
  let s ← get
  if size > limit then throw .limit
  if s.position + size > s.bytes.size then throw .syntax
  set { s with position := s.position + size }
  return s.bytes.extract s.position (s.position + size)

private def bytes : DecodeM ByteArray := block 16777216

private def array {α : Type} (read : DecodeM α) : DecodeM (Array α) := do
  let size ← word
  if size > 100000 || size > (← get).remaining then throw .limit
  let mut result := #[]
  for _ in [:size] do result := result.push (← read)
  return result

private def basis : DecodeM Basis := array do
  match ← word with
  | 0 => return .unit
  | 1 => return .bit
  | 2 => return .bits (← word)
  | 3 => return .tuple (← word)
  | _ => throw .syntax

private def side : DecodeM Side := do
  let quantum ← array do
    return (⟨← word, ← basis, ← array word⟩ : QuantumPort)
  let classical ← array do
    return (⟨← word, ← basis⟩ : ClassicalPort)
  return ⟨quantum,classical⟩

private def interface : DecodeM Interface := do return ⟨← side, ← side⟩
private def portMap : DecodeM PortMap := do return ⟨← array word, ← array word, ← array word⟩

private def structural : DecodeM StructuralOp := do
  match ← word with
  | 0 => return .takeBit (← word) (← word)
  | 1 => return .putBit (← word) (← word)
  | 2 => return .splitTuple
  | 3 => return .joinTuple
  | 4 => return .bitToBits
  | 5 => return .bitsToBit
  | 6 => return .packUnit
  | 7 => return .unpackUnit
  | 8 => return .packEmptyBits
  | 9 => return .unpackEmptyBits
  | _ => throw .syntax

private def body : DecodeM Body := do
  match ← word with
  | 0 => return .leaf (← bytes)
  | 1 => return .sequence (← array word)
  | 2 => return .tensor (← word) (← word)
  | 3 => return .call (← word) (← portMap) (← portMap)
  | 4 => return .repeatOp (← word) (← word)
  | 5 => return .inverse (← word)
  | 6 => return .control (← word) (← boolean)
  | 7 => return .rewire (← portMap)
  | 8 => return .structural (← structural)
  | 9 => return .dyadicPhase (← word) (← word) (← word)
  | 10 => return .computed (← word) (← word) (← word) (← word)
  | 11 => return .observeZ (← word) (← word)
  | 12 => return .init0 (← word)
  | _ => throw .syntax

private def definition : DecodeM Definition := do
  let header ← interface
  let effect ← match ← word with
    | 0 => pure Effect.unitary
    | 1 => pure Effect.iso
    | 2 => pure Effect.observe
    | _ => throw .syntax
  return ⟨header,effect,← body⟩

private def meaningBody : DecodeM MeaningBody := do
  match ← word with
  | 0 => return .identity
  | 1 => return .finite (← bytes)
  | 2 => return .sequence (← array word)
  | 3 => return .tensor (← word) (← word)
  | 4 => return .inverse (← word)
  | 5 => return .control (← word) (← boolean)
  | 6 => return .power (← word) (← word)
  | 7 => return .rewire (← portMap)
  | 8 => return .structural (← structural)
  | 9 => return .phase (← word) (← word)
  | 10 => return .qft (← word)
  | 11 => return .qpeInstrument (← word) (← word) (← word)
  | _ => throw .syntax

private def meaning : DecodeM Meaning := do return ⟨← interface, ← meaningBody⟩

private def encodingBody : DecodeM EncodingBody := do
  match ← word with
  | 0 => return .identity
  | 1 => return .tensor (← word) (← word)
  | 2 => return .rewire (← word) (← portMap)
  | 3 => return .zeroScratch (← word) (← word)
  | _ => throw .syntax

private def encoding : DecodeM Encoding := do return ⟨← side, ← side, ← encodingBody⟩

private def rule : DecodeM Rule := do
  match ← word with
  | 0 => return .finite
  | 1 => return .sequence
  | 2 => return .tensor
  | 3 => return .inverse
  | 4 => return .control
  | 5 => return .repeatOp
  | 6 => return .associativity
  | 7 => return .rewire
  | 8 => return .structural
  | 9 => return .phase
  | 10 => return .computed
  | 11 => return .conjugation
  | _ => throw .syntax  -- External schema entries remain disabled.

private def reference : DecodeM Ref := do
  let table ← match ← word with
    | 0 => pure Table.definition
    | 1 => pure Table.meaning
    | 2 => pure Table.encoding
    | 3 => pure Table.proof
    | _ => throw .syntax
  return ⟨table,← word⟩

private def proof : DecodeM Proof := do
  let kind ← match ← word with
    | 0 => pure Kind.equation
    | 1 => pure Kind.instrument
    | _ => throw .syntax
  let rule ← rule
  let premises ← array word
  let implementation ← word
  let meaning ← word
  let inputEncoding ← word
  let outputEncoding ← word
  let witness : Witness := ⟨← word, ← array word, ← array reference⟩
  return ⟨kind,rule,premises,implementation,meaning,inputEncoding,outputEncoding,witness⟩

/-- Decode complete tables and a proposed schedule, rejecting trailing data.
This never executes embedded strings and issues no evidence or acceptance. -/
private def parseBudget (input : ByteArray) (remaining : Nat) :
    Except Protocol.Error ((QleisliKernel.Hierarchical.Artifact.Artifact × Array Nat) × Nat) := do
  if input.size > maxBridgeBytes then throw .limit
  if input.size < 4 || input.extract 0 4 != "QLH1".toUTF8 then throw .syntax
  let read : DecodeM (QleisliKernel.Hierarchical.Artifact.Artifact × Array Nat) := do
    let definitions ← array definition
    let meanings ← array meaning
    let encodings ← array encoding
    let proofs ← array proof
    let entry : Entry := ⟨← word,← word⟩
    let order ← array word
    return (⟨definitions,meanings,encodings,proofs,entry⟩,order)
  let (result,final) ← read.run { bytes := input, remaining := remaining }
  if final.position != input.size then throw .syntax
  return (result,final.remaining)

def parse (input : ByteArray) : Except Protocol.Error (QleisliKernel.Hierarchical.Artifact.Artifact × Array Nat) :=
  (parseBudget input 1000000).map Prod.fst

/-- Separate caller request and untrusted pairing proposal. -/
structure RootPacket where
  artifact : QleisliKernel.Hierarchical.Artifact.Artifact
  order : Array Nat
  request : QleisliKernel.Hierarchical.Root.Request
  pairs : Array QleisliKernel.Hierarchical.Root.Pair
  pairOrder : Array Nat

private def parseRequestBudget (input : ByteArray) (remaining : Nat) (shared : Bool) :
    Except Protocol.Error (RootPacket × Nat) := do
  if input.size > maxBridgeBytes then throw .limit
  if input.size < 4 || input.extract 0 4 != "QLR1".toUTF8 then throw .syntax
  let read : DecodeM RootPacket := do
    let encoded ← block maxBridgeBytes
    let cursor ← get
    let allowance := if shared then cursor.remaining else 1000000
    let ((artifact,order),left) ← match parseBudget encoded allowance with
      | .error e => throw e
      | .ok result => pure result
    if shared then modify fun cursor => {cursor with remaining := left}
    let kind ← match ← word with
      | 0 => pure Kind.equation
      | 1 => pure Kind.instrument
      | _ => throw .syntax
    let effect ← match ← word with
      | 0 => pure Effect.unitary
      | 1 => pure Effect.iso
      | 2 => pure Effect.observe
      | _ => throw .syntax
    let request : QleisliKernel.Hierarchical.Root.Request :=
      ⟨kind,effect,← interface,← array meaning,← word⟩
    let pairs ← array do
      return (⟨← word,← word,← array word⟩ : QleisliKernel.Hierarchical.Root.Pair)
    return ⟨artifact,order,request,pairs,← array word⟩
  let (result,final) ← read.run { bytes := input, remaining := remaining }
  if final.position != input.size then throw .syntax
  return (result,final.remaining)

def parseRequest (input : ByteArray) : Except Protocol.Error RootPacket :=
  (parseRequestBudget input 1000000 false).map Prod.fst

/-- Canonical singleton Fourier request framing. The full independent interface
is transported twice, as in the external named meaning, and must agree. This
decoder is outside the pure acceptance core; its result remains untrusted. -/
structure FourierPacket where
  artifact : QleisliKernel.Hierarchical.Artifact.Artifact
  order : Array Nat
  request : QleisliKernel.Hierarchical.FourierRoot.Request
  wiringOrder : Array Nat

def parseFourier (input : ByteArray) : Except Protocol.Error FourierPacket := do
  if input.size > maxBridgeBytes then throw .limit
  if input.size < 4 || input.extract 0 4 != "QLF1".toUTF8 then throw .syntax
  let read : DecodeM FourierPacket := do
    let encoded ← block maxBridgeBytes
    let (artifact,order) ← match parse encoded with
      | .error e => throw e
      | .ok result => pure result
    if (← word) != 0 || (← word) != 0 then throw .syntax
    let header ← interface
    let meanings ← array meaning
    if (← word) != 0 || meanings.size != 1 then throw .syntax
    let some m := meanings[0]? | throw .syntax
    if m.interface != header then throw .syntax
    let .qft width := m.body | throw .syntax
    return ⟨artifact,order,⟨width,header⟩,← array word⟩
  let (result,final) ← read.run { bytes := input }
  if final.position != input.size then throw .syntax
  return result

/-- Additive internal readout framing. The request is supplied independently
by the caller; it is never inferred from the proposed measurement nodes. -/
structure ReadoutPacket where
  request : QleisliKernel.Hierarchical.Readout.Request
  packet : QleisliKernel.Hierarchical.Readout.Packet
  budget : Nat

def parseReadout (input : ByteArray) : Except Protocol.Error ReadoutPacket := do
  if input.size > maxBridgeBytes then throw .limit
  if input.size < 4 || input.extract 0 4 != "QLM1".toUTF8 then throw .syntax
  let read : DecodeM ReadoutPacket := do
    let request : QleisliKernel.Hierarchical.Readout.Request := ⟨← side, ← array word, ← word⟩
    let packet : QleisliKernel.Hierarchical.Readout.Packet := ⟨← array definition, ← array word, ← side⟩
    return ⟨request, packet, ← word⟩
  let (result, final) ← read.run { bytes := input }
  if final.position != input.size then throw .syntax
  return result

structure PreparationPacket where
  request : QleisliKernel.Hierarchical.Preparation.Request
  packet : QleisliKernel.Hierarchical.Preparation.Packet
  budget : Nat

/-- Separate explicit fresh-zero request, actual init nodes and work budget.
No field is a submitted success flag or an asserted initial quantum state. -/
def parsePreparation (input : ByteArray) : Except Protocol.Error PreparationPacket := do
  if input.size > maxBridgeBytes then throw .limit
  if input.size < 4 || input.extract 0 4 != "QLZ1".toUTF8 then throw .syntax
  let read : DecodeM PreparationPacket := do
    let inputs ← side
    let fresh ← side
    if !fresh.classical.isEmpty then throw .syntax
    let request : QleisliKernel.Hierarchical.Preparation.Request := ⟨inputs, fresh.quantum⟩
    let packet : QleisliKernel.Hierarchical.Preparation.Packet := ⟨← array definition, ← side⟩
    return ⟨request, packet, ← word⟩
  let (result, final) ← read.run { bytes := input }
  if final.position != input.size then throw .syntax
  return result

structure InstrumentPacket where
  request : QleisliKernel.Hierarchical.Instrument.Request
  packet : QleisliKernel.Hierarchical.Instrument.Packet

/-- The new composite frame shares its word allowance with both nested root
and artifact frames. Existing standalone transports retain their contracts. -/
def parseInstrument (input : ByteArray) : Except Protocol.Error InstrumentPacket := do
  if input.size > maxBridgeBytes then throw .limit
  if input.size < 4 || input.extract 0 4 != "QLI1".toUTF8 then throw .syntax
  let read : DecodeM InstrumentPacket := do
    let encoded ← block maxBridgeBytes
    let (root,left) ← match parseRequestBudget encoded (← get).remaining true with
      | .error error => throw error
      | .ok result => pure result
    modify fun cursor => {cursor with remaining := left}
    let inputs ← side
    let fresh ← side
    if !fresh.classical.isEmpty then throw .syntax
    let initialization : QleisliKernel.Hierarchical.Preparation.Packet := ⟨← array definition,← side⟩
    let readoutRequest : QleisliKernel.Hierarchical.Readout.Request := ⟨← side,← array word,← word⟩
    let readout : QleisliKernel.Hierarchical.Readout.Packet := ⟨← array definition,← array word,← side⟩
    let request : QleisliKernel.Hierarchical.Instrument.Request :=
      ⟨⟨inputs,fresh.quantum⟩,root.request,readoutRequest,← side⟩
    return ⟨request,⟨initialization,root.artifact,root.order,root.pairs,root.pairOrder,readout⟩⟩
  let (result,final) ← read.run {bytes := input}
  if final.position != input.size then throw .syntax
  return result

structure QpeInstrumentPacket where
  request : QleisliKernel.Hierarchical.QpeInstrument.Request
  packet : QleisliKernel.Hierarchical.QpeInstrument.Packet

/-- Private named-QPE framing. The nested root carries the independent provider
request; restore the original circuit entry before fresh whole-artifact checking.
Every nested frame and candidate field shares the same decoder allowance. -/
def parseQpeInstrument (input : ByteArray) : Except Protocol.Error QpeInstrumentPacket := do
  if input.size > maxBridgeBytes then throw .limit
  if input.size < 4 || input.extract 0 4 != "QLQ1".toUTF8 then throw .syntax
  let read : DecodeM QpeInstrumentPacket := do
    let encoded ← block maxBridgeBytes
    let (provider,left) ← match parseRequestBudget encoded (← get).remaining true with
      | .error error => throw error
      | .ok result => pure result
    modify fun cursor => {cursor with remaining := left}
    let entry : Entry := ⟨← word,← word⟩
    let circuit : QleisliKernel.Hierarchical.QpeSchedule.Request :=
      ⟨← interface,← array word,← array word,← array word,← word⟩
    let atom : DecodeM QleisliKernel.Hierarchical.CircuitTrace.Atom := do
      return ⟨← word,← interface⟩
    let candidate : QleisliKernel.Hierarchical.QpeSchedule.Candidate :=
      ⟨← array atom,← array atom,← atom,← array word,← array (array word),← array word⟩
    let root : QleisliKernel.Hierarchical.QpeRoot.Packet :=
      ⟨{provider.artifact with entry := entry},provider.order,provider.artifact.entry.proof,
        provider.pairs,provider.pairOrder,candidate⟩
    let inputs ← side
    let fresh ← side
    if !fresh.classical.isEmpty then throw .syntax
    let initialization : QleisliKernel.Hierarchical.Preparation.Packet := ⟨← array definition,← side⟩
    let readoutRequest : QleisliKernel.Hierarchical.Readout.Request := ⟨← side,← array word,← word⟩
    let readout : QleisliKernel.Hierarchical.Readout.Packet := ⟨← array definition,← array word,← side⟩
    let request : QleisliKernel.Hierarchical.QpeInstrument.Request :=
      ⟨⟨inputs,fresh.quantum⟩,⟨circuit,provider.request⟩,readoutRequest,← side⟩
    return ⟨request,⟨initialization,root,readout⟩⟩
  let (result,final) ← read.run {bytes := input}
  if final.position != input.size then throw .syntax
  return result

end QleisliKernel.Protocol.Hierarchical