arcan-core 0.3.0

Core traits, protocol types, and state management for the Arcan agent runtime
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
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
//! Liquid prompt system — assembles a structured system prompt from multiple sources.
//!
//! Architecture (cacheable vs. dynamic split for prompt cache savings):
//!
//! **Cacheable** (stable across turns — Anthropic auto-caches matching prefixes):
//! 1. Role definition
//! 2. Environment info (OS, shell, date, model)
//! 3. Project instructions (CLAUDE.md, AGENTS.md, docs/, .control/policy.yaml)
//! 4. Guidelines
//!
//! **Dynamic** (changes per turn — appended after cacheable prefix):
//! 5. Git context (branch, status, recent commits)
//! 6. Memory context (MEMORY.md index from `.arcan/memory/*.md`)
//! 7. Workspace context (shared cross-session journal summaries)
//! 8. Skill catalog
//!
//! This module lives in `arcan-core` so both the shell REPL (`arcan` binary)
//! and the daemon HTTP server (`arcand`) can share the same prompt builder.

use std::collections::BTreeMap;
use std::path::Path;

/// Structured system prompt split into cacheable and dynamic sections.
///
/// Anthropic automatically caches the longest matching prefix of the system
/// prompt across turns. By placing stable content first (cacheable) and
/// per-turn content after (dynamic), we get ~75% token savings on cache hits.
#[derive(Debug, Clone)]
pub struct SystemPrompt {
    /// Stable across turns — gets Anthropic prompt cache hits.
    pub cacheable: String,
    /// Changes per turn — always re-sent fresh.
    pub dynamic: String,
}

impl SystemPrompt {
    /// Combine both sections into a single prompt string (backward compatible).
    pub fn combined(&self) -> String {
        if self.dynamic.is_empty() {
            self.cacheable.clone()
        } else {
            format!("{}\n\n---\n\n{}", self.cacheable, self.dynamic)
        }
    }
}

/// Identity information for prompt injection.
///
/// When provided to [`build_system_prompt()`], an identity block is included
/// in the cacheable (stable) section of the system prompt.
#[derive(Debug, Clone)]
pub struct PromptIdentity {
    /// Tier label (e.g. "pro", "free", "anonymous").
    pub tier: String,
    /// Subject identifier (e.g. "user@example.com"). `None` for anonymous.
    pub subject: Option<String>,
}

/// Build an identity/persona block for the system prompt.
///
/// Matches the daemon's `AgentIdentityProvider::persona_block()` pattern
/// from `arcand/src/canonical.rs`.
pub fn build_identity_section(identity: Option<&PromptIdentity>) -> String {
    match identity {
        Some(id) => {
            let subject_line = id
                .subject
                .as_deref()
                .map(|s| format!("\n**Subject**: {s}"))
                .unwrap_or_default();
            format!(
                "## Identity\n\
                 **Agent**: arcan shell\n\
                 **Tier**: {}{}",
                id.tier, subject_line
            )
        }
        None => "## Identity\n\
             **Agent**: arcan shell\n\
             **Tier**: anonymous local agent"
            .to_string(),
    }
}

/// Build the complete system prompt from all available context sources.
///
/// Returns a [`SystemPrompt`] with cacheable (stable) and dynamic (per-turn)
/// sections. Use [`SystemPrompt::combined()`] for backward-compatible single string.
pub fn build_system_prompt(
    workspace: &Path,
    provider_name: &str,
    model_name: &str,
    memory_dir: &Path,
    workspace_context: Option<&str>,
    skill_catalog: Option<&str>,
    claude_md_content: Option<&str>,
) -> SystemPrompt {
    build_system_prompt_with_identity(
        workspace,
        provider_name,
        model_name,
        memory_dir,
        workspace_context,
        skill_catalog,
        claude_md_content,
        None,
    )
}

/// Build the complete system prompt with optional identity injection.
///
/// Same as [`build_system_prompt()`] but accepts a [`PromptIdentity`] for
/// persona injection into the cacheable section.
#[allow(clippy::too_many_arguments)]
pub fn build_system_prompt_with_identity(
    workspace: &Path,
    provider_name: &str,
    model_name: &str,
    memory_dir: &Path,
    workspace_context: Option<&str>,
    skill_catalog: Option<&str>,
    claude_md_content: Option<&str>,
    identity: Option<&PromptIdentity>,
) -> SystemPrompt {
    // --- CACHEABLE (stable across turns) ---
    let mut cacheable_sections = Vec::new();

    // 1. Role definition
    cacheable_sections.push(build_role_section());

    // 1b. Identity/persona block (BRO-367)
    cacheable_sections.push(build_identity_section(identity));

    // 2. Environment info
    cacheable_sections.push(build_environment_section(
        workspace,
        provider_name,
        model_name,
    ));

    // 3. CLAUDE.md / project instructions
    if let Some(instructions) = claude_md_content
        && !instructions.is_empty()
    {
        cacheable_sections.push(format!("# Project Instructions\n\n{instructions}"));
    }

    // 4. Guidelines
    cacheable_sections.push(build_guidelines_section());

    let cacheable = cacheable_sections.join("\n\n---\n\n");

    // --- DYNAMIC (changes per turn) ---
    let mut dynamic_sections = Vec::new();

    // 5. Git context
    if let Some(git) = build_git_section(workspace) {
        dynamic_sections.push(git);
    }

    // 6. Memory context (MEMORY.md index)
    if let Some(memory) = build_memory_section(memory_dir) {
        dynamic_sections.push(memory);
    }

    // 7. Workspace context
    if let Some(context) = workspace_context
        && !context.is_empty()
    {
        dynamic_sections.push(format!("# Workspace Context\n\n{context}"));
    }

    // 8. Skills catalog
    if let Some(catalog) = skill_catalog
        && !catalog.is_empty()
    {
        dynamic_sections.push(format!("# Available Skills\n\n{catalog}"));
    }

    let dynamic = if dynamic_sections.is_empty() {
        String::new()
    } else {
        dynamic_sections.join("\n\n---\n\n")
    };

    SystemPrompt { cacheable, dynamic }
}

