kowalski-cli 1.2.0

Kowalski CLI Interface: A Rust-based agent for interacting with Ollama models
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
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
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
//! Local **markdown-staged app** CLI (`app.md` / `horde.md` + `agents/*.md`).
//! Execution rules live in [`kowalski_core::markdown_pipeline`]; this module wires HTTP chat,
//! federation helpers, and filesystem paths.

use kowalski_core::markdown_pipeline::{
    maybe_normalize_markdown, parse_app_manifest, parse_stage_agent, render_context_attachments,
    resolve_manifest_path, AppManifestMeta, StageAgentMeta,
};
use kowalski_core::source_bundle::{ingest_assets_markdown, parse_input_assets};
use chrono::Utc;
use reqwest::blocking as reqwest_blocking;
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::io::BufRead;
use std::path::{Path, PathBuf};

/// Intermediate artifacts (ingest captures, per-stage LLM outputs) live here — for monitoring / debugging only.
const ARTIFACTS_DEBUG_DIR: &str = "debug";
/// Single operator-facing markdown at the `workdir` (or app run) root.
const PASTE_ME_FILENAME: &str = "PASTE_ME.md";

#[inline]
fn work_debug(workdir: &Path) -> PathBuf {
    workdir.join(ARTIFACTS_DEBUG_DIR)
}

/// Default workdir for local `agent-app run` when `horde.md` uses a relative `workdir` (often `output/`).
const LOCAL_AGENT_APP_WORKDIR: &str = "output";

#[inline]
fn local_agent_app_workdir(app_root: &Path) -> PathBuf {
    app_root.join(LOCAL_AGENT_APP_WORKDIR)
}

#[derive(Default, Clone)]
struct RunArtifacts {
    summary: Option<PathBuf>,
    report: Option<PathBuf>,
    handoff: Option<PathBuf>,
    log: Option<PathBuf>,
}

#[derive(Debug)]
struct AgentDoc<T> {
    meta: T,
    path: PathBuf,
}

type AgentSpecMap = BTreeMap<String, AgentDoc<StageAgentMeta>>;

fn app_root(path: Option<&str>) -> PathBuf {
    path.map(PathBuf::from)
        .or_else(|| std::env::var("KOWALSKI_AGENT_APP_ROOT").ok().map(PathBuf::from))
        .unwrap_or_else(|| PathBuf::from("examples/knowledge-compiler"))
}

fn agents_dir(root: &Path) -> PathBuf {
    root.join("agents")
}

fn load_spec(
    root: &Path,
) -> Result<(AgentDoc<AppManifestMeta>, AgentSpecMap), Box<dyn std::error::Error>> {
    let mpath = resolve_manifest_path(root);
    if !mpath.is_file() {
        return Err(format!(
            "missing manifest (tried {} and {}), expected next to agents/",
            root.join("app.md").display(),
            root.join("horde.md").display()
        )
        .into());
    }
    let meta = parse_app_manifest(&mpath).map_err(|e| e.to_string())?;
    let main = AgentDoc {
        meta,
        path: mpath,
    };
    let mut map = BTreeMap::new();
    for entry in fs::read_dir(agents_dir(root))? {
        let path = entry?.path();
        if path.extension().and_then(|x| x.to_str()) != Some("md") {
            continue;
        }
        let sm = parse_stage_agent(&path).map_err(|e| e.to_string())?;
        map.insert(
            sm.name.clone(),
            AgentDoc {
                meta: sm,
                path: path.to_path_buf(),
            },
        );
    }
    Ok((main, map))
}

pub fn list_agents(path: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
    let root = app_root(path);
    let (main, agents) = load_spec(&root)?;
    let title = main
        .meta
        .display_name
        .as_deref()
        .unwrap_or(&main.meta.id);
    println!("App: {} ({})", title, main.meta.id);
    println!("Pipeline: {}", main.meta.pipeline.join(" -> "));
    println!("Pipeline agents:");
    for step in &main.meta.pipeline {
        if let Some(agent) = agents.get(step) {
            println!("- {} ({})", step, agent.meta.kind);
        } else {
            println!("- {} (missing agents/{step}.md)", step);
        }
    }
    for name in agents.keys() {
        if !main.meta.pipeline.contains(name) {
            if let Some(agent) = agents.get(name) {
                println!(
                    "- {} ({}) [not in manifest pipeline — remove or add to pipeline]",
                    name, agent.meta.kind
                );
            }
        }
    }
    Ok(())
}

