iron-core 0.1.37

Core AgentIron loop, session state, and tool registry
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
//! Stored prompt definitions and registry.
//!
//! Stored prompts are named reusable task definitions persisted in the core
//! config store. They are invoked through delegated child-session execution.
//!
//! ```
//! use iron_core::{StoredPrompt, StoredPromptRegistry};
//!
//! let prompt = StoredPrompt {
//!     display_name: "Review Changes".into(),
//!     normalized_name: "review-changes".into(),
//!     instructions: "Review the current changes and report risks.".into(),
//!     skills: vec!["code-review".into()],
//!     profile: None,
//! };
//! let mut registry = StoredPromptRegistry::new();
//! registry.register("review".into(), prompt)?;
//! assert_eq!(registry.get("review").unwrap().normalized_name, "review-changes");
//! # Ok::<(), String>(())
//! ```

use crate::config::{ConfigError, ConfigStore};
use crate::profile::AgentProfileId;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Current schema version for typed `StoredPrompt` payloads stored in ConfigStore.
pub const STORED_PROMPT_SCHEMA_VERSION: i64 = 2;

/// Legacy schema version still recognized during best-effort loading.
pub const LEGACY_STORED_PROMPT_SCHEMA_VERSION: i64 = 1;

/// Identity state of a stored prompt record.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum IdentityState {
    /// The prompt has a valid display name and normalized handle.
    #[default]
    Ready,
    /// The prompt's handle collided during migration and must be renamed.
    NeedsRename,
}

/// A reusable prompt task definition.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StoredPrompt {
    /// User-facing display name. Mutable; renaming preserves the immutable ID.
    #[serde(default)]
    pub display_name: String,
    /// Canonical ASCII kebab-case lookup handle derived from `display_name`.
    #[serde(default)]
    pub normalized_name: String,
    /// Instructions passed as the child's goal or system prompt layer.
    pub instructions: String,
    /// Requested skills to activate for the child run.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub skills: Vec<String>,
    /// Optional profile ID to use for the child run.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub profile: Option<AgentProfileId>,
}

impl StoredPrompt {
    /// Validate invariants for current-schema records.
    ///
    /// # Errors
    ///
    /// Returns a diagnostic string when instructions or display identity are
    /// empty, the normalized handle is stale, a skill identifier is invalid,
    /// or skill identifiers repeat case-insensitively.
    pub fn validate(&self) -> Result<(), String> {
        if self.instructions.trim().is_empty() {
            return Err("stored prompt instructions must not be empty".to_string());
        }
        if self.display_name.trim().is_empty() {
            return Err("stored prompt display name must not be empty".to_string());
        }
        let normalized = normalize_prompt_name(&self.display_name);
        if normalized.is_empty() {
            return Err(
                "stored prompt display name must produce a non-empty normalized handle".to_string(),
            );
        }
        if self.normalized_name != normalized {
            return Err(format!(
                "stored prompt normalized_name '{}' does not match derived '{}'",
                self.normalized_name, normalized
            ));
        }
        for skill in &self.skills {
            validate_skill_identifier(skill)?;
        }
        let mut seen = std::collections::HashSet::new();
        for skill in &self.skills {
            let lower = skill.to_lowercase();
            if !seen.insert(lower) {
                return Err(format!(
                    "duplicate skill identifier '{}' (case-insensitive)",
                    skill
                ));
            }
        }
        Ok(())
    }
}

/// A stored prompt paired with its stable ID and identity state.
#[derive(Debug, Clone, PartialEq)]
pub struct StoredPromptEntry {
    /// Immutable record ID used by automation-task references.
    pub id: String,
    /// Decoded reusable prompt definition.
    pub prompt: StoredPrompt,
    /// Whether the prompt is usable by handle or quarantined pending a rename.
    pub identity_state: IdentityState,
}

