edda-pack 0.6.2

Context generation and budget controls for Edda
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
use edda_index::{fetch_store_line, read_index_tail, IndexRecordV1};
use edda_ledger::view::DecisionView;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::Path;

const DEFAULT_INDEX_TAIL_LINES: usize = 5000;
const DEFAULT_INDEX_TAIL_MAX_BYTES: u64 = 8 * 1024 * 1024; // 8MB
const DEFAULT_PACK_TURNS: usize = 12;
const DEFAULT_PACK_BUDGET_CHARS: usize = 12000;

// ── Turn + ToolUse structs ──

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Turn {
    pub user_uuid: String,
    pub assistant_uuid: String,
    pub user_text: String,
    pub assistant_texts: Vec<String>,
    pub tool_uses: Vec<ToolUse>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolUse {
    pub id: Option<String>,
    pub name: String,
    pub command: Option<String>,
    pub description: Option<String>,
    pub file_path: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PackMetadata {
    pub project_id: String,
    pub session_id: String,
    pub git_branch: String,
    pub turn_count: usize,
    pub budget_chars: usize,
}

// ── Turn alignment via uuid/parentUuid ──

/// Build turns from index records by matching assistant.parentUuid → user.uuid.
pub fn build_turns(
    project_dir: &Path,
    session_id: &str,
    max_turns: usize,
) -> anyhow::Result<Vec<Turn>> {
    let tail_lines: usize = std::env::var("EDDA_INDEX_TAIL_LINES")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(DEFAULT_INDEX_TAIL_LINES);
    let tail_bytes: u64 = std::env::var("EDDA_INDEX_TAIL_MAX_BYTES")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(DEFAULT_INDEX_TAIL_MAX_BYTES);
    let pack_turns: usize = std::env::var("EDDA_PACK_TURNS")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(DEFAULT_PACK_TURNS);
    let max_turns = max_turns.min(pack_turns);

    let index_path = project_dir
        .join("index")
        .join(format!("{session_id}.jsonl"));
    let records = read_index_tail(&index_path, tail_lines, tail_bytes)?;

    if records.is_empty() {
        return Ok(vec![]);
    }

    // Build lookup by uuid
    let by_uuid: HashMap<String, &IndexRecordV1> =
        records.iter().map(|r| (r.uuid.clone(), r)).collect();

    // Collect assistant records in order
    let assistants: Vec<&IndexRecordV1> = records
        .iter()
        .filter(|r| r.record_type == "assistant")
        .collect();

    let store_path = project_dir
        .join("transcripts")
        .join(format!("{session_id}.jsonl"));

    let mut turns = Vec::new();
    let mut seen_user_uuids = HashSet::new();

    // Process newest assistant first
    for asst_rec in assistants.iter().rev() {
        if turns.len() >= max_turns {
            break;
        }

        // Walk UP the parentUuid chain to find the real user prompt.
        // Claude Code transcript structure:
        //   user(STRING) → assistant(tool_use) → user(tool_result) → assistant(tool_use) → ... → assistant(text)
        // We start from the leaf assistant and walk up to find the root user with STRING content.
        let mut current_parent = asst_rec.parent_uuid.as_deref();
        let mut chain_tool_uses: Vec<ToolUse> = Vec::new();
        let mut real_user_uuid = String::new();
        let mut real_user_text = String::new();

        let mut depth = 0;
        const MAX_CHAIN_DEPTH: usize = 50;

        while let Some(parent_id) = current_parent {
            if depth >= MAX_CHAIN_DEPTH {
                break;
            }
            depth += 1;

            let parent_rec = match by_uuid.get(parent_id) {
                Some(r) => r,
                None => break,
            };

            if parent_rec.record_type == "user" {
                // Try to extract user text from this record
                if let Ok(raw) =
                    fetch_store_line(&store_path, parent_rec.store_offset, parent_rec.store_len)
                {
                    if let Ok(json) = serde_json::from_slice::<serde_json::Value>(&raw) {
                        let text = extract_user_text(&json);
                        if !text.is_empty() {
                            real_user_uuid = parent_rec.uuid.clone();
                            real_user_text = text;
                            break; // Found the real user prompt
                        }
                    }
                }
                // Content is array (tool_result) or empty → keep walking up
                current_parent = parent_rec.parent_uuid.as_deref();
            } else if parent_rec.record_type == "assistant" {
                // Intermediate assistant → collect its tool_uses
                if let Ok(raw) =
                    fetch_store_line(&store_path, parent_rec.store_offset, parent_rec.store_len)
                {
                    if let Ok(json) = serde_json::from_slice::<serde_json::Value>(&raw) {
                        let (_, tus) = parse_assistant_content(&json);
                        chain_tool_uses.extend(tus);
                    }
                }
                current_parent = parent_rec.parent_uuid.as_deref();
            } else {
                break; // unexpected record type
            }
        }

        if real_user_text.is_empty() || real_user_uuid.is_empty() {
            continue;
        }

        // Dedup: only one turn per real user prompt
        if !seen_user_uuids.insert(real_user_uuid.clone()) {
            continue;
        }

        // Parse final (leaf) assistant content
        let asst_raw =
            match fetch_store_line(&store_path, asst_rec.store_offset, asst_rec.store_len) {
                Ok(r) => r,
                Err(_) => continue,
            };
        let asst_json: serde_json::Value = match serde_json::from_slice(&asst_raw) {
            Ok(v) => v,
            Err(_) => continue,
        };
        let (assistant_texts, final_tool_uses) = parse_assistant_content(&asst_json);

        // Merge tool_uses: chain (reversed to chronological) + final assistant's
        chain_tool_uses.reverse();
        chain_tool_uses.extend(final_tool_uses);

        turns.push(Turn {
            user_uuid: real_user_uuid,
            assistant_uuid: asst_rec.uuid.clone(),
            user_text: real_user_text,
            assistant_texts,
            tool_uses: chain_tool_uses,
        });
    }

    Ok(turns)
}

/// Extract user text from a transcript user record.
/// Returns non-empty string only for real user prompts (STRING content).
/// Returns empty for tool_result arrays (these are tool execution results, not user input).
fn extract_user_text(user_json: &serde_json::Value) -> String {
    let content = match user_json.get("message").and_then(|m| m.get("content")) {
        Some(c) => c,
        None => return String::new(),
    };

    // String content → real user prompt
    if let Some(s) = content.as_str() {
        return s.to_string();
    }

    // Array content → check block types
    if let Some(arr) = content.as_array() {
        // If any block is tool_result, this is NOT a real user prompt
        let has_tool_result = arr
            .iter()
            .any(|b| b.get("type").and_then(|t| t.as_str()) == Some("tool_result"));
        if has_tool_result {
            return String::new();
        }

        // Extract text from text blocks (handles ARRAY(text) format)
        let texts: Vec<&str> = arr
            .iter()
            .filter_map(|b| {
                if b.get("type").and_then(|t| t.as_str()) == Some("text") {
                    b.get("text").and_then(|t| t.as_str())
                } else {
                    None
                }
            })
            .collect();
        if !texts.is_empty() {
            return texts.join(" ");
        }
    }

    String::new()
}

fn parse_assistant_content(asst_json: &serde_json::Value) -> (Vec<String>, Vec<ToolUse>) {
    let mut texts = Vec::new();
    let mut tool_uses = Vec::new();

    let content = asst_json.get("message").and_then(|m| m.get("content"));

    if let Some(arr) = content.and_then(|c| c.as_array()) {
        for block in arr {
            let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
            match block_type {
                "text" => {
                    if let Some(text) = block.get("text").and_then(|v| v.as_str()) {
                        texts.push(text.to_string());
                    }
                }
                "tool_use" => {
                    let name = block
                        .get("name")
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_string();
                    let id = block.get("id").and_then(|v| v.as_str()).map(|s| s.into());
                    let input = block.get("input");
                    let command = input
                        .and_then(|i| i.get("command"))
                        .and_then(|c| c.as_str())
                        .map(|s| s.into());
                    let description = input
                        .and_then(|i| i.get("description"))
                        .and_then(|d| d.as_str())
                        .map(|s| s.into());
                    let file_path = input
                        .and_then(|i| i.get("file_path"))
                        .and_then(|f| f.as_str())
                        .map(|s| s.into());

                    tool_uses.push(ToolUse {
                        id,
                        name,
                        command,
                        description,
                        file_path,
                    });
                }
                _ => {}
            }
        }
    } else if let Some(text) = content.and_then(|c| c.as_str()) {
        texts.push(text.to_string());
    }

    (texts, tool_uses)
}

// ── Pack rendering ──

/// The stable section order for neutral memory-pack items.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum PackSection {
    Goals,
    BindingDecisions,
    UnratifiedDecisions,
    OpenCheckpoints,
    Constraints,
    Coordination,
    FileStateDeltas,
    RecentTurns,
}

impl PackSection {
    fn title(self) -> &'static str {
        match self {
            Self::Goals => "Goals",
            Self::BindingDecisions => "Binding Decisions",
            Self::UnratifiedDecisions => "Unratified Decisions",
            Self::OpenCheckpoints => "Open Checkpoints",
            Self::Constraints => "Constraints",
            Self::Coordination => "Coordination",
            Self::FileStateDeltas => "File-State Deltas",
            Self::RecentTurns => "Recent Turns (deterministic)",
        }
    }
}