pub fn validate(path: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
    let root = app_root(path);
    let (main, agents) = load_spec(&root)?;
    let mut errs = Vec::new();
    let defs: BTreeSet<_> = agents.keys().cloned().collect();
    let pipeline_set: BTreeSet<_> = main.meta.pipeline.iter().cloned().collect();

    for name in &main.meta.pipeline {
        if !defs.contains(name) {
            errs.push(format!(
                "manifest pipeline references missing agent definition `{name}` (expected agents/{name}.md)"
            ));
        }
    }
    for name in &defs {
        if !pipeline_set.contains(name) {
            errs.push(format!(
                "agents/{name}.md exists but `{name}` is not listed in the manifest pipeline"
            ));
        }
    }
    for (name, agent) in &agents {
        if agent.meta.name != *name {
            errs.push(format!(
                "agent name mismatch in {} (key `{}` vs meta `{}`)",
                agent.path.display(),
                name,
                agent.meta.name
            ));
        }
    }

    if errs.is_empty() {
        println!("OK - manifest + agents/ definitions are valid");
        return Ok(());
    }
    for e in errs {
        eprintln!("ERROR: {}", e);
    }
    Err("manifest + agents/ definition invalid".into())
}

fn chat_no_tools(api: &str, prompt: &str) -> Result<String, Box<dyn std::error::Error>> {
    let client = reqwest_blocking::Client::builder()
        .timeout(std::time::Duration::from_secs(120))
        .build()?;
    let route = "/api/chat";
    let url = format!("{}{}", api.trim_end_matches('/'), route);
    let resp = client
        .post(format!("{}/api/chat", api.trim_end_matches('/')))
        .json(&serde_json::json!({
            "message": prompt,
            "use_memory": false,
            "use_tools": false
        }))
        .send()
        .map_err(|e| friendly_http_error(api, route, &url, &e))?;
    let status = resp.status();
    let body_text = resp.text().unwrap_or_default();
    if !status.is_success() {
        let detail = body_text.trim();
        let body_json = if detail.is_empty() {
            None
        } else {
            serde_json::from_str::<serde_json::Value>(detail)
                .ok()
                .or_else(|| Some(serde_json::json!({ "detail": detail })))
        };
        return Err(
            friendly_http_status_error(api, route, &url, status.as_u16(), body_json.as_ref())
                .into(),
        );
    }
    let v: serde_json::Value = serde_json::from_str(&body_text).map_err(|e| {
        format!(
            "response for {} ({}) was HTTP {} but not valid JSON: {}; body prefix: {:.200}",
            route, url, status.as_u16(), e, body_text
        )
    })?;
    Ok(v.get("reply")
        .and_then(|x| x.as_str())
        .unwrap_or("")
        .trim()
        .to_string())
}

fn read_or_empty(path: &Path) -> String {
    fs::read_to_string(path).unwrap_or_default()
}

fn ensure_dirs(root: &Path) -> Result<(), Box<dyn std::error::Error>> {
    fs::create_dir_all(root)?;
    let b = work_debug(root);
    for rel in [
        "raw",
        "raw/images",
        "reports",
        "slides",
        "lint",
        "scratch",
    ] {
        fs::create_dir_all(b.join(rel))?;
    }
    Ok(())
}

fn load_agent_doc(
    workspace_root: &Path,
    step: &str,
) -> Result<AgentDoc<StageAgentMeta>, Box<dyn std::error::Error>> {
    let path = workspace_root.join("agents").join(format!("{step}.md"));
    let sm = parse_stage_agent(&path).map_err(|e| e.to_string())?;
    Ok(AgentDoc {
        meta: sm,
        path,
    })
}

fn run_llm_stage(
    api: &str,
    app_root: &Path,
    workdir: &Path,
    agent: &AgentDoc<StageAgentMeta>,
    step: &str,
    extra_user_block: &str,
    step_paths: &BTreeMap<String, PathBuf>,
    previous_artifact: Option<&Path>,
) -> Result<PathBuf, Box<dyn std::error::Error>> {
    let rel = agent
        .meta
        .output
        .as_deref()
        .ok_or_else(|| format!("stage `{step}` missing `output` in {}", agent.path.display()))?;
    let out_path = workdir.join(rel);
    if let Some(parent) = out_path.parent() {
        fs::create_dir_all(parent)?;
    }
    let prompt_path = app_root.join(
        agent
            .meta
            .prompt_file
            .as_deref()
            .unwrap_or("prompts/stage.md"),
    );
    let prompt = read_or_empty(&prompt_path);
    let ctx = render_context_attachments(
        workdir,
        &agent.meta.context_paths,
        step_paths,
        previous_artifact,
    )
    .map_err(|e| -> Box<dyn std::error::Error> { e.to_string().into() })?;
    let msg = if extra_user_block.trim().is_empty() {
        format!("{prompt}\n\n{ctx}")
    } else {
        format!("{prompt}\n\n{extra_user_block}\n\n{ctx}")
    };
    let reply = chat_no_tools(api, &msg)?;
    let reply = maybe_normalize_markdown(&agent.meta, &reply);
    fs::write(&out_path, reply)?;
    Ok(out_path)
}