/// Issue category reported for a skipped prompt during `load_prompts`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PromptLoadIssue {
    /// The row uses a schema version this binary cannot decode.
    UnsupportedSchemaVersion {
        /// Unsupported version read from the prompt row.
        version: i64,
    },
    /// The row ID or serialized prompt failed decoding or validation.
    InvalidPayload,
    /// The ID appeared in a listing but disappeared before it could be read.
    MissingRecord,
    /// The prompt refers to a profile unavailable to the loading context.
    UnavailableProfile {
        /// Profile ID that could not be resolved.
        profile_id: String,
    },
    /// The prompt requests a skill unavailable to the loading context.
    UnavailableSkill {
        /// Requested skill identifier that was unavailable.
        skill: String,
    },
    /// Migration quarantined the prompt after a normalized-name collision.
    NeedsRename,
}

/// Per-prompt diagnostic returned by best-effort prompt loading.
#[derive(Debug, Clone, PartialEq)]
pub struct PromptLoadDiagnostic {
    /// Stable ID of the skipped or degraded prompt.
    pub prompt_id: String,
    /// Machine-readable reason the prompt was not loaded normally.
    pub issue: PromptLoadIssue,
}

/// Result of loading typed stored prompts from ConfigStore.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct PromptLoadReport {
    /// Successfully decoded prompt entries, including their identity state.
    pub loaded: Vec<StoredPromptEntry>,
    /// Record-local problems that did not abort the best-effort load.
    pub diagnostics: Vec<PromptLoadDiagnostic>,
}

/// In-memory registry of stored prompts.
#[derive(Debug, Default)]
pub struct StoredPromptRegistry {
    prompts: HashMap<String, StoredPrompt>,
}

impl StoredPromptRegistry {
    /// Create an empty in-memory prompt registry.
    pub fn new() -> Self {
        Self {
            prompts: HashMap::new(),
        }
    }

    /// Validate and register a prompt under a trimmed stable ID.
    ///
    /// Replaces an existing prompt with the same ID.
    ///
    /// # Errors
    ///
    /// Returns a diagnostic string if the ID is empty or contains control
    /// characters, or if [`StoredPrompt::validate`] rejects the prompt.
    pub fn register(&mut self, id: String, prompt: StoredPrompt) -> Result<(), String> {
        let trimmed = id.trim();
        if trimmed.is_empty() {
            return Err("prompt ID must not be empty".to_string());
        }
        if trimmed.as_bytes().iter().any(|b| b.is_ascii_control()) {
            return Err("prompt ID must not contain control characters".to_string());
        }
        prompt.validate()?;
        self.prompts.insert(trimmed.to_string(), prompt);
        Ok(())
    }

    /// Remove the prompt identified by the trimmed ID.
    ///
    /// Returns whether an entry was present.
    pub fn unregister(&mut self, id: &str) -> bool {
        self.prompts.remove(id.trim()).is_some()
    }

    /// Look up a prompt by its trimmed stable ID.
    pub fn get(&self, id: &str) -> Option<&StoredPrompt> {
        self.prompts.get(id.trim())
    }

    /// Return cloned entries sorted by stable ID.
    ///
    /// Registry entries are always returned with [`IdentityState::Ready`]
    /// because quarantined durable rows are not registered.
    pub fn list(&self) -> Vec<StoredPromptEntry> {
        let mut ids: Vec<&String> = self.prompts.keys().collect();
        ids.sort();
        ids.into_iter()
            .map(|id| StoredPromptEntry {
                id: id.clone(),
                prompt: self.prompts[id].clone(),
                identity_state: IdentityState::Ready,
            })
            .collect()
    }

    /// Return whether the registry contains no prompts.
    pub fn is_empty(&self) -> bool {
        self.prompts.is_empty()
    }

    /// Return the number of registered prompts.
    pub fn len(&self) -> usize {
        self.prompts.len()
    }
}

/// Prefix reserved for deterministic repair handles assigned to colliding
/// legacy records during migration. Normal user-facing handles cannot use this
/// namespace, so repair handles are never ambiguous with legitimate lookups.
pub const LEGACY_RESERVED_PREFIX: &str = "legacy-";

/// Returns true if the normalized handle uses the reserved repair namespace.
pub fn is_reserved_handle(normalized: &str) -> bool {
    normalized.starts_with(LEGACY_RESERVED_PREFIX)
}