/// The role identity block — defines what the agent is and how it should behave.
pub fn build_role_section() -> String {
    "# System\n\n\
     You are an AI coding assistant powered by Arcan, the Life Agent OS runtime. \
     You help users with software engineering tasks by reading files, editing code, \
     running commands, and searching codebases. Be concise and direct. \
     Read files before editing them. Use tools to explore rather than guessing. \
     Follow existing code style and conventions."
        .to_string()
}

/// Platform, runtime, and temporal context.
pub fn build_environment_section(workspace: &Path, provider: &str, model: &str) -> String {
    let cwd = workspace.display();
    let platform = std::env::consts::OS;
    let arch = std::env::consts::ARCH;
    let date = chrono::Local::now().format("%Y-%m-%d");
    let shell = std::env::var("SHELL").unwrap_or_else(|_| "unknown".into());

    format!(
        "# Environment\n\n\
         - Working directory: {cwd}\n\
         - Platform: {platform} ({arch})\n\
         - Shell: {shell}\n\
         - Date: {date}\n\
         - Provider: {provider}\n\
         - Model: {model}"
    )
}

/// Git branch, working-tree status, and recent commits.
///
/// Returns `None` if the workspace is not inside a git repository.
pub fn build_git_section(workspace: &Path) -> Option<String> {
    let branch = std::process::Command::new("git")
        .args(["rev-parse", "--abbrev-ref", "HEAD"])
        .current_dir(workspace)
        .output()
        .ok()?;
    if !branch.status.success() {
        return None;
    }
    let branch_name = String::from_utf8_lossy(&branch.stdout).trim().to_string();

    let status = std::process::Command::new("git")
        .args(["status", "--short"])
        .current_dir(workspace)
        .output()
        .ok()?;
    let status_text = String::from_utf8_lossy(&status.stdout).trim().to_string();
    let status_display = if status_text.is_empty() {
        "Clean".to_string()
    } else if status_text.len() > 500 {
        format!("{}...(truncated)", &status_text[..500])
    } else {
        status_text
    };

    let log = std::process::Command::new("git")
        .args(["log", "--oneline", "-5"])
        .current_dir(workspace)
        .output()
        .ok()?;
    let log_text = String::from_utf8_lossy(&log.stdout).trim().to_string();

    Some(format!(
        "# Git Context\n\n\
         - Branch: {branch_name}\n\
         - Status:\n```\n{status_display}\n```\n\
         - Recent commits:\n```\n{log_text}\n```"
    ))
}

/// Load project instructions from the workspace hierarchy.
///
/// Searches for instructions in multiple locations (all optional, concatenated):
///
/// **Base rules** (project-level, not tied to any specific agent framework):
/// 1. `<workspace>/CLAUDE.md` — Claude Code conventions
/// 2. `<workspace>/AGENTS.md` — Agent operational rules and boundaries
/// 3. `<workspace>/.claude/CLAUDE.md` — Additional Claude-specific instructions
/// 4. `<workspace>/.claude/rules/*.md` — Granular rule files (sorted)
///
/// **Life framework context** (if running inside a Life Agent OS workspace):
/// 5. `<workspace>/../CLAUDE.md` — Parent workspace instructions (e.g., `core/life/CLAUDE.md`)
/// 6. `<workspace>/docs/STATUS.md` — Current implementation status
/// 7. `<workspace>/docs/ARCHITECTURE.md` — System architecture
/// 8. `<workspace>/docs/ROADMAP.md` — Development roadmap
///
/// **Control metalayer** (if present):
/// 9. `<workspace>/.control/policy.yaml` — Enforceable policy constraints
///
/// Returns the concatenated content, or `None` if nothing was found.
pub fn load_project_instructions(workspace: &Path) -> Option<String> {
    let mut contents = Vec::new();

    // --- Base rules ---

    // CLAUDE.md (Claude Code conventions — widely adopted standard)
    load_file_if_exists(workspace, "CLAUDE.md", &mut contents);

    // AGENTS.md (agent operational rules — framework-agnostic)
    load_file_if_exists(workspace, "AGENTS.md", &mut contents);

    // .claude/CLAUDE.md (additional instructions)
    load_file_if_exists(workspace, ".claude/CLAUDE.md", &mut contents);

    // .claude/rules/*.md (granular rules, sorted for deterministic ordering)
    load_rules_dir(workspace, ".claude/rules", &mut contents);

    // --- Life framework context (if present) ---

    // Parent CLAUDE.md (e.g., core/life/CLAUDE.md when running in core/life/arcan/)
    if let Some(parent) = workspace.parent() {
        let parent_claude = parent.join("CLAUDE.md");
        if parent_claude.exists()
            && parent_claude != workspace.join("CLAUDE.md")
            && let Ok(content) = std::fs::read_to_string(&parent_claude)
            && !content.trim().is_empty()
        {
            contents.push(format!(
                "<!-- from {} -->\n{}",
                parent_claude.display(),
                content
            ));
        }
    }

    // docs/ context files — lightweight summaries that inform the agent
    // about project status without requiring tool calls
    for doc_file in &["docs/STATUS.md", "docs/ARCHITECTURE.md", "docs/ROADMAP.md"] {
        let path = workspace.join(doc_file);
        if path.exists()
            && let Ok(content) = std::fs::read_to_string(&path)
        {
            let trimmed = content.trim();
            if !trimmed.is_empty() {
                // Truncate large docs to first 2000 chars to save tokens
                let truncated = if trimmed.len() > 2000 {
                    format!(
                        "{}\n\n... (truncated, {} total chars — use read_file for full content)",
                        &trimmed[..2000],
                        trimmed.len()
                    )
                } else {
                    trimmed.to_string()
                };
                contents.push(format!("<!-- from {doc_file} -->\n{truncated}"));
            }
        }
    }

    // --- Control metalayer ---

    // .control/policy.yaml — machine-readable policy constraints
    let policy_path = workspace.join(".control/policy.yaml");
    if policy_path.exists()
        && let Ok(content) = std::fs::read_to_string(&policy_path)
        && !content.trim().is_empty()
    {
        contents.push(format!(
            "<!-- Control policy (.control/policy.yaml) -->\n```yaml\n{}\n```",
            content.trim()
        ));
    }

    if contents.is_empty() {
        None
    } else {
        Some(contents.join("\n\n"))
    }
}

