1use std::collections::{BTreeMap, BTreeSet};
2use std::fs;
3use std::path::{Path, PathBuf};
4
5use harn_parser::{Attribute, Node, SNode};
6use serde::{Deserialize, Serialize};
7use std::str::FromStr;
8
9#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
10pub struct PersonaManifestDocument {
11 #[serde(default)]
12 pub personas: Vec<PersonaManifestEntry>,
13}
14
15#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
21pub struct PersonaOutputStyle {
22 #[serde(default, skip_serializing_if = "Option::is_none")]
23 pub name: Option<String>,
24 #[serde(default, skip_serializing_if = "Option::is_none")]
25 pub instructions: Option<String>,
26}
27
28impl PersonaOutputStyle {
29 pub fn from_name(name: impl Into<String>) -> Self {
31 Self {
32 name: Some(name.into()),
33 instructions: None,
34 }
35 }
36
37 pub fn is_empty(&self) -> bool {
39 self.name.is_none() && self.instructions.is_none()
40 }
41}
42
43impl<'de> Deserialize<'de> for PersonaOutputStyle {
44 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
45 where
46 D: serde::Deserializer<'de>,
47 {
48 #[derive(Deserialize)]
52 #[serde(untagged)]
53 enum Repr {
54 Name(String),
55 Table {
56 #[serde(default)]
57 name: Option<String>,
58 #[serde(default)]
59 instructions: Option<String>,
60 },
61 }
62 Ok(match Repr::deserialize(deserializer)? {
63 Repr::Name(name) => PersonaOutputStyle::from_name(name),
64 Repr::Table { name, instructions } => PersonaOutputStyle { name, instructions },
65 })
66 }
67}
68
69#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
70pub struct PersonaManifestEntry {
71 #[serde(default)]
72 pub name: Option<String>,
73 #[serde(default)]
74 pub version: Option<String>,
75 #[serde(default)]
76 pub description: Option<String>,
77 #[serde(default, alias = "entry", alias = "entry_pipeline")]
78 pub entry_workflow: Option<String>,
79 #[serde(default)]
80 pub tools: Vec<String>,
81 #[serde(default)]
82 pub capabilities: Vec<String>,
83 #[serde(default, alias = "tier", alias = "autonomy")]
84 pub autonomy_tier: Option<PersonaAutonomyTier>,
85 #[serde(default, alias = "receipts")]
86 pub receipt_policy: Option<PersonaReceiptPolicy>,
87 #[serde(default)]
88 pub triggers: Vec<String>,
89 #[serde(default)]
90 pub schedules: Vec<String>,
91 #[serde(default)]
92 pub model_policy: PersonaModelPolicy,
93 #[serde(default)]
94 pub budget: PersonaBudget,
95 #[serde(default)]
96 pub handoffs: Vec<String>,
97 #[serde(default)]
98 pub context_packs: Vec<String>,
99 #[serde(default, alias = "eval_packs")]
100 pub evals: Vec<String>,
101 #[serde(default)]
102 pub owner: Option<String>,
103 #[serde(default)]
104 pub package_source: PersonaPackageSource,
105 #[serde(default)]
106 pub rollout_policy: PersonaRolloutPolicy,
107 #[serde(default)]
108 pub steps: Vec<PersonaStepMetadata>,
109 #[serde(default)]
113 pub stages: Vec<PersonaStageDecl>,
114 #[serde(default, skip_serializing_if = "Option::is_none")]
117 pub output_style: Option<PersonaOutputStyle>,
118 #[serde(flatten, default)]
119 pub extra: BTreeMap<String, toml::Value>,
120}
121
122#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
129pub struct PersonaStageDecl {
130 pub name: String,
131 #[serde(default, skip_serializing_if = "Option::is_none")]
132 pub allowed_tools: Option<Vec<String>>,
133 #[serde(default, skip_serializing_if = "Option::is_none")]
134 pub side_effect_level: Option<String>,
135 #[serde(default, skip_serializing_if = "Option::is_none")]
136 pub max_iterations: Option<u32>,
137 #[serde(default, skip_serializing_if = "Option::is_none")]
138 pub on_exit: Option<PersonaStageExit>,
139 #[serde(flatten, default)]
140 pub extra: BTreeMap<String, toml::Value>,
141}
142
143#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
144pub struct PersonaStageExit {
145 #[serde(default, skip_serializing_if = "Option::is_none")]
146 pub on_complete: Option<String>,
147 #[serde(default, skip_serializing_if = "Option::is_none")]
148 pub on_failure: Option<String>,
149 #[serde(flatten, default)]
150 pub extra: BTreeMap<String, toml::Value>,
151}
152
153#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
154pub struct PersonaStepMetadata {
155 pub name: String,
156 pub function: String,
157 #[serde(default, skip_serializing_if = "Option::is_none")]
158 pub model: Option<String>,
159 #[serde(default, skip_serializing_if = "Option::is_none")]
160 pub approval: Option<String>,
161 #[serde(default, skip_serializing_if = "Option::is_none")]
162 pub receipt: Option<String>,
163 #[serde(default, skip_serializing_if = "Option::is_none")]
164 pub error_boundary: Option<String>,
165 #[serde(default, skip_serializing_if = "Option::is_none")]
166 pub retry: Option<PersonaStepRetry>,
167 #[serde(default, skip_serializing_if = "Option::is_none")]
168 pub budget: Option<PersonaStepBudget>,
169 #[serde(default, skip_serializing_if = "Option::is_none")]
170 pub line: Option<usize>,
171}
172
173#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
174pub struct PersonaStepRetry {
175 pub max_attempts: u64,
176}
177
178#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
183pub struct PersonaStepBudget {
184 #[serde(default, skip_serializing_if = "Option::is_none")]
185 pub max_tokens: Option<u64>,
186 #[serde(default, skip_serializing_if = "Option::is_none")]
187 pub max_usd: Option<f64>,
188}
189
190#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
191#[serde(rename_all = "snake_case")]
192pub enum PersonaAutonomyTier {
193 Shadow,
194 Suggest,
195 ActWithApproval,
196 ActAuto,
197}
198
199impl PersonaAutonomyTier {
200 pub fn as_str(self) -> &'static str {
201 match self {
202 Self::Shadow => "shadow",
203 Self::Suggest => "suggest",
204 Self::ActWithApproval => "act_with_approval",
205 Self::ActAuto => "act_auto",
206 }
207 }
208}
209
210impl FromStr for PersonaAutonomyTier {
211 type Err = ();
212
213 fn from_str(value: &str) -> Result<Self, Self::Err> {
214 match value {
215 "shadow" => Ok(Self::Shadow),
216 "suggest" => Ok(Self::Suggest),
217 "act_with_approval" => Ok(Self::ActWithApproval),
218 "act_auto" => Ok(Self::ActAuto),
219 _ => Err(()),
220 }
221 }
222}
223
224#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
225#[serde(rename_all = "snake_case")]
226pub enum PersonaReceiptPolicy {
227 #[default]
228 Optional,
229 Required,
230 Disabled,
231}
232
233impl PersonaReceiptPolicy {
234 pub fn as_str(self) -> &'static str {
235 match self {
236 Self::Optional => "optional",
237 Self::Required => "required",
238 Self::Disabled => "disabled",
239 }
240 }
241}
242
243impl FromStr for PersonaReceiptPolicy {
244 type Err = ();
245
246 fn from_str(value: &str) -> Result<Self, Self::Err> {
247 match value {
248 "optional" => Ok(Self::Optional),
249 "required" => Ok(Self::Required),
250 "disabled" => Ok(Self::Disabled),
251 "none" => Ok(Self::Disabled),
252 _ => Err(()),
253 }
254 }
255}
256
257#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
258pub struct PersonaModelPolicy {
259 #[serde(default)]
260 pub default_model: Option<String>,
261 #[serde(default)]
262 pub escalation_model: Option<String>,
263 #[serde(default)]
264 pub fallback_models: Vec<String>,
265 #[serde(default)]
266 pub effort: Option<String>,
267 #[serde(flatten, default)]
268 pub extra: BTreeMap<String, toml::Value>,
269}
270
271#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
272pub struct PersonaBudget {
273 #[serde(default)]
274 pub daily_usd: Option<f64>,
275 #[serde(default)]
276 pub hourly_usd: Option<f64>,
277 #[serde(default)]
278 pub run_usd: Option<f64>,
279 #[serde(default)]
280 pub frontier_escalations: Option<u32>,
281 #[serde(default)]
282 pub max_tokens: Option<u64>,
283 #[serde(default)]
284 pub max_runtime_seconds: Option<u64>,
285 #[serde(flatten, default)]
286 pub extra: BTreeMap<String, toml::Value>,
287}
288
289#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
290pub struct PersonaPackageSource {
291 #[serde(default)]
292 pub package: Option<String>,
293 #[serde(default)]
294 pub path: Option<String>,
295 #[serde(default)]
296 pub git: Option<String>,
297 #[serde(default)]
298 pub rev: Option<String>,
299 #[serde(flatten, default)]
300 pub extra: BTreeMap<String, toml::Value>,
301}
302
303#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
304pub struct PersonaRolloutPolicy {
305 #[serde(default)]
306 pub mode: Option<String>,
307 #[serde(default)]
308 pub percentage: Option<u8>,
309 #[serde(default)]
310 pub cohorts: Vec<String>,
311 #[serde(flatten, default)]
312 pub extra: BTreeMap<String, toml::Value>,
313}
314
315#[derive(Debug, Clone, PartialEq, Serialize)]
316pub struct ResolvedPersonaManifest {
317 pub manifest_path: PathBuf,
318 pub manifest_dir: PathBuf,
319 pub personas: Vec<PersonaManifestEntry>,
320}
321
322#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
323pub struct PersonaValidationError {
324 pub manifest_path: PathBuf,
325 pub field_path: String,
326 pub message: String,
327}
328
329impl std::fmt::Display for PersonaValidationError {
330 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
331 write!(
332 f,
333 "{} {}: {}",
334 self.manifest_path.display(),
335 self.field_path,
336 self.message
337 )
338 }
339}
340
341impl std::error::Error for PersonaValidationError {}
342
343#[derive(Debug, Clone, Default)]
344pub struct PersonaValidationContext {
345 pub known_capabilities: BTreeSet<String>,
346 pub known_tools: BTreeSet<String>,
347 pub known_names: BTreeSet<String>,
348}
349
350pub fn parse_persona_manifest_str(
351 source: &str,
352) -> Result<PersonaManifestDocument, toml::de::Error> {
353 let document = toml::from_str::<PersonaManifestDocument>(source)?;
354 if !document.personas.is_empty() {
355 return Ok(document);
356 }
357 let entry = toml::from_str::<PersonaManifestEntry>(source)?;
358 if entry.name.is_some()
359 || entry.description.is_some()
360 || entry.entry_workflow.is_some()
361 || !entry.tools.is_empty()
362 || !entry.capabilities.is_empty()
363 {
364 Ok(PersonaManifestDocument {
365 personas: vec![entry],
366 })
367 } else {
368 Ok(document)
369 }
370}
371
372pub fn parse_persona_manifest_file(path: &Path) -> Result<PersonaManifestDocument, String> {
373 let content = fs::read_to_string(path)
374 .map_err(|error| format!("failed to read {}: {error}", path.display()))?;
375 parse_persona_manifest_str(&content)
376 .map_err(|error| format!("failed to parse {}: {error}", path.display()))
377}
378
379pub fn parse_persona_source_file(path: &Path) -> Result<PersonaManifestDocument, String> {
380 let content = fs::read_to_string(path)
381 .map_err(|error| format!("failed to read {}: {error}", path.display()))?;
382 parse_persona_source_str(&content)
383 .map_err(|error| format!("failed to parse {}: {error}", path.display()))
384}
385
386pub fn parse_persona_source_str(source: &str) -> Result<PersonaManifestDocument, String> {
387 let program = harn_parser::parse_source(source).map_err(|error| error.to_string())?;
388 Ok(extract_personas_from_program(&program))
389}
390
391pub fn extract_personas_from_program(program: &[SNode]) -> PersonaManifestDocument {
392 let step_decls = collect_step_declarations(program);
393 let mut personas = Vec::new();
394 for snode in program {
395 let Node::AttributedDecl { attributes, inner } = &snode.node else {
396 continue;
397 };
398 let Some(persona_attr) = attributes.iter().find(|attr| attr.name == "persona") else {
399 continue;
400 };
401 let Node::FnDecl { name, body, .. } = &inner.node else {
402 continue;
403 };
404 let persona_name = attr_string(persona_attr, "name").unwrap_or_else(|| name.clone());
405 let mut seen = BTreeSet::new();
406 let mut steps = Vec::new();
407 for call_name in collect_called_functions(body) {
408 if !seen.insert(call_name.clone()) {
409 continue;
410 }
411 if let Some(step) = step_decls.get(&call_name) {
412 steps.push(step.clone());
413 }
414 }
415 personas.push(PersonaManifestEntry {
416 name: Some(persona_name),
417 description: Some(
418 attr_string(persona_attr, "description")
419 .unwrap_or_else(|| "Source-declared persona".to_string()),
420 ),
421 entry_workflow: Some(name.clone()),
422 tools: attr_string_list(persona_attr, "tools"),
423 capabilities: {
424 let capabilities = attr_string_list(persona_attr, "capabilities");
425 if capabilities.is_empty() {
426 vec!["project.test_commands".to_string()]
427 } else {
428 capabilities
429 }
430 },
431 autonomy_tier: attr_string(persona_attr, "autonomy")
432 .as_deref()
433 .and_then(|value| PersonaAutonomyTier::from_str(value).ok())
434 .or(Some(PersonaAutonomyTier::Suggest)),
435 receipt_policy: attr_string(persona_attr, "receipts")
436 .as_deref()
437 .and_then(|value| PersonaReceiptPolicy::from_str(value).ok())
438 .or(Some(PersonaReceiptPolicy::Optional)),
439 steps,
440 stages: attr_stage_list(persona_attr),
441 output_style: attr_string(persona_attr, "output_style")
442 .map(PersonaOutputStyle::from_name),
443 ..PersonaManifestEntry::default()
444 });
445 }
446 PersonaManifestDocument { personas }
447}
448
449pub fn extract_step_metadata_from_program(program: &[SNode]) -> Vec<PersonaStepMetadata> {
450 collect_step_declarations(program).into_values().collect()
451}
452
453fn collect_step_declarations(program: &[SNode]) -> BTreeMap<String, PersonaStepMetadata> {
454 let mut steps = BTreeMap::new();
455 for snode in program {
456 let Node::AttributedDecl { attributes, inner } = &snode.node else {
457 continue;
458 };
459 let Some(step_attr) = attributes.iter().find(|attr| attr.name == "step") else {
460 continue;
461 };
462 let Node::FnDecl { name, .. } = &inner.node else {
463 continue;
464 };
465 steps.insert(
466 name.clone(),
467 PersonaStepMetadata {
468 name: attr_string(step_attr, "name").unwrap_or_else(|| name.clone()),
469 function: name.clone(),
470 model: attr_string(step_attr, "model"),
471 approval: attr_string(step_attr, "approval"),
472 receipt: attr_string(step_attr, "receipt"),
473 error_boundary: attr_string(step_attr, "error_boundary"),
474 retry: attr_retry(step_attr),
475 budget: attr_step_budget(step_attr),
476 line: Some(inner.span.line),
477 },
478 );
479 }
480 steps
481}
482
483fn attr_string(attr: &Attribute, key: &str) -> Option<String> {
484 attr.named_arg(key).and_then(node_string)
485}
486
487fn attr_string_list(attr: &Attribute, key: &str) -> Vec<String> {
488 let Some(value) = attr.named_arg(key) else {
489 return Vec::new();
490 };
491 let Node::ListLiteral(items) = &value.node else {
492 return Vec::new();
493 };
494 items.iter().filter_map(node_string).collect()
495}
496
497fn node_string(node: &SNode) -> Option<String> {
498 match &node.node {
499 Node::StringLiteral(value) | Node::RawStringLiteral(value) | Node::Identifier(value) => {
500 Some(value.clone())
501 }
502 _ => None,
503 }
504}
505
506fn attr_stage_list(attr: &Attribute) -> Vec<PersonaStageDecl> {
507 let Some(value) = attr.named_arg("stages") else {
508 return Vec::new();
509 };
510 let Node::ListLiteral(entries) = &value.node else {
511 return Vec::new();
512 };
513 let mut out = Vec::with_capacity(entries.len());
514 for entry in entries {
515 let Node::DictLiteral(fields) = &entry.node else {
516 continue;
517 };
518 let mut stage = PersonaStageDecl::default();
519 for dict_entry in fields {
520 let Some(key) = entry_key(&dict_entry.key) else {
521 continue;
522 };
523 match key {
524 "name" => {
525 if let Some(name) = node_string(&dict_entry.value) {
526 stage.name = name;
527 }
528 }
529 "allowed_tools" => {
530 if let Node::ListLiteral(items) = &dict_entry.value.node {
531 let tools: Vec<String> = items.iter().filter_map(node_string).collect();
532 stage.allowed_tools = Some(tools);
533 }
534 }
535 "side_effect_level" => {
536 stage.side_effect_level = node_string(&dict_entry.value);
537 }
538 "max_iterations" => {
539 if let Node::IntLiteral(n) = dict_entry.value.node {
540 if n >= 0 {
541 stage.max_iterations = Some(n as u32);
542 }
543 }
544 }
545 _ => {}
546 }
547 }
548 if !stage.name.is_empty() {
549 out.push(stage);
550 }
551 }
552 out
553}
554
555fn attr_retry(attr: &Attribute) -> Option<PersonaStepRetry> {
556 let retry = attr.named_arg("retry")?;
557 let Node::DictLiteral(entries) = &retry.node else {
558 return None;
559 };
560 for entry in entries {
561 if entry_key(&entry.key) == Some("max_attempts") {
562 if let Node::IntLiteral(value) = entry.value.node {
563 if value >= 1 {
564 return Some(PersonaStepRetry {
565 max_attempts: value as u64,
566 });
567 }
568 }
569 }
570 }
571 None
572}
573
574fn attr_step_budget(attr: &Attribute) -> Option<PersonaStepBudget> {
575 let budget = attr.named_arg("budget")?;
576 let Node::DictLiteral(entries) = &budget.node else {
577 return None;
578 };
579 let mut out = PersonaStepBudget::default();
580 let mut any = false;
581 for entry in entries {
582 match entry_key(&entry.key) {
583 Some("max_tokens") => {
584 if let Node::IntLiteral(value) = entry.value.node {
585 if value >= 1 {
586 out.max_tokens = Some(value as u64);
587 any = true;
588 }
589 }
590 }
591 Some("max_usd") => match entry.value.node {
592 Node::FloatLiteral(value) if value.is_finite() && value >= 0.0 => {
593 out.max_usd = Some(value);
594 any = true;
595 }
596 Node::IntLiteral(value) if value >= 0 => {
597 out.max_usd = Some(value as f64);
598 any = true;
599 }
600 _ => {}
601 },
602 _ => {}
603 }
604 }
605 any.then_some(out)
606}
607
608fn entry_key(node: &SNode) -> Option<&str> {
609 match &node.node {
610 Node::Identifier(value) | Node::StringLiteral(value) | Node::RawStringLiteral(value) => {
611 Some(value.as_str())
612 }
613 _ => None,
614 }
615}
616
617fn collect_called_functions(body: &[SNode]) -> Vec<String> {
618 fn collect(node: &SNode, calls: &mut Vec<String>) {
619 let (_, node) = harn_parser::peel_attributes(node);
620 if let Node::FunctionCall { name, .. } = &node.node {
621 calls.push(name.clone());
622 }
623 match &node.node {
624 Node::Pipeline { body, .. }
626 | Node::OverrideDecl { body, .. }
627 | Node::FnDecl { body, .. }
628 | Node::ToolDecl { body, .. }
629 | Node::Closure { body, .. } => {
630 for child in body {
631 collect(child, calls);
632 }
633 }
634 _ => harn_parser::visit::for_each_immediate_child(node, &mut |child| {
635 collect(child, calls);
636 }),
637 }
638 }
639
640 let mut calls = Vec::new();
641 for node in body {
642 collect(node, &mut calls);
643 }
644 calls
645}
646
647pub fn validate_persona_manifests(
648 manifest_path: &Path,
649 personas: &[PersonaManifestEntry],
650 context: &PersonaValidationContext,
651) -> Result<(), Vec<PersonaValidationError>> {
652 let mut errors = Vec::new();
653 for (index, persona) in personas.iter().enumerate() {
654 validate_persona(persona, index, manifest_path, context, &mut errors);
655 }
656 if errors.is_empty() {
657 Ok(())
658 } else {
659 Err(errors)
660 }
661}
662
663pub fn validate_persona(
664 persona: &PersonaManifestEntry,
665 index: usize,
666 manifest_path: &Path,
667 context: &PersonaValidationContext,
668 errors: &mut Vec<PersonaValidationError>,
669) {
670 let root = format!("[[personas]][{index}]");
671 for field in persona.extra.keys() {
672 persona_error(
673 manifest_path,
674 format!("{root}.{field}"),
675 "unknown persona field",
676 errors,
677 );
678 }
679 let name = validate_required_string(
680 manifest_path,
681 &root,
682 "name",
683 persona.name.as_deref(),
684 errors,
685 );
686 if let Some(name) = name {
687 validate_tokenish(manifest_path, &root, "name", name, errors);
688 }
689 validate_required_string(
690 manifest_path,
691 &root,
692 "description",
693 persona.description.as_deref(),
694 errors,
695 );
696 validate_required_string(
697 manifest_path,
698 &root,
699 "entry_workflow",
700 persona.entry_workflow.as_deref(),
701 errors,
702 );
703 if persona.tools.is_empty() && persona.capabilities.is_empty() {
704 persona_error(
705 manifest_path,
706 format!("{root}.tools"),
707 "persona requires at least one tool or capability",
708 errors,
709 );
710 }
711 if persona.autonomy_tier.is_none() {
712 persona_error(
713 manifest_path,
714 format!("{root}.autonomy_tier"),
715 "missing required autonomy tier",
716 errors,
717 );
718 }
719 if persona.receipt_policy.is_none() {
720 persona_error(
721 manifest_path,
722 format!("{root}.receipt_policy"),
723 "missing required receipt policy",
724 errors,
725 );
726 }
727 validate_string_list(manifest_path, &root, "tools", &persona.tools, errors);
728 for tool in &persona.tools {
729 if !context.known_tools.is_empty() && !context.known_tools.contains(tool) {
730 persona_error(
731 manifest_path,
732 format!("{root}.tools"),
733 format!("unknown tool '{tool}'"),
734 errors,
735 );
736 }
737 }
738 for capability in &persona.capabilities {
739 let Some((cap, op)) = capability.split_once('.') else {
740 persona_error(
741 manifest_path,
742 format!("{root}.capabilities"),
743 format!("capability '{capability}' must use capability.operation syntax"),
744 errors,
745 );
746 continue;
747 };
748 if cap.trim().is_empty() || op.trim().is_empty() {
749 persona_error(
750 manifest_path,
751 format!("{root}.capabilities"),
752 format!("capability '{capability}' must use capability.operation syntax"),
753 errors,
754 );
755 } else if !context.known_capabilities.is_empty()
756 && !context.known_capabilities.contains(capability)
757 {
758 persona_error(
759 manifest_path,
760 format!("{root}.capabilities"),
761 format!("unknown capability '{capability}'"),
762 errors,
763 );
764 }
765 }
766 validate_string_list(
767 manifest_path,
768 &root,
769 "context_packs",
770 &persona.context_packs,
771 errors,
772 );
773 validate_string_list(manifest_path, &root, "evals", &persona.evals, errors);
774 for schedule in &persona.schedules {
775 if schedule.trim().is_empty() {
776 persona_error(
777 manifest_path,
778 format!("{root}.schedules"),
779 "schedule entries must not be empty",
780 errors,
781 );
782 } else if let Err(error) = croner::Cron::from_str(schedule) {
783 persona_error(
784 manifest_path,
785 format!("{root}.schedules"),
786 format!("invalid cron schedule '{schedule}': {error}"),
787 errors,
788 );
789 }
790 }
791 for trigger in &persona.triggers {
792 match trigger.split_once('.') {
793 Some((provider, event)) if !provider.trim().is_empty() && !event.trim().is_empty() => {}
794 _ => persona_error(
795 manifest_path,
796 format!("{root}.triggers"),
797 format!("trigger '{trigger}' must use provider.event syntax"),
798 errors,
799 ),
800 }
801 }
802 for handoff in &persona.handoffs {
803 if !context.known_names.contains(handoff) {
804 persona_error(
805 manifest_path,
806 format!("{root}.handoffs"),
807 format!("unknown handoff target '{handoff}'"),
808 errors,
809 );
810 }
811 }
812 validate_persona_budget(manifest_path, &root, &persona.budget, errors);
813 validate_persona_stages(manifest_path, &root, persona, context, errors);
814 validate_persona_nested_extra(
815 manifest_path,
816 &root,
817 "model_policy",
818 &persona.model_policy.extra,
819 errors,
820 );
821 validate_persona_nested_extra(
822 manifest_path,
823 &root,
824 "package_source",
825 &persona.package_source.extra,
826 errors,
827 );
828 validate_persona_nested_extra(
829 manifest_path,
830 &root,
831 "rollout_policy",
832 &persona.rollout_policy.extra,
833 errors,
834 );
835 if let Some(percentage) = persona.rollout_policy.percentage {
836 if percentage > 100 {
837 persona_error(
838 manifest_path,
839 format!("{root}.rollout_policy.percentage"),
840 "rollout percentage must be between 0 and 100",
841 errors,
842 );
843 }
844 }
845}
846
847pub fn validate_required_string<'a>(
848 manifest_path: &Path,
849 root: &str,
850 field: &str,
851 value: Option<&'a str>,
852 errors: &mut Vec<PersonaValidationError>,
853) -> Option<&'a str> {
854 match value.map(str::trim) {
855 Some(value) if !value.is_empty() => Some(value),
856 _ => {
857 persona_error(
858 manifest_path,
859 format!("{root}.{field}"),
860 format!("missing required {field}"),
861 errors,
862 );
863 None
864 }
865 }
866}
867
868pub fn validate_string_list(
869 manifest_path: &Path,
870 root: &str,
871 field: &str,
872 values: &[String],
873 errors: &mut Vec<PersonaValidationError>,
874) {
875 for value in values {
876 if value.trim().is_empty() {
877 persona_error(
878 manifest_path,
879 format!("{root}.{field}"),
880 format!("{field} entries must not be empty"),
881 errors,
882 );
883 } else {
884 validate_tokenish(manifest_path, root, field, value, errors);
885 }
886 }
887}
888
889pub fn validate_tokenish(
890 manifest_path: &Path,
891 root: &str,
892 field: &str,
893 value: &str,
894 errors: &mut Vec<PersonaValidationError>,
895) {
896 if !value
897 .chars()
898 .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-' | '.' | '/'))
899 {
900 persona_error(
901 manifest_path,
902 format!("{root}.{field}"),
903 format!("'{value}' must contain only letters, numbers, '.', '-', '_', or '/'"),
904 errors,
905 );
906 }
907}
908
909pub fn validate_persona_budget(
910 manifest_path: &Path,
911 root: &str,
912 budget: &PersonaBudget,
913 errors: &mut Vec<PersonaValidationError>,
914) {
915 validate_persona_nested_extra(manifest_path, root, "budget", &budget.extra, errors);
916 for (field, value) in [
917 ("daily_usd", budget.daily_usd),
918 ("hourly_usd", budget.hourly_usd),
919 ("run_usd", budget.run_usd),
920 ] {
921 if value.is_some_and(|number| !number.is_finite() || number < 0.0) {
922 persona_error(
923 manifest_path,
924 format!("{root}.budget.{field}"),
925 "budget amounts must be finite non-negative numbers",
926 errors,
927 );
928 }
929 }
930}
931
932pub fn validate_persona_nested_extra(
933 manifest_path: &Path,
934 root: &str,
935 field: &str,
936 extra: &BTreeMap<String, toml::Value>,
937 errors: &mut Vec<PersonaValidationError>,
938) {
939 for key in extra.keys() {
940 persona_error(
941 manifest_path,
942 format!("{root}.{field}.{key}"),
943 format!("unknown {field} field"),
944 errors,
945 );
946 }
947}
948
949pub fn validate_persona_stages(
950 manifest_path: &Path,
951 root: &str,
952 persona: &PersonaManifestEntry,
953 context: &PersonaValidationContext,
954 errors: &mut Vec<PersonaValidationError>,
955) {
956 let stage_names: BTreeSet<&str> = persona
957 .stages
958 .iter()
959 .map(|stage| stage.name.as_str())
960 .collect();
961 let mut seen = BTreeSet::new();
962 for (index, stage) in persona.stages.iter().enumerate() {
963 let field = format!("{root}.stages[{index}]");
964 if stage.name.trim().is_empty() {
965 persona_error(
966 manifest_path,
967 format!("{field}.name"),
968 "stage name must not be empty",
969 errors,
970 );
971 } else {
972 validate_tokenish(manifest_path, &field, "name", &stage.name, errors);
973 if !seen.insert(stage.name.as_str()) {
974 persona_error(
975 manifest_path,
976 format!("{field}.name"),
977 format!("duplicate stage name '{}'", stage.name),
978 errors,
979 );
980 }
981 }
982 for key in stage.extra.keys() {
983 persona_error(
984 manifest_path,
985 format!("{field}.{key}"),
986 "unknown stage field",
987 errors,
988 );
989 }
990 if let Some(tools) = stage.allowed_tools.as_ref() {
991 for tool in tools {
992 if tool.trim().is_empty() {
993 persona_error(
994 manifest_path,
995 format!("{field}.allowed_tools"),
996 "allowed_tools entries must not be empty",
997 errors,
998 );
999 continue;
1000 }
1001 if !context.known_tools.is_empty() && !context.known_tools.contains(tool) {
1002 persona_error(
1003 manifest_path,
1004 format!("{field}.allowed_tools"),
1005 format!("unknown tool '{tool}'"),
1006 errors,
1007 );
1008 } else if !persona.tools.is_empty() && !persona.tools.contains(tool) {
1009 persona_error(
1010 manifest_path,
1011 format!("{field}.allowed_tools"),
1012 format!("tool '{tool}' is not part of the persona-level tools allowlist"),
1013 errors,
1014 );
1015 }
1016 }
1017 }
1018 if let Some(level) = stage.side_effect_level.as_deref() {
1019 use harn_execution_policy::tool_annotations::SideEffectLevel;
1020 if SideEffectLevel::parse(level).as_str() != level {
1021 persona_error(
1022 manifest_path,
1023 format!("{field}.side_effect_level"),
1024 format!(
1025 "unknown side_effect_level '{level}' (expected {})",
1026 SideEffectLevel::ALL.map(|level| level.as_str()).join(", ")
1027 ),
1028 errors,
1029 );
1030 }
1031 }
1032 if let Some(exit) = stage.on_exit.as_ref() {
1033 validate_persona_nested_extra(manifest_path, &field, "on_exit", &exit.extra, errors);
1034 for (key, target) in [
1035 ("on_complete", exit.on_complete.as_deref()),
1036 ("on_failure", exit.on_failure.as_deref()),
1037 ] {
1038 let Some(target) = target else { continue };
1039 if !stage_names.contains(target) {
1040 persona_error(
1041 manifest_path,
1042 format!("{field}.on_exit.{key}"),
1043 format!("unknown stage '{target}'"),
1044 errors,
1045 );
1046 }
1047 }
1048 }
1049 }
1050}
1051
1052pub fn persona_error(
1053 manifest_path: &Path,
1054 field_path: String,
1055 message: impl Into<String>,
1056 errors: &mut Vec<PersonaValidationError>,
1057) {
1058 errors.push(PersonaValidationError {
1059 manifest_path: manifest_path.to_path_buf(),
1060 field_path,
1061 message: message.into(),
1062 });
1063}
1064
1065pub fn default_persona_capability_map() -> BTreeMap<&'static str, Vec<&'static str>> {
1066 BTreeMap::from([
1067 (
1068 "workspace",
1069 vec![
1070 "read_text",
1071 "write_text",
1072 "apply_edit",
1073 "delete",
1074 "exists",
1075 "file_exists",
1076 "list",
1077 "project_root",
1078 "roots",
1079 ],
1080 ),
1081 ("process", vec!["exec"]),
1082 ("template", vec!["render"]),
1083 ("interaction", vec!["ask"]),
1084 (
1085 "runtime",
1086 vec![
1087 "approved_plan",
1088 "dry_run",
1089 "pipeline_input",
1090 "record_run",
1091 "set_result",
1092 "task",
1093 ],
1094 ),
1095 (
1096 "project",
1097 vec![
1098 "agent_instructions",
1099 "code_patterns",
1100 "compute_content_hash",
1101 "ide_context",
1102 "lessons",
1103 "mcp_config",
1104 "metadata_get",
1105 "metadata_inspect",
1106 "metadata_refresh_hashes",
1107 "metadata_save",
1108 "metadata_set",
1109 "metadata_stale",
1110 "path_metadata_entries",
1111 "path_metadata_get",
1112 "path_metadata_set",
1113 "scan",
1114 "scope_test_command",
1115 "test_commands",
1116 ],
1117 ),
1118 (
1119 "session",
1120 vec![
1121 "active_roots",
1122 "changed_paths",
1123 "preread_get",
1124 "preread_read_many",
1125 ],
1126 ),
1127 (
1128 "editor",
1129 vec!["get_active_file", "get_selection", "get_visible_files"],
1130 ),
1131 ("diagnostics", vec!["get_causal_traces", "get_errors"]),
1132 ("git", vec!["get_branch", "get_diff"]),
1133 ("learning", vec!["get_learned_rules", "report_correction"]),
1134 ])
1135}
1136
1137pub fn default_persona_capabilities() -> BTreeSet<String> {
1138 let mut capabilities = BTreeSet::new();
1139 for (capability, operations) in default_persona_capability_map() {
1140 for operation in operations {
1141 capabilities.insert(format!("{capability}.{operation}"));
1142 }
1143 }
1144 capabilities
1145}
1146
1147#[cfg(test)]
1148#[path = "personas_tests.rs"]
1149mod tests;