instinct-cli 0.3.8

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
// 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| {
            obj(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())),
            ])
        })
        .collect())
    // hlx:36
}
// hlx:38
fn sample_cards(case: &Json, changed: bool) -> Vec<Json> {
    // hlx:39
    let methods: &[&str] = if changed {
        &["adapt"]
    } else {
        &["move", "alternative"]
    };
    // hlx:40
    methods
        .iter()
        .map(|k| {
            obj(vec![
                ("id", txt(k)),
                (
                    "when",
                    txt(field(case, if changed { "changed" } else { "task" })),
                ),
                // hlx:41
                ("method", txt(field(case, k))),
                (
                    "exception",
                    txt(if changed {
                        ""
                    } else {
                        field(case, "exception")
                    }),
                ),
                ("evidence", txt("Illustrative example")),
                // hlx:42
                ("observed", Json::Null),
                ("proven", Json::Bool(false)),
                ("hits", Json::Num(0.0)),
                ("misses", Json::Num(0.0)),
            ])
        })
        .collect()
    // hlx:43
}
// hlx:45
pub(super) fn run(
    bank: impl Fn() -> Result<PathBuf, String>,
    request: &Json,
    scope: &eligibility::Scope,
) -> Result<Json, String> {
    // hlx:46
    let mut cache = std::collections::HashMap::new();
    // hlx:47
    let mode = field(request, "mode");
    // hlx:48
    if mode != "run" && request.get("steps").is_some() {
        // hlx:49
        return Err("--steps requires guide run".into());
        // hlx:50
    }
    // hlx:51
    let recipe = match mode {
        "prepare" => "start,options,challenge",
        "investigate" => "explain,rehearse,transfer",
        // hlx:52
        "review" => "verify,debrief,handoff",
        "run" => field(request, "steps"),
        _ => return one(&bank, request, scope, &mut cache),
    };
    // hlx:53
    let steps: Vec<_> = recipe.split(',').map(str::trim).collect();
    // hlx:54
    let mut seen = std::collections::HashSet::new();
    // hlx:55
    if steps.len() > MODES.len()
        || steps
            .iter()
            .any(|s| !MODES.iter().any(|(m, _)| m == s) || !seen.insert(*s))
    {
        // hlx:56
        return Err("select one to ten distinct workflow names from guide list".into());
        // hlx:57
    }
    // hlx:58
    let Json::Obj(fields) = request else {
        return Err("expected guide request".into());
    };
    // hlx:59
    let mut reports = Vec::new();
    // hlx:60
    for step in steps {
        // hlx:61
        let mut inputs: Vec<_> = fields
            .iter()
            .filter(|(k, _)| k != "steps" && k != "mode")
            .cloned()
            .collect();
        // hlx:62
        inputs.push(("mode".into(), txt(step)));
        // hlx:63
        reports.push(one(&bank, &Json::Obj(inputs), scope, &mut cache)?);
        // hlx:64
    }
    // hlx:65
    Ok(obj(vec![
        ("mode", txt(mode)),
        ("reports", Json::Arr(reports)),
    ]))
    // hlx:66
}
// hlx:68
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:69
    let fields = match request {
        Json::Obj(fields) => fields,
        _ => return Err("supply a guide request object".into()),
    };
    // hlx:70
    for (key, value) in fields {
        // hlx:71
        if !matches!(value, Json::Str(_)) {
            // hlx:72
            return Err(format!("guide field {key} must be a string"));
            // hlx:73
        }
        // hlx:74
    }
    // hlx:75
    let mode = field(request, "mode");
    // hlx:76
    if mode.is_empty() || mode == "list" {
        // hlx:77
        let modes = MODES
            .iter()
            .map(|(name, purpose)| obj(vec![("name", txt(name)), ("purpose", txt(purpose))]))
            .collect();
        // hlx:78
        let examples = scenarios()?.iter().map(|v| txt(field(v, "name"))).collect();
        // hlx:79
        return Ok(obj(vec![
            ("modes", Json::Arr(modes)),
            ("examples", Json::Arr(examples)),
            (
                "recipes",
                Json::Arr(
                    ["prepare", "investigate", "review"]
                        .iter()
                        .map(|s| txt(s))
                        .collect(),
                ),
            ),
        ]));
        // hlx:80
    }
    // hlx:81
    if !MODES.iter().any(|(m, _)| *m == mode) {
        // hlx:82
        return Err(format!("unknown workflow {mode}. Use guide list"));
        // hlx:83
    }
    // hlx:84
    let example = field(request, "example");
    // hlx:85
    let sample = if example.is_empty() {
        None
    } else {
        // hlx:86
        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:87
        Some(
            scenarios()?
                .into_iter()
                .find(|row| field(row, "name") == example)
                .ok_or("unknown example. Use guide list")?,
        )
    };
    // hlx:88
    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:89
    let q = input("q")
        .filter(|s| !s.trim().is_empty())
        .ok_or("guide requires a task via --q or --example")?;
    // hlx:90
    let changed = input("changed").unwrap_or("");
    // hlx:91
    if matches!(mode, "rehearse" | "transfer")
        && (changed.trim().is_empty() || changed.trim() == q.trim())
    {
        // hlx:92
        return Err("supply a different target situation via --changed".into());
        // hlx:93
    }
    // hlx:94
    let mut facts = Vec::new();
    // hlx:95
    let mut lines = Vec::new();
    // hlx:96
    let mut status = "ready";
    // hlx:97
    let mut lookup = |task: &str, changed: bool| match &sample {
        // hlx:98
        Some(row) => Ok(sample_cards(row, changed)),
        None => {
            // hlx:99
            if let Some(cards) = cache.get(task) {
                return Ok::<_, String>(cards.clone());
            }
            // hlx:100
            let cards = live(&bank()?, task, scope)?;
            cache.insert(task.into(), cards.clone());
            Ok(cards)
        }
    };
    // hlx:101
    if matches!(mode, "verify" | "debrief") {
        // hlx:102
        let expected = input("expected").ok_or("supply the expected result via --expected")?;
        // hlx:103
        facts.push(("expected", txt(expected)));
        // hlx:104
        if let Some(actual) = input("observed") {
            // hlx:105
            facts.push(("observed", txt(actual)));
            // hlx:106
            status = if expected == actual {
                "match"
            } else {
                "mismatch"
            };
            // hlx:107
            lines.push(format!("Expected {expected:?}; observed {actual:?}."));
            // hlx:108
            if mode == "debrief" {
                // hlx:109
                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:110
                if let Some(method) = input("method").filter(|s| !s.trim().is_empty()) {
                    // hlx:111
                    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:112
                    lines.push(format!("Method tried: {method}"));
                // hlx:113
                } else {
                    // hlx:114
                    lines.push("Add the method you tried to draft a reusable lesson.".into());
                    // hlx:115
                }
                // hlx:116
                facts.push(("feedback_recorded", Json::Bool(false)));
                // hlx:117
            }
        // hlx:118
        } else {
            // hlx:119
            status = "awaiting_observation";
            // hlx:120
            lines.push(format!(
                "Collect a current result to compare with {expected:?}."
            ));
            // hlx:121
        }
    // hlx:122
    } else if mode == "retry" {
        // hlx:123
        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:124
        let packet = match &sample {
            Some(row) => Some(obj(vec![("check", txt(field(row, "check")))])),
            // hlx:125
            None => {
                let raw = super::premortem(&bank()?, correction, Some(q), scope)?;
                if raw.is_empty() {
                    None
                } else {
                    Some(parse_json(&raw)?)
                }
            }
        };
        // hlx:126
        if let Some(p) = packet {
            // hlx:127
            lines.push(field(&p, "check").into());
            // hlx:128
            facts.push(("check", p));
        // hlx:129
        } else {
            // hlx:130
            status = "abstained";
            // hlx:131
            lines.push("No single proven check fits this correction.".into());
            // hlx:132
        }
    // hlx:133
    } else {
        // hlx:134
        let cards = lookup(q, false)?;
        // hlx:135
        let first = cards.first();
        // hlx:136
        if first.is_none() {
            // hlx:137
            status = "no_lesson";
            // hlx:138
        }
        // hlx:139
        match mode {
            // hlx:140
            "start" => {
                if let Some(c) = first {
                    // hlx:141
                    lines.push(field(c, "method").into());
                    facts.push(("choice", c.clone()));
                    // hlx:142
                    if c.get("proven") != Some(&Json::Bool(true)) {
                        lines.push("Try this as a candidate and check the result.".into());
                    }
                // hlx:143
                } else {
                    lines.push("Start with the smallest observable result the user needs.".into());
                }
            }
            // hlx:144
            "options" => {
                // hlx:145
                let mut seen = std::collections::HashSet::new();
                // hlx:146
                let choices: Vec<_> = cards
                    .iter()
                    .filter(|c| seen.insert(field(c, "method")))
                    .cloned()
                    .collect();
                // hlx:147
                for c in &choices {
                    lines.push(format!(
                        "{} — applies when {}",
                        field(c, "method"),
                        field(c, "when")
                    ));
                }
                // hlx:148
                if choices.is_empty() {
                    lines.push("No banked methods fit this brief.".into());
                }
                // hlx:149
                facts.push(("options", Json::Arr(choices)));
            }
            // hlx:150
            "challenge" => {
                // hlx:151
                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:152
                for b in &boundaries {
                    lines.push(format!(
                        "{} Reconsider if this applies: {}",
                        field(b, "method"),
                        field(b, "exception")
                    ));
                }
                // hlx:153
                if boundaries.is_empty() {
                    status = "missing_boundary";
                    lines.push(
                        "Identify one observation that would make you abandon the proposed method."
                            .into(),
                    );
                }
                // hlx:154
                facts.push(("boundaries", Json::Arr(boundaries)));
            }
            // hlx:155
            "explain" => {
                if let Some(c) = first {
                    // hlx:156
                    lines.push(format!("{} — {}", field(c, "method"), field(c, "evidence")));
                    // hlx:157
                    if let Some(obs) = c.get("observed").and_then(Json::as_str) {
                        lines.push(format!("Previously observed: {obs}"));
                    }
                    // hlx:158
                    facts.push(("evidence_card", c.clone()));
                // hlx:159
                } else {
                    lines.push("No scoped evidence supports a banked method for this task.".into());
                }
            }
            // hlx:160
            "rehearse" | "transfer" => {
                // hlx:161
                let next = lookup(changed, true)?;
                // hlx:162
                facts.push(("target", txt(changed)));
                // hlx:163
                if mode == "rehearse" {
                    status = "compared";
                    // hlx:164
                    for (label, a, b) in [
                        ("retained", &cards, &next),
                        ("dropped", &cards, &next),
                        ("introduced", &next, &cards),
                    ] {
                        // hlx:165
                        let subset: Vec<_> = a
                            .iter()
                            .filter(|c| {
                                b.iter().any(|d| field(c, "id") == field(d, "id"))
                                    == (label == "retained")
                            })
                            .cloned()
                            .collect();
                        // hlx:166
                        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:167
                } else {
                    // hlx:168
                    status = if first.is_some() {
                        "hypothesis"
                    } else {
                        "no_source_lesson"
                    };
                    // hlx:169
                    if let Some(c) = first {
                        facts.push(("source_lesson", c.clone()));
                        lines.push(format!(
                            "Test whether this move transfers: {}",
                            field(c, "method")
                        ));
                    }
                    // hlx:170
                    else {
                        lines.push("Find a source case with an observed outcome before proposing a transfer.".into());
                    }
                    // hlx:171
                    lines.push(format!("Target task: {changed}"));
                    if input("prediction").is_none() {
                        lines.push("Name a prediction that could turn out wrong.".into());
                    }
                    // hlx:172
                    if let Some(test) = input("test") {
                        facts.push(("test", txt(test)));
                        lines.push(format!("Test: {test}"));
                    }
                    // hlx:173
                    if let Some(prediction) = input("prediction") {
                        facts.push(("prediction", txt(prediction)));
                        lines.push(format!("Prediction: {prediction}"));
                    }
                    // hlx:174
                    if let Some(c) = first {
                        let known = next.iter().any(|d| field(d, "id") == field(c, "id"));
                        // hlx:175
                        facts.push(("source_also_retrieved_for_target", Json::Bool(known)));
                        // hlx:176
                        facts.push(("hypothesis",txt(&format!("Applying '{}' to '{}' may reproduce the relevant part of the earlier outcome.",field(c,"method"),changed))));
                        // hlx:177
                        if !field(c, "exception").is_empty() {
                            lines.push(format!(
                                "Check the source boundary: {}",
                                field(c, "exception")
                            ));
                        }
                        // hlx:178
                    }
                    // hlx:179
                    facts.push(("target_lessons", Json::Arr(next)));
                }
            }
            // hlx:180
            "handoff" => {
                // hlx:181
                lines.push(format!("Task: {q}"));
                // hlx:182
                if let Some(c) = first {
                    lines.push(format!("Try: {}", field(c, "method")));
                    lines.push(format!("Prior evidence: {}", field(c, "evidence")));
                    // hlx:183
                    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:184
                else {
                    lines.push("No prior method selected.".into());
                }
                // hlx:185
                if let (Some(expected), Some(observed)) = (input("expected"), input("observed")) {
                    // hlx:186
                    let state = if expected == observed {
                        "match"
                    } else {
                        "mismatch"
                    };
                    // hlx:187
                    facts.push((
                        "current_comparison",
                        obj(vec![
                            ("status", txt(state)),
                            ("expected", txt(expected)),
                            ("observed", txt(observed)),
                        ]),
                    ));
                    // hlx:188
                    lines.push(format!(
                        "Current observation: expected {expected:?}; observed {observed:?}."
                    ));
                    // hlx:189
                    if expected != observed {
                        lines.push(
                            "Still open: resolve the discrepancy and repeat the check.".into(),
                        );
                    }
                // hlx:190
                } else {
                    lines.push("Still open: verify the current outcome.".into());
                }
            }
            // hlx:191
            _ => unreachable!(),
        }
        // hlx:192
    }
    // hlx:193
    Ok(obj(vec![
        ("mode", txt(mode)),
        ("task", txt(q)),
        (
            "source",
            txt(if sample.is_some() { "example" } else { "live" }),
        ),
        ("status", txt(status)),
        // hlx:194
        (
            "steps",
            Json::Arr(lines.into_iter().map(Json::Str).collect()),
        ),
        ("details", obj(facts)),
    ]))
    // hlx:195
}
// hlx:197
pub(super) fn display(packet: &Json) -> String {
    // hlx:198
    if let Some(Json::Arr(reports)) = packet.get("reports") {
        // hlx:199
        return reports.iter().map(display).collect::<Vec<_>>().join("\n\n");
        // hlx:200
    }
    // hlx:201
    if let Some(Json::Arr(modes)) = packet.get("modes") {
        // hlx:202
        let mut rows: Vec<_> = modes
            .iter()
            .map(|m| format!("{:10} {}", field(m, "name"), field(m, "purpose")))
            .collect();
        // hlx:203
        if let Some(Json::Arr(names)) = packet.get("examples") {
            // hlx:204
            rows.push(format!(
                "Examples: {}",
                names
                    .iter()
                    .filter_map(Json::as_str)
                    .collect::<Vec<_>>()
                    .join(", ")
            ));
            // hlx:205
        }
        // hlx:206
        rows.push("Recipes: prepare, investigate, review. Choose your own with guide run --steps start,challenge,handoff".into());
        // hlx:207
        rows.push("Try: instinct guide challenge --example shared-document".into());
        // hlx:208
        return rows.join("\n");
        // hlx:209
    }
    // hlx:210
    let mut lines = vec![format!(
        "{} · {} · {}",
        field(packet, "mode"),
        field(packet, "source"),
        field(packet, "status")
    )];
    // hlx:211
    if field(packet, "source") == "example" && field(packet, "mode") != "handoff" {
        // hlx:212
        lines.push(field(packet, "task").into());
        // hlx:213
    }
    // hlx:214
    if let Some(Json::Arr(steps)) = packet.get("steps") {
        // hlx:215
        lines.extend(steps.iter().filter_map(Json::as_str).map(str::to_string));
        // hlx:216
    }
    // hlx:217
    lines.join("\n")
    // hlx:218
}
// hlx:221
pub(super) fn book() -> Result<String, String> {
    // hlx:222
    let scope = eligibility::env_scope();
    // hlx:223
    let no_bank = || Err("the guidebook cannot read a bank".to_string());
    // hlx:224
    let mut data = match run(no_bank, &obj(vec![]), &scope)? {
        Json::Obj(fields) => fields,
        _ => unreachable!(),
    };
    // hlx:225
    let mut examples = Vec::new();
    // hlx:226
    for row in scenarios()? {
        // hlx:227
        let name = field(&row, "name");
        // hlx:228
        let mut modes = Vec::new();
        // hlx:229
        for (mode, _) in MODES {
            // hlx:230
            let report = run(
                no_bank,
                &obj(vec![("mode", txt(mode)), ("example", txt(name))]),
                &scope,
            )?;
            // hlx:231
            modes.push((mode.to_string(), report));
            // hlx:232
        }
        // hlx:233
        examples.push((name.to_string(), Json::Obj(modes)));
        // hlx:234
    }
    // hlx:235
    data.push(("reports".into(), Json::Obj(examples)));
    // hlx:236
    let data = super::json_out(&Json::Obj(data))
        .replace('<', "\\u003c")
        .replace('>', "\\u003e")
        .replace('&', "\\u0026");
    // hlx:237
    Ok(include_str!("guidebook.html").replacen("__GUIDE_DATA__", &data, 1))
    // hlx:238
}