instinct-cli 0.3.10

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
// generated by hxc 1.0.0-acgt-compiler from src/guide.hlx -- do not edit by hand

#[cfg(windows)]
#[allow(dead_code)]
const SYS_CURL: &str = "C:\\Windows\\System32\\curl.exe";
#[cfg(not(windows))]
#[allow(dead_code)]
const SYS_CURL: &str = "curl";
#[allow(dead_code)]
fn _helix_allowed(var: &str, what: &str) -> bool {
    let ok = std::env::var(var).map(|v| v == "1").unwrap_or(false);
    if !ok {
        eprintln!("helix: BLOCKED {} -- permission denied (set {}=1 to allow; `hxc run` allows by default, a `hxc build`/`export-rust` binary does not)", what, var);
    }
    ok
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_exec(mut c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
        std::process::exit(13);
    }
    use std::os::windows::process::CommandExt;
    c.creation_flags(0x08000000);
    c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_exec(c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
        std::process::exit(13);
    }
    c
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_net(mut c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
        std::process::exit(13);
    }
    use std::os::windows::process::CommandExt;
    c.creation_flags(0x08000000);
    c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_net(c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
        std::process::exit(13);
    }
    c
}

// hlx:2
use super::{eligibility, parse_json, recall_methods, Json};
// hlx:3
use std::path::PathBuf;
// hlx:5
const MODES: &[(&str, &str)] = &[
    // hlx:6
    ("start", "Choose a first move"),
    ("options", "Compare available methods"),
    // hlx:7
    ("challenge", "Find what could invalidate a method"),
    ("explain", "Inspect the evidence behind a choice"),
    // hlx:8
    ("rehearse", "See which lessons survive a changed brief"),
    ("transfer", "Design a test in a different setting"),
    // hlx:9
    ("verify", "Compare an expectation with an observation"),
    ("retry", "Recover one check after a correction"),
    // hlx:10
    ("handoff", "Prepare a compact card for another agent"),
    ("debrief", "Draft feedback after an attempt"),
];
// hlx:12
fn field<'a>(v: &'a Json, key: &str) -> &'a str {
    // hlx:13
    v.get(key).and_then(Json::as_str).unwrap_or("")
    // hlx:14
}
// hlx:16
fn scenarios() -> Result<Vec<Json>, String> {
    // hlx:17
    match parse_json(include_str!("../skills/instinct/references/scenarios.json"))? {
        // hlx:18
        Json::Arr(rows) => Ok(rows),
        _ => Err("invalid built-in scenarios".into()),
    }
    // hlx:19
}
// hlx:21
fn obj(fields: Vec<(&str, Json)>) -> Json {
    // hlx:22
    Json::Obj(
        fields
            .into_iter()
            .map(|(k, v)| (k.to_string(), v))
            .collect(),
    )
    // hlx:23
}
// hlx:25
fn txt(value: &str) -> Json {
    // hlx:26
    Json::Str(value.into())
    // hlx:27
}
// hlx:29
fn live(path: &PathBuf, q: &str, scope: &eligibility::Scope) -> Result<Vec<Json>, String> {
    // hlx:30
    let matches = recall_methods(path, q, 3, scope)?;
    // hlx:31
    Ok(matches
        .iter()
        .map(|d| {
            let mut card = vec![
                // hlx:32
                ("id", txt(&d.id)),
                ("when", txt(&d.when)),
                ("method", txt(&d.how)),
                ("observed", txt(&d.found)),
                // hlx:33
                ("evidence", txt(&d.evidence)),
                ("exception", txt(&d.reconsider)),
                ("proven", Json::Bool(d.proven_in_use())),
                // hlx:34
                (
                    "scope",
                    obj(vec![
                        ("project", txt(&d.meta.project)),
                        ("persona", txt(&d.meta.persona)),
                        ("machine", txt(&d.meta.machine)),
                        ("harness", txt(&d.meta.harness)),
                        ("harness_version", txt(&d.meta.version)),
                    ]),
                ),
                // hlx:35
                ("hits", Json::Num(d.hits.into())),
                ("misses", Json::Num(d.misses.into())),
            ];
            // hlx:36
            if let Some(book) = d.casebook.as_ref().filter(|_| d.standing.is_none()) {
                card.push(("case_check", txt(&book.first_guidance())));
            }
            // hlx:37
            obj(card)
        })
        .collect())
    // hlx:38
}
// hlx:40
fn sample_cards(case: &Json, changed: bool) -> Vec<Json> {
    // hlx:41
    let methods: &[&str] = if changed {
        &["adapt"]
    } else {
        &["move", "alternative"]
    };
    // hlx:42
    methods
        .iter()
        .map(|k| {
            obj(vec![
                ("id", txt(k)),
                (
                    "when",
                    txt(field(case, if changed { "changed" } else { "task" })),
                ),
                // hlx:43
                ("method", txt(field(case, k))),
                (
                    "exception",
                    txt(if changed {
                        ""
                    } else {
                        field(case, "exception")
                    }),
                ),
                ("evidence", txt("Illustrative example")),
                // hlx:44
                ("observed", Json::Null),
                ("proven", Json::Bool(false)),
                ("hits", Json::Num(0.0)),
                ("misses", Json::Num(0.0)),
            ])
        })
        .collect()
    // hlx:45
}
// hlx:48
fn experiment(
    path: &std::path::PathBuf,
    request: &Json,
    scope: &eligibility::Scope,
) -> Result<Json, String> {
    // hlx:49
    let Json::Obj(fields) = request else {
        return Err("experiment expects an object".into());
    };
    // hlx:50
    let mut seen = std::collections::BTreeSet::new();
    // hlx:51
    for (key, value) in fields {
        // hlx:52
        if !seen.insert(key) {
            // hlx:53
            return Err(format!("duplicate experiment field {key}"));
            // hlx:54
        }
        // hlx:55
        match key.as_str() {
            // hlx:56
            "facts" | "pool" => (),
            // hlx:57
            "mode" | "id" | "after_ref" | "project" | "persona" | "harness" | "harness_version"
            | "machine"
                if value.as_str().is_some() =>
            {
                ()
            }
            // hlx:58
            _ => return Err(format!("unexpected or invalid experiment field {key}")),
            // hlx:59
        }
        // hlx:60
    }
    // hlx:61
    let id = field(request, "id");
    // hlx:62
    if id.trim().is_empty() {
        // hlx:63
        return Err("guide experiment requires a lesson id".into());
        // hlx:64
    }
    // hlx:65
    let missing = "no eligible personal casebook for this id and scope";
    // hlx:66
    let lesson = super::load_user_scoped(path, scope, super::now_secs())?
        .into_iter()
        .find(|d| d.id == id)
        .ok_or(missing)?;
    // hlx:67
    if lesson.meta.source != "banked"
        || lesson.standing.is_some()
        || eligibility::quiet(lesson.hits, lesson.misses)
        || super::quiet_ids(path).contains(id)
    {
        // hlx:68
        return Err(missing.into());
        // hlx:69
    }
    // hlx:70
    let book = lesson.casebook.as_ref().ok_or(missing)?;
    // hlx:71
    let mut result = super::case_experiment::experiment(
        book,
        request.get("facts"),
        request.get("pool"),
        request.get("after_ref").and_then(Json::as_str),
    )?;
    // hlx:72
    if let Json::Obj(fields) = &mut result {
        // hlx:73
        fields.push(("mode".into(), txt("experiment")));
        // hlx:74
        fields.push(("lesson_id".into(), txt(id)));
        // hlx:75
    }
    // hlx:76
    Ok(result)
    // hlx:77
}
// hlx:79
pub(super) fn run(
    bank: impl Fn() -> Result<PathBuf, String>,
    request: &Json,
    scope: &eligibility::Scope,
) -> Result<Json, String> {
    // hlx:80
    let mut cache = std::collections::HashMap::new();
    // hlx:81
    let mode = field(request, "mode");
    // hlx:82
    if mode == "experiment" {
        // hlx:83
        return experiment(&bank()?, request, scope);
        // hlx:84
    }
    // hlx:85
    if ["pool", "facts", "id", "after_ref"]
        .iter()
        .any(|key| request.get(key).is_some())
    {
        // hlx:86
        return Err("id, facts and pool require guide experiment".into());
        // hlx:87
    }
    // hlx:88
    if mode != "run" && request.get("steps").is_some() {
        // hlx:89
        return Err("--steps requires guide run".into());
        // hlx:90
    }
    // hlx:91
    let recipe = match mode {
        "prepare" => "start,options,challenge",
        "investigate" => "explain,rehearse,transfer",
        // hlx:92
        "review" => "verify,debrief,handoff",
        "run" => field(request, "steps"),
        _ => return one(&bank, request, scope, &mut cache),
    };
    // hlx:93
    let steps: Vec<_> = recipe.split(',').map(str::trim).collect();
    // hlx:94
    let mut seen = std::collections::HashSet::new();
    // hlx:95
    if steps.len() > MODES.len()
        || steps
            .iter()
            .any(|s| !MODES.iter().any(|(m, _)| m == s) || !seen.insert(*s))
    {
        // hlx:96
        return Err("select one to ten distinct workflow names from guide list".into());
        // hlx:97
    }
    // hlx:98
    let Json::Obj(fields) = request else {
        return Err("expected guide request".into());
    };
    // hlx:99
    let mut reports = Vec::new();
    // hlx:100
    for step in steps {
        // hlx:101
        let mut inputs: Vec<_> = fields
            .iter()
            .filter(|(k, _)| k != "steps" && k != "mode")
            .cloned()
            .collect();
        // hlx:102
        inputs.push(("mode".into(), txt(step)));
        // hlx:103
        reports.push(one(&bank, &Json::Obj(inputs), scope, &mut cache)?);
        // hlx:104
    }
    // hlx:105
    Ok(obj(vec![
        ("mode", txt(mode)),
        ("reports", Json::Arr(reports)),
    ]))
    // hlx:106
}
// hlx:108
fn one(
    bank: &impl Fn() -> Result<PathBuf, String>,
    request: &Json,
    scope: &eligibility::Scope,
    cache: &mut std::collections::HashMap<String, Vec<Json>>,
) -> Result<Json, String> {
    // hlx:109
    let fields = match request {
        Json::Obj(fields) => fields,
        _ => return Err("supply a guide request object".into()),
    };
    // hlx:110
    for (key, value) in fields {
        // hlx:111
        if !matches!(value, Json::Str(_)) {
            // hlx:112
            return Err(format!("guide field {key} must be a string"));
            // hlx:113
        }
        // hlx:114
    }
    // hlx:115
    let mode = field(request, "mode");
    // hlx:116
    if mode.is_empty() || mode == "list" {
        // hlx:117
        let modes = MODES
            .iter()
            .map(|(name, purpose)| obj(vec![("name", txt(name)), ("purpose", txt(purpose))]))
            .collect();
        // hlx:118
        let examples = scenarios()?.iter().map(|v| txt(field(v, "name"))).collect();
        // hlx:119
        return Ok(obj(vec![
            ("modes", Json::Arr(modes)),
            ("examples", Json::Arr(examples)),
            (
                "experiment",
                txt("Choose a teaching case for one banked lesson with two observed actions"),
            ),
            (
                "recipes",
                Json::Arr(
                    ["prepare", "investigate", "review"]
                        .iter()
                        .map(|s| txt(s))
                        .collect(),
                ),
            ),
        ]));
        // hlx:120
    }
    // hlx:121
    if !MODES.iter().any(|(m, _)| *m == mode) {
        // hlx:122
        return Err(format!("unknown workflow {mode}. Use guide list"));
        // hlx:123
    }
    // hlx:124
    let example = field(request, "example");
    // hlx:125
    let sample = if example.is_empty() {
        None
    } else {
        // hlx:126
        if [
            "q",
            "changed",
            "expected",
            "observed",
            "correction",
            "method",
            "test",
            "prediction",
            "exception",
        ]
        .iter()
        .any(|k| request.get(k).is_some())
        {
            return Err("use either an example or your own inputs".into());
        }
        // hlx:127
        Some(
            scenarios()?
                .into_iter()
                .find(|row| field(row, "name") == example)
                .ok_or("unknown example. Use guide list")?,
        )
    };
    // hlx:128
    let input = |key| {
        sample
            .as_ref()
            .and_then(|row| {
                row.get(match key {
                    "q" => "task",
                    "method" => "move",
                    "test" => "adapt",
                    other => other,
                })
            })
            .or_else(|| request.get(key))
            .and_then(Json::as_str)
    };
    // hlx:129
    let q = input("q")
        .filter(|s| !s.trim().is_empty())
        .ok_or("guide requires a task via --q or --example")?;
    // hlx:130
    let changed = input("changed").unwrap_or("");
    // hlx:131
    if matches!(mode, "rehearse" | "transfer")
        && (changed.trim().is_empty() || changed.trim() == q.trim())
    {
        // hlx:132
        return Err("supply a different target situation via --changed".into());
        // hlx:133
    }
    // hlx:134
    let mut facts = Vec::new();
    // hlx:135
    let mut lines = Vec::new();
    // hlx:136
    let mut status = "ready";
    // hlx:137
    let mut lookup = |task: &str, changed: bool| match &sample {
        // hlx:138
        Some(row) => Ok(sample_cards(row, changed)),
        None => {
            // hlx:139
            if let Some(cards) = cache.get(task) {
                return Ok::<_, String>(cards.clone());
            }
            // hlx:140
            let cards = live(&bank()?, task, scope)?;
            cache.insert(task.into(), cards.clone());
            Ok(cards)
        }
    };
    // hlx:141
    if matches!(mode, "verify" | "debrief") {
        // hlx:142
        let expected = input("expected").ok_or("supply the expected result via --expected")?;
        // hlx:143
        facts.push(("expected", txt(expected)));
        // hlx:144
        if let Some(actual) = input("observed") {
            // hlx:145
            facts.push(("observed", txt(actual)));
            // hlx:146
            status = if expected == actual {
                "match"
            } else {
                "mismatch"
            };
            // hlx:147
            lines.push(format!("Expected {expected:?}; observed {actual:?}."));
            // hlx:148
            if mode == "debrief" {
                // hlx:149
                lines.push(
                    if expected == actual {
                        "Record a hit only if the method contributed to this result."
                    } else {
                        "Identify which assumption failed before attributing a miss to the method."
                    }
                    .into(),
                );
                // hlx:150
                if let Some(method) = input("method").filter(|s| !s.trim().is_empty()) {
                    // hlx:151
                    facts.push((
                        "lesson_draft",
                        obj(vec![
                            ("when", txt(q)),
                            ("method_tried", txt(method)),
                            ("expected", txt(expected)),
                            ("observed", txt(actual)),
                            ("reconsider_if", input("exception").map_or(Json::Null, txt)),
                        ]),
                    ));
                    // hlx:152
                    lines.push(format!("Method tried: {method}"));
                // hlx:153
                } else {
                    // hlx:154
                    lines.push("Add the method you tried to draft a reusable lesson.".into());
                    // hlx:155
                }
                // hlx:156
                facts.push(("feedback_recorded", Json::Bool(false)));
                // hlx:157
            }
        // hlx:158
        } else {
            // hlx:159
            status = "awaiting_observation";
            // hlx:160
            lines.push(format!(
                "Collect a current result to compare with {expected:?}."
            ));
            // hlx:161
        }
    // hlx:162
    } else if mode == "retry" {
        // hlx:163
        let correction = if sample.is_some() {
            "That's still wrong."
        } else {
            input("correction")
                .filter(|s| !s.trim().is_empty())
                .ok_or("supply the current user correction via --correction")?
        };
        // hlx:164
        let packet = match &sample {
            Some(row) => Some(obj(vec![("check", txt(field(row, "check")))])),
            // hlx:165
            None => {
                let raw = super::premortem(&bank()?, correction, Some(q), scope)?;
                if raw.is_empty() {
                    None
                } else {
                    Some(parse_json(&raw)?)
                }
            }
        };
        // hlx:166
        if let Some(p) = packet {
            // hlx:167
            lines.push(field(&p, "check").into());
            // hlx:168
            facts.push(("check", p));
        // hlx:169
        } else {
            // hlx:170
            status = "abstained";
            // hlx:171
            lines.push("No single proven check fits this correction.".into());
            // hlx:172
        }
    // hlx:173
    } else {
        // hlx:174
        let cards = lookup(q, false)?;
        // hlx:175
        let first = cards.first();
        // hlx:176
        if first.is_none() {
            // hlx:177
            status = "no_lesson";
            // hlx:178
        }
        // hlx:179
        match mode {
            // hlx:180
            "start" => {
                if let Some(c) = first {
                    // hlx:181
                    lines.push(
                        c.get("case_check")
                            .and_then(Json::as_str)
                            .unwrap_or(field(c, "method"))
                            .into(),
                    );
                    facts.push(("choice", c.clone()));
                    // hlx:182
                    if c.get("proven") != Some(&Json::Bool(true)) {
                        lines.push("Try this as a candidate and check the result.".into());
                    }
                // hlx:183
                } else {
                    lines.push("Start with the smallest observable result the user needs.".into());
                }
            }
            // hlx:184
            "options" => {
                // hlx:185
                let mut seen = std::collections::HashSet::new();
                // hlx:186
                let choices: Vec<_> = cards
                    .iter()
                    .filter(|c| seen.insert(field(c, "method")))
                    .cloned()
                    .collect();
                // hlx:187
                for c in &choices {
                    lines.push(format!(
                        "{} — applies when {}",
                        field(c, "method"),
                        field(c, "when")
                    ));
                }
                // hlx:188
                if choices.is_empty() {
                    lines.push("No banked methods fit this brief.".into());
                }
                // hlx:189
                facts.push(("options", Json::Arr(choices)));
            }
            // hlx:190
            "challenge" => {
                // hlx:191
                let boundaries: Vec<_> = cards
                    .iter()
                    .filter(|c| !field(c, "exception").is_empty())
                    .map(|c| {
                        obj(vec![
                            ("id", txt(field(c, "id"))),
                            ("method", txt(field(c, "method"))),
                            ("exception", txt(field(c, "exception"))),
                        ])
                    })
                    .collect();
                // hlx:192
                for b in &boundaries {
                    lines.push(format!(
                        "{} Reconsider if this applies: {}",
                        field(b, "method"),
                        field(b, "exception")
                    ));
                }
                // hlx:193
                if boundaries.is_empty() {
                    status = "missing_boundary";
                    lines.push(
                        "Identify one observation that would make you abandon the proposed method."
                            .into(),
                    );
                }
                // hlx:194
                facts.push(("boundaries", Json::Arr(boundaries)));
            }
            // hlx:195
            "explain" => {
                if let Some(c) = first {
                    // hlx:196
                    lines.push(format!("{} — {}", field(c, "method"), field(c, "evidence")));
                    // hlx:197
                    if let Some(obs) = c.get("observed").and_then(Json::as_str) {
                        lines.push(format!("Previously observed: {obs}"));
                    }
                    // hlx:198
                    facts.push(("evidence_card", c.clone()));
                // hlx:199
                } else {
                    lines.push("No scoped evidence supports a banked method for this task.".into());
                }
            }
            // hlx:200
            "rehearse" | "transfer" => {
                // hlx:201
                let next = lookup(changed, true)?;
                // hlx:202
                facts.push(("target", txt(changed)));
                // hlx:203
                if mode == "rehearse" {
                    status = "compared";
                    // hlx:204
                    for (label, a, b) in [
                        ("retained", &cards, &next),
                        ("dropped", &cards, &next),
                        ("introduced", &next, &cards),
                    ] {
                        // hlx:205
                        let subset: Vec<_> = a
                            .iter()
                            .filter(|c| {
                                b.iter().any(|d| field(c, "id") == field(d, "id"))
                                    == (label == "retained")
                            })
                            .cloned()
                            .collect();
                        // hlx:206
                        lines.push(format!(
                            "{label}: {}",
                            if subset.is_empty() {
                                "none".into()
                            } else {
                                subset
                                    .iter()
                                    .map(|c| field(c, "method"))
                                    .collect::<Vec<_>>()
                                    .join(" / ")
                            }
                        ));
                        facts.push((label, Json::Arr(subset)));
                    }
                // hlx:207
                } else {
                    // hlx:208
                    status = if first.is_some() {
                        "hypothesis"
                    } else {
                        "no_source_lesson"
                    };
                    // hlx:209
                    if let Some(c) = first {
                        facts.push(("source_lesson", c.clone()));
                        lines.push(format!(
                            "Test whether this move transfers: {}",
                            field(c, "method")
                        ));
                    }
                    // hlx:210
                    else {
                        lines.push("Find a source case with an observed outcome before proposing a transfer.".into());
                    }
                    // hlx:211
                    if let Some(check) = first
                        .and_then(|c| c.get("case_check"))
                        .and_then(Json::as_str)
                    {
                        lines.push(check.into());
                    }
                    // hlx:212
                    lines.push(format!("Target task: {changed}"));
                    if input("prediction").is_none() {
                        lines.push("Name a prediction that could turn out wrong.".into());
                    }
                    // hlx:213
                    if let Some(test) = input("test") {
                        facts.push(("test", txt(test)));
                        lines.push(format!("Test: {test}"));
                    }
                    // hlx:214
                    if let Some(prediction) = input("prediction") {
                        facts.push(("prediction", txt(prediction)));
                        lines.push(format!("Prediction: {prediction}"));
                    }
                    // hlx:215
                    if let Some(c) = first {
                        let known = next.iter().any(|d| field(d, "id") == field(c, "id"));
                        // hlx:216
                        facts.push(("source_also_retrieved_for_target", Json::Bool(known)));
                        // hlx:217
                        facts.push(("hypothesis",txt(&format!("Applying '{}' to '{}' may reproduce the relevant part of the earlier outcome.",field(c,"method"),changed))));
                        // hlx:218
                        if !field(c, "exception").is_empty() {
                            lines.push(format!(
                                "Check the source boundary: {}",
                                field(c, "exception")
                            ));
                        }
                        // hlx:219
                    }
                    // hlx:220
                    facts.push(("target_lessons", Json::Arr(next)));
                }
            }
            // hlx:221
            "handoff" => {
                // hlx:222
                lines.push(format!("Task: {q}"));
                // hlx:223
                if let Some(c) = first {
                    lines.push(format!("Try: {}", field(c, "method")));
                    lines.push(format!("Prior evidence: {}", field(c, "evidence")));
                    // hlx:224
                    if !field(c, "exception").is_empty() {
                        lines.push(format!("Reconsider if: {}", field(c, "exception")));
                    }
                    facts.push(("lesson_id", txt(field(c, "id"))));
                    if let Some(scope) = c.get("scope") {
                        facts.push(("scope", scope.clone()));
                    }
                    if c.get("proven") != Some(&Json::Bool(true)) {
                        lines.push("Treat this method as a candidate.".into());
                    }
                }
                // hlx:225
                else {
                    lines.push("No prior method selected.".into());
                }
                // hlx:226
                if let (Some(expected), Some(observed)) = (input("expected"), input("observed")) {
                    // hlx:227
                    let state = if expected == observed {
                        "match"
                    } else {
                        "mismatch"
                    };
                    // hlx:228
                    facts.push((
                        "current_comparison",
                        obj(vec![
                            ("status", txt(state)),
                            ("expected", txt(expected)),
                            ("observed", txt(observed)),
                        ]),
                    ));
                    // hlx:229
                    lines.push(format!(
                        "Current observation: expected {expected:?}; observed {observed:?}."
                    ));
                    // hlx:230
                    if expected != observed {
                        lines.push(
                            "Still open: resolve the discrepancy and repeat the check.".into(),
                        );
                    }
                // hlx:231
                } else {
                    lines.push("Still open: verify the current outcome.".into());
                }
            }
            // hlx:232
            _ => unreachable!(),
        }
        // hlx:233
    }
    // hlx:234
    Ok(obj(vec![
        ("mode", txt(mode)),
        ("task", txt(q)),
        (
            "source",
            txt(if sample.is_some() { "example" } else { "live" }),
        ),
        ("status", txt(status)),
        // hlx:235
        (
            "steps",
            Json::Arr(lines.into_iter().map(Json::Str).collect()),
        ),
        ("details", obj(facts)),
    ]))
    // hlx:236
}
// hlx:238
pub(super) fn display(packet: &Json) -> String {
    // hlx:239
    if field(packet, "mode") == "experiment" {
        // hlx:240
        return super::json_out(packet);
        // hlx:241
    }
    // hlx:242
    if let Some(Json::Arr(reports)) = packet.get("reports") {
        // hlx:243
        return reports.iter().map(display).collect::<Vec<_>>().join("\n\n");
        // hlx:244
    }
    // hlx:245
    if let Some(Json::Arr(modes)) = packet.get("modes") {
        // hlx:246
        let mut rows: Vec<_> = modes
            .iter()
            .map(|m| format!("{:10} {}", field(m, "name"), field(m, "purpose")))
            .collect();
        // hlx:247
        if let Some(Json::Arr(names)) = packet.get("examples") {
            // hlx:248
            rows.push(format!(
                "Examples: {}",
                names
                    .iter()
                    .filter_map(Json::as_str)
                    .collect::<Vec<_>>()
                    .join(", ")
            ));
            // hlx:249
        }
        // hlx:250
        rows.push("experiment Choose a teaching case for a two-action lesson with --id ID".into());
        // hlx:251
        rows.push("Recipes: prepare, investigate, review. Choose your own with guide run --steps start,challenge,handoff".into());
        // hlx:252
        rows.push("Try: instinct guide challenge --example shared-document".into());
        // hlx:253
        return rows.join("\n");
        // hlx:254
    }
    // hlx:255
    let mut lines = vec![format!(
        "{} · {} · {}",
        field(packet, "mode"),
        field(packet, "source"),
        field(packet, "status")
    )];
    // hlx:256
    if field(packet, "source") == "example" && field(packet, "mode") != "handoff" {
        // hlx:257
        lines.push(field(packet, "task").into());
        // hlx:258
    }
    // hlx:259
    if let Some(Json::Arr(steps)) = packet.get("steps") {
        // hlx:260
        lines.extend(steps.iter().filter_map(Json::as_str).map(str::to_string));
        // hlx:261
    }
    // hlx:262
    lines.join("\n")
    // hlx:263
}
// hlx:266
pub(super) fn book() -> Result<String, String> {
    // hlx:267
    let scope = eligibility::env_scope();
    // hlx:268
    let no_bank = || Err("the guidebook cannot read a bank".to_string());
    // hlx:269
    let mut data = match run(no_bank, &obj(vec![]), &scope)? {
        Json::Obj(fields) => fields,
        _ => unreachable!(),
    };
    // hlx:270
    let mut examples = Vec::new();
    // hlx:271
    for row in scenarios()? {
        // hlx:272
        let name = field(&row, "name");
        // hlx:273
        let mut modes = Vec::new();
        // hlx:274
        for (mode, _) in MODES {
            // hlx:275
            let report = run(
                no_bank,
                &obj(vec![("mode", txt(mode)), ("example", txt(name))]),
                &scope,
            )?;
            // hlx:276
            modes.push((mode.to_string(), report));
            // hlx:277
        }
        // hlx:278
        examples.push((name.to_string(), Json::Obj(modes)));
        // hlx:279
    }
    // hlx:280
    data.push(("reports".into(), Json::Obj(examples)));
    // hlx:281
    let data = super::json_out(&Json::Obj(data))
        .replace('<', "\\u003c")
        .replace('>', "\\u003e")
        .replace('&', "\\u0026");
    // hlx:282
    Ok(include_str!("guidebook.html").replacen("__GUIDE_DATA__", &data, 1))
    // hlx:283
}