/// Backward-compatible alias for `load_project_instructions`.
pub fn load_claude_md(workspace: &Path) -> Option<String> {
    load_project_instructions(workspace)
}

/// Load a single file relative to workspace if it exists and is non-empty.
fn load_file_if_exists(workspace: &Path, relative: &str, contents: &mut Vec<String>) {
    let path = workspace.join(relative);
    if path.exists()
        && let Ok(content) = std::fs::read_to_string(&path)
        && !content.trim().is_empty()
    {
        contents.push(content);
    }
}

/// Load all .md files from a rules directory, sorted alphabetically.
fn load_rules_dir(workspace: &Path, relative: &str, contents: &mut Vec<String>) {
    let rules_dir = workspace.join(relative);
    if rules_dir.is_dir()
        && let Ok(entries) = std::fs::read_dir(&rules_dir)
    {
        let mut rule_files: Vec<_> = entries
            .flatten()
            .filter(|e| e.path().extension().is_some_and(|ext| ext == "md"))
            .collect();
        rule_files.sort_by_key(std::fs::DirEntry::path);

        for entry in rule_files {
            if let Ok(content) = std::fs::read_to_string(entry.path())
                && !content.trim().is_empty()
            {
                contents.push(content);
            }
        }
    }
}

/// Cross-session memory loaded from the MEMORY.md index.
///
/// Reads the generated `MEMORY.md` index from the memory directory and returns
/// a formatted string for inclusion in the system prompt. Falls back to reading
/// individual `.md` files if the index doesn't exist.
///
/// Returns `None` if the directory doesn't exist or contains no memory files.
pub fn build_memory_section(memory_dir: &Path) -> Option<String> {
    if !memory_dir.exists() {
        return None;
    }

    // Prefer the generated MEMORY.md index
    let index_path = memory_dir.join("MEMORY.md");
    if index_path.exists()
        && let Ok(content) = std::fs::read_to_string(&index_path)
        && !content.trim().is_empty()
    {
        return Some(format!("# Agent Memory\n\n{content}"));
    }

    // Fallback: read individual files (backward compat)
    let entries = std::fs::read_dir(memory_dir).ok()?;
    let mut sections = Vec::new();

    for entry in entries.flatten() {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("md") {
            continue;
        }
        if path.file_name().and_then(|n| n.to_str()) == Some("MEMORY.md") {
            continue;
        }
        let key = path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("unknown")
            .to_string();
        if let Ok(content) = std::fs::read_to_string(&path)
            && !content.trim().is_empty()
        {
            sections.push(format!("## {key}\n{content}"));
        }
    }

    if sections.is_empty() {
        return None;
    }

    sections.sort();
    Some(format!(
        "# Agent Memory (cross-session)\n\n{}",
        sections.join("\n\n")
    ))
}

// ---------------------------------------------------------------------------
// MEMORY.md index generation (BRO-419)
// ---------------------------------------------------------------------------

/// Maximum number of lines allowed in the MEMORY.md index.
const MEMORY_INDEX_MAX_LINES: usize = 200;

/// Maximum number of bytes allowed in the MEMORY.md index.
const MEMORY_INDEX_MAX_BYTES: usize = 25_000;

/// Generate a `MEMORY.md` index from all `.md` files in the memory directory.
///
/// Groups entries by the `type` field in YAML frontmatter (defaults to "general").
/// Each entry is a markdown link with a description extracted from the first
/// non-frontmatter, non-heading content line.
///
/// The output is capped at 200 lines / 25KB.
pub fn generate_memory_index(memory_dir: &Path) -> String {
    let mut sections: BTreeMap<String, Vec<String>> = BTreeMap::new();

    let Ok(entries) = std::fs::read_dir(memory_dir) else {
        return String::from("# Memory Index\n");
    };

    for entry in entries.flatten() {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("md") {
            continue;
        }
        if path.file_name().and_then(|n| n.to_str()) == Some("MEMORY.md") {
            continue;
        }

        let key = path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("unknown")
            .to_string();
        let content = std::fs::read_to_string(&path).unwrap_or_default();

        let mem_type = extract_frontmatter_type(&content).unwrap_or_else(|| "general".to_string());

        let description = extract_first_content_line(&content);

        sections
            .entry(mem_type)
            .or_default()
            .push(format!("- [{}]({}.md) — {}", key, key, description));
    }

    let mut index = String::from("# Memory Index\n\n");
    for (section, entries) in &sections {
        index.push_str(&format!("## {}\n", capitalize(section)));
        for entry in entries {
            index.push_str(entry);
            index.push('\n');
        }
        index.push('\n');
    }

    // Cap at 200 lines
    let lines: Vec<&str> = index.lines().collect();
    if lines.len() > MEMORY_INDEX_MAX_LINES {
        index = lines[..MEMORY_INDEX_MAX_LINES].join("\n");
        index.push_str("\n\n... (truncated, showing first 200 entries)\n");
    }

    // Cap at 25KB
    if index.len() > MEMORY_INDEX_MAX_BYTES {
        index.truncate(MEMORY_INDEX_MAX_BYTES);
        index.push_str("\n\n... (truncated at 25KB)\n");
    }

    index
}

/// Write the generated MEMORY.md index to disk.
///
/// Creates the memory directory if it doesn't exist.
pub fn write_memory_index(memory_dir: &Path) {
    let _ = std::fs::create_dir_all(memory_dir);
    let index = generate_memory_index(memory_dir);
    let index_path = memory_dir.join("MEMORY.md");
    let _ = std::fs::write(&index_path, &index);
}

