-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathphase_prompt.rs
More file actions
991 lines (918 loc) · 44.6 KB
/
Copy pathphase_prompt.rs
File metadata and controls
991 lines (918 loc) · 44.6 KB
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
use std::collections::HashMap;
use crate::agent_state::{list_agent_messages, load_agent_memory, AgentMessage};
use crate::config_context::RuntimeConfigContext;
use crate::phase_output::{build_workflow_pipeline_context, format_prior_phase_outputs, load_prior_phase_outputs};
use orchestrator_config::{AgentChannelConfig, AgentProfile, SkillApplicationResult};
use serde::Serialize;
use serde_json::{Map, Value};
pub struct PhasePromptParams<'a> {
pub project_root: &'a str,
pub execution_cwd: &'a str,
pub workflow_id: &'a str,
pub subject_id: &'a str,
pub subject_title: &'a str,
pub subject_description: &'a str,
pub phase_id: &'a str,
pub rework_context: Option<&'a str>,
pub pipeline_vars: Option<&'a HashMap<String, String>>,
pub dispatch_input: Option<&'a str>,
pub schedule_input: Option<&'a str>,
}
pub struct PhaseRenderParams<'a> {
pub project_root: &'a str,
pub execution_cwd: &'a str,
pub workflow_id: &'a str,
pub subject_id: &'a str,
pub subject_title: &'a str,
pub subject_description: &'a str,
pub phase_id: &'a str,
}
pub(crate) const WORKFLOW_PHASE_PROMPT_TEMPLATE: &str =
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/prompts/runtime/workflow_phase.prompt"));
#[derive(Debug, Clone, Default, Serialize)]
pub struct PhasePromptInputs {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rework_context: Option<String>,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub pipeline_vars: HashMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub dispatch_input: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub schedule_input: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct RenderedPhasePrompt {
pub project_root: String,
pub execution_cwd: String,
pub workflow_id: String,
pub subject_id: String,
pub subject_title: String,
pub subject_description: String,
pub phase_id: String,
pub inputs: PhasePromptInputs,
pub capabilities: protocol::PhaseCapabilities,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub phase_output_contract: Option<orchestrator_core::PhaseOutputContract>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub phase_decision_contract: Option<orchestrator_core::PhaseDecisionContract>,
pub phase_directive: String,
pub phase_action_rule: String,
pub product_change_rule: String,
pub phase_safety_rules: String,
pub phase_decision_rule: String,
pub structured_result_rule: String,
pub pipeline_context: String,
pub prior_phase_outputs: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub system_prompt: Option<String>,
pub phase_prompt_body: String,
pub final_prompt: String,
}
pub fn build_phase_prompt(params: &PhasePromptParams<'_>) -> String {
let inputs = PhasePromptInputs {
rework_context: params.rework_context.map(ToOwned::to_owned),
pipeline_vars: params.pipeline_vars.cloned().unwrap_or_default(),
dispatch_input: params.dispatch_input.map(ToOwned::to_owned),
schedule_input: params.schedule_input.map(ToOwned::to_owned),
};
let ctx = RuntimeConfigContext::load(params.project_root);
render_phase_prompt_with_ctx(
&ctx,
&PhaseRenderParams {
project_root: params.project_root,
execution_cwd: params.execution_cwd,
workflow_id: params.workflow_id,
subject_id: params.subject_id,
subject_title: params.subject_title,
subject_description: params.subject_description,
phase_id: params.phase_id,
},
inputs,
)
.final_prompt
}
pub fn render_phase_prompt(params: &PhaseRenderParams<'_>, inputs: PhasePromptInputs) -> RenderedPhasePrompt {
let ctx = RuntimeConfigContext::load(params.project_root);
render_phase_prompt_with_ctx(&ctx, params, inputs)
}
pub fn render_phase_prompt_with_ctx(
ctx: &RuntimeConfigContext,
params: &PhaseRenderParams<'_>,
inputs: PhasePromptInputs,
) -> RenderedPhasePrompt {
render_phase_prompt_with_ctx_overrides(ctx, params, inputs, None, None)
}
pub fn render_phase_prompt_with_ctx_overrides(
ctx: &RuntimeConfigContext,
params: &PhaseRenderParams<'_>,
inputs: PhasePromptInputs,
capabilities_override: Option<protocol::PhaseCapabilities>,
skill_result: Option<&SkillApplicationResult>,
) -> RenderedPhasePrompt {
let project_root = params.project_root;
let execution_cwd = params.execution_cwd;
let workflow_id = params.workflow_id;
let subject_id = params.subject_id;
let subject_title = params.subject_title;
let subject_description = params.subject_description;
let phase_id = params.phase_id;
let caps = capabilities_override.unwrap_or_else(|| ctx.phase_capabilities(phase_id));
let agent_id = ctx.phase_agent_id(phase_id);
let agent_profile = agent_id.as_deref().and_then(|id| ctx.agent_runtime_config.agent_profile(id));
let phase_decision_contract = ctx.phase_decision_contract(phase_id).cloned();
let phase_action_rule = phase_action_rule(&caps);
let phase_contract = ctx.phase_output_contract(phase_id).cloned();
let require_commit_message = phase_requires_commit_message_with_ctx(ctx, phase_id);
let product_change_rule = if caps.enforce_product_changes {
"- For this phase, changes must include product source/config/test files outside `.animus/` unless the task is explicitly documentation-only."
} else {
""
};
let phase_directive = ctx.phase_directive(phase_id);
let phase_safety_rules = phase_safety_rules(&caps);
let decision_extra_field_rule =
phase_decision_contract.as_ref().map(phase_decision_extra_field_rule).unwrap_or_default();
let result_field_description_rule = phase_contract.as_ref().map(phase_output_field_rule).unwrap_or_default();
let structured_result_rule = match (phase_contract.as_ref(), phase_decision_contract.as_ref()) {
(Some(contract), Some(_)) => {
let required_fields = if contract.required_fields.is_empty() {
"- The top-level result object has no extra required fields beyond its kind.".to_string()
} else {
format!(
"- The top-level result object must include these required fields: {}.",
contract.required_fields.iter().map(|field| format!("`{field}`")).collect::<Vec<_>>().join(", ")
)
};
let result_example = phase_result_example_for_prompt(contract, phase_id, phase_decision_contract.as_ref());
format!(
"- Before finishing, emit one JSON line as the FINAL line of output with your phase result and nested phase decision:\n {}\n{}\n{}\n- Put any prose summary BEFORE the JSON line and emit nothing after it.",
result_example,
required_fields,
result_field_description_rule,
)
}
(Some(contract), None) => {
let result_rule = if require_commit_message {
format!(
"- Before finishing, emit one JSON line exactly like: {{\"kind\":\"{}\",\"commit_message\":\"<clear commit subject>\"}}.",
contract.kind
)
} else {
format!(
"- Before finishing, emit one JSON line as the FINAL line of output with kind `{}`.",
contract.kind
)
};
let required_fields = if contract.required_fields.is_empty() {
String::new()
} else {
format!(
"\n- Include these required result fields: {}.",
contract.required_fields.iter().map(|field| format!("`{field}`")).collect::<Vec<_>>().join(", ")
)
};
format!("{result_rule}{required_fields}\n{result_field_description_rule}")
}
(None, _) => String::new(),
};
let phase_decision_rule = if phase_contract.is_some() {
if phase_decision_contract.is_some() {
format!(
"- The nested `phase_decision` object must describe whether this phase should advance, rework, fail, or skip.\n- Set `phase_decision.verdict` to `advance` if work is complete and correct.\n- Set `phase_decision.verdict` to `rework` if issues remain that need another pass.\n- Set `phase_decision.verdict` to `fail` only if problems are unrecoverable.\n- Set `phase_decision.verdict` to `skip` to close the task without further work. Use with a reason from: `already_done`, `duplicate`, `no_longer_valid`, `out_of_scope`.\n{}",
decision_extra_field_rule
)
} else {
String::new()
}
} else if let Some(contract) = phase_decision_contract.as_ref() {
let required_evidence = if contract.required_evidence.is_empty() {
"- Include evidence entries when they materially support your verdict.\n - If you analyzed code/files but did not modify any files, include evidence with kind \"no_changes_needed\" explaining why (e.g., \"code already meets requirements\", \"no issues found\", \"working as designed\").".to_string()
} else {
format!(
"- Evidence must include these kinds when applicable: {}.\n - If you analyzed code/files but did not modify any files, include evidence with kind \"no_changes_needed\" explaining why (e.g., \"code already meets requirements\", \"no issues found\", \"working as designed\").",
contract
.required_evidence
.iter()
.map(|kind| serde_json::to_string(kind).unwrap_or_else(|_| "\"custom\"".to_string()))
.collect::<Vec<_>>()
.join(", ")
)
};
let missing_decision_rule = if contract.allow_missing_decision {
""
} else {
"\n- A missing phase_decision is invalid. Do not finish without emitting it."
};
let decision_example = phase_decision_example_for_prompt(phase_id, Some(contract));
format!(
"- Before finishing, emit one JSON line with your phase assessment as the FINAL line of output:\n {}\n- Set verdict to \"advance\" if work is complete and correct.\n- Set verdict to \"rework\" if issues remain that need another pass.\n- Set verdict to \"fail\" only if problems are unrecoverable.\n- Set verdict to \"skip\" to close the task without further work. Use with a reason from: \"already_done\", \"duplicate\", \"no_longer_valid\", \"out_of_scope\".\n- Confidence must be at least {} unless you truly cannot justify a decision.\n- Risk must not exceed {:?} unless you are explicitly failing the phase.\n{}\n{}\n- Put any prose summary BEFORE the JSON line and emit nothing after it.{}",
decision_example,
contract.min_confidence,
contract.max_risk,
required_evidence,
decision_extra_field_rule,
missing_decision_rule
)
} else {
String::new()
};
let (pipeline_context, phase_order) = build_workflow_pipeline_context(project_root, workflow_id, phase_id);
let prior_outputs = load_prior_phase_outputs(project_root, workflow_id, phase_id, &phase_order);
let prior_phase_context = format_prior_phase_outputs(&prior_outputs);
let rework_context = inputs.rework_context.as_deref().map(str::trim).filter(|value| !value.is_empty());
let mut prior_context = prior_phase_context;
if let Some(context) = rework_context {
prior_context.push_str("\n\nFailure context:\n");
prior_context.push_str(context);
}
let mut phase_prompt = WORKFLOW_PHASE_PROMPT_TEMPLATE
.replace("__PROJECT_ROOT__", project_root)
.replace("__EXECUTION_CWD__", execution_cwd)
.replace("__WORKFLOW_ID__", workflow_id)
.replace("__SUBJECT_ID__", subject_id)
.replace("__SUBJECT_TITLE__", subject_title)
.replace("__SUBJECT_DESCRIPTION__", subject_description)
.replace("__PHASE_ID__", phase_id)
.replace("__PHASE_DIRECTIVE__", phase_directive.trim())
.replace("__PHASE_ACTION_RULE__", phase_action_rule)
.replace("__PRODUCT_CHANGE_RULE__", product_change_rule)
.replace("__PHASE_SAFETY_RULES__", phase_safety_rules)
.replace("__PHASE_DECISION_RULE__", &phase_decision_rule)
.replace("__IMPLEMENTATION_COMMIT_RULE__", structured_result_rule.as_str())
.replace("__WORKFLOW_PIPELINE_CONTEXT__", &pipeline_context)
.replace("__PRIOR_PHASE_OUTPUTS__", &prior_context);
if !inputs.pipeline_vars.is_empty() {
phase_prompt = orchestrator_core::workflow_config::expand_variables(&phase_prompt, &inputs.pipeline_vars);
}
if let Some(dispatch_input) = inputs.dispatch_input.as_deref().filter(|value| !value.is_empty()) {
phase_prompt.push_str("\n\nDispatch input:\n");
phase_prompt.push_str(dispatch_input);
} else if let Some(schedule_input) = inputs.schedule_input.as_deref().filter(|value| !value.is_empty()) {
phase_prompt.push_str("\n\nSchedule trigger input:\n");
phase_prompt.push_str(schedule_input);
}
let mut prompt_sections = Vec::new();
if let Some(skill_result) = skill_result {
for prefix in &skill_result.prompt_prefixes {
if let Some(expanded) = expand_prompt_fragment(prefix, &inputs.pipeline_vars) {
prompt_sections.push(expanded);
}
}
if !skill_result.directives.is_empty() {
let directives = skill_result
.directives
.iter()
.filter_map(|directive| expand_prompt_fragment(directive, &inputs.pipeline_vars))
.collect::<Vec<_>>();
if let Some(section) = skill_directives_section(&directives) {
prompt_sections.push(section);
}
}
}
if let (Some(agent_id), Some(profile)) = (agent_id.as_deref(), agent_profile) {
if let Some(memory_context) = render_agent_memory_context(project_root, agent_id, profile) {
prompt_sections.push(memory_context);
}
if let Some(message_context) = render_agent_message_context(project_root, agent_id, profile, ctx) {
prompt_sections.push(message_context);
}
if let Some(coaching) = render_agent_coordination_coaching(agent_id, profile) {
prompt_sections.push(coaching);
}
}
prompt_sections.push(phase_prompt);
if let Some(skill_result) = skill_result {
for suffix in &skill_result.prompt_suffixes {
if let Some(expanded) = expand_prompt_fragment(suffix, &inputs.pipeline_vars) {
prompt_sections.push(expanded);
}
}
}
let phase_prompt_body = prompt_sections.join("\n\n");
let mut system_prompt_sections = Vec::new();
if let Some(profile) = agent_profile {
if let Some(agent_context) = render_agent_identity_context(agent_id.as_deref(), profile) {
system_prompt_sections.push(agent_context);
}
}
if let Some(prompt) = ctx.phase_system_prompt(phase_id) {
if let Some(expanded) = expand_prompt_fragment(&prompt, &inputs.pipeline_vars) {
system_prompt_sections.push(expanded);
}
}
if let Some(skill_result) = skill_result {
for fragment in &skill_result.system_prompt_fragments {
if let Some(expanded) = expand_prompt_fragment(fragment, &inputs.pipeline_vars) {
system_prompt_sections.push(expanded);
}
}
}
let system_prompt = (!system_prompt_sections.is_empty()).then(|| system_prompt_sections.join("\n\n"));
let final_prompt = match system_prompt.as_deref() {
Some(system_prompt) => format!("{system_prompt}\n\n{phase_prompt_body}"),
None => phase_prompt_body.clone(),
};
RenderedPhasePrompt {
project_root: project_root.to_string(),
execution_cwd: execution_cwd.to_string(),
workflow_id: workflow_id.to_string(),
subject_id: subject_id.to_string(),
subject_title: subject_title.to_string(),
subject_description: subject_description.to_string(),
phase_id: phase_id.to_string(),
inputs,
capabilities: caps,
phase_output_contract: phase_contract,
phase_decision_contract,
phase_directive,
phase_action_rule: phase_action_rule.to_string(),
product_change_rule: product_change_rule.to_string(),
phase_safety_rules: phase_safety_rules.to_string(),
phase_decision_rule,
structured_result_rule,
pipeline_context,
prior_phase_outputs: prior_context,
system_prompt,
phase_prompt_body,
final_prompt,
}
}
/// Render a "Skill directives:" bullet section from already-expanded
/// directive lines. Returns `None` when no non-empty directive remains.
/// Shared core between the workflow phase renderer (which expands pipeline
/// vars per directive first) and the ad-hoc prompt assembly (which has no
/// pipeline vars).
pub fn skill_directives_section<S: AsRef<str>>(directives: &[S]) -> Option<String> {
let cleaned: Vec<&str> = directives.iter().map(|d| d.as_ref().trim()).filter(|d| !d.is_empty()).collect();
if cleaned.is_empty() {
return None;
}
let mut section = String::from("Skill directives:");
for directive in cleaned {
section.push_str("\n- ");
section.push_str(directive);
}
Some(section)
}
/// Wrap an ad-hoc prompt body with a skill's prompt fragments, in the SAME
/// order the workflow phase renderer applies them: prefixes first, then the
/// "Skill directives:" section, then the body, then suffixes — sections
/// joined by blank lines. No pipeline-var expansion happens here (ad-hoc runs
/// have no pipeline vars); empty/whitespace fragments are skipped. A skill
/// with no prompt fragments returns the body unchanged.
pub fn apply_skill_prompt_to_body(body: &str, skill: &SkillApplicationResult) -> String {
let mut sections: Vec<String> = Vec::new();
for prefix in &skill.prompt_prefixes {
let trimmed = prefix.trim();
if !trimmed.is_empty() {
sections.push(trimmed.to_string());
}
}
if let Some(directives) = skill_directives_section(&skill.directives) {
sections.push(directives);
}
if sections.is_empty() && skill.prompt_suffixes.iter().all(|s| s.trim().is_empty()) {
return body.to_string();
}
sections.push(body.to_string());
for suffix in &skill.prompt_suffixes {
let trimmed = suffix.trim();
if !trimmed.is_empty() {
sections.push(trimmed.to_string());
}
}
sections.join("\n\n")
}
/// Merge an explicit caller-supplied system prompt with a skill's
/// `system_prompt_fragments`. The EXPLICIT value comes first (matching the
/// workflow renderer, where the configured phase system prompt precedes the
/// skill fragments), then each non-empty fragment, joined by blank lines.
/// Returns `None` when neither side contributes anything.
pub fn merge_skill_system_prompt(explicit: Option<&str>, skill: &SkillApplicationResult) -> Option<String> {
let mut sections: Vec<String> = Vec::new();
if let Some(explicit) = explicit.map(str::trim).filter(|value| !value.is_empty()) {
sections.push(explicit.to_string());
}
for fragment in &skill.system_prompt_fragments {
let trimmed = fragment.trim();
if !trimmed.is_empty() {
sections.push(trimmed.to_string());
}
}
(!sections.is_empty()).then(|| sections.join("\n\n"))
}
fn expand_prompt_fragment(fragment: &str, pipeline_vars: &HashMap<String, String>) -> Option<String> {
let trimmed = fragment.trim();
if trimmed.is_empty() {
return None;
}
if pipeline_vars.is_empty() {
return Some(trimmed.to_string());
}
Some(orchestrator_core::workflow_config::expand_variables(trimmed, pipeline_vars))
}
fn tail_chars(value: &str, max_chars: usize) -> String {
let count = value.chars().count();
if count <= max_chars {
return value.to_string();
}
value.chars().skip(count.saturating_sub(max_chars)).collect()
}
fn render_agent_identity_context(agent_id: Option<&str>, profile: &AgentProfile) -> Option<String> {
let mut lines = Vec::new();
if let Some(name) = profile.name.as_deref().map(str::trim).filter(|value| !value.is_empty()) {
lines.push(format!("Name: {name}"));
}
if let Some(agent_id) = agent_id.map(str::trim).filter(|value| !value.is_empty()) {
lines.push(format!("Profile id: {agent_id}"));
}
if let Some(persona) = profile.persona.as_ref() {
if let Some(style) = persona.style.as_deref().map(str::trim).filter(|value| !value.is_empty()) {
lines.push(format!("Style: {style}"));
}
if !persona.traits.is_empty() {
let traits = persona
.traits
.iter()
.map(String::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.collect::<Vec<_>>();
if !traits.is_empty() {
lines.push(format!("Traits: {}", traits.join(", ")));
}
}
if let Some(instructions) = persona.instructions.as_deref().map(str::trim).filter(|value| !value.is_empty()) {
lines.push(format!("Persona instructions:\n{instructions}"));
}
if !persona.customizations.is_empty() {
if let Ok(customizations) = serde_json::to_string(&persona.customizations) {
lines.push(format!("Customizations: {customizations}"));
}
}
}
(!lines.is_empty()).then(|| format!("Agent identity:\n{}", lines.join("\n")))
}
/// Append a SHORT coaching paragraph telling the agent the coordination tools
/// exist and when to reach for them — but ONLY when the agent's profile
/// actually carries the capability, so phases without memory/messaging stay
/// free of prompt bloat. Memory coaching is gated on the same condition that
/// injects the memory MCP server (`agent_memory_capability_enabled`, i.e.
/// `capabilities.memory: true`) — NOT on `memory.enabled`, which only surfaces
/// read-only memory context. Coaching an agent to call `animus.memory.append`
/// when no memory tool is injected would point it at an unavailable tool.
/// Messaging coaching gates on `communication.enabled` with at least one
/// channel; it names the `animus.agent.message.send` MCP tool only when the
/// profile's `mcp_servers` actually includes the full `animus` server (the
/// only surface that exposes it), and falls back to the equivalent CLI
/// command otherwise. Returns `None` when neither capability is on.
fn render_agent_coordination_coaching(agent_id: &str, profile: &AgentProfile) -> Option<String> {
let memory_on = orchestrator_config::agent_memory_capability_enabled(profile);
let messaging_on = profile.communication.enabled
&& profile.communication.channels.iter().any(|channel| !channel.trim().is_empty());
if !memory_on && !messaging_on {
return None;
}
let mut lines = vec!["Coordination tools:".to_string()];
if memory_on {
lines.push(format!(
"- If your findings should influence later phases, append them to your durable memory via the `animus.memory.append` MCP tool (`agent_id` = `{agent_id}`; the full `animus mcp serve` surface exposes the same store as `animus.agent.memory.append`). Memory is per-agent: later phases run by this same agent profile see recent entries in their prompt automatically, but other agents do not — hand off to a different agent via a channel message instead. Oldest entries are trimmed FIFO once the cap is reached."
));
}
if messaging_on {
let channels = profile
.communication
.channels
.iter()
.map(|channel| channel.trim())
.filter(|channel| !channel.is_empty())
.map(|channel| format!("`{channel}`"))
.collect::<Vec<_>>()
.join(", ");
let has_animus_server = profile.mcp_servers.iter().any(|server| server.trim().eq_ignore_ascii_case("animus"));
let send_surface = if has_animus_server {
"the `animus.agent.message.send` MCP tool".to_string()
} else {
format!("the `animus agent message send --channel <channel> --from {agent_id}` CLI command")
};
lines.push(format!(
"- To hand off to a named agent, send a message on one of your channels ({channels}) via {send_surface}; recent channel messages are surfaced in the recipient's prompt."
));
}
Some(lines.join("\n"))
}
fn render_agent_memory_context(project_root: &str, agent_id: &str, profile: &AgentProfile) -> Option<String> {
if !profile.memory.enabled {
return None;
}
let memory = load_agent_memory(project_root, agent_id).ok()?;
if memory.entries.is_empty() {
return None;
}
let mut sections = Vec::new();
for entry in memory.entries.iter().rev().take(20).rev() {
let mut line = format!("- [{}] {}", entry.created_at, entry.text.trim());
if let Some(source) = entry.source.as_deref().map(str::trim).filter(|value| !value.is_empty()) {
line.push_str(&format!(" (source: {source})"));
}
sections.push(line);
}
let max_chars = profile.memory.max_context_chars.unwrap_or(4000);
Some(format!("Agent memory:\n{}", tail_chars(§ions.join("\n"), max_chars)))
}
fn channel_context_limit(channel: Option<&AgentChannelConfig>, profile: &AgentProfile) -> usize {
profile
.communication
.max_context_chars
.or_else(|| channel.and_then(|config| config.max_context_chars))
.unwrap_or(4000)
}
fn message_visible_to_agent(message: &AgentMessage, agent_id: &str) -> bool {
message.from_agent.eq_ignore_ascii_case(agent_id)
|| message.to_agent.as_deref().is_none()
|| message.to_agent.as_deref().is_some_and(|target| target.eq_ignore_ascii_case(agent_id))
}
fn render_agent_message_context(
project_root: &str,
agent_id: &str,
profile: &AgentProfile,
ctx: &RuntimeConfigContext,
) -> Option<String> {
if !profile.communication.enabled || profile.communication.channels.is_empty() {
return None;
}
let mut sections = Vec::new();
for channel in &profile.communication.channels {
let channel_name = channel.trim();
if channel_name.is_empty() {
continue;
}
let channel_config = ctx.workflow_config.config.agent_channels.get(channel_name);
let messages = list_agent_messages(project_root, Some(channel_name), None, Some(20)).ok()?;
let visible =
messages.into_iter().filter(|message| message_visible_to_agent(message, agent_id)).collect::<Vec<_>>();
if visible.is_empty() {
continue;
}
let mut lines = Vec::new();
for message in visible {
let target = message.to_agent.as_deref().map(|target| format!(" -> {target}")).unwrap_or_default();
lines.push(format!("- [{}] {}{}: {}", message.created_at, message.from_agent, target, message.text.trim()));
}
let max_chars = channel_context_limit(channel_config, profile);
sections.push(format!("Channel `{channel_name}` messages:\n{}", tail_chars(&lines.join("\n"), max_chars)));
}
(!sections.is_empty()).then(|| format!("Agent communication context:\n{}", sections.join("\n\n")))
}
fn phase_decision_example_for_prompt(
phase_id: &str,
contract: Option<&orchestrator_core::PhaseDecisionContract>,
) -> String {
let mut object = Map::new();
object.insert("kind".to_string(), Value::String("phase_decision".to_string()));
object.insert("phase_id".to_string(), Value::String(phase_id.to_string()));
object.insert("verdict".to_string(), Value::String("advance|rework|fail|skip".to_string()));
object.insert("confidence".to_string(), serde_json::json!(0.95));
object.insert("risk".to_string(), Value::String("low|medium|high".to_string()));
object.insert("reason".to_string(), Value::String("...".to_string()));
object.insert(
"evidence".to_string(),
Value::Array(vec![serde_json::json!({
"kind": "...",
"description": "..."
})]),
);
if let Some(contract) = contract {
for (field_name, field) in &contract.fields {
object.insert(field_name.clone(), phase_field_placeholder(field_name, field));
}
}
serde_json::to_string(&Value::Object(object)).unwrap_or_else(|_| "{\"kind\":\"phase_decision\"}".to_string())
}
fn phase_result_example_for_prompt(
contract: &orchestrator_core::PhaseOutputContract,
phase_id: &str,
decision_contract: Option<&orchestrator_core::PhaseDecisionContract>,
) -> String {
let mut object = Map::new();
object.insert("kind".to_string(), Value::String(contract.kind.clone()));
for field_name in &contract.required_fields {
object.insert(field_name.clone(), Value::String(format!("<{}>", field_name.replace('_', " "))));
}
for (field_name, field) in &contract.fields {
object.insert(field_name.clone(), phase_field_placeholder(field_name, field));
}
object.insert(
"phase_decision".to_string(),
serde_json::from_str::<Value>(&phase_decision_example_for_prompt(phase_id, decision_contract))
.unwrap_or_else(|_| Value::Object(Map::new())),
);
serde_json::to_string(&Value::Object(object)).unwrap_or_else(|_| {
format!("{{\"kind\":\"{}\",\"phase_decision\":{{\"kind\":\"phase_decision\"}}}}", contract.kind)
})
}
fn phase_field_placeholder(
field_name: &str,
field: &orchestrator_core::agent_runtime_config::PhaseFieldDefinition,
) -> Value {
match field.field_type.as_str() {
"string" => field
.enum_values
.first()
.map(|value| Value::String(value.clone()))
.unwrap_or_else(|| Value::String(format!("<{}>", field_name.replace('_', " ")))),
"number" => serde_json::json!(0.0),
"integer" => serde_json::json!(0),
"boolean" => Value::Bool(false),
"array" => Value::Array(vec![field
.items
.as_ref()
.map(|item| phase_field_placeholder(field_name, item))
.unwrap_or_else(|| Value::String("...".to_string()))]),
"object" => {
let mut map = Map::new();
for (nested_name, nested_field) in &field.fields {
map.insert(nested_name.clone(), phase_field_placeholder(nested_name, nested_field));
}
Value::Object(map)
}
_ => Value::String(format!("<{}>", field_name.replace('_', " "))),
}
}
fn phase_output_field_rule(contract: &orchestrator_core::PhaseOutputContract) -> String {
if contract.fields.is_empty() {
return String::new();
}
let mut lines = vec!["- The top-level result object may include these config-defined fields:".to_string()];
for (field_name, field) in &contract.fields {
lines.push(format!(
" - `{field_name}` ({}){}{}",
field.field_type,
if field.required { ", required" } else { "" },
field.description.as_deref().map(|value| format!(": {value}")).unwrap_or_default()
));
}
lines.join("\n")
}
fn phase_decision_extra_field_rule(contract: &orchestrator_core::PhaseDecisionContract) -> String {
let mut lines = Vec::new();
let mut required_fields = contract
.fields
.iter()
.filter_map(|(field_name, field)| if field.required { Some(field_name.clone()) } else { None })
.collect::<Vec<_>>();
if let Some(schema) = contract.extra_json_schema.as_ref() {
let extra_required = schema
.get("required")
.and_then(serde_json::Value::as_array)
.map(|items| items.iter().filter_map(serde_json::Value::as_str).map(ToOwned::to_owned).collect::<Vec<_>>())
.unwrap_or_default();
for field_name in extra_required {
if !required_fields.iter().any(|existing| existing.eq_ignore_ascii_case(&field_name)) {
required_fields.push(field_name);
}
}
}
if !required_fields.is_empty() {
lines.push(format!(
"- The `phase_decision` object must also include these config-required fields: {}.",
required_fields.iter().map(|field| format!("`{field}`")).collect::<Vec<_>>().join(", ")
));
}
let mut optional_fields = contract
.fields
.keys()
.filter(|field| !required_fields.iter().any(|required| required == *field))
.cloned()
.collect::<Vec<_>>();
if let Some(schema) = contract.extra_json_schema.as_ref() {
let property_names = schema
.get("properties")
.and_then(serde_json::Value::as_object)
.map(|properties| properties.keys().cloned().collect::<Vec<_>>())
.unwrap_or_default();
for field_name in property_names {
if !required_fields.iter().any(|required| required == &field_name)
&& !optional_fields.iter().any(|existing| existing == &field_name)
{
optional_fields.push(field_name);
}
}
}
let optional_fields = optional_fields.into_iter().collect::<Vec<_>>();
if !optional_fields.is_empty() {
lines.push(format!(
"- The `phase_decision` object may include these additional config-defined fields when relevant: {}.",
optional_fields.iter().map(|field| format!("`{field}`")).collect::<Vec<_>>().join(", ")
));
}
if !contract.fields.is_empty() {
lines.push("- Decision field descriptions:".to_string());
for (field_name, field) in &contract.fields {
let detail = field.description.as_deref().unwrap_or("No description provided.");
lines.push(format!(
" - `{field_name}` ({}){}: {}",
field.field_type,
if field.required { ", required" } else { "" },
detail
));
}
}
lines.join("\n")
}
pub(crate) fn phase_safety_rules(caps: &protocol::PhaseCapabilities) -> &'static str {
if caps.is_research {
return "- For research phases, treat greenfield repositories as valid: missing app source files is not a blocker by itself.\n- Do targeted discovery only: inspect first-party code (`src/`, `apps/`, `db/`, `tests/`) and active `.animus` task/requirement docs; avoid broad recursive listings.\n- Do not scan dependency or checkpoint trees unless explicitly required: skip `node_modules/`, `.git/`, and scoped runtime state under `~/.animus/<scope>/`.\n- If code context is limited, produce concrete assumptions, risks, and a build-ready plan in repository artifacts instead of stopping.";
}
""
}
pub(crate) fn phase_action_rule(caps: &protocol::PhaseCapabilities) -> &'static str {
if caps.writes_files {
return "Requirements:\n- Make concrete file changes in this repository.\n- When you analyze code but determine no changes are needed, explain why in your phase decision evidence (use kind \"no_changes_needed\").";
}
if caps.mutates_state {
return "Requirements:\n- Do NOT create, edit, or write repository files.\n- You may use approved Animus/MCP/runtime operations to perform the state mutations required by this phase.\n- Keep those mutations scoped to the current task, workflow, or managed system state, then emit the required structured phase result.";
}
"Requirements:\n- This is a READ-ONLY phase. Do NOT create, edit, or write any files. Do NOT run commands that modify the repository.\n- Read and analyze the codebase to assess the task. Your only output should be your assessment and phase decision."
}
pub fn phase_requires_commit_message(phase_id: &str) -> bool {
protocol::PhaseCapabilities::defaults_for_phase(phase_id).requires_commit
}
pub fn phase_requires_commit_message_with_config(project_root: &str, phase_id: &str) -> bool {
let ctx = RuntimeConfigContext::load(project_root);
phase_requires_commit_message_with_ctx(&ctx, phase_id)
}
pub fn phase_requires_commit_message_with_ctx(ctx: &RuntimeConfigContext, phase_id: &str) -> bool {
ctx.phase_output_contract(phase_id)
.map(|contract| contract.requires_field("commit_message"))
.unwrap_or_else(|| phase_requires_commit_message(phase_id))
}
pub fn phase_result_kind_for_ctx(ctx: &RuntimeConfigContext, phase_id: &str) -> String {
ctx.phase_output_contract(phase_id)
.map(|contract| contract.kind.clone())
.filter(|kind| !kind.trim().is_empty())
.unwrap_or_else(|| "implementation_result".to_string())
}
#[cfg(test)]
mod tests {
use super::{
apply_skill_prompt_to_body, merge_skill_system_prompt, phase_action_rule, render_agent_coordination_coaching,
skill_directives_section, SkillApplicationResult,
};
use orchestrator_config::{AgentCommunicationConfig, AgentMemoryConfig, AgentProfile};
// Memory coaching gates on the `memory` capability flag (the one that
// actually injects the memory MCP server), not on `memory.enabled`.
fn profile_with_memory_capability() -> AgentProfile {
let mut profile =
AgentProfile { memory: AgentMemoryConfig { enabled: true, ..Default::default() }, ..Default::default() };
profile.capabilities.insert("memory".to_string(), true);
profile
}
#[test]
fn coaching_absent_when_no_capability_is_on() {
let profile = AgentProfile::default();
assert!(
render_agent_coordination_coaching("architect", &profile).is_none(),
"no memory/messaging capability must add no coaching paragraph (no prompt bloat)"
);
}
#[test]
fn coaching_absent_when_memory_enabled_but_capability_off() {
// `memory.enabled: true` surfaces read-only memory context but injects
// no memory tool, so coaching must stay silent to avoid pointing the
// agent at an unavailable `animus.memory.append`.
let profile =
AgentProfile { memory: AgentMemoryConfig { enabled: true, ..Default::default() }, ..Default::default() };
assert!(
render_agent_coordination_coaching("architect", &profile).is_none(),
"memory.enabled without the memory capability must not coach a missing tool"
);
}
#[test]
fn coaching_mentions_memory_only_when_memory_enabled() {
let profile = profile_with_memory_capability();
let coaching = render_agent_coordination_coaching("architect", &profile).expect("memory coaching present");
assert!(
coaching.contains("`animus.memory.append`"),
"primary tool is animus.memory.append — the one the injected memory MCP server actually exposes"
);
assert!(coaching.contains("animus.agent.memory.append"), "full-serve equivalent also named");
assert!(coaching.contains("architect"), "agent id threaded into coaching");
assert!(!coaching.contains("animus.agent.message.send"), "no messaging line without channels");
}
#[test]
fn coaching_mentions_messaging_only_when_channels_present() {
// communication enabled but with no usable channel → no messaging line.
let enabled_no_channel = AgentProfile {
communication: AgentCommunicationConfig {
enabled: true,
channels: vec![" ".to_string()],
..Default::default()
},
..Default::default()
};
assert!(
render_agent_coordination_coaching("architect", &enabled_no_channel).is_none(),
"blank channel does not count as messaging capability"
);
// Without the full `animus` MCP server, coaching must point at the
// CLI command — the animus.agent.message.send tool is not injected.
let profile = AgentProfile {
communication: AgentCommunicationConfig {
enabled: true,
channels: vec!["engineering".to_string()],
..Default::default()
},
..Default::default()
};
let coaching = render_agent_coordination_coaching("architect", &profile).expect("messaging coaching present");
assert!(!coaching.contains("animus.agent.message.send"), "MCP tool not named without the animus server");
assert!(coaching.contains("animus agent message send"), "CLI fallback named instead");
assert!(coaching.contains("`engineering`"), "channel named in coaching");
assert!(!coaching.contains("animus.agent.memory.append"), "no memory line when memory disabled");
// With the full `animus` server configured, the MCP tool is named.
let mut with_server = AgentProfile {
communication: AgentCommunicationConfig {
enabled: true,
channels: vec!["engineering".to_string()],
..Default::default()
},
..Default::default()
};
with_server.mcp_servers = vec!["animus".to_string()];
let coaching =
render_agent_coordination_coaching("architect", &with_server).expect("messaging coaching present");
assert!(coaching.contains("animus.agent.message.send"), "MCP tool named when the animus server is configured");
}
#[test]
fn coaching_combines_both_capabilities() {
let mut profile = profile_with_memory_capability();
profile.communication =
AgentCommunicationConfig { enabled: true, channels: vec!["engineering".to_string()], ..Default::default() };
profile.mcp_servers = vec!["animus".to_string()];
let coaching = render_agent_coordination_coaching("architect", &profile).expect("coaching present");
assert!(coaching.contains("animus.agent.memory.append"));
assert!(coaching.contains("animus.agent.message.send"));
}
#[test]
fn mutating_state_phases_are_not_rendered_as_strictly_read_only() {
let rule = phase_action_rule(&protocol::PhaseCapabilities { mutates_state: true, ..Default::default() });
assert!(rule.contains("Animus/MCP/runtime operations"));
assert!(!rule.contains("READ-ONLY phase"));
}
#[test]
fn strict_read_only_phases_keep_read_only_guidance() {
let rule = phase_action_rule(&protocol::PhaseCapabilities::default());
assert!(rule.contains("READ-ONLY phase"));
}
fn skill_with_prompt() -> SkillApplicationResult {
SkillApplicationResult {
system_prompt_fragments: vec!["You are skill-guided.".to_string()],
prompt_prefixes: vec!["PREFIX-TEXT".to_string()],
prompt_suffixes: vec!["SUFFIX-TEXT".to_string()],
directives: vec!["Directive one".to_string(), "Directive two".to_string()],
..Default::default()
}
}
#[test]
fn apply_skill_prompt_to_body_orders_prefix_directives_body_suffix() {
let wrapped = apply_skill_prompt_to_body("THE-BODY", &skill_with_prompt());
let expected = "PREFIX-TEXT\n\nSkill directives:\n- Directive one\n- Directive two\n\nTHE-BODY\n\nSUFFIX-TEXT";
assert_eq!(wrapped, expected);
}
#[test]
fn apply_skill_prompt_to_body_without_fragments_returns_body_unchanged() {
let wrapped = apply_skill_prompt_to_body("THE-BODY", &SkillApplicationResult::default());
assert_eq!(wrapped, "THE-BODY");
}
#[test]
fn apply_skill_prompt_to_body_skips_blank_fragments() {
let skill = SkillApplicationResult {
prompt_prefixes: vec![" ".to_string()],
prompt_suffixes: vec!["TAIL".to_string()],
..Default::default()
};
assert_eq!(apply_skill_prompt_to_body("BODY", &skill), "BODY\n\nTAIL");
}
#[test]
fn merge_skill_system_prompt_puts_explicit_value_first() {
let merged = merge_skill_system_prompt(Some("EXPLICIT"), &skill_with_prompt()).expect("merged");
assert_eq!(merged, "EXPLICIT\n\nYou are skill-guided.");
}
#[test]
fn merge_skill_system_prompt_without_explicit_uses_fragments_only() {
let merged = merge_skill_system_prompt(None, &skill_with_prompt()).expect("merged");
assert_eq!(merged, "You are skill-guided.");
}
#[test]
fn merge_skill_system_prompt_returns_none_when_nothing_contributes() {
assert!(merge_skill_system_prompt(None, &SkillApplicationResult::default()).is_none());
assert!(merge_skill_system_prompt(Some(" "), &SkillApplicationResult::default()).is_none());
}
#[test]
fn skill_directives_section_skips_empty_lines() {
assert!(skill_directives_section::<&str>(&[]).is_none());
assert!(skill_directives_section(&[" "]).is_none());
assert_eq!(skill_directives_section(&["One", " "]).as_deref(), Some("Skill directives:\n- One"));
}
}