fn run_with_progress<F>(
    path: Option<&str>,
    source: &str,
    question: Option<&str>,
    api_url: Option<&str>,
    mut on_step: F,
) -> Result<RunArtifacts, Box<dyn std::error::Error>>
where
    F: FnMut(&str, &str, &Path),
{
    validate(path)?;
    let root = app_root(path);
    let work = local_agent_app_workdir(&root);
    let (main, agents) = load_spec(&root)?;
    let api = api_url.unwrap_or("http://127.0.0.1:3456");
    ensure_dirs(&work)?;
    let q = question
        .map(ToString::to_string)
        .or(main.meta.default_question.clone())
        .unwrap_or_else(|| "What changed?".to_string());

    let run_stamp = Utc::now().format("%Y%m%d-%H%M%S");
    let log_file = work_debug(&work)
        .join("scratch")
        .join(format!("orchestration-{run_stamp}.md"));
    let mut log = String::new();
    let mut task_outputs: Vec<(String, PathBuf)> = Vec::new();
    let mut artifacts = RunArtifacts::default();
    let total_steps = main.meta.pipeline.len();
    let run_title = main
        .meta
        .display_name
        .as_deref()
        .unwrap_or(&main.meta.id);
    log.push_str("# Agent App Run\n\n");
    log.push_str(&format!(
        "- App: {} ({})\n- Source: {}\n- Question: {}\n\n",
        run_title, main.meta.id, source, q
    ));
    println!("Starting staged app: {} ({})", run_title, main.meta.id);
    println!("Task count: {}", total_steps);

    let mut step_paths: BTreeMap<String, PathBuf> = BTreeMap::new();
    let mut prev_path: Option<PathBuf> = None;

    for (idx, step) in main.meta.pipeline.iter().enumerate() {
        let agent = agents
            .get(step)
            .ok_or_else(|| format!("missing step agent: {step}"))?;
        println!(
            "[{}/{}] {} ({})",
            idx + 1,
            total_steps,
            step,
            agent.meta.kind
        );
        log.push_str(&format!("## Step: {} ({})\n\n", step, agent.meta.kind));

        let out_path = if agent.meta.kind == "ingest" {
            let p = ingest_assets_markdown(&work_debug(&work), source)?;
            log.push_str(&format!("- output: {}\n\n", p.display()));
            task_outputs.push((step.clone(), p.clone()));
            on_step(step, agent.meta.kind.as_str(), p.as_path());
            println!("  -> {}", p.display());
            p
        } else {
            let extra = if agent.meta.kind == "ask" {
                format!("User question:\n{q}\n")
            } else {
                String::new()
            };
            let op = run_llm_stage(
                api,
                &root,
                &work,
                agent,
                step,
                &extra,
                &step_paths,
                prev_path.as_deref(),
            )?;
            log.push_str(&format!("- output: {}\n\n", op.display()));
            task_outputs.push((step.clone(), op.clone()));
            let is_last = idx + 1 == total_steps;
            if is_last {
                artifacts.handoff = Some(op.clone());
            } else if agent.meta.kind != "ingest" {
                if artifacts.summary.is_none() {
                    artifacts.summary = Some(op.clone());
                } else if artifacts.report.is_none() {
                    artifacts.report = Some(op.clone());
                }
            }
            on_step(step, agent.meta.kind.as_str(), op.as_path());
            println!("  -> {}", op.display());
            op
        };
        step_paths.insert(step.clone(), out_path.clone());
        prev_path = Some(out_path);
    }

    fs::write(&log_file, log)?;
    println!("\nSub-agent execution trace:");
    for (task, out) in &task_outputs {
        println!("- {} -> {}", task, out.display());
    }

    println!("\nFinal output artifacts:");
    if let Some(p) = &artifacts.summary {
        println!("- summary stage: {}", p.display());
    }
    if let Some(p) = &artifacts.report {
        println!("- report stage: {}", p.display());
    }
    if let Some(p) = &artifacts.handoff {
        println!("- final handoff: {}", p.display());
    }
    println!("Agent app run complete. Log: {}", log_file.display());
    artifacts.log = Some(log_file);
    Ok(artifacts)
}

