inky-engine 3.0.1

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
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
------------------------------ MODULE ThinkCap ------------------------------
\* Formal specification of Inkling serve's multi-message thinking-token cap and
\* output-position answer-room state machine (`src/serve/think_cap.rs`,
\* `ThinkBudget` + speculative verify loop + `TurnDelivery` reconciliation in
\* `src/serve.rs`, and `ToolCallGrammar` `Idle -> Header -> Json` transitions
\* in `src/json_grammar.rs`).
\*
\* Models PR #241 (`rowan/fast-thinking-reentry`) semantics across arbitrary
\* multi-message turns:
\* 1. Output-position `Room`: `close_len = bridge_len + 2`,
\*    `room = Min(answer_room, max_gen \div 2)`,
\*    `close_from = Max(0, max_gen - (close_len + room))`,
\*    `first_message_limit = Max(0, close_from - THINK_OPEN)`.
\*    When `first_message_limit = 0`, `Budget::NoThinking` latches `hard_banned`
\*    before token 0. Otherwise `eff_budget = Min(req_budget, first_message_limit)`
\*    and `room_clamped = (first_message_limit < req_budget)`.
\* 2. Dynamic `think_banned`: `<|content_thinking|>` is masked out after a cap
\*    hit (`hard_banned`), once `used >= eff_budget`, or whenever opening at
\*    output index `seen` could not think one token before `close_from`
\*    (`~MayOpenAt(close_from, seen)`). Whenever `~think_banned`,
\*    `<|content_thinking|>` may open at token 0 or in any `<|message_model|>`
\*    header (at turn start, re-entry after a natural `<|end_message|>`, or
\*    opening thinking after text).
\* 3. Inside an open thinking message (`in_think = TRUE`), `<|content_thinking|>`
\*    counts as continuing thinking AND increments `used` by 1 just like any
\*    other thinking body token (`ThinkCapNestedCThinkFree`), while every
\*    closing token (`End`, `EndSampling`, `RoleStop`, `MsgModel`, `CText`,
\*    `CTool`) closes thinking naturally without firing a cap hit.
\* 4. Speculative verify gate `draft_ok(k)` (`k \in 1..4`):
\*    - when `in_think`: `used + k < eff_budget /\ ~MustCloseAt(close_from, seen + k)`
\*    - when `~in_think`: `think_banned \/ (MayOpenAt(close_from, seen + k) /\ (k < 4 \/ used + (k - 3) < eff_budget))`
\*    preventing both the 5-token `[CThink, body, End, MsgModel, CThink]`
\*    re-entry overflow (Hole A) and the `seen = close_from - 1` pre-close
\*    short-circuit (Hole B) (`ThinkCapDraftBoundaryHole`).
\* 5. `role_stopped` freeze on `ThinkBudget` (`PostRoleStopObserve`), forced
\*    `bridge ++ [<|end_message|>, <|message_model|>]` queue drain into
\*    `ToolCallGrammar` `"Header"` mode, and deferred `think_cap_room_clamped`.
\* 6. PR #224's tool-call header mask and marker rewrite (`ToolCallGrammar::header_allows`,
\*    `idle_allows`, `committed_token`, `Active::observe_drawn_token`). The request offers one
\*    tool, `fn`; the vocabulary spells it as one token (`HeaderTok` = "fn") or as two
\*    (`NameHead` = "f", `NameTail` = "n"). `header_name` abstracts the grammar's header bytes
\*    against the offered names: "empty", "prefix" (a proper prefix of an offered name),
\*    "exact" (an offered name), "off" (no offered name's prefix).
\*    - Masked header: name bytes only while they stay a prefix of an offered name, the tool
\*      marker only on an exact name, a content marker only before any name byte, no other
\*      special token.
\*    - Outside a header or JSON body the grammar refuses the tool marker, but the paths that
\*      draw without the mask (GPU Gumbel, DSpark verify) can still draw it (`IdleDraws`).
\*      Every path commits through `committed_token`: a marker that does not follow an exactly
\*      offered header becomes `End` inside an open text/thinking message, `MsgModel` between
\*      messages, `CText` in a header that is no name (unreachable). A forced close's tokens
\*      are never rewritten.

EXTENDS Integers, Sequences, FiniteSets

CONSTANTS Budgets, MaxGens, AnswerRooms, BridgeLens, Bug

\* Bug values for #224 (the others are the thinking-cap witnesses):
\*   "pre_224"           the code before #224: header unmasked, no marker rewrite
\*   "no_header_mask"    the marker rewrite without the header mask
\*   "no_marker_rewrite" the header mask without the marker rewrite

ASSUME MaxGens # {} /\ \A mg \in MaxGens : mg >= 1
ASSUME Budgets # {} /\ \A b \in Budgets : b >= 0
ASSUME AnswerRooms # {} /\ \A r \in AnswerRooms : r >= 0
ASSUME BridgeLens # {} /\ \A bl \in BridgeLens : bl >= 0

VARIABLES
  req_budget,
  max_gen,
  answer_room,
  bridge_len,
  eff_budget,
  close_from,
  room_clamped,
  seen,
  gen,
  in_think,
  entered_think,
  role_stopped,
  post_stop_checked,
  used,
  think_span_emitted,
  recorded_thinking,
  hard_banned,
  think_banned,
  draft_ok_vec,
  hit_at,
  cont_at_cap,
  mode,
  forcing,
  grammar_mode,
  header_name,
  body_open,
  marker_rewrites,
  last_raw,
  last_drawn,
  json_ready,
  last_committed_close_msg_model,
  post_close_tokens,
  answer_tokens,
  cap_answer_tokens,
  cap_tool_call,
  published_hits,
  published_clamp,
  published_tool,
  published_cap_answer,
  done_reason

vars == <<
  req_budget, max_gen, answer_room, bridge_len, eff_budget, close_from,
  room_clamped, seen, gen, in_think, entered_think, role_stopped,
  post_stop_checked, used, think_span_emitted, recorded_thinking,
  hard_banned, think_banned, draft_ok_vec, hit_at, cont_at_cap, mode,
  forcing, grammar_mode, header_name, body_open, marker_rewrites,
  last_raw, last_drawn, json_ready,
  last_committed_close_msg_model, post_close_tokens, answer_tokens,
  cap_answer_tokens, cap_tool_call, published_hits, published_clamp,
  published_tool, published_cap_answer, done_reason
>>

THINK_OPEN == 2
DraftKs == 1..4

Min(a, b) == IF a <= b THEN a ELSE b
Max(a, b) == IF a >= b THEN a ELSE b
MaxInSet(S) == CHOOSE x \in S : \A y \in S : x >= y

MAX_GEN    == MaxInSet(MaxGens)
MAX_BUDGET == MaxInSet(Budgets)
MAX_BRIDGE == MaxInSet(BridgeLens)
UNBOUNDED_CF == MAX_GEN + 10

CloseLenFor(bl) == bl + 2

CloseSeqFor(bl) ==
  (IF bl = 0 THEN <<>> ELSE [i \in 1..bl |-> "BridgeTok"]) \o <<"End", "MsgModel">>

SpecRoomFor(mg, ar) == Min(ar, mg \div 2)

SpecCloseFromFor(mg, ar, bl) ==
  Max(0, mg - (CloseLenFor(bl) + SpecRoomFor(mg, ar)))

SpecFirstMsgLimitFor(mg, ar, bl) ==
  Max(0, SpecCloseFromFor(mg, ar, bl) - THINK_OPEN)

MustCloseAt(cf, at) == at >= cf

MayOpenAt(cf, at) == ~MustCloseAt(cf, Max(at, THINK_OPEN - 1) + 1)

CloseSeq == CloseSeqFor(bridge_len)
Room     == SpecRoomFor(max_gen, answer_room)
SpecCloseFrom ==
  IF req_budget = 0 \/ SpecFirstMsgLimitFor(max_gen, answer_room, bridge_len) = 0 THEN UNBOUNDED_CF
  ELSE SpecCloseFromFor(max_gen, answer_room, bridge_len)
FirstMsgLimit == SpecFirstMsgLimitFor(max_gen, answer_room, bridge_len)

Tokens == {
  "MsgModel", "CThink", "ThinkBody", "BridgeTok", "CText", "TextBody",
  "HeaderTok", "NameHead", "NameTail", "CTool", "JsonBody", "End",
  "EndSampling", "RoleStop"
}

\* Tokens with bytes (`VocabBytes::non_special_bytes`); the rest are special tokens.
ByteTokens == {"ThinkBody", "BridgeTok", "TextBody", "HeaderTok", "NameHead", "NameTail", "JsonBody"}
HeaderNames == {"empty", "prefix", "exact", "off"}
\* What a rewritten tool marker may become (`committed_token`).
RewriteTargets == {"End", "MsgModel", "CText"}

StopTokens   == {"EndSampling", "RoleStop"}
CloserTokens == {"RoleStop", "CText", "CTool", "MsgModel", "End", "EndSampling"}
GrammarModes == {"Idle", "Header", "Json"}
LastToks     == Tokens \cup {"None"}
DoneReasons  == {"none", "stop", "length"}

ImplRoomFor(mg, ar) ==
  IF Bug = "no_half_cap" THEN ar
  ELSE IF Bug = "third_cap" THEN Min(ar, mg \div 3)
  ELSE SpecRoomFor(mg, ar)

ImplCloseLenFor(bl) ==
  IF Bug = "ignore_bridge_len" THEN 2
  ELSE CloseLenFor(bl)

ImplCloseFromFor(mg, ar, bl) ==
  Max(0, mg - (ImplCloseLenFor(bl) + ImplRoomFor(mg, ar)))

ImplThinkBanned(hb, rb, u, eb, cf, s) ==
  IF Bug = "reentry_hole" THEN hb
  ELSE hb \/ (rb > 0 /\ (u >= eb \/ ~MayOpenAt(cf, s)))

ImplDraftOkAt(forcing_len, rb, it, u, eb, tb, cf, s, k) ==
  /\ forcing_len = 0
  /\ (rb = 0 \/
       IF Bug = "be9dd086_draft_ok" THEN
         /\ (~it \/ u + k < eb)
         /\ (tb \/ MayOpenAt(cf, s + k))
       ELSE IF it THEN
         u + k < eb /\ ~MustCloseAt(cf, s + k) /\ (tb \/ MayOpenAt(cf, s + k))
       ELSE
         tb \/ (u + (k - 1) < eb /\ MayOpenAt(cf, s + k)))

ImplDraftVec(forcing_len, rb, it, u, eb, tb, cf, s) ==
  [k \in DraftKs |-> ImplDraftOkAt(forcing_len, rb, it, u, eb, tb, cf, s, k)]

ComputePolicy(rb, mg, ar, bl) ==
  IF rb = 0 THEN
    [eff |-> 0, cf |-> UNBOUNDED_CF, clamped |-> FALSE, ban_init |-> FALSE]
  ELSE
    LET cf_calc == ImplCloseFromFor(mg, ar, bl)
        cf_eff  == IF Bug = "reentry_hole" THEN UNBOUNDED_CF ELSE cf_calc
        lim     == Max(0, cf_calc - THINK_OPEN) IN
    IF Bug = "tiny_max_gen_hole" THEN
      LET l1 == Max(1, lim) IN
      [eff |-> Min(rb, l1), cf |-> UNBOUNDED_CF, clamped |-> (l1 < rb), ban_init |-> FALSE]
    ELSE IF lim = 0 THEN
      [eff |-> 1, cf |-> UNBOUNDED_CF, clamped |-> FALSE, ban_init |-> TRUE]
    ELSE IF Bug = "clamp_le_boundary" THEN
      [eff |-> Min(rb, lim), cf |-> cf_eff, clamped |-> (lim <= rb), ban_init |-> FALSE]
    ELSE
      [eff |-> Min(rb, lim), cf |-> cf_eff, clamped |-> (lim < rb), ban_init |-> FALSE]

InitFor(rb, mg, ar, bl) ==
  LET pol == ComputePolicy(rb, mg, ar, bl)
      tb0 == ImplThinkBanned(pol.ban_init, rb, 0, pol.eff, pol.cf, 0) IN
  /\ req_budget = rb
  /\ max_gen = mg
  /\ answer_room = ar
  /\ bridge_len = bl
  /\ eff_budget = pol.eff
  /\ close_from = pol.cf
  /\ room_clamped = pol.clamped
  /\ seen = 0
  /\ gen = 0
  /\ in_think = FALSE
  /\ entered_think = FALSE
  /\ role_stopped = FALSE
  /\ post_stop_checked = FALSE
  /\ used = 0
  /\ think_span_emitted = 0
  /\ recorded_thinking = 0
  /\ hard_banned = pol.ban_init
  /\ think_banned = tb0
  /\ draft_ok_vec = ImplDraftVec(0, rb, FALSE, 0, pol.eff, tb0, pol.cf, 0)
  /\ hit_at = -1
  /\ cont_at_cap = FALSE
  /\ mode = 0
  /\ forcing = <<>>
  /\ grammar_mode = "Idle"
  /\ header_name = "empty"
  /\ body_open = FALSE
  /\ marker_rewrites = 0
  /\ last_raw = "None"
  /\ last_drawn = "None"
  /\ json_ready = FALSE
  /\ last_committed_close_msg_model = FALSE
  /\ post_close_tokens = 0
  /\ answer_tokens = 0
  /\ cap_answer_tokens = 0
  /\ cap_tool_call = FALSE
  /\ published_hits = 0
  /\ published_clamp = 0
  /\ published_tool = 0
  /\ published_cap_answer = 0
  /\ done_reason = "none"

Init ==
  \E rb \in Budgets, mg \in MaxGens, ar \in AnswerRooms, bl \in BridgeLens :
    InitFor(rb, mg, ar, bl)

HeaderMasked ==
  IF Bug \in {"no_header_mask", "pre_224"} THEN FALSE ELSE TRUE

MarkerRewritten ==
  IF Bug \in {"no_marker_rewrite", "pre_224"} THEN FALSE ELSE TRUE

\* `ToolCallGrammar::allows_token` in a JSON body: the one body token, then `End` once complete.
JsonAllowed == IF json_ready THEN {"End"} ELSE {"JsonBody"}

\* `ToolCallGrammar::header_allows` (a request with tools, `with_marks`).
HeaderAllowed ==
  CASE header_name = "empty"  -> {"CText", "CThink", "HeaderTok", "NameHead"}
    [] header_name = "prefix" -> {"NameTail"}
    [] header_name = "exact"  -> {"CTool"}
    [] OTHER                  -> {"CText", "CThink"}

\* Every token the real grammar allows now (`allows_token` over `Tokens`); the trace check
\* binds the code's answer to this in every replayed state (`ThinkCapTrace!MaskConforms`).
GrammarAllowed ==
  IF grammar_mode = "Json" THEN JsonAllowed
  ELSE IF grammar_mode = "Header" THEN HeaderAllowed
  ELSE Tokens \ {"CTool"}

\* A header before #224: the template's markers and name bytes, unchecked.
UnmaskedHeaderDraws ==
  {"CText", "CThink", "HeaderTok", "NameHead", "NameTail", "TextBody", "CTool",
   "End", "EndSampling", "RoleStop"}

\* Outside a header or JSON body. A raw tool marker is the draw of a path without the mask.
IdleDraws ==
  IF seen = 0 THEN
    {"MsgModel", "CText", "CThink", "CTool", "EndSampling", "RoleStop"}
  ELSE IF in_think THEN
    {"ThinkBody", "End", "MsgModel", "CText", "CThink", "CTool", "EndSampling", "RoleStop"}
  ELSE IF mode = 2 THEN
    {"TextBody", "End", "MsgModel", "CTool", "EndSampling", "RoleStop"}
  ELSE
    {"MsgModel", "CText", "CTool", "EndSampling", "RoleStop"}

LegalRawTokens ==
  IF Len(forcing) > 0 THEN
    {"ThinkBody", "End", "EndSampling", "RoleStop"}
  ELSE
    (IF grammar_mode = "Json" THEN JsonAllowed
     ELSE IF grammar_mode = "Header" THEN
       (IF HeaderMasked THEN HeaderAllowed ELSE UnmaskedHeaderDraws)
     ELSE IdleDraws)
      \ (IF think_banned THEN {"CThink"} ELSE {})

\* `ToolCallGrammar::committed_token`: a tool marker that does not follow an exactly offered
\* header goes back onto the template; every other draw is committed as drawn.
CommittedTok(raw) ==
  IF ~MarkerRewritten \/ raw # "CTool" THEN raw
  ELSE IF grammar_mode = "Json" THEN raw
  ELSE IF grammar_mode = "Header" THEN (IF header_name = "exact" THEN raw ELSE "CText")
  ELSE IF body_open THEN "End"
  ELSE "MsgModel"

GrammarAfter(tok) ==
  IF tok = "MsgModel" THEN "Header"
  ELSE IF tok \in {"CThink", "CText", "End", "EndSampling"} THEN "Idle"
  ELSE IF tok = "CTool" THEN "Json"
  ELSE grammar_mode

\* The header bytes after one more name token, against the offered name "fn".
NameStep(tok) ==
  IF header_name = "empty" /\ tok = "HeaderTok" THEN "exact"
  ELSE IF header_name = "empty" /\ tok = "NameHead" THEN "prefix"
  ELSE IF header_name = "prefix" /\ tok = "NameTail" THEN "exact"
  ELSE "off"

\* `observe_token`: `<|message_model|>` and the content/end markers clear the header, the tool
\* marker keeps it (the JSON body is bound to it), byte tokens extend it only in a header.
HeaderNameAfter(tok) ==
  IF tok \in {"MsgModel", "CThink", "CText", "End", "EndSampling"} THEN "empty"
  ELSE IF grammar_mode = "Header" /\ tok \in ByteTokens THEN NameStep(tok)
  ELSE header_name

BodyOpenAfter(tok) ==
  IF tok \in {"CThink", "CText"} THEN TRUE
  ELSE IF tok \in {"MsgModel", "CTool", "End", "EndSampling"} THEN FALSE
  ELSE body_open

JsonReadyAfter(tok) ==
  IF tok = "JsonBody" /\ grammar_mode = "Json" THEN TRUE
  ELSE IF tok \in {"MsgModel", "CThink", "CText", "CTool", "End", "EndSampling"} THEN FALSE
  ELSE json_ready

ContinuesThinking(raw_tok) ==
  IF Bug = "false_hit_at_boundary" THEN
    ~(raw_tok \in (CloserTokens \ {"End"}))
  ELSE
    ~(raw_tok \in CloserTokens)

CapFires(drawn) ==
  /\ Len(forcing) = 0
  /\ in_think
  /\ req_budget > 0
  /\ (used >= eff_budget \/ MustCloseAt(close_from, seen))
  /\ ContinuesThinking(drawn)

ImplCloseSeq ==
  IF Bug = "close_no_msg_model" THEN
    (IF bridge_len = 0 THEN <<>> ELSE [i \in 1..bridge_len |-> "BridgeTok"]) \o <<"End">>
  ELSE
    CloseSeq

Step(raw_tok) ==
  /\ done_reason = "none"
  /\ gen < max_gen
  /\ raw_tok \in LegalRawTokens
  /\ UNCHANGED <<req_budget, max_gen, answer_room, bridge_len, eff_budget, close_from, room_clamped, post_stop_checked>>
  /\ seen' = seen + 1
  /\ gen' = gen + 1
  /\ last_raw' = raw_tok
  \* `observe_drawn_token`: a forced close discards the draw, so nothing is rewritten then.
  /\ LET drawn == IF Len(forcing) > 0 THEN raw_tok ELSE CommittedTok(raw_tok) IN
     /\ last_drawn' = drawn
     /\ marker_rewrites' = (IF drawn # raw_tok THEN marker_rewrites + 1 ELSE marker_rewrites)
  /\ IF Len(forcing) > 0 THEN
       LET tok == Head(forcing)
           rem == Tail(forcing)
           tb1 == ImplThinkBanned(hard_banned, req_budget, used, eff_budget, close_from, seen + 1) IN
       /\ forcing' = rem
       /\ grammar_mode' = GrammarAfter(tok)
       /\ header_name' = HeaderNameAfter(tok)
       /\ body_open' = BodyOpenAfter(tok)
       /\ json_ready' = JsonReadyAfter(tok)
       /\ last_committed_close_msg_model' = (Len(rem) = 0)
       /\ think_banned' = tb1
       /\ draft_ok_vec' = ImplDraftVec(Len(rem), req_budget, in_think, used, eff_budget, tb1, close_from, seen + 1)
       /\ recorded_thinking' =
            IF Bug = "bridge_in_reply_counter" /\ tok = "BridgeTok"
            THEN recorded_thinking + 1
            ELSE recorded_thinking
       /\ done_reason' =
            IF tok \in StopTokens THEN "stop"
            ELSE IF gen + 1 >= max_gen THEN "length"
            ELSE "none"
       /\ UNCHANGED <<
            in_think, entered_think, role_stopped, used, think_span_emitted,
            hard_banned, hit_at, cont_at_cap, mode, post_close_tokens,
            answer_tokens, cap_answer_tokens, cap_tool_call, published_hits,
            published_clamp, published_tool, published_cap_answer
          >>
     ELSE IF CapFires(CommittedTok(raw_tok)) THEN
       LET seq == ImplCloseSeq
           tok == Head(seq)
           rem == Tail(seq)
           tb1 == ImplThinkBanned(TRUE, req_budget, used, eff_budget, close_from, seen + 1) IN
       /\ forcing' = rem
       /\ in_think' = FALSE
       /\ mode' = 0
       /\ hard_banned' = TRUE
       /\ think_banned' = tb1
       /\ draft_ok_vec' = ImplDraftVec(Len(rem), req_budget, FALSE, used, eff_budget, tb1, close_from, seen + 1)
       /\ hit_at' = (IF hit_at = -1 THEN used ELSE hit_at)
       /\ published_hits' = (IF hit_at = -1 THEN published_hits + 1 ELSE published_hits)
       /\ cont_at_cap' = (cont_at_cap \/ ~(CommittedTok(raw_tok) \in CloserTokens))
       /\ grammar_mode' = GrammarAfter(tok)
       /\ header_name' = HeaderNameAfter(tok)
       /\ body_open' = BodyOpenAfter(tok)
       /\ json_ready' = JsonReadyAfter(tok)
       /\ last_committed_close_msg_model' = (Len(rem) = 0)
       /\ recorded_thinking' =
            IF Bug = "bridge_in_reply_counter" /\ tok = "BridgeTok"
            THEN recorded_thinking + 1
            ELSE recorded_thinking
       /\ done_reason' =
            IF tok \in StopTokens THEN "stop"
            ELSE IF gen + 1 >= max_gen THEN "length"
            ELSE "none"
       /\ UNCHANGED <<
            entered_think, role_stopped, used, think_span_emitted,
            post_close_tokens, answer_tokens, cap_answer_tokens,
            cap_tool_call, published_clamp, published_tool,
            published_cap_answer
          >>
     ELSE
       LET tok       == CommittedTok(raw_tok)
           opens_th  == (tok = "CThink" /\ (~in_think \/ Bug = "nested_cthink_free"))
           think_inc == ~role_stopped /\ mode = 1 /\ ~opens_th /\ ~(tok \in CloserTokens)
           new_used  == IF think_inc THEN used + 1 ELSE used
           span_inc  == ~role_stopped /\ in_think /\ ~(tok \in CloserTokens)
           body_ans  == ~role_stopped /\ mode \in {2, 3} /\ ~(tok \in (CloserTokens \cup {"CThink"}))
           tool_inc  == ~role_stopped /\ tok = "CTool" /\ ~cap_tool_call
                        /\ (hit_at # -1 \/ Bug = "cap_tool_without_hit")
           next_it   == IF role_stopped THEN in_think
                        ELSE IF tok = "CThink" THEN TRUE
                        ELSE IF tok \in CloserTokens THEN FALSE
                        ELSE in_think
           tb1       == ImplThinkBanned(hard_banned, req_budget, new_used, eff_budget, close_from, seen + 1) IN
       /\ forcing' = <<>>
       /\ last_committed_close_msg_model' = FALSE
       /\ post_close_tokens' = (IF hit_at # -1 THEN post_close_tokens + 1 ELSE post_close_tokens)
       /\ cont_at_cap' = cont_at_cap
       /\ hard_banned' = hard_banned
       /\ hit_at' = hit_at
       /\ published_hits' = published_hits
       /\ grammar_mode' = GrammarAfter(tok)
       /\ header_name' = HeaderNameAfter(tok)
       /\ body_open' = BodyOpenAfter(tok)
       /\ json_ready' = JsonReadyAfter(tok)
       /\ role_stopped' = (role_stopped \/ tok = "RoleStop")
       /\ in_think' = next_it
       /\ entered_think' = (IF role_stopped THEN entered_think ELSE (entered_think \/ tok = "CThink"))
       /\ mode' =
            IF role_stopped THEN mode
            ELSE IF tok = "CThink" THEN 1
            ELSE IF tok = "CText" THEN 2
            ELSE IF tok = "CTool" THEN 3
            ELSE IF tok \in {"RoleStop", "MsgModel", "End", "EndSampling"} THEN 0
            ELSE mode
       /\ used' = new_used
       /\ think_span_emitted' = (IF span_inc THEN think_span_emitted + 1 ELSE think_span_emitted)
       /\ recorded_thinking' = new_used
       /\ answer_tokens' = (IF body_ans THEN answer_tokens + 1 ELSE answer_tokens)
       /\ cap_answer_tokens' = (IF body_ans /\ hit_at # -1 THEN cap_answer_tokens + 1 ELSE cap_answer_tokens)
       /\ published_cap_answer' = (IF body_ans /\ hit_at # -1 THEN published_cap_answer + 1 ELSE published_cap_answer)
       /\ cap_tool_call' = (cap_tool_call \/ tool_inc)
       /\ published_tool' = (IF tool_inc THEN published_tool + 1 ELSE published_tool)
       /\ published_clamp' =
            IF ~role_stopped /\ room_clamped /\ ~entered_think /\ tok = "CThink"
            THEN published_clamp + 1
            ELSE IF Bug = "clamp_before_thinking" /\ room_clamped /\ published_clamp = 0
            THEN 1
            ELSE published_clamp
       /\ think_banned' = tb1
       /\ draft_ok_vec' = ImplDraftVec(0, req_budget, next_it, new_used, eff_budget, tb1, close_from, seen + 1)
       /\ done_reason' =
            IF tok \in StopTokens THEN "stop"
            ELSE IF gen + 1 >= max_gen THEN "length"
            ELSE "none"

\* Models a trailing buffered token observed on `ThinkBudget` after `RoleStop`:
\* `if self.role_stopped { return tok; }` must freeze all mode and token counts.
PostRoleStopObserve(raw_tok) ==
  /\ done_reason = "stop"
  /\ role_stopped
  /\ ~post_stop_checked
  /\ raw_tok \in {"CText", "TextBody", "CThink", "ThinkBody", "CTool"}
  /\ seen' = seen + 1
  /\ post_stop_checked' = TRUE
  /\ LET tb1 == ImplThinkBanned(hard_banned, req_budget, used, eff_budget, close_from, seen + 1) IN
     /\ think_banned' = tb1
     /\ draft_ok_vec' = ImplDraftVec(Len(forcing), req_budget, in_think, used, eff_budget, tb1, close_from, seen + 1)
  /\ UNCHANGED <<
       req_budget, max_gen, answer_room, bridge_len, eff_budget, close_from,
       room_clamped, gen, in_think, entered_think, role_stopped, used,
       think_span_emitted, recorded_thinking, hard_banned, hit_at, cont_at_cap,
       mode, forcing, grammar_mode, header_name, body_open, marker_rewrites,
       last_raw, last_drawn, json_ready,
       last_committed_close_msg_model, post_close_tokens, answer_tokens,
       cap_answer_tokens, cap_tool_call, published_hits, published_clamp,
       published_tool, published_cap_answer, done_reason
     >>

StutterWhenDone ==
  /\ done_reason # "none"
  /\ UNCHANGED vars

Next ==
  \/ \E raw_tok \in Tokens : Step(raw_tok)
  \/ \E raw_tok \in {"CText", "TextBody", "CThink", "ThinkBody", "CTool"} : PostRoleStopObserve(raw_tok)
  \/ StutterWhenDone

Spec == Init /\ [][Next]_vars

\* ---------------------------------------------------------------------------
\* Invariants (every conjunct backed by a reversed witness `.cfg` or mutant)
\* ---------------------------------------------------------------------------

TypeOK ==
  /\ req_budget \in Budgets
  /\ max_gen \in MaxGens
  /\ answer_room \in AnswerRooms
  /\ bridge_len \in BridgeLens
  /\ eff_budget \in 0..Max(1, MAX_BUDGET)
  /\ close_from \in 0..UNBOUNDED_CF
  /\ room_clamped \in BOOLEAN
  /\ seen \in 0..(max_gen + 1)
  /\ gen \in 0..max_gen
  /\ in_think \in BOOLEAN
  /\ entered_think \in BOOLEAN
  /\ role_stopped \in BOOLEAN
  /\ post_stop_checked \in BOOLEAN
  /\ used \in 0..max_gen
  /\ think_span_emitted \in 0..max_gen
  /\ recorded_thinking \in 0..(max_gen + MAX_BRIDGE)
  /\ hard_banned \in BOOLEAN
  /\ think_banned \in BOOLEAN
  /\ draft_ok_vec \in [DraftKs -> BOOLEAN]
  /\ hit_at \in -1..max_gen
  /\ cont_at_cap \in BOOLEAN
  /\ mode \in 0..3
  /\ Len(forcing) <= MAX_BRIDGE + 2
  /\ grammar_mode \in GrammarModes
  /\ header_name \in HeaderNames
  /\ body_open \in BOOLEAN
  /\ marker_rewrites \in 0..max_gen
  /\ last_raw \in LastToks
  /\ last_drawn \in LastToks
  /\ json_ready \in BOOLEAN
  /\ last_committed_close_msg_model \in BOOLEAN
  /\ post_close_tokens \in 0..max_gen
  /\ answer_tokens \in 0..max_gen
  /\ cap_answer_tokens \in 0..max_gen
  /\ cap_tool_call \in BOOLEAN
  /\ published_hits \in 0..1
  /\ published_clamp \in 0..1
  /\ published_tool \in 0..1
  /\ published_cap_answer \in 0..max_gen
  /\ done_reason \in DoneReasons

\* 1. Under an active thinking cap (`req_budget > 0`), hitting `max_gen`
\*    (`done_reason = "length"`) never strands the turn inside thinking
\*    (`ThinkCapReentryHole`, `ThinkCapTinyMaxGenHole`) or mid-forced-close
\*    (`ThinkCapIgnoreBridgeLen`), and preserves at least `Room` post-close
\*    tokens on every capped turn (`ThinkCapThirdCap`).
NoDeadThinkingAtStop ==
  (req_budget > 0 /\ done_reason = "length") =>
    /\ ~in_think
    /\ Len(forcing) = 0
    /\ (hit_at # -1 => post_close_tokens >= Room)

ExpectedHardBanned ==
  (req_budget > 0 /\ FirstMsgLimit = 0) \/ hit_at # -1

ExpectedThinkBanned ==
  ExpectedHardBanned \/ (req_budget > 0 /\ (used >= eff_budget \/ ~MayOpenAt(SpecCloseFrom, seen)))

SpecDraftOk(k) ==
  /\ Len(forcing) = 0
  /\ (req_budget = 0 \/
       IF in_think THEN
         used + k < eff_budget /\ ~MustCloseAt(SpecCloseFrom, seen + k) /\ (ExpectedThinkBanned \/ MayOpenAt(SpecCloseFrom, seen + k))
       ELSE
         ExpectedThinkBanned \/
           (used + (k - 1) < eff_budget /\ MayOpenAt(SpecCloseFrom, seen + k)))

\* 2. `think_banned` matches the exact output-position `Room` (`Min(answer_room, max_gen \div 2)`)
\*    and budget boundary (`ThinkCapNoHalfCap`), and `draft_ok(1..4)` matches the exact
\*    multi-token verify boundary condition (`ThinkCapDraftBoundaryHole`).
ThinkBanAndDraftExact ==
  /\ think_banned = ExpectedThinkBanned
  /\ draft_ok_vec = [k \in DraftKs |-> SpecDraftOk(k)]

\* 3. `think_budget_hits` fires iff continued thinking hit the budget or room limit
\*    (`ThinkCapFalseHitAtBoundary`), and `cap_tool_call` / `think_cap_tool_calls`
\*    fires only after a cap hit (`ThinkCapToolWithoutHit`).
CapHitOnlyOnContinuedThinking ==
  /\ (published_hits = 1 <=> cont_at_cap)
  /\ (hit_at # -1 <=> cont_at_cap)
  /\ (published_tool = 1 <=> cap_tool_call)
  /\ (cap_tool_call => hit_at # -1)

\* 4. Forced bridge tokens never leak into `thinking_tokens` (`ThinkCapBridgeCounted`),
\*    every token emitted inside an open thinking span (including nested `<|content_thinking|>`)
\*    counts against `used` and stays `<= eff_budget` (`ThinkCapNestedCThinkFree`),
\*    and `think_cap_answer_tokens` tracks post-cap answer/tool body tokens only.
BridgeCountedAsNeither ==
  /\ recorded_thinking = used
  /\ think_span_emitted = used
  /\ (req_budget > 0 => think_span_emitted <= eff_budget)
  /\ published_cap_answer = cap_answer_tokens
  /\ (hit_at = -1 => cap_answer_tokens = 0)

\* 5. `think_cap_room_clamped` publishes iff the turn entered `<|content_thinking|>`
\*    under a strictly lowered budget (`FirstMsgLimit < req_budget`, `FirstMsgLimit >= 1`)
\*    (`ThinkCapEagerClamp`, `ThinkCapClampLeBoundary`).
ClampCountedOnlyOnThinking ==
  published_clamp = 1 <=>
    (entered_think /\ req_budget > 0 /\ FirstMsgLimit >= 1 /\ FirstMsgLimit < req_budget)

\* 6. Immediately when the forced close finishes, `ToolCallGrammar` is in `"Header"`
\*    mode, thinking is closed, and `hard_banned` is latched (`ThinkCapCloseNoMsgModel`).
GrammarHeaderOnCloseDone ==
  last_committed_close_msg_model =>
    /\ grammar_mode = "Header"
    /\ ~in_think
    /\ hard_banned
    /\ Len(forcing) = 0

\* 7. #224: an emitted tool-call header only ever names an offered tool. Whenever the grammar is
\*    in a tool-call JSON body, the header that opened it is exactly an offered name
\*    (`ThinkCapPre224`, `ThinkCapNoMarkerRewrite`).
ToolHeaderOffered ==
  grammar_mode = "Json" => header_name = "exact"

\* 8. #224: a header only ever holds a prefix of an offered name (`ThinkCapNoHeaderMask`).
HeaderIsNamePrefix ==
  header_name # "off"

\* 9. #224: the marker rewrite changes nothing but a tool marker, and only into a marker that puts
\*    the turn back on the template; message content (and every forced token) is committed as drawn.
RewriteOnlyMisplacedMarker ==
  last_drawn # last_raw =>
    /\ last_raw = "CTool"
    /\ last_drawn \in RewriteTargets

\* Non-vacuity reachability witness negated in `ThinkCapReach.cfg`: reaches a
\* multi-message turn that opens after text under a clamped budget with a
\* non-empty bridge, hits the cap, opens a tool call, and emits JSON body tokens.
NoCapToolAnswerReached ==
  ~(published_hits = 1
    /\ bridge_len > 0
    /\ cap_tool_call
    /\ cap_answer_tokens >= 1
    /\ published_clamp = 1
    /\ answer_tokens > cap_answer_tokens)

\* Non-vacuity reachability witness negated in `ThinkCapRewriteReach.cfg`: a misplaced tool marker
\* is rewritten, and the turn still reaches a tool call to the offered name afterwards.
NoRewriteThenToolReached ==
  ~(marker_rewrites >= 1 /\ grammar_mode = "Json")
=============================================================================