/// Extract the `type` value from YAML frontmatter (between `---` markers).
///
/// Returns `None` if no frontmatter or no `type:` field is found.
fn extract_frontmatter_type(content: &str) -> Option<String> {
    if !content.starts_with("---") {
        return None;
    }
    let end = content[3..].find("---")?;
    let frontmatter = &content[3..3 + end];
    for line in frontmatter.lines() {
        let trimmed = line.trim();
        if let Some(value) = trimmed.strip_prefix("type:") {
            return Some(value.trim().to_string());
        }
    }
    None
}

/// Extract the first non-empty, non-heading content line after any frontmatter.
///
/// Skips YAML frontmatter (between `---` markers) and markdown headings.
/// Truncates to 120 characters.
fn extract_first_content_line(content: &str) -> String {
    let body = if let Some(after_prefix) = content.strip_prefix("---") {
        after_prefix
            .find("---")
            .map(|i| &after_prefix[i + 3..])
            .unwrap_or(content)
    } else {
        content
    };
    body.lines()
        .map(str::trim)
        .find(|l| !l.is_empty() && !l.starts_with('#'))
        .unwrap_or("(no description)")
        .chars()
        .take(120)
        .collect()
}

/// Capitalize the first character of a string.
fn capitalize(s: &str) -> String {
    let mut c = s.chars();
    match c.next() {
        Some(first) => first.to_uppercase().collect::<String>() + c.as_str(),
        None => String::new(),
    }
}

/// Build a minimal system prompt for small-context-window models.
///
/// Omits project instructions, memory, git context, and skills to stay
/// under ~300 tokens. Designed for models with ≤4K context windows
/// (e.g. Apple's on-device model via apfel).
///
/// Tool definitions are described as plain text (not OpenAI function schemas)
/// so the model knows what capabilities exist without attempting function calls.
pub fn build_bare_prompt(workspace: &Path, provider: &str, model: &str) -> String {
    let cwd = workspace.display();
    let platform = std::env::consts::OS;
    let date = chrono::Local::now().format("%Y-%m-%d");

    format!(
        "You are an AI coding assistant running on {platform}. \
         Help with software engineering tasks and answer questions. \
         Be concise and direct.\n\n\
         Workspace: {cwd} | Date: {date} | Provider: {provider} | Model: {model}\n\n\
         You have these capabilities (available as tools when needed):\n\
         - read_file: Read file contents from the workspace\n\
         - write_file: Create or overwrite a file\n\
         - edit_file: Make targeted edits to existing files\n\
         - bash: Run shell commands\n\
         - glob: Find files by pattern\n\
         - grep: Search file contents with regex\n\n\
         When answering questions directly, respond with plain text. \
         Only suggest using tools when the user needs to interact with files or run commands."
    )
}

/// Behavioral guidelines that bound how the agent operates.
pub fn build_guidelines_section() -> String {
    "# Guidelines\n\n\
     - Read files before editing them\n\
     - Use tools to explore the codebase rather than guessing\n\
     - Be concise and direct in responses\n\
     - Follow existing code style and conventions\n\
     - Prefer editing existing files over creating new ones\n\
     - Do not add features beyond what was asked"
        .to_string()
}