pub fn run(
    path: Option<&str>,
    source: &str,
    question: Option<&str>,
    api_url: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
    let _ = run_with_progress(path, source, question, api_url, |_step, _kind, _output| {})?;
    Ok(())
}

fn post_json(
    api: &str,
    route: &str,
    payload: serde_json::Value,
) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
    let client = reqwest_blocking::Client::builder()
        .timeout(std::time::Duration::from_secs(60))
        .build()?;
    let resp = client
        .post(format!("{}{}", api.trim_end_matches('/'), route))
        .json(&payload)
        .send()
        .map_err(|e| {
            friendly_http_error(
                api,
                route,
                &format!("{}{}", api.trim_end_matches('/'), route),
                &e,
            )
        })?;
    let status = resp.status();
    let v: serde_json::Value = resp.json().unwrap_or_else(|_| serde_json::json!({}));
    if !status.is_success() {
        return Err(friendly_http_status_error(
            api,
            route,
            &format!("{}{}", api.trim_end_matches('/'), route),
            status.as_u16(),
            Some(&v),
        )
        .into());
    }
    Ok(v)
}

fn friendly_http_error(api: &str, route: &str, url: &str, err: &reqwest::Error) -> String {
    let mut msg = format!("request failed for {} ({}): {}", route, url, err);
    msg.push_str("\nPossible root causes:");
    if err.is_connect() {
        msg.push_str("\n- Kowalski server is not running or not reachable.");
        msg.push_str("\n- API URL is wrong.");
    } else if err.is_timeout() {
        msg.push_str("\n- Server is running but timed out.");
        msg.push_str("\n- LLM/provider backend is slow or blocked.");
    } else {
        msg.push_str("\n- Network or server-side error.");
    }
    msg.push_str("\nHow to fix:");
    msg.push_str("\n- Start server: cargo run -p kowalski --bin kowalski");
    msg.push_str(&format!(
        "\n- Verify health: curl {}/api/health",
        api.trim_end_matches('/')
    ));
    msg.push_str(&format!(
        "\n- If using custom API, set KOWALSKI_API and retry (current: {}).",
        api
    ));
    msg
}

fn friendly_http_status_error(
    api: &str,
    route: &str,
    url: &str,
    status_code: u16,
    body: Option<&serde_json::Value>,
) -> String {
    let mut msg = format!(
        "request failed for {} ({}): HTTP {}",
        route, url, status_code
    );
    if let Some(v) = body {
        if let Some(d) = v.get("detail").and_then(|x| x.as_str()).filter(|s| !s.is_empty()) {
            msg.push_str("\nServer detail:\n");
            msg.push_str(d);
        } else if *v != serde_json::json!({}) {
            msg.push_str(&format!("\nResponse body: {}", v));
        }
    }
    msg.push_str("\nPossible root causes:");
    if status_code == 404 {
        msg.push_str("\n- Endpoint is missing (version mismatch or wrong API URL).");
    } else if status_code >= 500 {
        msg.push_str("\n- Kowalski server hit an error while handling the request (see \"Server detail\" above if present).");
        msg.push_str("\n- Upstream LLM (Ollama/OpenAI) unreachable, wrong host/port, or model missing.");
        if route == "/api/chat" {
            msg.push_str("\n- For Ollama: run `ollama serve` (or the desktop app), then `curl -s http://127.0.0.1:11434/api/tags` and `ollama pull <model>` for the model in the server's `config.toml` `[llm]` / `[ollama]`.");
        }
    } else if status_code == 401 || status_code == 403 {
        msg.push_str("\n- Authentication/authorization problem.");
    } else {
        msg.push_str("\n- Request rejected by server configuration.");
    }
    msg.push_str("\nHow to fix:");
    msg.push_str("\n- Ensure server is running: cargo run -p kowalski --bin kowalski");
    msg.push_str(&format!(
        "\n- Verify health: curl {}/api/health",
        api.trim_end_matches('/')
    ));
    msg.push_str(&format!(
        "\n- Confirm API URL and route availability (current API: {}, route: {}).",
        api, route
    ));
    msg
}

fn latest_md_in(dir: &Path) -> Option<PathBuf> {
    let mut files: Vec<PathBuf> = fs::read_dir(dir)
        .ok()?
        .filter_map(|e| e.ok().map(|x| x.path()))
        .filter(|p| p.extension().and_then(|x| x.to_str()) == Some("md"))
        .collect();
    files.sort();
    files.pop()
}

