imp-core 0.1.0

Agent engine for imp: loop, tools, sessions, hooks, context, and SDK
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
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
use std::fmt;

use crate::config::AgentMode;
use crate::context::estimate_tokens;
use crate::guardrails::{self, GuardrailProfile};
use crate::personality::{soul_identity_text, PersonalityBand, PersonalityProfile};
use crate::resources::{AgentsMd, Skill, SoulDoc};
use crate::roles::Role;
use crate::tools::ToolRegistry;

/// A project fact from mana-core.
#[derive(Debug, Clone)]
pub struct Fact {
    pub text: String,
    pub verified_ago: String,
}

/// Previous attempt info for task context.
#[derive(Debug, Clone)]
pub struct Attempt {
    pub number: u32,
    pub outcome: String,
    pub summary: String,
}

/// Dependency info for task context.
#[derive(Debug, Clone)]
pub struct Dependency {
    pub name: String,
    pub status: String,
    pub detail: String,
}

/// Task context for headless/task mode (Layer 5).
#[derive(Debug, Clone)]
pub struct TaskContext {
    pub title: String,
    pub description: String,
    pub acceptance: Option<String>,
    pub verify: Option<String>,
    pub notes: Option<String>,
    pub attempts: Vec<Attempt>,
    pub dependencies: Vec<Dependency>,
    pub decisions: Vec<String>,
    pub context_paths: Vec<String>,
    pub constraints: Vec<String>,
}

/// Result of system prompt assembly, including size tracking.
#[derive(Debug)]
pub struct AssembledPrompt {
    pub text: String,
    pub estimated_tokens: u32,
}

impl fmt::Display for AssembledPrompt {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.text)
    }
}

/// All inputs needed to assemble a system prompt.
pub struct AssembleParams<'a> {
    pub tools: &'a ToolRegistry,
    pub agents_md: &'a [AgentsMd],
    pub skills: &'a [Skill],
    pub facts: &'a [Fact],
    pub project_memory_status: Option<&'a str>,
    pub personality: Option<&'a PersonalityProfile>,
    pub soul: Option<&'a SoulDoc>,
    pub task: Option<&'a TaskContext>,
    pub role: Option<&'a Role>,
    pub mode: &'a AgentMode,
    pub memory: Option<&'a str>,
    pub user_profile: Option<&'a str>,
    pub cwd: Option<&'a std::path::Path>,
    /// Whether to include learning instructions in the system prompt.
    pub learning_enabled: bool,
    /// Resolved guardrail profile (None = guardrails disabled).
    pub guardrail_profile: Option<GuardrailProfile>,
}

/// Assemble the system prompt from seven layers.
///
/// - Layer 1: Identity + tool descriptions (+ role instructions if any)
/// - Layer 1.25: Execution policy
/// - Layer 1.5: Environment context
/// - Layer 2: Project context from AGENTS.md files
/// - Layer 3: Skills index
/// - Layer 4: Mana facts (skipped if empty)
/// - Layer 4.25: Compact project memory status (skipped if empty)
/// - Layer 5: Task context (only in headless/task mode)
/// - Layer 6: Agent memory (if present)
pub fn assemble(params: &AssembleParams<'_>) -> AssembledPrompt {
    assemble_inner(params)
}

fn assemble_inner(p: &AssembleParams<'_>) -> AssembledPrompt {
    let mut parts = Vec::new();

    // Layer 1: Identity + tool descriptions
    parts.push(identity_layer(
        p.tools,
        p.role,
        p.mode,
        p.learning_enabled,
        p.personality,
        p.soul,
    ));

    // Layer 1.25: Execution policy
    parts.push(execution_policy_layer());

    // Layer 1.5: Environment context
    parts.push(environment_layer(p.cwd));

    // Layer 2: Project context from AGENTS.md
    if !p.agents_md.is_empty() {
        parts.push(agents_md_layer(p.agents_md));
    }

    // Layer 3: Skills index
    if !p.skills.is_empty() {
        parts.push(skills_layer(p.skills, p.mode));
    }

    // Layer 4: Mana facts
    if !p.facts.is_empty() {
        parts.push(facts_layer(p.facts));
    }

    // Layer 4.25: Compact project memory status
    if let Some(status) = p.project_memory_status {
        if !status.is_empty() {
            parts.push(project_memory_status_layer(status));
        }
    }

    // Layer 4.5: Engineering guardrails (when enabled)
    if let Some(profile) = p.guardrail_profile {
        parts.push(guardrails::guardrails_layer(profile));
    }

    // Layer 5: Task context (headless mode only)
    if let Some(task) = p.task {
        parts.push(task_layer(task));
        parts.push(headless_execution_layer(task));
    }

    // Layer 6: Agent memory
    if let Some(mem) = p.memory {
        if !mem.is_empty() {
            parts.push(mem.to_string());
        }
    }
    if let Some(user) = p.user_profile {
        if !user.is_empty() {
            parts.push(user.to_string());
        }
    }

    let text = parts.join("\n\n");
    let estimated_tokens = estimate_tokens(&text);

    AssembledPrompt {
        text,
        estimated_tokens,
    }
}