/// Normalize a user-facing prompt name into a canonical ASCII kebab-case handle.
///
/// Lowercases the input, converts whitespace, underscores, and existing hyphens
/// to single hyphens, removes all other non-alphanumeric characters, collapses
/// consecutive hyphens, and strips leading/trailing hyphens.
///
/// Examples:
/// - `Check Email` → `check-email`
/// - `Check_Email` → `check-email`
/// - `CHECK-EMAIL` → `check-email`
pub fn normalize_prompt_name(name: &str) -> String {
    let trimmed = name.trim();
    let mut result = String::with_capacity(trimmed.len());
    let mut prev_was_hyphen = false;

    for c in trimmed.chars() {
        // Filter to ASCII before lowercasing so Unicode characters whose
        // lowercase mapping introduces ASCII (e.g. K → k) are removed
        // rather than contributing unexpected ASCII letters.
        if c.is_ascii_alphanumeric() {
            result.push(c.to_ascii_lowercase());
            prev_was_hyphen = false;
        } else if (c == '-' || c == '_' || c.is_whitespace())
            && !prev_was_hyphen
            && !result.is_empty()
        {
            result.push('-');
            prev_was_hyphen = true;
        }
    }

    if result.ends_with('-') {
        result.pop();
    }

    result
}

/// Validate a requested skill identifier.
///
/// Skill identifiers must be non-empty, must not contain control characters or
/// whitespace, and must consist only of ASCII alphanumeric characters,
/// hyphens, underscores, dots, or slashes.
pub fn validate_skill_identifier(skill: &str) -> Result<(), String> {
    let trimmed = skill.trim();
    if trimmed.is_empty() {
        return Err("skill identifier must not be empty or whitespace".to_string());
    }
    if trimmed != skill {
        return Err(format!(
            "skill identifier '{}' must not have leading or trailing whitespace",
            skill
        ));
    }
    if trimmed.as_bytes().iter().any(|b| b.is_ascii_control()) {
        return Err(format!(
            "skill identifier '{}' must not contain control characters",
            trimmed
        ));
    }
    if trimmed.contains(char::is_whitespace) {
        return Err(format!(
            "skill identifier '{}' must not contain whitespace",
            trimmed
        ));
    }
    if !trimmed
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' || c == '/')
    {
        return Err(format!(
            "skill identifier '{}' contains invalid characters; use only letters, digits, hyphens, underscores, dots, or slashes",
            trimmed
        ));
    }
    Ok(())
}