pub fn federate_delegate(
    api_url: Option<&str>,
    capability: &str,
    source: &str,
    question: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
    let api = api_url.unwrap_or("http://127.0.0.1:3456");
    let task_id = format!("kc-{}", Utc::now().timestamp());
    let instruction = format!(
        "kc.run:{}|{}",
        source,
        question.unwrap_or("What changed in the latest source?")
    );
    let body = serde_json::json!({
        "task_id": task_id,
        "instruction": instruction,
        "capability": capability,
    });
    let out = post_json(api, "/api/federation/delegate", body)?;
    println!("{}", serde_json::to_string_pretty(&out)?);
    Ok(())
}

pub fn federate_worker(
    path: Option<&str>,
    api_url: Option<&str>,
    agent_id: &str,
    topic: Option<&str>,
    role: Option<&str>,
    capability_override: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
    let api = api_url.unwrap_or("http://127.0.0.1:3456");
    let root = app_root(path);
    let topic = topic.unwrap_or("federation");

    let role = role.map(|s| s.to_string());
    let capabilities: Vec<String> = if let Some(cap) = capability_override {
        vec![cap.to_string()]
    } else if let Some(r) = role.as_deref() {
        vec![format!("kc.{}", r)]
    } else {
        vec!["knowledge-compiler".to_string(), "kc.run".to_string()]
    };

    let reg = serde_json::json!({
        "id": agent_id,
        "capabilities": capabilities.clone(),
    });
    let _ = post_json(api, "/api/federation/register", reg)?;
    println!(
        "Registered worker `{}` (role={}, capabilities={}). Listening on topic `{}`.",
        agent_id,
        role.as_deref().unwrap_or("(legacy: kc.run)"),
        capabilities.join(","),
        topic
    );

    // SSE worker must keep the HTTP connection open indefinitely.
    // reqwest blocking `Client` defaults to a 30s **overall** timeout; idle SSE
    // reads then fail with `error decoding response body` (Decode kind) — disable it here.
    let client = reqwest_blocking::Client::builder()
        .timeout(None::<std::time::Duration>)
        .build()?;
    let stream_url = format!(
        "{}/api/federation/stream?topic={}",
        api.trim_end_matches('/'),
        topic
    );
    let resp = client.get(stream_url).send()?;
    if !resp.status().is_success() {
        return Err(format!("stream failed: HTTP {}", resp.status()).into());
    }
    let reader = std::io::BufReader::new(resp);

    for line in reader.lines() {
        let line = match line {
            Ok(v) => v,
            Err(e) => {
                eprintln!("federation stream decode warning (ignored): {}", e);
                continue;
            }
        };
        if !line.starts_with("data: ") {
            continue;
        }
        let data = &line[6..];
        let env: serde_json::Value = match serde_json::from_str(data) {
            Ok(v) => v,
            Err(_) => continue,
        };
        let payload = env
            .get("payload")
            .cloned()
            .unwrap_or_else(|| serde_json::json!({}));
        if payload.get("kind").and_then(|x| x.as_str()) != Some("task_delegate") {
            continue;
        }
        if payload.get("to_agent").and_then(|x| x.as_str()) != Some(agent_id) {
            continue;
        }
        let task_id = payload
            .get("task_id")
            .and_then(|x| x.as_str())
            .unwrap_or("unknown-task")
            .to_string();
        let instruction = payload
            .get("instruction")
            .and_then(|x| x.as_str())
            .unwrap_or("")
            .to_string();

        if let Some(role_kind) = role.as_deref() {
            handle_role_delegate(
                api,
                topic,
                agent_id,
                role_kind,
                &root,
                &task_id,
                &instruction,
            );
        } else {
            handle_legacy_run_delegate(api, topic, agent_id, &root, &task_id, &instruction);
        }
        let _ = post_json(
            api,
            "/api/federation/heartbeat",
            serde_json::json!({ "agent_id": agent_id }),
        );
    }
    Ok(())
}

fn parse_horde_instruction(instruction: &str) -> Option<HordeInstruction> {
    let v: serde_json::Value = serde_json::from_str(instruction).ok()?;
    let horde = v
        .get("horde")
        .and_then(|x| x.as_str())
        .unwrap_or("")
        .to_string();
    let run_id = v
        .get("run_id")
        .and_then(|x| x.as_str())
        .unwrap_or("")
        .to_string();
    let step = v
        .get("step")
        .and_then(|x| x.as_str())
        .unwrap_or("")
        .to_string();
    let kind = v
        .get("kind")
        .and_then(|x| x.as_str())
        .unwrap_or(&step)
        .to_string();
    if horde.is_empty() || run_id.is_empty() || step.is_empty() {
        return None;
    }
    Some(HordeInstruction {
        horde,
        run_id,
        step,
        kind,
        source: v
            .get("source")
            .and_then(|x| x.as_str())
            .map(ToString::to_string),
        question: v
            .get("question")
            .and_then(|x| x.as_str())
            .map(ToString::to_string),
        previous_artifact: v
            .get("previous_artifact")
            .and_then(|x| x.as_str())
            .map(ToString::to_string),
        horde_root: v
            .get("horde_root")
            .and_then(|x| x.as_str())
            .map(ToString::to_string),
        workdir: v
            .get("workdir")
            .and_then(|x| x.as_str())
            .map(ToString::to_string),
    })
}