/// Build a "Peer Activity" section from Spaces agent-logs messages (BRO-369).
///
/// Call this separately and append to the `SystemPrompt.dynamic` section
/// when Spaces is connected and has recent peer messages.
pub fn build_peer_context_section(messages: &[String]) -> Option<String> {
    if messages.is_empty() {
        return None;
    }
    let mut section = String::from("# Peer Activity\n\nRecent messages from other agents:\n\n");
    for msg in messages.iter().take(10) {
        section.push_str(&format!("- {msg}\n"));
    }
    Some(section)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_build_system_prompt_includes_all_sections() {
        let tmp = TempDir::new().unwrap();
        let workspace = tmp.path();
        let memory_dir = workspace.join(".arcan/memory");
        fs::create_dir_all(&memory_dir).unwrap();
        fs::write(memory_dir.join("notes.md"), "Some notes here").unwrap();

        let sp = build_system_prompt(
            workspace,
            "anthropic",
            "claude-sonnet-4-5-20250929",
            &memory_dir,
            Some("- Peer session: explored workspace journal"),
            Some("- skill_a: Does A\n- skill_b: Does B"),
            Some("# My Project\n\nBuild fast."),
        );
        let prompt = sp.combined();

        // All sections should be present
        assert!(prompt.contains("# System"), "missing role section");
        assert!(
            prompt.contains("# Environment"),
            "missing environment section"
        );
        assert!(
            prompt.contains("# Project Instructions"),
            "missing claude.md section"
        );
        assert!(prompt.contains("# Agent Memory"), "missing memory section");
        assert!(
            prompt.contains("# Workspace Context"),
            "missing workspace context section"
        );
        assert!(
            prompt.contains("# Available Skills"),
            "missing skills section"
        );
        assert!(
            prompt.contains("# Guidelines"),
            "missing guidelines section"
        );
        // Section separators
        assert!(prompt.contains("---"), "missing section separators");
    }

    #[test]
    fn test_build_system_prompt_omits_empty_sections() {
        let tmp = TempDir::new().unwrap();
        let workspace = tmp.path();
        let memory_dir = workspace.join(".arcan/memory");
        // Don't create memory dir — should be omitted

        let sp = build_system_prompt(
            workspace,
            "mock",
            "mock-model",
            &memory_dir,
            None,
            None,
            None,
        );
        let prompt = sp.combined();

        assert!(prompt.contains("# System"));
        assert!(prompt.contains("# Environment"));
        assert!(prompt.contains("# Guidelines"));
        assert!(
            !prompt.contains("# Project Instructions"),
            "should omit empty claude.md"
        );
        assert!(
            !prompt.contains("# Agent Memory"),
            "should omit missing memory"
        );
        assert!(
            !prompt.contains("# Available Skills"),
            "should omit empty skills"
        );
    }

    #[test]
    fn test_load_claude_md_from_workspace() {
        let tmp = TempDir::new().unwrap();
        let workspace = tmp.path();
        fs::write(workspace.join("CLAUDE.md"), "# Instructions\nDo X.").unwrap();

        let result = load_project_instructions(workspace);
        assert!(result.is_some());
        assert!(result.unwrap().contains("Do X."));
    }

    #[test]
    fn test_load_agents_md() {
        let tmp = TempDir::new().unwrap();
        let workspace = tmp.path();
        fs::write(workspace.join("AGENTS.md"), "# Agent Rules\nBe safe.").unwrap();

        let result = load_project_instructions(workspace);
        assert!(result.is_some());
        assert!(result.unwrap().contains("Be safe."));
    }

    #[test]
    fn test_load_both_claude_and_agents_md() {
        let tmp = TempDir::new().unwrap();
        let workspace = tmp.path();
        fs::write(workspace.join("CLAUDE.md"), "Claude rules.").unwrap();
        fs::write(workspace.join("AGENTS.md"), "Agent rules.").unwrap();

        let result = load_project_instructions(workspace).unwrap();
        assert!(result.contains("Claude rules."));
        assert!(result.contains("Agent rules."));
    }

    #[test]
    fn test_load_rules_dir() {
        let tmp = TempDir::new().unwrap();
        let workspace = tmp.path();
        let rules_dir = workspace.join(".claude/rules");
        fs::create_dir_all(&rules_dir).unwrap();
        fs::write(rules_dir.join("code-style.md"), "Use snake_case.").unwrap();
        fs::write(rules_dir.join("testing.md"), "All code needs tests.").unwrap();

        let result = load_project_instructions(workspace);
        assert!(result.is_some());
        let content = result.unwrap();
        assert!(content.contains("Use snake_case."));
        assert!(content.contains("All code needs tests."));
    }

    #[test]
    fn test_load_docs_context() {
        let tmp = TempDir::new().unwrap();
        let workspace = tmp.path();
        let docs_dir = workspace.join("docs");
        fs::create_dir_all(&docs_dir).unwrap();
        fs::write(docs_dir.join("STATUS.md"), "# Status\n100% tests passing").unwrap();
        fs::write(docs_dir.join("ARCHITECTURE.md"), "# Arch\nEvent-sourced.").unwrap();

        let result = load_project_instructions(workspace).unwrap();
        assert!(result.contains("100% tests passing"));
        assert!(result.contains("Event-sourced."));
    }

    #[test]
    fn test_load_control_policy() {
        let tmp = TempDir::new().unwrap();
        let workspace = tmp.path();
        let control_dir = workspace.join(".control");
        fs::create_dir_all(&control_dir).unwrap();
        fs::write(
            control_dir.join("policy.yaml"),
            "gates:\n  - name: G1\n    blocking: true",
        )
        .unwrap();

        let result = load_project_instructions(workspace).unwrap();
        assert!(result.contains("gates:"));
        assert!(result.contains("blocking: true"));
    }

    #[test]
    fn test_load_empty_workspace_returns_none() {
        let tmp = TempDir::new().unwrap();
        let result = load_project_instructions(tmp.path());
        assert!(result.is_none());
    }

    #[test]
    fn test_git_section_in_repo() {
        // Run in the actual workspace which is a git repo
        let workspace = std::env::current_dir().unwrap();
        let result = build_git_section(&workspace);
        // This test is running inside a git repo (the arcan worktree),
        // so we should get a result.
        if let Some(git_section) = result {
            assert!(git_section.contains("# Git Context"));
            assert!(git_section.contains("Branch:"));
        }
        // If git is not available, the test passes trivially.
    }

    #[test]
    fn test_git_section_non_repo() {
        let tmp = TempDir::new().unwrap();
        let result = build_git_section(tmp.path());
        assert!(result.is_none(), "non-repo dir should return None");
    }

    #[test]
    fn test_environment_section() {
        let tmp = TempDir::new().unwrap();
        let section = build_environment_section(tmp.path(), "anthropic", "claude-sonnet");

        assert!(section.contains("# Environment"));
        assert!(section.contains("Platform:"));
        assert!(section.contains("Provider: anthropic"));
        assert!(section.contains("Model: claude-sonnet"));
        assert!(section.contains("Date:"));
    }

    #[test]
    fn test_memory_section() {
        let tmp = TempDir::new().unwrap();
        let memory_dir = tmp.path().join("memory");
        fs::create_dir_all(&memory_dir).unwrap();
        fs::write(memory_dir.join("notes.md"), "Remember this.").unwrap();

        let result = build_memory_section(&memory_dir);
        assert!(result.is_some());
        let content = result.unwrap();
        assert!(content.contains("# Agent Memory"));
        assert!(content.contains("Remember this."));
    }

    #[test]
    fn test_memory_section_empty_dir() {
        let tmp = TempDir::new().unwrap();
        let memory_dir = tmp.path().join("memory");
        fs::create_dir_all(&memory_dir).unwrap();

        let result = build_memory_section(&memory_dir);
        assert!(result.is_none(), "empty memory dir should return None");
    }

    #[test]
    fn test_memory_section_missing_dir() {
        let tmp = TempDir::new().unwrap();
        let memory_dir = tmp.path().join("nonexistent");

        let result = build_memory_section(&memory_dir);
        assert!(result.is_none(), "missing memory dir should return None");
    }

    #[test]
    fn test_role_section_content() {
        let role = build_role_section();
        assert!(role.contains("Arcan"));
        assert!(role.contains("Life Agent OS"));
    }

    #[test]
    fn test_guidelines_section_content() {
        let guidelines = build_guidelines_section();
        assert!(guidelines.contains("Read files before editing"));
        assert!(guidelines.contains("Do not add features beyond what was asked"));
    }

    #[test]
    fn test_load_combines_all_sources() {
        let tmp = TempDir::new().unwrap();
        let workspace = tmp.path();

        // Create all sources
        fs::write(workspace.join("CLAUDE.md"), "Root instructions.").unwrap();
        fs::write(workspace.join("AGENTS.md"), "Agent boundaries.").unwrap();
        let dot_claude = workspace.join(".claude");
        fs::create_dir_all(&dot_claude).unwrap();
        fs::write(dot_claude.join("CLAUDE.md"), "Dot-claude instructions.").unwrap();
        let rules_dir = dot_claude.join("rules");
        fs::create_dir_all(&rules_dir).unwrap();
        fs::write(rules_dir.join("style.md"), "Style rules.").unwrap();
        let docs = workspace.join("docs");
        fs::create_dir_all(&docs).unwrap();
        fs::write(docs.join("STATUS.md"), "All green.").unwrap();
        let control = workspace.join(".control");
        fs::create_dir_all(&control).unwrap();
        fs::write(control.join("policy.yaml"), "version: 1").unwrap();

        let result = load_project_instructions(workspace).unwrap();
        assert!(result.contains("Root instructions."));
        assert!(result.contains("Agent boundaries."));
        assert!(result.contains("Dot-claude instructions."));
        assert!(result.contains("Style rules."));
        assert!(result.contains("All green."));
        assert!(result.contains("version: 1"));
    }

    #[test]
    fn test_backward_compat_load_claude_md() {
        let tmp = TempDir::new().unwrap();
        let workspace = tmp.path();
        fs::write(workspace.join("CLAUDE.md"), "Legacy call.").unwrap();
        let result = load_claude_md(workspace);
        assert!(result.is_some());
        assert!(result.unwrap().contains("Legacy call."));
    }

    /// Verify the prompt module is accessible from arcan-core's public API.
    #[test]
    fn test_prompt_available_from_core() {
        // Key public functions that both shell and daemon need.
        let _ = build_system_prompt
            as fn(
                &Path,
                &str,
                &str,
                &Path,
                Option<&str>,
                Option<&str>,
                Option<&str>,
            ) -> SystemPrompt;
        let _ = build_system_prompt_with_identity
            as fn(
                &Path,
                &str,
                &str,
                &Path,
                Option<&str>,
                Option<&str>,
                Option<&str>,
                Option<&PromptIdentity>,
            ) -> SystemPrompt;
        let _ = build_identity_section as fn(Option<&PromptIdentity>) -> String;
        let _ = build_git_section as fn(&Path) -> Option<String>;
        let _ = load_project_instructions as fn(&Path) -> Option<String>;
        let _ = build_environment_section as fn(&Path, &str, &str) -> String;
        let _ = build_memory_section as fn(&Path) -> Option<String>;
        let _ = build_role_section as fn() -> String;
        let _ = build_guidelines_section as fn() -> String;
        let _ = build_bare_prompt as fn(&Path, &str, &str) -> String;
        let _ = generate_memory_index as fn(&Path) -> String;
        let _ = write_memory_index as fn(&Path);
    }

    // ── BRO-367: Identity section tests ──

    #[test]
    fn test_identity_section_with_full_identity() {
        let id = PromptIdentity {
            tier: "pro".to_string(),
            subject: Some("user@example.com".to_string()),
        };
        let section = build_identity_section(Some(&id));
        assert!(section.contains("## Identity"));
        assert!(section.contains("**Agent**: arcan shell"));
        assert!(section.contains("**Tier**: pro"));
        assert!(section.contains("**Subject**: user@example.com"));
    }

    #[test]
    fn test_identity_section_without_subject() {
        let id = PromptIdentity {
            tier: "free".to_string(),
            subject: None,
        };
        let section = build_identity_section(Some(&id));
        assert!(section.contains("**Tier**: free"));
        assert!(!section.contains("**Subject**"));
    }

    #[test]
    fn test_identity_section_anonymous() {
        let section = build_identity_section(None);
        assert!(section.contains("## Identity"));
        assert!(section.contains("anonymous local agent"));
    }

    #[test]
    fn test_system_prompt_with_identity_includes_block() {
        let tmp = TempDir::new().unwrap();
        let workspace = tmp.path();
        let memory_dir = workspace.join(".arcan/memory");

        let id = PromptIdentity {
            tier: "enterprise".to_string(),
            subject: Some("admin@corp.com".to_string()),
        };
        let sp = build_system_prompt_with_identity(
            workspace,
            "anthropic",
            "claude-sonnet",
            &memory_dir,
            None,
            None,
            None,
            Some(&id),
        );
        let combined = sp.combined();
        assert!(combined.contains("## Identity"), "missing identity section");
        assert!(
            combined.contains("**Tier**: enterprise"),
            "missing tier in identity"
        );
        assert!(
            combined.contains("**Subject**: admin@corp.com"),
            "missing subject in identity"
        );
    }

    #[test]
    fn test_system_prompt_without_identity_shows_anonymous() {
        let tmp = TempDir::new().unwrap();
        let workspace = tmp.path();
        let memory_dir = workspace.join(".arcan/memory");

        let sp = build_system_prompt(workspace, "mock", "mock", &memory_dir, None, None, None);
        let combined = sp.combined();
        assert!(
            combined.contains("anonymous local agent"),
            "should show anonymous when no identity"
        );
    }

    // ── BRO-419: MEMORY.md index tests ──

    #[test]
    fn test_generate_memory_index() {
        let tmp = TempDir::new().unwrap();
        let memory_dir = tmp.path().join("memory");
        fs::create_dir_all(&memory_dir).unwrap();

        fs::write(
            memory_dir.join("project_notes.md"),
            "Key architecture decisions for the project.",
        )
        .unwrap();
        fs::write(
            memory_dir.join("user_prefs.md"),
            "---\ntype: user\n---\n# Preferences\nPrefers dark mode.",
        )
        .unwrap();

        let index = generate_memory_index(&memory_dir);

        assert!(index.contains("# Memory Index"), "missing header");
        assert!(
            index.contains("[project_notes]"),
            "missing project_notes entry"
        );
        assert!(index.contains("[user_prefs]"), "missing user_prefs entry");
        // user_prefs should be grouped under "User" section
        assert!(index.contains("## User"), "missing User section header");
        // project_notes has no frontmatter, defaults to "General"
        assert!(
            index.contains("## General"),
            "missing General section header"
        );
        // Description extraction
        assert!(
            index.contains("Key architecture decisions"),
            "missing description from project_notes"
        );
        assert!(
            index.contains("Prefers dark mode"),
            "missing description from user_prefs"
        );
    }

    #[test]
    fn test_memory_index_skips_memory_md() {
        let tmp = TempDir::new().unwrap();
        let memory_dir = tmp.path().join("memory");
        fs::create_dir_all(&memory_dir).unwrap();

        fs::write(memory_dir.join("MEMORY.md"), "# Old index").unwrap();
        fs::write(memory_dir.join("real_note.md"), "A real note.").unwrap();

        let index = generate_memory_index(&memory_dir);
        assert!(index.contains("[real_note]"));
        // MEMORY.md should not appear as an entry
        assert!(!index.contains("[MEMORY]"));
    }

    #[test]
    fn test_memory_index_caps_at_200_lines() {
        let tmp = TempDir::new().unwrap();
        let memory_dir = tmp.path().join("memory");
        fs::create_dir_all(&memory_dir).unwrap();

        // Create enough files to exceed 200 lines.
        // Each file adds 1 line. With header (2 lines), section header (1 line),
        // and trailing blank (1 line), we need >196 files to exceed 200 lines.
        for i in 0..250 {
            fs::write(
                memory_dir.join(format!("note_{i:03}.md")),
                format!("Content for note {i}."),
            )
            .unwrap();
        }

        let index = generate_memory_index(&memory_dir);
        let line_count = index.lines().count();
        // Should be capped (200 lines + truncation message ~2 more lines)
        assert!(line_count <= 205, "expected <= 205 lines, got {line_count}");
        assert!(
            index.contains("truncated"),
            "should contain truncation notice"
        );
    }

    #[test]
    fn test_memory_index_extracts_frontmatter_type() {
        let tmp = TempDir::new().unwrap();
        let memory_dir = tmp.path().join("memory");
        fs::create_dir_all(&memory_dir).unwrap();

        fs::write(
            memory_dir.join("arch_notes.md"),
            "---\ntype: project\ntags: [arch]\n---\n# Architecture\nEvent-sourced design.",
        )
        .unwrap();
        fs::write(
            memory_dir.join("tax_info.md"),
            "---\ntype: user\n---\nColombian tax rules.",
        )
        .unwrap();
        fs::write(
            memory_dir.join("general_stuff.md"),
            "Just some general notes without frontmatter.",
        )
        .unwrap();

        let index = generate_memory_index(&memory_dir);

        assert!(index.contains("## Project"), "missing Project section");
        assert!(index.contains("## User"), "missing User section");
        assert!(index.contains("## General"), "missing General section");
    }

    #[test]
    fn test_write_memory_index_creates_file() {
        let tmp = TempDir::new().unwrap();
        let memory_dir = tmp.path().join("memory");
        fs::create_dir_all(&memory_dir).unwrap();
        fs::write(memory_dir.join("test.md"), "Test content.").unwrap();

        write_memory_index(&memory_dir);

        let index_path = memory_dir.join("MEMORY.md");
        assert!(index_path.exists(), "MEMORY.md should be created");
        let content = fs::read_to_string(&index_path).unwrap();
        assert!(content.contains("# Memory Index"));
        assert!(content.contains("[test]"));
    }

    #[test]
    fn test_memory_section_prefers_index() {
        let tmp = TempDir::new().unwrap();
        let memory_dir = tmp.path().join("memory");
        fs::create_dir_all(&memory_dir).unwrap();

        fs::write(memory_dir.join("notes.md"), "Individual note.").unwrap();
        // Write a MEMORY.md index
        write_memory_index(&memory_dir);

        let section = build_memory_section(&memory_dir).unwrap();
        // Should use the MEMORY.md index (contains "Memory Index" heading)
        assert!(
            section.contains("Memory Index"),
            "should prefer MEMORY.md index"
        );
    }

    // ── BRO-420: Prompt cache boundary tests ──

    #[test]
    fn test_system_prompt_struct_has_both_sections() {
        let tmp = TempDir::new().unwrap();
        let workspace = tmp.path();
        let memory_dir = workspace.join(".arcan/memory");
        fs::create_dir_all(&memory_dir).unwrap();
        fs::write(memory_dir.join("notes.md"), "Some notes.").unwrap();

        let sp = build_system_prompt(
            workspace,
            "anthropic",
            "claude-sonnet",
            &memory_dir,
            None,
            Some("- skill_a: Does A"),
            Some("Build fast."),
        );

        assert!(!sp.cacheable.is_empty(), "cacheable should not be empty");
        assert!(!sp.dynamic.is_empty(), "dynamic should not be empty");
    }

    #[test]
    fn test_cacheable_section_stable() {
        let tmp = TempDir::new().unwrap();
        let workspace = tmp.path();
        fs::write(workspace.join("CLAUDE.md"), "Project rules.").unwrap();
        let memory_dir = workspace.join(".arcan/memory");

        let sp1 = build_system_prompt(
            workspace,
            "anthropic",
            "claude-sonnet",
            &memory_dir,
            None,
            None,
            Some("Project rules."),
        );
        let sp2 = build_system_prompt(
            workspace,
            "anthropic",
            "claude-sonnet",
            &memory_dir,
            None,
            None,
            Some("Project rules."),
        );

        assert_eq!(
            sp1.cacheable, sp2.cacheable,
            "cacheable section should be identical for same inputs"
        );
    }

    #[test]
    fn test_dynamic_section_changes_with_memory() {
        let tmp = TempDir::new().unwrap();
        let workspace = tmp.path();
        let memory_dir = workspace.join(".arcan/memory");
        fs::create_dir_all(&memory_dir).unwrap();

        // No memory files
        let sp1 = build_system_prompt(
            workspace,
            "anthropic",
            "claude-sonnet",
            &memory_dir,
            None,
            None,
            None,
        );

        // Add a memory file
        fs::write(memory_dir.join("new_note.md"), "New insight.").unwrap();

        let sp2 = build_system_prompt(
            workspace,
            "anthropic",
            "claude-sonnet",
            &memory_dir,
            None,
            None,
            None,
        );

        assert_ne!(
            sp1.dynamic, sp2.dynamic,
            "dynamic section should change when memory files are added"
        );
        // Cacheable should remain the same
        assert_eq!(
            sp1.cacheable, sp2.cacheable,
            "cacheable section should not change with memory"
        );
    }

    #[test]
    fn test_cacheable_contains_role_env_guidelines() {
        let tmp = TempDir::new().unwrap();
        let workspace = tmp.path();
        let memory_dir = workspace.join("memory");

        let sp = build_system_prompt(
            workspace,
            "anthropic",
            "claude-sonnet",
            &memory_dir,
            None,
            None,
            None,
        );

        assert!(
            sp.cacheable.contains("# System"),
            "cacheable should contain role"
        );
        assert!(
            sp.cacheable.contains("# Environment"),
            "cacheable should contain environment"
        );
        assert!(
            sp.cacheable.contains("# Guidelines"),
            "cacheable should contain guidelines"
        );
    }

    #[test]
    fn test_dynamic_contains_git_memory_skills() {
        let tmp = TempDir::new().unwrap();
        let workspace = tmp.path();
        let memory_dir = workspace.join(".arcan/memory");
        fs::create_dir_all(&memory_dir).unwrap();
        fs::write(memory_dir.join("notes.md"), "Remember.").unwrap();

        let sp = build_system_prompt(
            workspace,
            "anthropic",
            "claude-sonnet",
            &memory_dir,
            Some("- Session abc turn 3: Added memory_similar"),
            Some("- skill_a"),
            None,
        );

        assert!(
            sp.dynamic.contains("# Agent Memory"),
            "dynamic should contain memory"
        );
        assert!(
            sp.dynamic.contains("# Workspace Context"),
            "dynamic should contain workspace context"
        );
        assert!(
            sp.dynamic.contains("# Available Skills"),
            "dynamic should contain skills"
        );
    }

    #[test]
    fn test_backward_compat_combined() {
        let tmp = TempDir::new().unwrap();
        let workspace = tmp.path();
        let memory_dir = workspace.join(".arcan/memory");
        fs::create_dir_all(&memory_dir).unwrap();
        fs::write(memory_dir.join("notes.md"), "Some notes.").unwrap();

        let sp = build_system_prompt(
            workspace,
            "anthropic",
            "claude-sonnet",
            &memory_dir,
            None,
            Some("- skill_a"),
            Some("Project instructions."),
        );
        let combined = sp.combined();

        // Combined should contain content from both sections
        assert!(combined.contains("# System"));
        assert!(combined.contains("# Guidelines"));
        assert!(combined.contains("# Agent Memory"));
        assert!(combined.contains("# Available Skills"));
    }

    #[test]
    fn test_combined_empty_dynamic() {
        let tmp = TempDir::new().unwrap();
        let workspace = tmp.path();
        let memory_dir = workspace.join("nonexistent");

        let sp = build_system_prompt(workspace, "mock", "mock", &memory_dir, None, None, None);

        // With no git, no memory, no skills — dynamic should be empty
        let combined = sp.combined();
        // Combined should just be the cacheable section (no trailing ---)
        assert_eq!(combined, sp.cacheable);
    }

    // ── Helper function tests ──

    #[test]
    fn test_extract_frontmatter_type_valid() {
        let content = "---\ntype: project\ntags: [a, b]\n---\n# Title\nBody.";
        assert_eq!(
            extract_frontmatter_type(content),
            Some("project".to_string())
        );
    }

    #[test]
    fn test_extract_frontmatter_type_missing() {
        let content = "---\ntags: [a]\n---\nNo type field.";
        assert_eq!(extract_frontmatter_type(content), None);
    }

    #[test]
    fn test_extract_frontmatter_type_no_frontmatter() {
        let content = "Just plain text.";
        assert_eq!(extract_frontmatter_type(content), None);
    }

    #[test]
    fn test_extract_first_content_line_with_frontmatter() {
        let content = "---\ntype: user\n---\n# Heading\nFirst real line.";
        assert_eq!(extract_first_content_line(content), "First real line.");
    }

    #[test]
    fn test_extract_first_content_line_no_frontmatter() {
        let content = "# Heading\nContent line.";
        assert_eq!(extract_first_content_line(content), "Content line.");
    }

    #[test]
    fn test_extract_first_content_line_empty() {
        let content = "";
        assert_eq!(extract_first_content_line(content), "(no description)");
    }

    #[test]
    fn test_capitalize() {
        assert_eq!(capitalize("general"), "General");
        assert_eq!(capitalize("user"), "User");
        assert_eq!(capitalize(""), "");
        assert_eq!(capitalize("ALREADY"), "ALREADY");
    }

    #[test]
    fn test_bare_prompt_is_compact() {
        let tmp = TempDir::new().unwrap();
        let prompt = build_bare_prompt(tmp.path(), "apfel", "apple-foundationmodel");

        // Must contain key info
        assert!(prompt.contains("AI coding assistant"), "missing role");
        assert!(prompt.contains("Date:"), "missing date");
        assert!(prompt.contains("Provider: apfel"), "missing provider");
        assert!(
            prompt.contains("Model: apple-foundationmodel"),
            "missing model"
        );

        // Must contain tool descriptions as text
        assert!(prompt.contains("read_file"), "missing read_file tool");
        assert!(prompt.contains("bash"), "missing bash tool");
        assert!(prompt.contains("grep"), "missing grep tool");

        // Must NOT contain heavy sections
        assert!(
            !prompt.contains("# Project Instructions"),
            "bare prompt should not have project instructions"
        );
        assert!(
            !prompt.contains("# Agent Memory"),
            "bare prompt should not have memory"
        );
        assert!(
            !prompt.contains("# Git Context"),
            "bare prompt should not have git context"
        );

        // Should be compact — under ~300 tokens (~4 chars/token heuristic)
        assert!(
            prompt.len() < 1200,
            "bare prompt too long: {} chars (target <1200)",
            prompt.len()
        );
    }
}