/// A complete, neutral item in a memory pack.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PackItem {
    pub section: PackSection,
    pub key: String,
    pub body: String,
    pub salience: u64,
}

/// Convert checkpoint events into neutral hot-pack items.
pub fn checkpoint_items(events: &[edda_core::Event]) -> Vec<PackItem> {
    events
        .iter()
        .rev()
        .enumerate()
        .filter_map(|(index, event)| {
            let payload: edda_core::event::CheckpointPayload =
                serde_json::from_value(event.payload.clone()).ok()?;
            let rejected = payload
                .rejected
                .iter()
                .map(|item| format!("{}{}", item.hypothesis, item.reason))
                .collect::<Vec<_>>();
            let body = format!(
                "- hypotheses: {}\n- rejected: {}\n- open: {}\n- next: {}\n",
                payload.hypotheses.join(" | "),
                rejected.join(" | "),
                payload.open.join(" | "),
                payload.next,
            );
            Some(PackItem {
                section: PackSection::OpenCheckpoints,
                key: format!("Checkpoint {}", event.event_id),
                body,
                salience: 90 + (events.len() - index) as u64,
            })
        })
        .collect()
}

fn latest_registered_checkpoint_items(project_id: &str) -> Vec<PackItem> {
    let Some(project) = edda_store::registry::get_project(project_id) else {
        return Vec::new();
    };
    let Ok(ledger) = edda_ledger::Ledger::open(project.path) else {
        return Vec::new();
    };
    let Ok(branch) = ledger.head_branch() else {
        return Vec::new();
    };
    let Ok(events) = ledger.iter_events_by_type("checkpoint") else {
        return Vec::new();
    };
    let events: Vec<_> = events
        .into_iter()
        .filter(|event| event.branch == branch)
        .collect();
    checkpoint_items(&events).into_iter().take(1).collect()
}