#[derive(Debug, Clone)]
struct HordeInstruction {
    horde: String,
    run_id: String,
    step: String,
    kind: String,
    source: Option<String>,
    question: Option<String>,
    previous_artifact: Option<String>,
    horde_root: Option<String>,
    workdir: Option<String>,
}

fn publish_acl(api: &str, topic: &str, sender: &str, payload: serde_json::Value) {
    let body = serde_json::json!({
        "sender": sender,
        "topic": topic,
        "payload": payload,
    });
    if let Err(e) = post_json(api, "/api/federation/publish", body) {
        eprintln!("publish failed: {}", e);
    }
}

fn publish_task_started(
    api: &str,
    topic: &str,
    sender: &str,
    instr: &HordeInstruction,
    text: &str,
) {
    publish_acl(
        api,
        topic,
        sender,
        serde_json::json!({
            "kind": "task_started",
            "run_id": instr.run_id,
            "horde": instr.horde,
            "step": instr.step,
            "agent": sender,
            "text": text,
        }),
    );
}

fn publish_agent_message(
    api: &str,
    topic: &str,
    sender: &str,
    instr: &HordeInstruction,
    text: &str,
) {
    publish_acl(
        api,
        topic,
        sender,
        serde_json::json!({
            "kind": "agent_message",
            "run_id": instr.run_id,
            "horde": instr.horde,
            "from": sender,
            "step": instr.step,
            "text": text,
        }),
    );
}

fn publish_task_finished(
    api: &str,
    topic: &str,
    sender: &str,
    instr: &HordeInstruction,
    success: bool,
    artifact: Option<&str>,
    summary: &str,
) {
    publish_acl(
        api,
        topic,
        sender,
        serde_json::json!({
            "kind": "task_finished",
            "run_id": instr.run_id,
            "horde": instr.horde,
            "step": instr.step,
            "agent": sender,
            "success": success,
            "artifact": artifact,
            "summary": summary,
        }),
    );
}

fn publish_task_result(
    api: &str,
    topic: &str,
    sender: &str,
    task_id: &str,
    outcome: &str,
    success: bool,
) {
    publish_acl(
        api,
        topic,
        sender,
        serde_json::json!({
            "kind": "task_result",
            "task_id": task_id,
            "from_agent": sender,
            "outcome": outcome,
            "success": success,
        }),
    );
}

fn handle_role_delegate(
    api: &str,
    topic: &str,
    agent_id: &str,
    role_kind: &str,
    fallback_root: &Path,
    task_id: &str,
    instruction: &str,
) {
    let Some(instr) = parse_horde_instruction(instruction) else {
        let summary = format!(
            "rejected: instruction is not a horde JSON envelope (task_id={})",
            task_id
        );
        eprintln!("{}", summary);
        publish_task_result(api, topic, agent_id, task_id, &summary, false);
        return;
    };

    if instr.kind != role_kind {
        let summary = format!(
            "rejected: agent role `{}` does not match instruction kind `{}`",
            role_kind, instr.kind
        );
        publish_task_finished(api, topic, agent_id, &instr, false, None, &summary);
        publish_task_result(api, topic, agent_id, task_id, &summary, false);
        return;
    }

    let workspace_root = instr
        .horde_root
        .clone()
        .map(PathBuf::from)
        .filter(|p| p.exists())
        .unwrap_or_else(|| fallback_root.to_path_buf());
    let workdir = instr
        .workdir
        .clone()
        .map(PathBuf::from)
        .unwrap_or_else(|| workspace_root.clone());

    publish_task_started(
        api,
        topic,
        agent_id,
        &instr,
        &format!("{} agent starting", role_kind),
    );

    let result = match role_kind {
        "ingest" => execute_ingest(api, topic, agent_id, &instr, &workspace_root, &workdir),
        "compile" => execute_compile(api, topic, agent_id, &instr, &workspace_root, &workdir),
        "ask" => execute_ask(api, topic, agent_id, &instr, &workspace_root, &workdir),
        "lint" => execute_lint(api, topic, agent_id, &instr, &workspace_root, &workdir),
        other => Err(format!("unsupported role kind `{}`", other).into()),
    };

    match result {
        Ok((artifact, summary)) => {
            publish_task_finished(
                api,
                topic,
                agent_id,
                &instr,
                true,
                Some(&artifact),
                &summary,
            );
            publish_task_result(
                api,
                topic,
                agent_id,
                task_id,
                &format!("artifact={}; {}", artifact, summary),
                true,
            );
        }
        Err(e) => {
            let summary = format!("{} step failed: {}", role_kind, e);
            publish_task_finished(api, topic, agent_id, &instr, false, None, &summary);
            publish_task_result(api, topic, agent_id, task_id, &summary, false);
        }
    }
}