fn identity_layer(
    tools: &ToolRegistry,
    role: Option<&Role>,
    mode: &AgentMode,
    learning_enabled: bool,
    personality: Option<&PersonalityProfile>,
    soul: Option<&SoulDoc>,
) -> String {
    let mut s = String::new();
    if let Some(soul) = soul {
        s.push_str(&soul_identity_text(&soul.content));
    } else if let Some(personality) = personality {
        s.push_str(&personality.identity.render_sentence());
    } else {
        s.push_str("You are imp, a coding agent.");
    }
    s.push_str("\n\nAvailable tools:\n");

    let defs = match role {
        Some(r) if r.readonly => tools.readonly_definitions(),
        _ => tools.definitions_for_mode(mode),
    };

    for def in &defs {
        s.push_str(&format!("- {}: {}\n", def.name, def.description));
    }

    if let Some(soul) = soul {
        s.push_str("\n\nSoul:\n");
        s.push_str(&soul.content);
        s.push('\n');
    } else if let Some(personality) = personality {
        let working_style = working_style_lines(&personality.sliders);
        if !working_style.is_empty() {
            s.push_str("\nWorking style:\n");
            for line in working_style {
                s.push_str("- ");
                s.push_str(line);
                s.push('\n');
            }
        }
    }

    s.push_str("\nTool usage guide:\n");
    s.push_str("- Use `shell` for search, file discovery, directory listing, builds, tests, scripts, package managers, and other shell-native tasks. Prefer `scan` for structural code understanding before broad text search when symbol relationships or code blocks matter.\n");
    if defs.iter().any(|def| def.name == "git") {
        s.push_str("- Use `git` for local repo/worktree operations; use `shell` for uncovered git commands.\n");
    }
    if defs.iter().any(|def| def.name == "mana") {
        s.push_str("- Prefer the native `mana` tool over `shell` for mana operations when an equivalent action exists; use `shell` only for mana-adjacent shell work with no native mana action.\n");
    }
    s.push_str("- Use `read` to inspect a specific file with stable line-oriented output.\n");
    s.push_str("- Use `scan` for structural code understanding and for extracting code at file:line, file:start-end, or file#symbol. Prefer it over `shell`+search when you need symbols, call sites, or coherent code blocks.\n");
    s.push_str("- Use `edit` and `write` for file changes.\n");
    s.push_str("- Use specialized tools like `mana`, `ask`, `web`, `extend`, and `recall` when the task calls for them. Use `recall` when you need to search past conversations.\n");

    s.push_str("\nMana doctrine:\n");
    s.push_str("- Mana is imp's substrate for explicit work. Represent work in mana whenever structure, verification, retries, dependencies, or handoff would help. Any mana unit must be detailed enough for another agent to execute cold without guesswork, even if you end up doing the work yourself.\n");
    s.push_str("- Treat each unit description as an execution prompt.\n");
    s.push_str("- Include current state, concrete steps, file paths with intent, edge cases, and a targeted verify command.\n");
    s.push_str("- Update units with new context after failures; do not retry unchanged.\n");
    s.push_str("- Mana is the durable project context — session memory is ephemeral, personal memory is global preferences; project plans, architecture decisions, verified facts, and implementation structure belong in mana, not in session history or memory.md.\n");
    s.push_str("- During planning and design conversations, proactively externalize durable structure as it appears. When the conversation settles on a goal, decomposition, architecture direction, dependency, blocker, or follow-up that should survive the turn, create or update mana during the conversation.\n");
    s.push_str("- Map durable planning artifacts deliberately: use an epic, child job, note, or decision based on the shape of the information, and keep facts reserved for verifiable claims.\n");
    s.push_str("- Do not ask permission merely to capture plan artifacts in mana. Do ask before making consequential scope, architecture, destructive, or execution commitments on the user's behalf.\n");
    s.push_str("- If durable planning state changed this turn, make the between-turn mana update before the substantive reply. Summarize the delta only when it adds value beyond what the mana tool or UI already made visible.\n");
    s.push_str("- A future wiki layer at `.mana/wiki/` will hold synthesized project knowledge; for now, use mana facts for verifiable claims and mana units/notes for everything else that should survive the session.\n");

    // Append role instructions after identity layer
    if let Some(role) = role {
        if let Some(ref instructions) = role.instructions {
            s.push('\n');
            s.push_str(instructions);
            s.push('\n');
        }
    }

    // Append mode instructions if present
    if let Some(instructions) = mode.instructions() {
        s.push('\n');
        s.push_str(instructions);
        s.push('\n');
    }

    // Append learning instructions when enabled
    if learning_enabled {
        s.push('\n');
        s.push_str(crate::learning::LEARNING_INSTRUCTIONS);
        s.push('\n');
    }

    s
}

fn execution_policy_layer() -> String {
    let mut s = String::from("Execution discipline:\n");
    s.push_str("- Re-evaluate the user's intent on every new message before acting. Distinguish analysis, implementation, planning, review, and orchestration.\n");
    s.push_str("- Never claim repository facts that you have not inspected in this session. Ground important claims in opened files, tool output, or explicit user-provided evidence.\n");
    s.push_str("- If the user references a specific file, symbol, command, or error, inspect it before explaining or proposing changes.\n");
    s.push_str("- For analysis-only requests, stay read-only unless the user asks for changes.\n");
    s.push_str("- For implementation, prefer small, reversible changes and verify them with the smallest relevant checks before declaring success.\n");
    s.push_str("- Do not treat failed commands, failed checks, or missing evidence as success. If blocked, report the exact blocker and the next useful action.\n");
    s.push_str("- Before changing code, make sure you understand the relevant local context: inspect the files you will modify, nearby patterns, and any task-specific constraints already present in the repo.\n");
    s.push_str("- Match the completion mode to the request. For diagnosis, provide findings, root cause, and concrete next-step options without making changes. For implementation, make the change, verify it, and summarize the evidence.\n");
    s.push_str("- Treat task verify commands, failing tests, compiler errors, and tool errors as first-class evidence. Either resolve them or explain precisely why they remain blocked.\n");
    s.push_str("- Prefer the smallest check that proves the work: targeted tests, focused builds, existence checks, or narrow validation commands before broad project-wide verification.\n");
    s.push_str("- When uncertainty is consequential, ask one concise question instead of guessing. When uncertainty is local and low-risk, proceed and state the assumption briefly.\n");
    s.push_str("- If prior attempts failed, do not retry the same plan unchanged. Use the new evidence to adapt the approach first.\n");
    s.push_str("- Keep user-facing updates concise and evidence-oriented: what you inspected, what you changed, what you verified, and what remains.\n");
    s.push_str("- When working from a mana unit, treat the unit as an execution contract: use its scope, verify gate, dependencies, and embedded context before broadening the search.\n");
    s.push_str("- Prefer mana-native inspection and progress recording over ad hoc shell workflows when mana already models the work state.\n");
    s.push_str("- For worker-style execution, keep planning lightweight and execution direct; use `mana update` to record discoveries and blockers instead of carrying them only in transient chat.\n");
    s.push_str("- If a mana unit is underspecified, identify the exact missing context and either inspect the relevant artifacts or report the gap precisely rather than inventing missing requirements.\n");
    s.push_str("- Treat chat as discussion and mana as the persistent external work and idea graph. When a conversation produces durable structure — plans, architecture, decomposition, migrations, blockers, dependencies, or follow-up work — represent that structure in mana during the conversation, not after it.\n");
    s.push_str("- When durable planning state changes, update mana before the substantive reply when that durable state should become the source of truth for the next turn. Avoid restating mana-visible deltas verbosely when the tool output or UI already shows them.\n");
    s.push_str("- Do not use mana only when work is large; use it whenever externalizing the plan is likely to improve execution quality, correctness, scope clarity, reviewability, or future continuation.\n");
    s.push_str("- Prefer native mana actions over shell or direct file mutation for durable planning/work structure. Use append-style mana updates to keep the graph current during conversation.\n");
    s.push_str("- If work spans more than one project or clearly belongs at the ecosystem layer, target root mana explicitly rather than relying on the nearest project scope.\n");
    s
}

fn working_style_lines(sliders: &crate::personality::PersonalitySliders) -> Vec<&'static str> {
    vec![
        autonomy_line(sliders.autonomy),
        verbosity_line(sliders.verbosity),
        caution_line(sliders.caution),
        warmth_line(sliders.warmth),
        planning_depth_line(sliders.planning_depth),
        "If you find yourself repeating the same action without progress, step back and try a different approach or ask the user for guidance.",
    ]
}

pub(crate) fn autonomy_line(band: PersonalityBand) -> &'static str {
    match band {
        PersonalityBand::VeryLow => {
            "Ask for confirmation before making consequential decisions or larger changes."
        }
        PersonalityBand::Low => {
            "Prefer confirmation before acting when requirements or consequences are unclear."
        }
        PersonalityBand::Medium => {
            "Act on clear next steps, but ask when requirements are ambiguous."
        }
        PersonalityBand::High => {
            "Act independently by default and ask when blocked, uncertain, or facing a consequential decision. Keep working until the task is fully resolved before yielding."
        }
        PersonalityBand::VeryHigh => {
            "Take initiative aggressively on clear work and only ask when blocked or genuinely uncertain. Keep working until the task is fully resolved before yielding."
        }
    }
}