fn pack_budget(budget_chars: usize) -> usize {
    if budget_chars == 0 {
        std::env::var("EDDA_PACK_BUDGET_CHARS")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(DEFAULT_PACK_BUDGET_CHARS)
    } else {
        budget_chars
    }
}

fn render_pack_header(metadata: &PackMetadata, dropped_items: usize) -> String {
    format!(
        "# edda memory pack (hot)\n\n- project_id: {}\n- session_id: {}\n- git_branch: {}\n- turns: {}\n- dropped_items: {}\n\n",
        metadata.project_id,
        metadata.session_id,
        metadata.git_branch,
        metadata.turn_count,
        dropped_items,
    )
}

fn render_selected_items(
    metadata: &PackMetadata,
    items: &[PackItem],
    selected: &[usize],
    dropped_items: usize,
) -> String {
    let mut ordered = selected.to_vec();
    ordered.sort_by(|a, b| {
        items[*a]
            .section
            .cmp(&items[*b].section)
            .then_with(|| items[*a].key.cmp(&items[*b].key))
            .then_with(|| a.cmp(b))
    });

    let mut out = render_pack_header(metadata, dropped_items);
    let mut section = None;
    for index in ordered {
        let item = &items[index];
        if section != Some(item.section) {
            out.push_str(&format!("## {}\n\n", item.section.title()));
            section = Some(item.section);
        }
        out.push_str(&format!("### {}\n", item.key));
        out.push_str(&item.body);
        if !item.body.ends_with('\n') {
            out.push('\n');
        }
        out.push('\n');
    }
    out
}

fn select_items(
    metadata: &PackMetadata,
    items: &[PackItem],
    budget: usize,
    dropped_items: usize,
) -> Vec<usize> {
    let mut ranked: Vec<usize> = (0..items.len()).collect();
    ranked.sort_by(|a, b| {
        items[*b]
            .salience
            .cmp(&items[*a].salience)
            .then_with(|| items[*a].section.cmp(&items[*b].section))
            .then_with(|| items[*a].key.cmp(&items[*b].key))
            .then_with(|| a.cmp(b))
    });

    let mut selected = Vec::new();
    for index in ranked {
        selected.push(index);
        if render_selected_items(metadata, items, &selected, dropped_items).len() > budget {
            selected.pop();
        }
    }
    selected
}

/// Render neutral items in deterministic section and salience order.
///
/// Items are selected by salience, with stable tie-breakers, and are either
/// included in full or omitted. The dropped count is part of the pack header.
pub fn render_ordered_pack(
    items: &[PackItem],
    metadata: &PackMetadata,
    budget_chars: usize,
) -> String {
    let budget = pack_budget(budget_chars);
    let mut dropped_items = items.len();
    let mut selected = Vec::new();

    // The count is in the header, so a digit-boundary change can affect fit.
    for _ in 0..4 {
        selected = select_items(metadata, items, budget, dropped_items);
        let next_dropped = items.len() - selected.len();
        if next_dropped == dropped_items {
            break;
        }
        dropped_items = next_dropped;
    }

    render_selected_items(metadata, items, &selected, items.len() - selected.len())
}