fn execute_ingest(
    api: &str,
    topic: &str,
    agent_id: &str,
    instr: &HordeInstruction,
    _workspace_root: &Path,
    workdir: &Path,
) -> Result<(String, String), Box<dyn std::error::Error>> {
    let _ = api;
    let _ = topic;
    let _ = agent_id;
    let source = instr
        .source
        .as_deref()
        .ok_or("ingest: missing `source` in horde instruction")?;
    ensure_dirs(workdir)?;
    let source_list = parse_input_assets(source);
    let path = ingest_assets_markdown(&work_debug(workdir), source)?;
    Ok((
        path.display().to_string(),
        format!(
            "Captured {} source(s) into raw collection: {}",
            source_list.len(),
            path.display()
        ),
    ))
}

fn execute_compile(
    api: &str,
    topic: &str,
    agent_id: &str,
    instr: &HordeInstruction,
    workspace_root: &Path,
    workdir: &Path,
) -> Result<(String, String), Box<dyn std::error::Error>> {
    ensure_dirs(workdir)?;
    let agent = load_agent_doc(workspace_root, &instr.step)?;
    let raw_dir = work_debug(workdir).join("raw");
    let prev_owned = instr
        .previous_artifact
        .as_ref()
        .map(PathBuf::from)
        .or_else(|| latest_md_in(&raw_dir));
    let prev = prev_owned.as_deref();
    if prev.is_none() {
        return Err("compile: no input artifact available (run ingest first)".into());
    }
    publish_agent_message(
        api,
        topic,
        agent_id,
        instr,
        &format!("LLM stage `{}` (federation worker)", instr.step),
    );
    let step_paths = BTreeMap::new();
    let out = run_llm_stage(
        api,
        workspace_root,
        workdir,
        &agent,
        &instr.step,
        "",
        &step_paths,
        prev,
    )?;
    Ok((
        out.display().to_string(),
        format!("stage output: {}", out.display()),
    ))
}

fn execute_ask(
    api: &str,
    topic: &str,
    agent_id: &str,
    instr: &HordeInstruction,
    workspace_root: &Path,
    workdir: &Path,
) -> Result<(String, String), Box<dyn std::error::Error>> {
    ensure_dirs(workdir)?;
    let agent = load_agent_doc(workspace_root, &instr.step)?;
    let q = instr
        .question
        .clone()
        .unwrap_or_else(|| "What changed in the latest source?".to_string());
    publish_agent_message(
        api,
        topic,
        agent_id,
        instr,
        &format!("LLM stage `{}` (federation): {}", instr.step, q),
    );
    let step_paths = BTreeMap::new();
    let prev = instr.previous_artifact.as_deref().map(Path::new);
    let extra = format!("User question:\n{q}\n");
    let out = run_llm_stage(
        api,
        workspace_root,
        workdir,
        &agent,
        &instr.step,
        &extra,
        &step_paths,
        prev,
    )?;
    Ok((
        out.display().to_string(),
        format!("stage output: {}", out.display()),
    ))
}

fn execute_lint(
    api: &str,
    topic: &str,
    agent_id: &str,
    instr: &HordeInstruction,
    workspace_root: &Path,
    workdir: &Path,
) -> Result<(String, String), Box<dyn std::error::Error>> {
    ensure_dirs(workdir)?;
    let agent = load_agent_doc(workspace_root, &instr.step)?;
    publish_agent_message(
        api,
        topic,
        agent_id,
        instr,
        &format!("LLM stage `{}` (federation handoff)", instr.step),
    );
    let step_paths = BTreeMap::new();
    let prev = instr.previous_artifact.as_deref().map(Path::new);
    let out = run_llm_stage(
        api,
        workspace_root,
        workdir,
        &agent,
        &instr.step,
        "",
        &step_paths,
        prev,
    )?;
    Ok((
        out.display().to_string(),
        format!("handoff output: {}", out.display()),
    ))
}