/// Convert a kebab-case identifier to title case for display purposes.
///
/// Used during v1 migration to derive a human-readable display name from
/// a legacy record ID.
///
/// Examples:
/// - `check-email` → `Check Email`
/// - `daily_report` → `Daily Report`
pub fn kebab_to_title_case(id: &str) -> String {
    let normalized = id.replace('_', "-");
    normalized
        .split('-')
        .filter(|s| !s.is_empty())
        .map(|s| {
            let mut chars = s.chars();
            match chars.next() {
                Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
                None => String::new(),
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

/// Load stored prompts from a ConfigStore.
///
/// Accepts both legacy v1 and current v2 schema versions. For v1 records,
/// display name and normalized handle are derived from the stable record ID.
pub async fn load_prompts(store: &ConfigStore) -> Result<PromptLoadReport, ConfigError> {
    let mut report = PromptLoadReport::default();
    let mut ids = store.list_prompt_ids().await?;
    ids.sort();

    for id in ids {
        let trimmed_id = id.trim();
        if trimmed_id.is_empty() || trimmed_id.as_bytes().iter().any(|b| b.is_ascii_control()) {
            report.diagnostics.push(PromptLoadDiagnostic {
                prompt_id: id,
                issue: PromptLoadIssue::InvalidPayload,
            });
            continue;
        }
        let record = match store.get_prompt(&id).await? {
            Some(record) => record,
            None => {
                report.diagnostics.push(PromptLoadDiagnostic {
                    prompt_id: id,
                    issue: PromptLoadIssue::MissingRecord,
                });
                continue;
            }
        };

        if record.schema_version == LEGACY_STORED_PROMPT_SCHEMA_VERSION {
            let prompt: StoredPrompt = match serde_json::from_value(record.payload.clone()) {
                Ok(p) => p,
                Err(_) => {
                    report.diagnostics.push(PromptLoadDiagnostic {
                        prompt_id: record.id,
                        issue: PromptLoadIssue::InvalidPayload,
                    });
                    continue;
                }
            };
            if prompt.instructions.trim().is_empty() {
                report.diagnostics.push(PromptLoadDiagnostic {
                    prompt_id: record.id,
                    issue: PromptLoadIssue::InvalidPayload,
                });
                continue;
            }
            let display_name = kebab_to_title_case(&record.id);
            // Derive normalized handle from the deterministic display name
            // rather than trusting the DB column, which may be a repair handle
            // or stale placeholder.
            let normalized_name = normalize_prompt_name(&display_name);
            let identity_state = if record.identity_state == "needs_rename" {
                IdentityState::NeedsRename
            } else {
                IdentityState::Ready
            };
            let prompt = StoredPrompt {
                display_name,
                normalized_name,
                instructions: prompt.instructions,
                skills: prompt.skills,
                profile: prompt.profile,
            };
            if prompt.validate().is_err() {
                report.diagnostics.push(PromptLoadDiagnostic {
                    prompt_id: record.id,
                    issue: PromptLoadIssue::InvalidPayload,
                });
                continue;
            }
            report.loaded.push(StoredPromptEntry {
                id: record.id,
                prompt,
                identity_state,
            });
            continue;
        }

        if record.schema_version != STORED_PROMPT_SCHEMA_VERSION {
            report.diagnostics.push(PromptLoadDiagnostic {
                prompt_id: record.id,
                issue: PromptLoadIssue::UnsupportedSchemaVersion {
                    version: record.schema_version,
                },
            });
            continue;
        }

        let prompt: StoredPrompt = match serde_json::from_value(record.payload.clone()) {
            Ok(prompt) => prompt,
            Err(_) => {
                report.diagnostics.push(PromptLoadDiagnostic {
                    prompt_id: record.id,
                    issue: PromptLoadIssue::InvalidPayload,
                });
                continue;
            }
        };

        if prompt.validate().is_err() {
            report.diagnostics.push(PromptLoadDiagnostic {
                prompt_id: record.id,
                issue: PromptLoadIssue::InvalidPayload,
            });
            continue;
        }

        let identity_state = if record.identity_state == "needs_rename" {
            IdentityState::NeedsRename
        } else {
            IdentityState::Ready
        };

        report.loaded.push(StoredPromptEntry {
            id: record.id,
            prompt,
            identity_state,
        });
    }

    Ok(report)
}

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

    fn valid_prompt() -> StoredPrompt {
        StoredPrompt {
            display_name: "Check Email".to_string(),
            normalized_name: "check-email".to_string(),
            instructions: "do thing".to_string(),
            skills: Vec::new(),
            profile: None,
        }
    }

    #[test]
    fn stored_prompt_rejects_empty_instructions() {
        let prompt = StoredPrompt {
            display_name: "Test".to_string(),
            normalized_name: "test".to_string(),
            instructions: "   ".to_string(),
            skills: Vec::new(),
            profile: None,
        };
        assert!(prompt.validate().is_err());
    }

    #[test]
    fn stored_prompt_rejects_empty_display_name() {
        let prompt = StoredPrompt {
            display_name: "  ".to_string(),
            normalized_name: "".to_string(),
            instructions: "do thing".to_string(),
            skills: Vec::new(),
            profile: None,
        };
        assert!(prompt.validate().is_err());
    }

    #[test]
    fn stored_prompt_rejects_mismatched_normalized() {
        let prompt = StoredPrompt {
            display_name: "Check Email".to_string(),
            normalized_name: "wrong-handle".to_string(),
            instructions: "do thing".to_string(),
            skills: Vec::new(),
            profile: None,
        };
        assert!(prompt.validate().is_err());
    }

    #[test]
    fn registry_replaces_existing() {
        let mut reg = StoredPromptRegistry::new();
        let prompt = valid_prompt();
        reg.register("task".to_string(), prompt.clone()).unwrap();
        reg.register("task".to_string(), prompt).unwrap();
        assert_eq!(reg.len(), 1);
    }

    #[test]
    fn registry_list_is_sorted() {
        let mut reg = StoredPromptRegistry::new();
        let prompt = valid_prompt();
        reg.register("b".to_string(), prompt.clone()).unwrap();
        reg.register("a".to_string(), prompt).unwrap();
        let list = reg.list();
        assert_eq!(list[0].id, "a");
        assert_eq!(list[1].id, "b");
    }

    #[tokio::test]
    async fn legacy_load_reports_invalid_prompt_without_suppressing_valid_siblings() {
        use crate::config::PromptInput;

        let store = ConfigStore::open_in_memory().await.unwrap();
        store
            .set_prompt(&PromptInput {
                id: "valid-legacy".to_string(),
                schema_version: LEGACY_STORED_PROMPT_SCHEMA_VERSION,
                payload: serde_json::json!({"instructions": "Do work"}),
                display_name: "valid-legacy".to_string(),
                normalized_name: "valid-legacy".to_string(),
            })
            .await
            .unwrap();
        store
            .set_prompt(&PromptInput {
                id: "invalid-legacy".to_string(),
                schema_version: LEGACY_STORED_PROMPT_SCHEMA_VERSION,
                payload: serde_json::json!({
                    "instructions": "Do work",
                    "skills": ["invalid skill"]
                }),
                display_name: "invalid-legacy".to_string(),
                normalized_name: "invalid-legacy".to_string(),
            })
            .await
            .unwrap();

        let report = load_prompts(&store).await.unwrap();
        assert_eq!(report.loaded.len(), 1);
        assert_eq!(report.loaded[0].id, "valid-legacy");
        assert!(report.diagnostics.iter().any(|diagnostic| {
            diagnostic.prompt_id == "invalid-legacy"
                && diagnostic.issue == PromptLoadIssue::InvalidPayload
        }));
    }

    // ---- normalize_prompt_name tests ----

    #[test]
    fn normalize_basic() {
        assert_eq!(normalize_prompt_name("Check Email"), "check-email");
    }

    #[test]
    fn normalize_underscore_as_separator() {
        assert_eq!(normalize_prompt_name("Check_Email"), "check-email");
    }

    #[test]
    fn normalize_equivalent_separators() {
        assert_eq!(normalize_prompt_name("Check Email"), "check-email");
        assert_eq!(normalize_prompt_name("Check_Email"), "check-email");
        assert_eq!(normalize_prompt_name("CHECK-EMAIL"), "check-email");
    }

    #[test]
    fn normalize_collapses_multiple_separators() {
        assert_eq!(normalize_prompt_name("My___Task"), "my-task");
        assert_eq!(normalize_prompt_name("My   Task"), "my-task");
    }

    #[test]
    fn normalize_strips_leading_trailing() {
        assert_eq!(normalize_prompt_name("  __Check__  "), "check");
    }

    #[test]
    fn normalize_removes_special_chars() {
        assert_eq!(normalize_prompt_name("Paul's Brief!"), "pauls-brief");
    }

    #[test]
    fn normalize_empty_result() {
        assert_eq!(normalize_prompt_name("'!!!'"), "");
    }

    #[test]
    fn normalize_ascii_only() {
        assert_eq!(normalize_prompt_name("Café Report"), "caf-report");
    }

    // ---- kebab_to_title_case tests ----

    #[test]
    fn title_case_basic() {
        assert_eq!(kebab_to_title_case("check-email"), "Check Email");
    }

    #[test]
    fn title_case_underscore() {
        assert_eq!(kebab_to_title_case("daily_report"), "Daily Report");
    }

    #[test]
    fn title_case_single_word() {
        assert_eq!(kebab_to_title_case("report"), "Report");
    }
}