fn render_turn_body(turn: &Turn) -> String {
    let mut body = format!("- User: {}\n", turn.user_text);
    for tu in &turn.tool_uses {
        let cmd_str = tu
            .command
            .as_deref()
            .map(|c| format!(" `{c}`"))
            .unwrap_or_default();
        let desc_str = tu
            .description
            .as_deref()
            .map(|d| format!(" ({d})"))
            .unwrap_or_default();
        let file_str = tu
            .file_path
            .as_deref()
            .map(|f| format!(" file={f}"))
            .unwrap_or_default();
        body.push_str(&format!(
            "  - ToolUse: {}{}{}{}\n",
            tu.name, cmd_str, desc_str, file_str
        ));
    }
    for text in &turn.assistant_texts {
        body.push_str(&format!("  - Assistant: {text}\n"));
    }
    body
}

/// Render turns into a hot pack without truncating any turn item.
pub fn render_pack(turns: &[Turn], metadata: &PackMetadata, budget_chars: usize) -> String {
    let mut items: Vec<PackItem> = turns
        .iter()
        .enumerate()
        .map(|(index, turn)| PackItem {
            section: PackSection::RecentTurns,
            key: format!("Turn {} (newest first)", index + 1),
            body: render_turn_body(turn),
            salience: (turns.len() - index) as u64,
        })
        .collect();
    items.extend(latest_registered_checkpoint_items(&metadata.project_id));
    render_ordered_pack(&items, metadata, budget_chars)
}

/// Write hot.md and hot.meta.json to the packs directory.
pub fn write_pack(project_dir: &Path, pack_md: &str, meta: &PackMetadata) -> anyhow::Result<()> {
    let packs_dir = project_dir.join("packs");
    std::fs::create_dir_all(&packs_dir)?;

    edda_store::write_atomic(&packs_dir.join("hot.md"), pack_md.as_bytes())?;

    let meta_json = serde_json::to_string_pretty(meta)?;
    edda_store::write_atomic(&packs_dir.join("hot.meta.json"), meta_json.as_bytes())?;

    Ok(())
}

// ── Doctrine Pack (judgment layer) ──

const DEFAULT_DOCTRINE_FILE: &str = ".havamal-pack.md";

/// Read the project's doctrine hot pack (judgment layer).
///
/// Contract with havamal (github.com/fagemx/havamal): the project curates
/// judgment — ideology, failure memory, taste — as doctrine files and
/// generates a compressed pack via `havamal pack --out .havamal-pack.md`.
/// edda transports that pack into the session. edda never generates judgment
/// itself: machine-extracted judgment without curation is noise; facts flow
/// automatically, judgment enters signed.
///
/// Resolution order:
/// 1. `EDDA_DOCTRINE_PATH` env var (absolute, or relative to `repo_root`)
/// 2. `<repo_root>/.havamal-pack.md`
///
/// Returns `None` when no doctrine source exists or the file is empty.
/// Content is truncated at `budget` bytes on a char boundary.
pub fn read_doctrine_pack(repo_root: &Path, budget: usize) -> Option<String> {
    let path = match std::env::var("EDDA_DOCTRINE_PATH") {
        Ok(p) if !p.trim().is_empty() => {
            let pb = std::path::PathBuf::from(p.trim());
            if pb.is_absolute() {
                pb
            } else {
                repo_root.join(pb)
            }
        }
        _ => repo_root.join(DEFAULT_DOCTRINE_FILE),
    };

    let raw = std::fs::read_to_string(&path).ok()?;
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return None;
    }

    let mut body = trimmed.to_string();
    if body.len() > budget {
        let mut end = budget;
        while end > 0 && !body.is_char_boundary(end) {
            end -= 1;
        }
        body.truncate(end);
        body.push_str("\n<!-- doctrine truncated by EDDA_DOCTRINE_BUDGET_CHARS -->");
    }

    Some(format!("## Doctrine (judgment layer)\n\n{body}"))
}

// ── Decision Pack ──

/// A pack of active decisions grouped by domain, ready for session injection.
#[derive(Debug, Clone)]
pub struct DecisionPack {
    /// Decisions grouped by domain (e.g., "db", "error", "auth")
    pub groups: Vec<DecisionGroup>,
    /// Total number of decisions included
    pub total: usize,
    /// Branch these decisions are scoped to
    pub branch: String,
}