fn handle_legacy_run_delegate(
    api: &str,
    topic: &str,
    agent_id: &str,
    root: &Path,
    task_id: &str,
    instruction: &str,
) {
    let mut success = true;
    let outcome: String;
    if let Some(raw) = instruction.strip_prefix("kc.run:") {
        let mut parts = raw.splitn(2, '|');
        let source = parts.next().unwrap_or("").trim();
        let question = parts
            .next()
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .unwrap_or("What changed in the latest source?");
        if source.is_empty() {
            success = false;
            outcome = "missing source in instruction".to_string();
        } else {
            let root_s = root.to_string_lossy().to_string();
            let work = local_agent_app_workdir(root);
            let run_out = run_with_progress(
                Some(root_s.as_str()),
                source,
                Some(question),
                Some(api),
                |_step, _kind, _output| {},
            );
            match run_out {
                Err(e) => {
                    success = false;
                    outcome = format!("run failed: {}", e);
                }
                Ok(done) => {
                    let report = done
                        .report
                        .or_else(|| latest_md_in(&work_debug(&work).join("reports")))
                        .map(|p| p.display().to_string())
                        .unwrap_or_else(|| "(none)".to_string());
                    let handoff_disp = done
                        .handoff
                        .map(|p| p.display().to_string())
                        .unwrap_or_else(|| "(none)".to_string());
                    let summary = done
                        .summary
                        .map(|p| p.display().to_string())
                        .unwrap_or_else(|| "(none)".to_string());
                    let log = done
                        .log
                        .map(|p| p.display().to_string())
                        .unwrap_or_else(|| "(none)".to_string());
                    outcome = format!(
                        "run complete; summary={}; report={}; handoff={}; log={}",
                        summary, report, handoff_disp, log
                    );
                }
            }
        }
    } else {
        success = false;
        outcome = format!("unsupported instruction: {}", instruction);
    }
    publish_task_result(api, topic, agent_id, task_id, &outcome, success);
}

pub fn proof_check(
    path: Option<&str>,
    api_url: Option<&str>,
    agent_id: Option<&str>,
    capability: Option<&str>,
    source: Option<&str>,
    question: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
    let root = app_root(path);
    let work = local_agent_app_workdir(&root);
    let api = api_url.unwrap_or("http://127.0.0.1:3456");
    let agent_id = agent_id.unwrap_or("kc-worker-1");
    let capability = capability.unwrap_or("kc.run");
    let source = source.unwrap_or("https://example.com/article");
    let question = question.unwrap_or("What changed?");

    // Preflight checks
    println!("Preflight:");
    validate(Some(root.to_string_lossy().as_ref()))?;
    let health = reqwest_blocking::get(format!("{}/api/health", api.trim_end_matches('/')));
    match health {
        Ok(r) if r.status().is_success() => println!("- API reachable at {}", api),
        Ok(r) => println!("- API responded with HTTP {} at {}", r.status(), api),
        Err(e) => println!("- API not reachable at {} ({})", api, e),
    }
    println!("- App path: {}", root.display());

    println!("\nProof-run checklist (3 terminals):");
    println!("1) Terminal A: start server");
    println!("   cargo run -p kowalski --bin kowalski");
    println!("2) Terminal B: start worker");
    println!(
        "   cargo run -p kowalski-cli -- agent-app worker --path \"{}\" --api \"{}\" \"{}\"",
        root.display(),
        api,
        agent_id
    );
    println!("3) Terminal C: delegate task");
    println!(
        "   cargo run -p kowalski-cli -- agent-app delegate --api \"{}\" --question \"{}\" \"{}\" \"{}\"",
        api, question, capability, source
    );
    println!("\nVerify artifacts (under {}):", work.display());
    println!(
        "- latest report: {}",
        latest_md_in(&work_debug(&work).join("reports"))
            .map(|p| p.display().to_string())
            .unwrap_or_else(|| "(none yet)".to_string())
    );
    println!(
        "- stage outputs (see manifest `agents/*.md` `output` paths): {}",
        work_debug(&work).display()
    );
    println!(
        "- latest run log: {}",
        latest_md_in(&work_debug(&work).join("scratch"))
            .map(|p| p.display().to_string())
            .unwrap_or_else(|| "(none yet)".to_string())
    );
    println!(
        "- paste pack: {}",
        work.join(PASTE_ME_FILENAME).display()
    );
    Ok(())
}