pub(crate) fn verbosity_line(band: PersonalityBand) -> &'static str {
    match band {
        PersonalityBand::VeryLow => "Keep responses terse and strongly action-oriented.",
        PersonalityBand::Low => "Keep responses brief and focused on progress.",
        PersonalityBand::Medium => {
            "Be concise by default, but explain important tradeoffs when useful."
        }
        PersonalityBand::High => {
            "Explain reasoning and tradeoffs when they help the user follow the work."
        }
        PersonalityBand::VeryHigh => {
            "Give fuller explanations of reasoning, tradeoffs, and next steps."
        }
    }
}

pub(crate) fn caution_line(band: PersonalityBand) -> &'static str {
    match band {
        PersonalityBand::VeryLow => {
            "Move forward with reasonable assumptions when the path is clear."
        }
        PersonalityBand::Low => "Favor progress over caution when risks are limited and local.",
        PersonalityBand::Medium => "Balance steady progress with avoiding avoidable risk.",
        PersonalityBand::High => {
            "Prefer small, reversible changes and verify assumptions before riskier actions."
        }
        PersonalityBand::VeryHigh => {
            "Be highly conservative with risky changes: verify assumptions and avoid acting on weak evidence."
        }
    }
}

pub(crate) fn warmth_line(band: PersonalityBand) -> &'static str {
    match band {
        PersonalityBand::VeryLow => "Use a direct, neutral tone.",
        PersonalityBand::Low => "Use a clear, matter-of-fact tone.",
        PersonalityBand::Medium => "Use a clear and calm tone.",
        PersonalityBand::High => "Use a warm, supportive tone without becoming verbose.",
        PersonalityBand::VeryHigh => {
            "Use a notably warm, encouraging tone while staying useful and grounded."
        }
    }
}

pub(crate) fn planning_depth_line(band: PersonalityBand) -> &'static str {
    match band {
        PersonalityBand::VeryLow => "Favor immediate execution on the most obvious next step.",
        PersonalityBand::Low => "Plan lightly, then move quickly into execution.",
        PersonalityBand::Medium => "Plan briefly, then execute.",
        PersonalityBand::High => "Think through structure and likely consequences before acting.",
        PersonalityBand::VeryHigh => {
            "Be methodical: think through structure, dependencies, and consequences before acting."
        }
    }
}

fn environment_layer(cwd: Option<&std::path::Path>) -> String {
    let home = std::env::var("HOME").unwrap_or_default();
    let cwd_str = cwd.map(|p| p.display().to_string()).unwrap_or_else(|| {
        std::env::current_dir()
            .map(|p| p.display().to_string())
            .unwrap_or_default()
    });
    let os = std::env::consts::OS;
    let today = {
        use std::time::{SystemTime, UNIX_EPOCH};
        let secs = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        let days = secs / 86400;
        // Simple date calculation
        let (y, m, d) = days_to_ymd(days);
        format!("{y}-{m:02}-{d:02}")
    };
    format!("Environment: cwd={cwd_str}, os={os}, home={home}, date={today}")
}

/// Convert days since Unix epoch to (year, month, day).
fn days_to_ymd(mut days: u64) -> (u64, u64, u64) {
    // Civil days algorithm (Howard Hinnant)
    days += 719_468;
    let era = days / 146_097;
    let doe = days - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };
    (y, m, d)
}

fn agents_md_layer(agents: &[AgentsMd]) -> String {
    let mut s = String::from("# Project Context\n\n");
    for agent in agents {
        s.push_str(&agent.content);
        s.push('\n');
    }
    s
}

fn skills_layer(skills: &[Skill], mode: &AgentMode) -> String {
    let mut s = String::from("Available skills (use read to load when relevant):\n");
    if let Some(trigger) = mana_skill_trigger(skills, mode) {
        s.push_str(&format!("- Trigger: {trigger}\n"));
    }
    for skill in skills {
        s.push_str(&format!(
            "- {}: {} [{}]\n",
            skill.name,
            skill.description,
            skill.path.display()
        ));
    }
    s
}

fn mana_skill_trigger(skills: &[Skill], mode: &AgentMode) -> Option<&'static str> {
    let has_mana = skills.iter().any(|skill| skill.name == "mana");
    let has_mana_basics = skills.iter().any(|skill| skill.name == "mana-basics");

    match mode {
        AgentMode::Full | AgentMode::Orchestrator | AgentMode::Planner => {
            if has_mana {
                Some("Load `mana` before writing or restructuring mana units for non-trivial work.")
            } else {
                None
            }
        }
        AgentMode::Worker => {
            if has_mana_basics {
                Some(
                    "Load `mana-basics` before using worker-safe mana actions beyond a quick status check.",
                )
            } else if has_mana {
                Some(
                    "Load `mana` before using worker-safe mana actions beyond a quick status check.",
                )
            } else {
                None
            }
        }
        AgentMode::Auditor => {
            if has_mana_basics {
                Some(
                    "Load `mana-basics` before inspecting mana state across multiple units or runs.",
                )
            } else if has_mana {
                Some("Load `mana` before inspecting mana state across multiple units or runs.")
            } else {
                None
            }
        }
        AgentMode::Reviewer => None,
    }
}

fn facts_layer(facts: &[Fact]) -> String {
    let mut s = String::from("Project facts:\n");
    for fact in facts {
        s.push_str(&format!(
            "- \"{}\" [verified {}]\n",
            fact.text, fact.verified_ago
        ));
    }
    s
}

fn project_memory_status_layer(status: &str) -> String {
    status.to_string()
}

fn task_layer(task: &TaskContext) -> String {
    let mut s = String::from("## Task\n");
    s.push_str(&format!("Title: {}\n", task.title));
    s.push_str(&format!("Description: {}\n", task.description));
    if let Some(ref notes) = task.notes {
        if !notes.trim().is_empty() {
            s.push_str("Notes:\n");
            s.push_str(notes);
            s.push('\n');
        }
    }
    if let Some(ref acceptance) = task.acceptance {
        s.push_str("Acceptance:\n");
        s.push_str(acceptance);
        s.push('\n');
    }
    if let Some(ref verify) = task.verify {
        s.push_str(&format!("Verify: {}\n", verify));
        s.push_str("Treat the verify command as the primary completion check for this task.\n");
    }

    if !task.context_paths.is_empty() {
        s.push_str("\n## Referenced files\n");
        s.push_str("Use these declared file/path hints before broadening the search.\n");
        for path in &task.context_paths {
            s.push_str(&format!("- {}\n", path));
        }
    }

    if !task.constraints.is_empty() {
        s.push_str("\n## Constraints\n");
        for constraint in &task.constraints {
            s.push_str(&format!("- {}\n", constraint));
        }
    }

    if !task.attempts.is_empty() {
        s.push_str("\n## Previous attempts\n");
        s.push_str("Do not repeat a failed approach unchanged; use the attempt history to adjust your plan.\n");
        for attempt in &task.attempts {
            s.push_str(&format!(
                "Attempt {} ({}): {}\n",
                attempt.number, attempt.outcome, attempt.summary
            ));
        }
    }

    if !task.dependencies.is_empty() {
        s.push_str("\n## Dependencies\n");
        s.push_str("Respect dependency state when sequencing work; unresolved dependencies are potential blockers.\n");
        for dep in &task.dependencies {
            s.push_str(&format!(
                "- {} ({}): {}\n",
                dep.name, dep.status, dep.detail
            ));
        }
    }

    if !task.decisions.is_empty() {
        s.push_str("\n## Unresolved decisions\n");
        s.push_str("These decisions block fully autonomous execution; resolve them or surface them clearly instead of guessing.\n");
        for decision in &task.decisions {
            s.push_str(&format!("- {}\n", decision));
        }
    }

    s
}