/// A group of decisions sharing the same domain prefix.
#[derive(Debug, Clone)]
pub struct DecisionGroup {
    /// Domain name (e.g., "db", "error", "auth")
    pub domain: String,
    /// Decisions in this domain, sorted by key
    pub decisions: Vec<DecisionSummary>,
}

/// Minimal decision summary for pack rendering (avoids carrying full DecisionView).
#[derive(Debug, Clone)]
pub struct DecisionSummary {
    pub key: String,
    pub value: String,
    pub reason: String,
    pub status: String,
    pub authority: String,
    pub reversibility: String,
    pub affected_paths: Vec<String>,
    /// Ratified by the operator or the cited-authority sweep (GH-401, GH-1063).
    /// Derived from `decision_ratify` events at build time — `From<&DecisionView>`
    /// alone cannot know it, so callers with ratified-state must set it explicitly.
    pub ratified: bool,
}

impl From<&DecisionView> for DecisionSummary {
    fn from(v: &DecisionView) -> Self {
        Self {
            key: v.key.clone(),
            value: v.value.clone(),
            reason: v.reason.clone(),
            status: v.status.clone(),
            authority: v.authority.clone(),
            reversibility: v.reversibility.clone(),
            affected_paths: v.affected_paths.clone(),
            ratified: false,
        }
    }
}

/// Build a decision pack from active decisions in the ledger.
///
/// Queries active decisions (status IN active, experimental) on the given
/// branch, groups by domain, and limits to `max_items` total decisions.
///
/// Returns a pack with 0 groups if no active decisions exist.
pub fn build_decision_pack(repo_root: &Path, branch: &str, max_items: usize) -> DecisionPack {
    let (mut views, ratified): (Vec<DecisionView>, std::collections::BTreeSet<String>) =
        match edda_ledger::Ledger::open(repo_root) {
            // Fetch ALL active decisions (not SQL-limited): active_decisions is
            // not branch-filtered, so a SQL LIMIT applied before the branch
            // retain below could be entirely consumed by other branches and
            // drop every decision for this branch. Filter by branch first,
            // then cap at max_items.
            Ok(ledger) => (
                ledger
                    .active_decisions(None, None, None, None)
                    .unwrap_or_default(),
                // GH-401: ratified decision event_ids, derived by rowid order.
                ledger.ratified_decision_events().unwrap_or_default(),
            ),
            Err(_) => (Vec::new(), std::collections::BTreeSet::new()),
        };
    // Keep only this branch's decisions (see above), then cap at max_items so
    // a decision — and its ratified-state — from another branch is never
    // rendered under this branch's header.
    views.retain(|v| v.branch == branch);
    views.truncate(max_items);

    if views.is_empty() {
        return DecisionPack {
            groups: Vec::new(),
            total: 0,
            branch: branch.to_string(),
        };
    }

    // Group by domain, limit to max_items total
    let mut by_domain: BTreeMap<String, Vec<DecisionSummary>> = BTreeMap::new();
    let mut count = 0;

    for d in &views {
        if count >= max_items {
            break;
        }
        let mut summary = DecisionSummary::from(d);
        summary.ratified = edda_ledger::view::is_decision_ratified(d, &ratified);
        by_domain.entry(d.domain.clone()).or_default().push(summary);
        count += 1;
    }

    let groups = by_domain
        .into_iter()
        .map(|(domain, mut decisions)| {
            decisions.sort_by(|a, b| a.key.cmp(&b.key));
            DecisionGroup { domain, decisions }
        })
        .collect();

    DecisionPack {
        groups,
        total: count,
        branch: branch.to_string(),
    }
}

/// Render a decision pack as a markdown section, split into an
/// operator-ratified (binding) tier and an unratified tier (GH-401).
///
/// Binding status comes from `decision_ratify` events (carried on each
/// summary as `ratified`), never from the authority string — so the pack
/// can never launder agent inference into operator authority. Each domain
/// group is preserved within its tier; unratified lines are annotated with
/// their authorship. Returns an empty string if the pack has 0 decisions.
pub fn render_decision_pack_md(pack: &DecisionPack) -> String {
    if pack.total == 0 {
        return String::new();
    }

    let ratified_count = pack
        .groups
        .iter()
        .flat_map(|g| &g.decisions)
        .filter(|d| d.ratified)
        .count();
    let unratified_count = pack.total.saturating_sub(ratified_count);

    let mut sections: Vec<String> = Vec::new();
    if ratified_count > 0 {
        sections.push(render_decision_tier(
            pack,
            true,
            &format!(
                "## Ratified Decisions ({} on `{}`)",
                ratified_count, pack.branch
            ),
        ));
    }
    if unratified_count > 0 {
        sections.push(render_decision_tier(
            pack,
            false,
            &format!(
                "## Unratified Decisions ({} on `{}`) — recorded, not binding until `edda ratify`",
                unratified_count, pack.branch
            ),
        ));
    }
    sections.join("\n\n")
}