fn headless_execution_layer(task: &TaskContext) -> String {
    let mut s = String::from("## Headless execution contract\n");
    s.push_str("- You are executing an explicit mana unit, not exploring broadly.\n");
    s.push_str("- Treat the unit title, description, notes, acceptance criteria, and verify gate as the source of truth for scope and success.\n");
    s.push_str("- Execute the assigned outcome before expanding into adjacent cleanup, refactors, or unrelated improvements.\n");
    s.push_str("- Use explicit file references and prefilled context first before searching more broadly.\n");
    s.push_str(
        "- If the unit includes prior failed attempts, do not retry the same plan unchanged.\n",
    );
    s.push_str("- If dependency state or prerequisite decisions are unresolved, treat that as a blocker rather than improvising around it.\n");
    s.push_str("- Keep progress updates concise and useful. Record meaningful discoveries, blockers, and revised plans with `mana update`.\n");
    if task.verify.is_some() {
        s.push_str("- If the verify command fails, either fix the issue or report the exact blocker. Do not claim completion anyway.\n");
    }
    s.push_str("- In batch-verify flows, treat your goal as leaving the unit ready for verify rather than assuming verify already passed.\n");
    s.push_str(
        "- Respect parent/child structure: finish this unit's outcome, not the whole feature.\n",
    );
    s
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;
    use std::sync::Arc;

    use crate::personality::{
        PersonaFocus, PersonaRole, PersonalityBand, PersonalityIdentity, PersonalityProfile,
        PersonalitySliders, VoiceWord, WorkStyleWord,
    };
    use crate::resources::SoulDoc;
    use crate::tools::{Tool, ToolContext, ToolOutput};
    use async_trait::async_trait;

    // -- Test tool helpers --

    struct FakeTool {
        name: &'static str,
        description: &'static str,
        readonly: bool,
    }

    #[async_trait]
    impl Tool for FakeTool {
        fn name(&self) -> &str {
            self.name
        }
        fn label(&self) -> &str {
            self.name
        }
        fn description(&self) -> &str {
            self.description
        }
        fn parameters(&self) -> serde_json::Value {
            serde_json::json!({"type": "object"})
        }
        fn is_readonly(&self) -> bool {
            self.readonly
        }
        async fn execute(
            &self,
            _: &str,
            _: serde_json::Value,
            _: ToolContext,
        ) -> crate::Result<ToolOutput> {
            Ok(ToolOutput::text("ok"))
        }
    }

    fn make_registry() -> ToolRegistry {
        let mut reg = ToolRegistry::new();
        reg.register(Arc::new(FakeTool {
            name: "read",
            description: "Read file contents",
            readonly: true,
        }));
        reg.register(Arc::new(FakeTool {
            name: "write",
            description: "Write content to a file",
            readonly: false,
        }));
        reg.register(Arc::new(FakeTool {
            name: "edit",
            description: "Edit a file by replacing exact text",
            readonly: false,
        }));
        reg.register(Arc::new(FakeTool {
            name: "bash",
            description: "Run shell commands",
            readonly: false,
        }));
        reg
    }

    fn make_skill(name: &str, desc: &str, path: &str) -> Skill {
        Skill {
            name: name.into(),
            description: desc.into(),
            path: PathBuf::from(path),
        }
    }

    fn make_agents_md(content: &str) -> AgentsMd {
        AgentsMd {
            path: PathBuf::from("/project/AGENTS.md"),
            content: content.into(),
        }
    }

    fn make_readonly_role() -> Role {
        use crate::roles::ToolSet;
        Role {
            name: "reviewer".into(),
            model: None,
            thinking_level: None,
            tool_set: ToolSet::All,
            readonly: true,
            instructions: Some("Review code carefully. Do not modify files.".into()),
            max_turns: Some(10),
        }
    }

    fn make_worker_role() -> Role {
        use crate::roles::ToolSet;
        Role {
            name: "worker".into(),
            model: None,
            thinking_level: None,
            tool_set: ToolSet::All,
            readonly: false,
            instructions: None,
            max_turns: None,
        }
    }

    fn make_personality() -> PersonalityProfile {
        PersonalityProfile {
            identity: PersonalityIdentity {
                name: "Nova".into(),
                work_style: WorkStyleWord::Careful,
                voice: VoiceWord::Direct,
                focus: PersonaFocus::Research,
                role: PersonaRole::Assistant,
            },
            sliders: PersonalitySliders {
                autonomy: PersonalityBand::Low,
                verbosity: PersonalityBand::Medium,
                caution: PersonalityBand::VeryHigh,
                warmth: PersonalityBand::High,
                planning_depth: PersonalityBand::VeryLow,
            },
        }
    }

    /// Test helper: shorthand for assemble() with no memory/user_profile.
    fn test_assemble(
        tools: &ToolRegistry,
        agents_md: &[AgentsMd],
        skills: &[Skill],
        facts: &[Fact],
        personality: Option<&PersonalityProfile>,
        task: Option<&TaskContext>,
        role: Option<&Role>,
    ) -> AssembledPrompt {
        assemble(&AssembleParams {
            tools,
            agents_md,
            skills,
            facts,
            project_memory_status: None,
            personality,
            soul: None,
            task,
            role,
            mode: &AgentMode::Full,
            memory: None,
            user_profile: None,
            cwd: None,
            learning_enabled: false,
            guardrail_profile: None,
        })
    }

    // -- Layer 1: Identity --

    #[test]
    fn system_prompt_includes_execution_policy_layer() {
        let reg = make_registry();
        let result = test_assemble(&reg, &[], &[], &[], None, None, None);
        assert!(result.text.contains("Execution discipline:"));
        assert!(result
            .text
            .contains("Never claim repository facts that you have not inspected in this session."));
        assert!(result.text.contains(
            "For analysis-only requests, stay read-only unless the user asks for changes."
        ));
    }

    #[test]
    fn system_prompt_includes_conversation_time_mana_planning_doctrine() {
        let reg = make_registry();
        let result = test_assemble(&reg, &[], &[], &[], None, None, None);
        assert!(result.text.contains(
            "During planning and design conversations, proactively externalize durable structure as it appears."
        ));
        assert!(result.text.contains("epic, child job, note, or decision"));
        assert!(result
            .text
            .contains("Do not ask permission merely to capture plan artifacts in mana."));
        assert!(result.text.contains(
            "If durable planning state changed this turn, make the between-turn mana update before the substantive reply"
        ));
        assert!(result.text.contains(
            "Summarize the delta only when it adds value beyond what the mana tool or UI already made visible."
        ));
        assert_eq!(
            result
                .text
                .matches("between-turn mana update before the substantive reply")
                .count(),
            1,
            "between-turn mana update guidance should appear once"
        );
        assert!(!result
            .text
            .contains("include a concise mana delta summary in the response"));
    }

    #[test]
    fn system_prompt_identity_includes_all_tools() {
        let reg = make_registry();
        let result = test_assemble(&reg, &[], &[], &[], None, None, None);
        assert!(result.text.contains("You are imp, a coding agent."));
        assert!(result.text.contains("- read: Read file contents"));
        assert!(result.text.contains("- write: Write content to a file"));
        assert!(result
            .text
            .contains("- edit: Edit a file by replacing exact text"));
        assert!(result.text.contains("- bash: Run shell commands"));
    }

    #[test]
    fn system_prompt_mana_guidance_prefers_native_tool_when_available() {
        let mut reg = make_registry();
        reg.register(Arc::new(FakeTool {
            name: "mana",
            description: "Manage mana work natively",
            readonly: false,
        }));

        let result = test_assemble(&reg, &[], &[], &[], None, None, None);
        assert!(result.text.contains(
            "Prefer the native `mana` tool over `bash` for mana operations when an equivalent action exists"
        ));
    }

    #[test]
    fn system_prompt_mana_guidance_omitted_without_mana_tool() {
        let reg = make_registry();
        let result = test_assemble(&reg, &[], &[], &[], None, None, None);
        assert!(!result.text.contains(
            "Prefer the native `mana` tool over `bash` for mana operations when an equivalent action exists"
        ));
    }

    #[test]
    fn system_prompt_no_mana_guidance_or_delegation_in_prompt() {
        // Mana guidance and delegation blocks have been moved to the mana skill.
        // Verify they no longer appear regardless of tool availability.
        let mut reg = make_registry();
        reg.register(Arc::new(FakeTool {
            name: "bash",
            description: "Run shell commands",
            readonly: false,
        }));
        reg.register(Arc::new(FakeTool {
            name: "mana",
            description: "Manage mana work",
            readonly: false,
        }));

        let result = test_assemble(&reg, &[], &[], &[], None, None, None);
        assert!(
            !result.text.contains("Mana guidance:"),
            "mana guidance block should not appear in system prompt"
        );
        assert!(
            !result.text.contains("## Mana delegation"),
            "delegation guidance should not appear in system prompt"
        );
    }

    #[test]
    fn system_prompt_identity_only_when_all_layers_empty() {
        let reg = make_registry();
        let result = test_assemble(&reg, &[], &[], &[], None, None, None);
        // Should have identity but no section headers for missing layers
        assert!(result.text.contains("You are imp"));
        assert!(!result.text.contains("# Project Context"));
        assert!(!result.text.contains("Available skills"));
        assert!(!result.text.contains("Project facts"));
        assert!(!result.text.contains("## Task"));
    }

    #[test]
    fn system_prompt_uses_personality_identity_sentence() {
        let reg = make_registry();
        let personality = make_personality();
        let result = test_assemble(&reg, &[], &[], &[], Some(&personality), None, None);
        assert!(result
            .text
            .contains("You are Nova, a careful, direct, research assistant."));
    }

    #[test]
    fn system_prompt_renders_personality_working_style_block() {
        let reg = make_registry();
        let personality = make_personality();
        let result = test_assemble(&reg, &[], &[], &[], Some(&personality), None, None);
        assert!(result.text.contains("Working style:"));
        assert!(result.text.contains(
            "Prefer confirmation before acting when requirements or consequences are unclear."
        ));
        assert!(result
            .text
            .contains("Be concise by default, but explain important tradeoffs when useful."));
        assert!(result.text.contains(
            "Be highly conservative with risky changes: verify assumptions and avoid acting on weak evidence."
        ));
        assert!(result
            .text
            .contains("Use a warm, supportive tone without becoming verbose."));
        assert!(result
            .text
            .contains("Favor immediate execution on the most obvious next step."));
    }

    #[test]
    fn system_prompt_prefers_soul_over_personality_profile() {
        let reg = make_registry();
        let personality = make_personality();
        let soul = SoulDoc {
            path: PathBuf::from("/tmp/soul.md"),
            content: "# Soul\n\nYou are Sol, a tuned and reflective collaborator.\n\n## Tunables\n\n- Autonomy: Act independently by default.\n".into(),
        };
        let result = assemble(&AssembleParams {
            tools: &reg,
            agents_md: &[],
            skills: &[],
            facts: &[],
            project_memory_status: None,
            personality: Some(&personality),
            soul: Some(&soul),
            task: None,
            role: None,
            mode: &AgentMode::Full,
            memory: None,
            user_profile: None,
            cwd: None,
            learning_enabled: false,
            guardrail_profile: None,
        });
        assert!(result
            .text
            .contains("You are Sol, a tuned and reflective collaborator."));
        assert!(result.text.contains("Soul:"));
        assert!(result.text.contains("## Tunables"));
        assert!(!result.text.contains("Working style:"));
    }

    #[test]
    fn system_prompt_without_soul_keeps_personality_working_style_block() {
        let reg = make_registry();
        let personality = make_personality();
        let result = test_assemble(&reg, &[], &[], &[], Some(&personality), None, None);
        assert!(result.text.contains("Working style:"));
    }

    // -- Layer 2: AGENTS.md --

    #[test]
    fn system_prompt_agents_md_included_verbatim() {
        let reg = make_registry();
        let agents = vec![make_agents_md("# Rules\n\nUse snake_case everywhere.")];
        let result = test_assemble(&reg, &agents, &[], &[], None, None, None);
        assert!(result.text.contains("# Project Context"));
        assert!(result
            .text
            .contains("# Rules\n\nUse snake_case everywhere."));
    }

    #[test]
    fn system_prompt_multiple_agents_md_concatenated() {
        let reg = make_registry();
        let agents = vec![
            make_agents_md("Global rules here."),
            make_agents_md("Project rules here."),
        ];
        let result = test_assemble(&reg, &agents, &[], &[], None, None, None);
        assert!(result.text.contains("Global rules here."));
        assert!(result.text.contains("Project rules here."));
    }

    #[test]
    fn system_prompt_empty_agents_md_skipped() {
        let reg = make_registry();
        let result = test_assemble(&reg, &[], &[], &[], None, None, None);
        assert!(!result.text.contains("# Project Context"));
    }

    // -- Layer 3: Skills --

    #[test]
    fn system_prompt_skills_listed_with_paths() {
        let reg = make_registry();
        let skills = vec![
            make_skill(
                "rust",
                "Conventions for Rust code",
                "/home/.imp/skills/rust/SKILL.md",
            ),
            make_skill(
                "testing",
                "Write and review tests",
                "/home/.imp/skills/testing/SKILL.md",
            ),
        ];
        let result = test_assemble(&reg, &[], &skills, &[], None, None, None);
        assert!(result
            .text
            .contains("Available skills (use read to load when relevant):"));
        assert!(result
            .text
            .contains("- rust: Conventions for Rust code [/home/.imp/skills/rust/SKILL.md]"));
        assert!(result
            .text
            .contains("- testing: Write and review tests [/home/.imp/skills/testing/SKILL.md]"));
    }

    #[test]
    fn system_prompt_includes_mode_aware_mana_skill_trigger() {
        let reg = make_registry();
        let skills = vec![make_skill(
            "mana",
            "Coordinate explicit work through mana",
            "/home/.imp/skills/mana/SKILL.md",
        )];
        let result = assemble(&AssembleParams {
            tools: &reg,
            agents_md: &[],
            skills: &skills,
            facts: &[],
            project_memory_status: None,
            personality: None,
            soul: None,
            task: None,
            role: None,
            mode: &AgentMode::Planner,
            memory: None,
            user_profile: None,
            cwd: None,
            learning_enabled: false,
            guardrail_profile: None,
        });

        assert!(result.text.contains("- Trigger:"));
        assert!(result.text.contains(
            "Load `mana` before writing or restructuring mana units for non-trivial work."
        ));
    }

    #[test]
    fn system_prompt_orchestrator_uses_same_mana_trigger() {
        let reg = make_registry();
        let skills = vec![make_skill(
            "mana",
            "Coordinate explicit work through mana",
            "/home/.imp/skills/mana/SKILL.md",
        )];
        let result = assemble(&AssembleParams {
            tools: &reg,
            agents_md: &[],
            skills: &skills,
            facts: &[],
            project_memory_status: None,
            personality: None,
            soul: None,
            task: None,
            role: None,
            mode: &AgentMode::Orchestrator,
            memory: None,
            user_profile: None,
            cwd: None,
            learning_enabled: false,
            guardrail_profile: None,
        });

        assert!(result.text.contains(
            "Load `mana` before writing or restructuring mana units for non-trivial work."
        ));
    }

    #[test]
    fn system_prompt_worker_prefers_mana_basics_trigger() {
        let reg = make_registry();
        let skills = vec![
            make_skill(
                "mana",
                "Coordinate multi-step work through mana",
                "/home/.imp/skills/mana/SKILL.md",
            ),
            make_skill(
                "mana-basics",
                "Use native mana actions safely and efficiently",
                "/home/.imp/skills/mana-basics/SKILL.md",
            ),
        ];
        let result = assemble(&AssembleParams {
            tools: &reg,
            agents_md: &[],
            skills: &skills,
            facts: &[],
            project_memory_status: None,
            personality: None,
            soul: None,
            task: None,
            role: None,
            mode: &AgentMode::Worker,
            memory: None,
            user_profile: None,
            cwd: None,
            learning_enabled: false,
            guardrail_profile: None,
        });

        assert!(result.text.contains(
            "Load `mana-basics` before using worker-safe mana actions beyond a quick status check."
        ));
    }

    #[test]
    fn system_prompt_omits_mana_trigger_without_mana_skill() {
        let reg = make_registry();
        let skills = vec![make_skill(
            "rust",
            "Conventions for Rust code",
            "/home/.imp/skills/rust/SKILL.md",
        )];
        let result = assemble(&AssembleParams {
            tools: &reg,
            agents_md: &[],
            skills: &skills,
            facts: &[],
            project_memory_status: None,
            personality: None,
            soul: None,
            task: None,
            role: None,
            mode: &AgentMode::Planner,
            memory: None,
            user_profile: None,
            cwd: None,
            learning_enabled: false,
            guardrail_profile: None,
        });

        assert!(!result.text.contains("- Trigger:"));
    }

    #[test]
    fn system_prompt_reviewer_mode_omits_mana_trigger() {
        let reg = make_registry();
        let skills = vec![make_skill(
            "mana",
            "Coordinate multi-step work through mana",
            "/home/.imp/skills/mana/SKILL.md",
        )];
        let result = assemble(&AssembleParams {
            tools: &reg,
            agents_md: &[],
            skills: &skills,
            facts: &[],
            project_memory_status: None,
            personality: None,
            soul: None,
            task: None,
            role: None,
            mode: &AgentMode::Reviewer,
            memory: None,
            user_profile: None,
            cwd: None,
            learning_enabled: false,
            guardrail_profile: None,
        });

        assert!(!result.text.contains("- Trigger:"));
    }

    #[test]
    fn system_prompt_empty_skills_skipped() {
        let reg = make_registry();
        let result = test_assemble(&reg, &[], &[], &[], None, None, None);
        assert!(!result.text.contains("Available skills"));
    }

    // -- Layer 4: Mana facts --

    #[test]
    fn system_prompt_facts_included() {
        let reg = make_registry();
        let facts = vec![
            Fact {
                text: "Uses JWT for auth".into(),
                verified_ago: "2h ago".into(),
            },
            Fact {
                text: "Test suite requires Docker".into(),
                verified_ago: "1d ago".into(),
            },
        ];
        let result = test_assemble(&reg, &[], &[], &facts, None, None, None);
        assert!(result.text.contains("Project facts:"));
        assert!(result
            .text
            .contains("\"Uses JWT for auth\" [verified 2h ago]"));
        assert!(result
            .text
            .contains("\"Test suite requires Docker\" [verified 1d ago]"));
    }

    #[test]
    fn system_prompt_empty_facts_skipped() {
        let reg = make_registry();
        let result = test_assemble(&reg, &[], &[], &[], None, None, None);
        assert!(!result.text.contains("Project facts"));
    }

    #[test]
    fn system_prompt_project_memory_status_included() {
        let reg = make_registry();
        let result = assemble(&AssembleParams {
            tools: &reg,
            agents_md: &[],
            skills: &[],
            facts: &[],
            project_memory_status: Some(
                "Project memory status:\nWarnings:\n- STALE: \"Lockfile drift\"\n\nWorking on:\n- [12] Refresh auth flow",
            ),
            personality: None,
            soul: None,
            task: None,
            role: None,
            mode: &AgentMode::Full,
            memory: None,
            user_profile: None,
            cwd: None,
            learning_enabled: false,
            guardrail_profile: None,
        });
        assert!(result.text.contains("Project memory status:"));
        assert!(result.text.contains("Warnings:"));
        assert!(result.text.contains("Working on:"));
    }

    #[test]
    fn system_prompt_project_memory_status_empty_string_is_skipped() {
        let reg = make_registry();
        let result = assemble(&AssembleParams {
            tools: &reg,
            agents_md: &[],
            skills: &[],
            facts: &[],
            project_memory_status: Some(""),
            personality: None,
            soul: None,
            task: None,
            role: None,
            mode: &AgentMode::Full,
            memory: None,
            user_profile: None,
            cwd: None,
            learning_enabled: false,
            guardrail_profile: None,
        });
        assert!(!result.text.contains("Project memory status:"));
    }

    #[test]
    fn system_prompt_project_memory_status_included_separately_from_facts() {
        let reg = make_registry();
        let facts = vec![Fact {
            text: "Uses JWT for auth".into(),
            verified_ago: "2h ago".into(),
        }];
        let status =
            "Project memory status:\nWarnings:\n- stale fact\n\nWorking on:\n- [7] Fix auth flow";
        let result = assemble(&AssembleParams {
            tools: &reg,
            agents_md: &[],
            skills: &[],
            facts: &facts,
            project_memory_status: Some(status),
            personality: None,
            soul: None,
            task: None,
            role: None,
            mode: &AgentMode::Full,
            memory: None,
            user_profile: None,
            cwd: None,
            learning_enabled: false,
            guardrail_profile: None,
        });

        let facts_pos = result.text.find("Project facts:").unwrap();
        let status_pos = result.text.find("Project memory status:").unwrap();
        assert!(result
            .text
            .contains("\"Uses JWT for auth\" [verified 2h ago]"));
        assert!(result.text.contains("Warnings:"));
        assert!(result.text.contains("Working on:"));
        assert!(facts_pos < status_pos);
    }

    // -- Layer 5: Task context --

    #[test]
    fn system_prompt_task_context_included() {
        let reg = make_registry();
        let task = TaskContext {
            title: "Fix the failing auth test".into(),
            description: "The JWT validation test panics on expired tokens".into(),
            acceptance: None,
            verify: Some("cargo test auth::jwt_test".into()),
            notes: None,
            attempts: vec![],
            dependencies: vec![],
            decisions: vec![],
            context_paths: vec![],
            constraints: vec![],
        };
        let result = test_assemble(&reg, &[], &[], &[], None, Some(&task), None);
        assert!(result.text.contains("## Task"));
        assert!(result.text.contains("Title: Fix the failing auth test"));
        assert!(result
            .text
            .contains("Description: The JWT validation test panics"));
        assert!(result.text.contains("Verify: cargo test auth::jwt_test"));
        assert!(result
            .text
            .contains("Treat the verify command as the primary completion check for this task."));
    }

    #[test]
    fn system_prompt_task_with_attempts() {
        let reg = make_registry();
        let task = TaskContext {
            title: "Fix bug".into(),
            description: "Something is broken".into(),
            acceptance: None,
            verify: None,
            notes: None,
            attempts: vec![
                Attempt {
                    number: 1,
                    outcome: "failed".into(),
                    summary: "Tried X, got error Y".into(),
                },
                Attempt {
                    number: 2,
                    outcome: "failed".into(),
                    summary: "Tried Z, still broken".into(),
                },
            ],
            dependencies: vec![],
            decisions: vec![],
            context_paths: vec![],
            constraints: vec![],
        };
        let result = test_assemble(&reg, &[], &[], &[], None, Some(&task), None);
        assert!(result.text.contains("## Previous attempts"));
        assert!(result.text.contains(
            "Do not repeat a failed approach unchanged; use the attempt history to adjust your plan."
        ));
        assert!(result
            .text
            .contains("Attempt 1 (failed): Tried X, got error Y"));
        assert!(result
            .text
            .contains("Attempt 2 (failed): Tried Z, still broken"));
    }

    #[test]
    fn system_prompt_task_with_dependencies() {
        let reg = make_registry();
        let task = TaskContext {
            title: "Implement feature".into(),
            description: "New feature".into(),
            acceptance: None,
            verify: None,
            notes: None,
            attempts: vec![],
            dependencies: vec![Dependency {
                name: "Schema types".into(),
                status: "completed".into(),
                detail: "defined in src/schema.rs".into(),
            }],
            decisions: vec![],
            context_paths: vec![],
            constraints: vec![],
        };
        let result = test_assemble(&reg, &[], &[], &[], None, Some(&task), None);
        assert!(result.text.contains("## Dependencies"));
        assert!(result.text.contains(
            "Respect dependency state when sequencing work; unresolved dependencies are potential blockers."
        ));
        assert!(result
            .text
            .contains("- Schema types (completed): defined in src/schema.rs"));
    }

    #[test]
    fn system_prompt_task_with_notes_and_context_paths() {
        let reg = make_registry();
        let task = TaskContext {
            title: "Fix auth".into(),
            description: "Tighten token validation".into(),
            acceptance: None,
            verify: Some("cargo test auth".into()),
            notes: Some("Prefer touching only auth paths unless necessary".into()),
            attempts: vec![],
            dependencies: vec![],
            decisions: vec![],
            context_paths: vec!["src/auth.rs".into(), "tests/auth.rs".into()],
            constraints: vec![
                "Scope changes to auth-related files unless broader edits are necessary".into(),
            ],
        };
        let result = test_assemble(&reg, &[], &[], &[], None, Some(&task), None);
        assert!(result.text.contains("Notes:"));
        assert!(result
            .text
            .contains("Prefer touching only auth paths unless necessary"));
        assert!(result.text.contains("## Referenced files"));
        assert!(result.text.contains("- src/auth.rs"));
        assert!(result.text.contains("- tests/auth.rs"));
        assert!(result.text.contains("## Constraints"));
        assert!(result
            .text
            .contains("Scope changes to auth-related files unless broader edits are necessary"));
    }

    #[test]
    fn system_prompt_no_task_skips_layer5() {
        let reg = make_registry();
        let result = test_assemble(&reg, &[], &[], &[], None, None, None);
        assert!(!result.text.contains("## Task"));
    }

    #[test]
    fn system_prompt_task_without_verify_omits_verify_line() {
        let reg = make_registry();
        let task = TaskContext {
            title: "Do something".into(),
            description: "Details here".into(),
            acceptance: None,
            verify: None,
            notes: None,
            attempts: vec![],
            dependencies: vec![],
            decisions: vec![],
            context_paths: vec![],
            constraints: vec![],
        };
        let result = test_assemble(&reg, &[], &[], &[], None, Some(&task), None);
        assert!(result.text.contains("Title: Do something"));
        assert!(!result.text.contains("Verify:"));
    }

    // -- Role-aware assembly --

    #[test]
    fn system_prompt_readonly_role_filters_tools() {
        let reg = make_registry();
        let role = make_readonly_role();
        let result = test_assemble(&reg, &[], &[], &[], None, None, Some(&role));
        // Should include readonly tools
        assert!(result.text.contains("- read:"));
        // Should NOT include write tools
        assert!(!result.text.contains("- write:"));
        assert!(!result.text.contains("- edit:"));
    }

    #[test]
    fn system_prompt_role_instructions_appended() {
        let reg = make_registry();
        let role = make_readonly_role();
        let result = test_assemble(&reg, &[], &[], &[], None, None, Some(&role));
        assert!(result
            .text
            .contains("Review code carefully. Do not modify files."));
    }

    #[test]
    fn system_prompt_worker_role_includes_all_tools() {
        let reg = make_registry();
        let role = make_worker_role();
        let result = test_assemble(&reg, &[], &[], &[], None, None, Some(&role));
        assert!(result.text.contains("- read:"));
        assert!(result.text.contains("- write:"));
        assert!(result.text.contains("- edit:"));
        assert!(result.text.contains("- bash:"));
    }

    #[test]
    fn system_prompt_no_role_instructions_when_none() {
        let reg = make_registry();
        let role = make_worker_role();
        let result = test_assemble(&reg, &[], &[], &[], None, None, Some(&role));
        // Worker has no instructions, so the prompt shouldn't have extra instruction text
        let lines: Vec<&str> = result.text.lines().collect();
        let after_tools = lines.iter().position(|l| l.starts_with("- bash:")).unwrap();
        // Next non-empty line after the last tool should be end of identity layer
        // (no instructions appended)
        let remaining = &lines[after_tools + 1..];
        let next_content = remaining.iter().find(|l| !l.is_empty());
        assert!(next_content.is_none() || !next_content.unwrap().contains("Review"));
    }

    // -- Size tracking --

    #[test]
    fn system_prompt_tracks_estimated_tokens() {
        let reg = make_registry();
        let result = test_assemble(&reg, &[], &[], &[], None, None, None);
        assert!(result.estimated_tokens > 0);
        // Rough check: the text is at least ~100 chars, so >= 25 tokens
        assert!(result.estimated_tokens >= 10);
    }

    #[test]
    fn system_prompt_more_layers_means_more_tokens() {
        let reg = make_registry();

        let minimal = test_assemble(&reg, &[], &[], &[], None, None, None);

        let agents = vec![make_agents_md(
            "Lots of project context here with many words.",
        )];
        let skills = vec![make_skill(
            "rust",
            "Rust conventions",
            "/skills/rust/SKILL.md",
        )];
        let facts = vec![Fact {
            text: "Uses Postgres".into(),
            verified_ago: "1h ago".into(),
        }];

        let full = test_assemble(&reg, &agents, &skills, &facts, None, None, None);

        assert!(
            full.estimated_tokens > minimal.estimated_tokens,
            "full ({}) should have more tokens than minimal ({})",
            full.estimated_tokens,
            minimal.estimated_tokens
        );
    }

    // -- Full assembly --

    #[test]
    fn system_prompt_all_layers_present() {
        let reg = make_registry();
        let agents = vec![make_agents_md("Be concise.")];
        let skills = vec![make_skill(
            "rust",
            "Rust code conventions",
            "/skills/rust/SKILL.md",
        )];
        let facts = vec![Fact {
            text: "Uses SQLite".into(),
            verified_ago: "30m ago".into(),
        }];
        let task = TaskContext {
            title: "Add caching".into(),
            description: "Add Redis caching layer".into(),
            acceptance: None,
            verify: Some("cargo test cache".into()),
            notes: None,
            attempts: vec![Attempt {
                number: 1,
                outcome: "failed".into(),
                summary: "Wrong key format".into(),
            }],
            dependencies: vec![Dependency {
                name: "Config".into(),
                status: "done".into(),
                detail: "src/config.rs".into(),
            }],
            decisions: vec![],
            context_paths: vec![],
            constraints: vec![],
        };

        let result = test_assemble(&reg, &agents, &skills, &facts, None, Some(&task), None);

        // All layers present in order
        let identity_pos = result.text.find("You are imp").unwrap();
        let policy_pos = result.text.find("Execution discipline").unwrap();
        let context_pos = result.text.find("# Project Context").unwrap();
        let skills_pos = result.text.find("Available skills").unwrap();
        let facts_pos = result.text.find("Project facts").unwrap();
        let task_pos = result.text.find("## Task").unwrap();

        assert!(identity_pos < policy_pos, "identity before policy");
        assert!(policy_pos < context_pos, "policy before context");
        assert!(context_pos < skills_pos, "context before skills");
        assert!(skills_pos < facts_pos, "skills before facts");
        assert!(facts_pos < task_pos, "facts before task");
    }

    #[test]
    fn system_prompt_display_impl() {
        let reg = make_registry();
        let result = test_assemble(&reg, &[], &[], &[], None, None, None);
        let displayed = format!("{result}");
        assert_eq!(displayed, result.text);
    }

    // -- Layer 6: Agent Memory --

    #[test]
    fn system_prompt_memory_included() {
        let reg = make_registry();
        let mem = "══════════════════\nMEMORY [50% — 100/200]\n══════════════════\nUser runs macOS";
        let result = assemble(&AssembleParams {
            tools: &reg,
            agents_md: &[],
            skills: &[],
            facts: &[],
            project_memory_status: None,
            personality: None,
            soul: None,
            task: None,
            role: None,
            mode: &AgentMode::Full,
            memory: Some(mem),
            user_profile: None,
            cwd: None,
            learning_enabled: false,
            guardrail_profile: None,
        });
        assert!(result.text.contains("MEMORY"));
        assert!(result.text.contains("User runs macOS"));
    }

    #[test]
    fn system_prompt_user_profile_included() {
        let reg = make_registry();
        let user =
            "══════════════════\nUSER PROFILE [30% — 42/140]\n══════════════════\nPrefers concise";
        let result = assemble(&AssembleParams {
            tools: &reg,
            agents_md: &[],
            skills: &[],
            facts: &[],
            project_memory_status: None,
            personality: None,
            soul: None,
            task: None,
            role: None,
            mode: &AgentMode::Full,
            memory: None,
            user_profile: Some(user),
            cwd: None,
            learning_enabled: false,
            guardrail_profile: None,
        });
        assert!(result.text.contains("USER PROFILE"));
        assert!(result.text.contains("Prefers concise"));
    }

    #[test]
    fn system_prompt_empty_memory_skipped() {
        let reg = make_registry();
        let result = assemble(&AssembleParams {
            tools: &reg,
            agents_md: &[],
            skills: &[],
            facts: &[],
            project_memory_status: None,
            personality: None,
            soul: None,
            task: None,
            role: None,
            mode: &AgentMode::Full,
            memory: Some(""),
            user_profile: Some(""),
            cwd: None,
            learning_enabled: false,
            guardrail_profile: None,
        });
        assert!(!result.text.contains("MEMORY"));
        assert!(!result.text.contains("USER PROFILE"));
    }

    #[test]
    fn system_prompt_memory_after_all_other_layers() {
        let reg = make_registry();
        let agents = vec![make_agents_md("Project context.")];
        let skills = vec![make_skill("rust", "Rust", "/skills/rust/SKILL.md")];
        let facts = vec![Fact {
            text: "Uses SQLite".into(),
            verified_ago: "1h".into(),
        }];
        let task = TaskContext {
            title: "Fix bug".into(),
            description: "Broken".into(),
            acceptance: None,
            verify: None,
            notes: None,
            attempts: vec![],
            dependencies: vec![],
            decisions: vec![],
            context_paths: vec![],
            constraints: vec![],
        };
        let mem = "══════\nMEMORY [50%]\n══════\nSome fact";
        let result = assemble(&AssembleParams {
            tools: &reg,
            agents_md: &agents,
            skills: &skills,
            facts: &facts,
            project_memory_status: None,
            personality: None,
            soul: None,
            task: Some(&task),
            role: None,
            mode: &AgentMode::Full,
            memory: Some(mem),
            user_profile: None,
            cwd: None,
            learning_enabled: false,
            guardrail_profile: None,
        });

        let identity_pos = result.text.find("You are imp").unwrap();
        let context_pos = result.text.find("# Project Context").unwrap();
        let facts_pos = result.text.find("Project facts").unwrap();
        let task_pos = result.text.find("## Task").unwrap();
        let memory_pos = result.text.find("MEMORY").unwrap();

        assert!(identity_pos < context_pos);
        assert!(context_pos < facts_pos);
        assert!(facts_pos < task_pos);
        assert!(task_pos < memory_pos, "memory should come after task");
    }
}