/// Render one tier (ratified or not) of a decision pack, preserving domain
/// grouping. Unratified lines carry an authorship tag; ratified lines do not.
fn render_decision_tier(pack: &DecisionPack, want_ratified: bool, header: &str) -> String {
    let mut lines = vec![header.to_string()];
    for group in &pack.groups {
        let decs: Vec<&DecisionSummary> = group
            .decisions
            .iter()
            .filter(|d| d.ratified == want_ratified)
            .collect();
        if decs.is_empty() {
            continue;
        }
        lines.push(format!("\n### {}", group.domain));
        for d in decs {
            let mut entry = if want_ratified {
                format!("- **`{}={}`**", d.key, d.value)
            } else {
                format!(
                    "- [{}] **`{}={}`**",
                    edda_core::types::authorship_tag(&d.authority),
                    d.key,
                    d.value
                )
            };
            if !d.reason.is_empty() {
                entry.push_str(&format!("{}", d.reason));
            }
            if !d.affected_paths.is_empty() {
                entry.push_str(&format!("\n  paths: `{}`", d.affected_paths.join("`, `")));
            }
            lines.push(entry);
        }
    }
    lines.join("\n")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn render_pack_basic() {
        let turns = vec![Turn {
            user_uuid: "u1".into(),
            assistant_uuid: "a1".into(),
            user_text: "How do I sort a list?".into(),
            assistant_texts: vec!["Use the sort() method.".into()],
            tool_uses: vec![ToolUse {
                id: Some("tu1".into()),
                name: "Bash".into(),
                command: Some("ls -la".into()),
                description: Some("List files".into()),
                file_path: None,
            }],
        }];

        let meta = PackMetadata {
            project_id: "abc123".into(),
            session_id: "s1".into(),
            git_branch: "main".into(),
            turn_count: 1,
            budget_chars: 12000,
        };

        let md = render_pack(&turns, &meta, 12000);
        assert!(md.contains("# edda memory pack (hot)"));
        assert!(md.contains("How do I sort a list?"));
        assert!(md.contains("ToolUse: Bash"));
        assert!(md.contains("Use the sort() method."));
    }

    #[test]
    fn checkpoint_items_join_the_hot_pack_schema() {
        let checkpoint = edda_core::event::CheckpointPayload {
            hypotheses: vec!["cache invalidation is the cause".to_string()],
            rejected: vec![edda_core::event::RejectedHypothesis {
                hypothesis: "database corruption".to_string(),
                reason: "integrity check passes".to_string(),
            }],
            open: vec!["confirm the next rebuild".to_string()],
            next: "run the rebuild check".to_string(),
        };
        let event =
            edda_core::event::new_checkpoint_event("main", None, "agent", &checkpoint).unwrap();
        let items = checkpoint_items(&[event]);
        let meta = PackMetadata {
            project_id: "abc".into(),
            session_id: "s1".into(),
            git_branch: "main".into(),
            turn_count: 0,
            budget_chars: 12000,
        };

        let md = render_ordered_pack(&items, &meta, 12000);

        assert!(md.contains("## Open Checkpoints"));
        assert!(md.contains("cache invalidation is the cause"));
        assert!(md.contains("integrity check passes"));
        assert!(md.contains("run the rebuild check"));
    }

    #[test]
    fn render_pack_drops_whole_items_at_budget() {
        let turns: Vec<Turn> = (0..20)
            .map(|i| Turn {
                user_uuid: format!("u{i}"),
                assistant_uuid: format!("a{i}"),
                user_text: format!("Question {i} with some extra text padding to fill space"),
                assistant_texts: vec![format!(
                    "Answer {i} with a reasonably long response text to consume budget"
                )],
                tool_uses: vec![],
            })
            .collect();

        let meta = PackMetadata {
            project_id: "abc".into(),
            session_id: "s1".into(),
            git_branch: "main".into(),
            turn_count: 20,
            budget_chars: 500,
        };

        let md = render_pack(&turns, &meta, 500);
        assert!(md.contains("- dropped_items: "));
        assert!(!md.contains("truncated by budget"));
        assert!(md.len() <= 500);
    }

    #[test]
    fn write_pack_creates_files() {
        let tmp = tempfile::tempdir().unwrap();
        let meta = PackMetadata {
            project_id: "test".into(),
            session_id: "s1".into(),
            git_branch: "main".into(),
            turn_count: 0,
            budget_chars: 12000,
        };

        write_pack(tmp.path(), "# pack content", &meta).unwrap();

        let hot = tmp.path().join("packs").join("hot.md");
        assert!(hot.exists());
        assert_eq!(std::fs::read_to_string(&hot).unwrap(), "# pack content");

        let meta_path = tmp.path().join("packs").join("hot.meta.json");
        assert!(meta_path.exists());
    }

    // ── Doctrine Pack tests ──

    #[test]
    fn doctrine_pack_missing_returns_none() {
        let tmp = tempfile::tempdir().unwrap();
        assert!(read_doctrine_pack(tmp.path(), 4000).is_none());
    }

    #[test]
    fn doctrine_pack_reads_default_file() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(
            tmp.path().join(".havamal-pack.md"),
            "## L1 — MUST STAY TRUE\nClaims never close work.",
        )
        .unwrap();
        let md = read_doctrine_pack(tmp.path(), 4000).unwrap();
        assert!(md.starts_with("## Doctrine (judgment layer)"));
        assert!(md.contains("Claims never close work."));
    }

    #[test]
    fn doctrine_pack_empty_file_returns_none() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join(".havamal-pack.md"), "  \n\n").unwrap();
        assert!(read_doctrine_pack(tmp.path(), 4000).is_none());
    }

    #[test]
    fn doctrine_pack_truncates_at_budget() {
        let tmp = tempfile::tempdir().unwrap();
        let long = "x".repeat(500);
        std::fs::write(tmp.path().join(".havamal-pack.md"), &long).unwrap();
        let md = read_doctrine_pack(tmp.path(), 100).unwrap();
        assert!(md.contains("doctrine truncated"));
        assert!(md.len() < 300);
    }

    // ── Decision Pack tests ──

    fn make_summary(key: &str, value: &str, reason: &str, paths: Vec<&str>) -> DecisionSummary {
        DecisionSummary {
            key: key.to_string(),
            value: value.to_string(),
            reason: reason.to_string(),
            status: "active".to_string(),
            authority: "agent".to_string(),
            reversibility: "medium".to_string(),
            affected_paths: paths.into_iter().map(|s| s.to_string()).collect(),
            ratified: false,
        }
    }

    fn make_ratified(key: &str, value: &str, reason: &str) -> DecisionSummary {
        let mut s = make_summary(key, value, reason, vec![]);
        s.authority = "operator".to_string();
        s.ratified = true;
        s
    }

    fn make_pack(groups: Vec<(&str, Vec<DecisionSummary>)>, branch: &str) -> DecisionPack {
        let total: usize = groups.iter().map(|(_, ds)| ds.len()).sum();
        DecisionPack {
            groups: groups
                .into_iter()
                .map(|(domain, decisions)| DecisionGroup {
                    domain: domain.to_string(),
                    decisions,
                })
                .collect(),
            total,
            branch: branch.to_string(),
        }
    }

    #[test]
    fn test_empty_pack() {
        let pack = DecisionPack {
            groups: Vec::new(),
            total: 0,
            branch: "main".to_string(),
        };
        let md = render_decision_pack_md(&pack);
        assert!(md.is_empty());
    }

    #[test]
    fn test_full_pack_grouped_by_domain() {
        let pack = make_pack(
            vec![
                (
                    "auth",
                    vec![make_summary("auth.strategy", "JWT", "stateless", vec![])],
                ),
                (
                    "db",
                    vec![
                        make_summary("db.engine", "sqlite", "embedded", vec![]),
                        make_summary("db.pool", "r2d2", "connection pooling", vec![]),
                    ],
                ),
                (
                    "error",
                    vec![
                        make_summary("error.lib", "thiserror", "typed errors", vec![]),
                        make_summary("error.pattern", "enum", "exhaustive", vec![]),
                    ],
                ),
            ],
            "main",
        );

        assert_eq!(pack.groups.len(), 3);
        assert_eq!(pack.total, 5);

        let md = render_decision_pack_md(&pack);
        // All make_summary decisions are unratified → Unratified section.
        assert!(md.contains("## Unratified Decisions (5 on `main`)"));
        assert!(!md.contains("## Ratified Decisions"));
        assert!(md.contains("### auth"));
        assert!(md.contains("### db"));
        assert!(md.contains("### error"));
    }

    #[test]
    fn two_tier_splits_ratified_and_unratified() {
        let pack = make_pack(
            vec![
                ("db", vec![make_ratified("db.engine", "postgres", "JSONB")]),
                (
                    "api",
                    vec![make_summary("api.style", "REST", "compat", vec![])],
                ),
            ],
            "main",
        );
        let md = render_decision_pack_md(&pack);
        assert!(md.contains("## Ratified Decisions (1 on `main`)"));
        assert!(md.contains("## Unratified Decisions (1 on `main`)"));
        // Ratified renders before unratified.
        let r = md.find("## Ratified Decisions").unwrap();
        let u = md.find("## Unratified Decisions").unwrap();
        assert!(r < u, "ratified tier must render first");
        // Ratified line has no authorship tag; unratified line is tagged.
        assert!(md.contains("**`db.engine=postgres`**"));
        assert!(md.contains("[agent] **`api.style=REST`**"));
    }

    #[test]
    fn all_ratified_omits_unratified_section() {
        let pack = make_pack(
            vec![("db", vec![make_ratified("db.engine", "pg", "r")])],
            "main",
        );
        let md = render_decision_pack_md(&pack);
        assert!(md.contains("## Ratified Decisions (1 on `main`)"));
        assert!(!md.contains("## Unratified Decisions"));
    }

    #[test]
    fn test_domain_grouping_order() {
        let pack = make_pack(
            vec![
                ("a_first", vec![make_summary("a_first.x", "1", "r", vec![])]),
                (
                    "m_middle",
                    vec![make_summary("m_middle.x", "2", "r", vec![])],
                ),
                ("z_test", vec![make_summary("z_test.x", "3", "r", vec![])]),
            ],
            "main",
        );

        let md = render_decision_pack_md(&pack);
        let a_pos = md.find("### a_first").unwrap();
        let m_pos = md.find("### m_middle").unwrap();
        let z_pos = md.find("### z_test").unwrap();
        assert!(a_pos < m_pos);
        assert!(m_pos < z_pos);
    }

    #[test]
    fn test_render_with_paths() {
        let pack = make_pack(
            vec![(
                "db",
                vec![make_summary(
                    "db.engine",
                    "sqlite",
                    "embedded",
                    vec!["crates/foo/**", "src/**"],
                )],
            )],
            "main",
        );

        let md = render_decision_pack_md(&pack);
        assert!(md.contains("paths: `crates/foo/**`, `src/**`"));
    }

    #[test]
    fn test_render_without_reason() {
        let pack = make_pack(
            vec![("db", vec![make_summary("db.engine", "sqlite", "", vec![])])],
            "main",
        );

        let md = render_decision_pack_md(&pack);
        assert!(md.contains("**`db.engine=sqlite`**"));
        // The decision line itself carries no reason separator (the header may).
        let decision_line = md.lines().find(|l| l.contains("db.engine=sqlite")).unwrap();
        assert!(!decision_line.contains(""));
    }

    #[test]
    fn test_build_decision_pack_nonexistent_repo() {
        // Non-existent path should return empty pack
        let pack = build_decision_pack(Path::new("/nonexistent/path"), "main", 7);
        assert_eq!(pack.total, 0);
        assert!(pack.groups.is_empty());
        assert_eq!(render_decision_pack_md(&pack), "");
    }

    #[test]
    fn build_decision_pack_derives_ratified_from_real_ledger() {
        // End-to-end: a real ledger with two decisions and one ratify event
        // must split into ratified/unratified through the full
        // ledger → ratified_decision_events → is_decision_ratified → render
        // chain. The ratify is given an EARLIER timestamp than the decisions
        // but appended last (highest rowid) — so a green result proves rowid,
        // not the timestamp, is authoritative.
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let ledger = edda_ledger::Ledger::open_or_init(root).unwrap();

        let decide = |key: &str, value: &str| {
            let parent = ledger.last_event_hash().unwrap();
            let dp = edda_core::types::DecisionPayload {
                key: key.into(),
                value: value.into(),
                reason: None,
                scope: None,
                authority: Some("agent".into()),
                affected_paths: None,
                tags: None,
                review_after: None,
                reversibility: None,
                village_id: None,
                cites: None,
            };
            let ev = edda_core::event::new_decision_event("main", parent.as_deref(), "worker", &dp)
                .unwrap();
            ledger.append_event(&ev).unwrap();
        };
        decide("db.engine", "postgres");
        decide("api.style", "REST");

        // Ratify db.engine, appended LAST but with an EARLIER timestamp than
        // the decisions — a timestamp model would call it stale/unratified;
        // the rowid model correctly binds it.
        let parent = ledger.last_event_hash().unwrap();
        let mut rat = edda_core::event::new_decision_ratify_event(
            "main",
            parent.as_deref(),
            "db.engine",
            "operator",
            None,
        )
        .unwrap();
        rat.ts = "2000-01-01T00:00:00Z".into();
        edda_core::event::finalize_event(&mut rat).unwrap();
        ledger.append_event(&rat).unwrap();

        let pack = build_decision_pack(root, "main", 10);
        let md = render_decision_pack_md(&pack);

        assert!(md.contains("## Ratified Decisions (1 on `main`)"));
        assert!(md.contains("**`db.engine=postgres`**"));
        assert!(md.contains("## Unratified Decisions (1 on `main`)"));
        assert!(md.contains("[agent] **`api.style=REST`**"));
    }
}