organism-runtime 1.4.0

Curated embedded runtime for Organism — registry, readiness, and pipeline wiring
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
//! Readiness check — validates that a resolved intent binding can actually execute.
//!
//! Resolution says what you NEED. Readiness says what you HAVE.
//! The gap between them is the readiness report.
//!
//! Checks:
//! - Are required capabilities compiled in? (feature flags)
//! - Are credentials available? (API keys, tokens)
//! - Is there budget? (token limits, spend caps)
//! - Are external services reachable? (optional, expensive)
//!
//! ```rust,ignore
//! let binding = resolver.resolve(&intent, &baseline);
//! let report = readiness::check(&binding, &registry);
//!
//! if !report.ready {
//!     for gap in &report.gaps {
//!         eprintln!("{}: {}", gap.resource, gap.reason);
//!     }
//!     // → "linkedin: LINKEDIN_API_KEY not set"
//!     // → "ocr: feature 'ocr' not compiled"
//!     return Err(report);
//! }
//! ```

use organism_pack::IntentBinding;
use serde::{Deserialize, Serialize};

// ── Readiness Report ───────────────────────────────────────────────

/// Result of checking whether a binding can execute.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReadinessReport {
    /// Can the binding execute right now?
    pub ready: bool,
    /// What's available and confirmed.
    pub confirmed: Vec<ReadinessConfirmation>,
    /// What's missing or degraded.
    pub gaps: Vec<ReadinessGap>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReadinessConfirmation {
    pub resource: String,
    pub kind: ResourceKind,
    pub detail: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReadinessGap {
    pub resource: String,
    pub kind: ResourceKind,
    pub severity: GapSeverity,
    pub reason: String,
    pub suggestion: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ResourceKind {
    /// A compiled feature flag (e.g., "ocr", "vision").
    Feature,
    /// An API key or credential (e.g., ANTHROPIC_API_KEY).
    Credential,
    /// A spending or token budget.
    Budget,
    /// An external service endpoint.
    Service,
    /// A domain pack being registered.
    Pack,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GapSeverity {
    /// Cannot proceed without this. Hard stop.
    Blocking,
    /// Can proceed but with degraded quality.
    Degraded,
    /// Informational — might affect results.
    Advisory,
}

// ── Readiness Checker ──────────────────────────────────────────────

/// A single readiness probe. Implementations check one kind of resource.
pub trait ReadinessProbe: Send + Sync {
    fn kind(&self) -> ResourceKind;
    fn check(&self, binding: &IntentBinding) -> Vec<ReadinessItem>;
}

/// Single item from a probe — either confirmed or a gap.
pub enum ReadinessItem {
    Confirmed(ReadinessConfirmation),
    Gap(ReadinessGap),
}

/// Run all probes against a binding and produce a report.
pub fn check(binding: &IntentBinding, probes: &[&dyn ReadinessProbe]) -> ReadinessReport {
    let mut confirmed = Vec::new();
    let mut gaps = Vec::new();

    for probe in probes {
        for item in probe.check(binding) {
            match item {
                ReadinessItem::Confirmed(c) => confirmed.push(c),
                ReadinessItem::Gap(g) => gaps.push(g),
            }
        }
    }

    let ready = !gaps.iter().any(|g| g.severity == GapSeverity::Blocking);

    ReadinessReport {
        ready,
        confirmed,
        gaps,
    }
}

// ── Built-in Probes ────────────────────────────────────────────────

/// Checks that required capabilities have their credentials available
/// by reading environment variables.
pub struct CredentialProbe {
    /// Maps capability name → environment variable name.
    checks: Vec<(String, String)>,
}

impl CredentialProbe {
    #[must_use]
    pub fn new() -> Self {
        Self { checks: Vec::new() }
    }

    /// Register a credential requirement: if capability X is needed,
    /// environment variable Y must be set.
    #[must_use]
    pub fn require(mut self, capability: impl Into<String>, env_var: impl Into<String>) -> Self {
        self.checks.push((capability.into(), env_var.into()));
        self
    }

    /// Standard credential checks for organism-intelligence providers.
    #[must_use]
    pub fn with_standard_checks(self) -> Self {
        self.require("vision", "ANTHROPIC_API_KEY")
            .require("ocr", "MISTRAL_API_KEY")
            .require("linkedin", "LINKEDIN_API_KEY")
            .require("patent", "USPTO_API_KEY")
            .require("social", "ANTHROPIC_API_KEY")
    }
}

impl Default for CredentialProbe {
    fn default() -> Self {
        Self::new()
    }
}

impl ReadinessProbe for CredentialProbe {
    fn kind(&self) -> ResourceKind {
        ResourceKind::Credential
    }

    fn check(&self, binding: &IntentBinding) -> Vec<ReadinessItem> {
        let needed_capabilities: Vec<&str> = binding
            .capabilities
            .iter()
            .map(|c| c.capability.as_str())
            .collect();

        let mut items = Vec::new();
        for (capability, env_var) in &self.checks {
            if !needed_capabilities.contains(&capability.as_str()) {
                continue;
            }
            if std::env::var(env_var).is_ok() {
                items.push(ReadinessItem::Confirmed(ReadinessConfirmation {
                    resource: capability.clone(),
                    kind: ResourceKind::Credential,
                    detail: format!("{env_var} is set"),
                }));
            } else {
                items.push(ReadinessItem::Gap(ReadinessGap {
                    resource: capability.clone(),
                    kind: ResourceKind::Credential,
                    severity: GapSeverity::Blocking,
                    reason: format!("{env_var} is not set"),
                    suggestion: Some(format!("export {env_var}=<your-key>")),
                }));
            }
        }
        items
    }
}

/// Checks that all packs in the binding are registered in the registry.
pub struct PackProbe<'a> {
    registry: &'a super::registry::Registry,
}

impl<'a> PackProbe<'a> {
    #[must_use]
    pub fn new(registry: &'a super::registry::Registry) -> Self {
        Self { registry }
    }
}

impl ReadinessProbe for PackProbe<'_> {
    fn kind(&self) -> ResourceKind {
        ResourceKind::Pack
    }

    fn check(&self, binding: &IntentBinding) -> Vec<ReadinessItem> {
        let mut items = Vec::new();
        for pack_req in &binding.packs {
            let registered = self
                .registry
                .packs()
                .iter()
                .any(|p| p.name == pack_req.pack_name);
            if registered {
                items.push(ReadinessItem::Confirmed(ReadinessConfirmation {
                    resource: pack_req.pack_name.clone(),
                    kind: ResourceKind::Pack,
                    detail: "registered in runtime".into(),
                }));
            } else {
                let severity = if pack_req.confidence >= 0.8 {
                    GapSeverity::Blocking
                } else {
                    GapSeverity::Degraded
                };
                items.push(ReadinessItem::Gap(ReadinessGap {
                    resource: pack_req.pack_name.clone(),
                    kind: ResourceKind::Pack,
                    severity,
                    reason: format!(
                        "pack '{}' needed ({:?}, confidence {:.0}%) but not registered",
                        pack_req.pack_name,
                        pack_req.source,
                        pack_req.confidence * 100.0
                    ),
                    suggestion: Some(format!(
                        "registry.register_pack(\"{}\", ...)",
                        pack_req.pack_name
                    )),
                }));
            }
        }
        items
    }
}

/// Checks token/spend budget.
pub struct BudgetProbe {
    /// Maximum token spend allowed for this intent.
    pub token_budget: Option<u64>,
    /// Maximum dollar spend allowed.
    pub spend_budget: Option<f64>,
}

impl BudgetProbe {
    #[must_use]
    pub fn new() -> Self {
        Self {
            token_budget: None,
            spend_budget: None,
        }
    }

    #[must_use]
    pub fn with_token_budget(mut self, tokens: u64) -> Self {
        self.token_budget = Some(tokens);
        self
    }

    #[must_use]
    pub fn with_spend_budget(mut self, dollars: f64) -> Self {
        self.spend_budget = Some(dollars);
        self
    }
}

impl Default for BudgetProbe {
    fn default() -> Self {
        Self::new()
    }
}

impl ReadinessProbe for BudgetProbe {
    fn kind(&self) -> ResourceKind {
        ResourceKind::Budget
    }

    fn check(&self, binding: &IntentBinding) -> Vec<ReadinessItem> {
        let mut items = Vec::new();
        let needs_llm = binding
            .capabilities
            .iter()
            .any(|c| ["vision", "ocr", "social"].contains(&c.capability.as_str()));

        if needs_llm {
            if let Some(tokens) = self.token_budget {
                if tokens > 0 {
                    items.push(ReadinessItem::Confirmed(ReadinessConfirmation {
                        resource: "token_budget".into(),
                        kind: ResourceKind::Budget,
                        detail: format!("{tokens} tokens available"),
                    }));
                } else {
                    items.push(ReadinessItem::Gap(ReadinessGap {
                        resource: "token_budget".into(),
                        kind: ResourceKind::Budget,
                        severity: GapSeverity::Blocking,
                        reason: "token budget exhausted".into(),
                        suggestion: Some("increase token budget or remove LLM capabilities".into()),
                    }));
                }
            }

            if let Some(spend) = self.spend_budget {
                if spend > 0.0 {
                    items.push(ReadinessItem::Confirmed(ReadinessConfirmation {
                        resource: "spend_budget".into(),
                        kind: ResourceKind::Budget,
                        detail: format!("${spend:.2} remaining"),
                    }));
                } else {
                    items.push(ReadinessItem::Gap(ReadinessGap {
                        resource: "spend_budget".into(),
                        kind: ResourceKind::Budget,
                        severity: GapSeverity::Blocking,
                        reason: "spend budget exhausted".into(),
                        suggestion: Some("increase spend budget".into()),
                    }));
                }
            }
        }

        items
    }
}

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

    #[test]
    fn reports_ready_when_no_gaps() {
        let binding = DeclarativeBinding::new()
            .pack("customers", "lead qualification")
            .build();

        let report = check(&binding, &[]);
        assert!(report.ready);
        assert!(report.gaps.is_empty());
    }

    #[test]
    fn credential_probe_detects_missing_key() {
        let binding = DeclarativeBinding::new()
            .capability("vision", "scene understanding")
            .build();

        let probe =
            CredentialProbe::new().require("vision", "ORGANISM_TEST_KEY_THAT_DOES_NOT_EXIST");
        let report = check(&binding, &[&probe]);

        assert!(!report.ready);
        assert_eq!(report.gaps.len(), 1);
        assert_eq!(report.gaps[0].resource, "vision");
        assert_eq!(report.gaps[0].severity, GapSeverity::Blocking);
        assert!(report.gaps[0].reason.contains("not set"));
    }

    #[test]
    fn pack_probe_detects_unregistered_pack() {
        let binding = DeclarativeBinding::new()
            .pack("customers", "lead qualification")
            .pack("legal", "contract review")
            .build();

        let mut registry = super::super::registry::Registry::new();
        registry.register_pack_raw(super::super::registry::RegisteredPack {
            name: "customers".into(),
            description: "revenue ops".into(),
            fact_prefixes: vec!["lead:".into()],
            agent_names: vec![],
            invariant_names: vec![],
            agent_count: 8,
            invariant_count: 2,
            context_keys_read: vec![],
            context_keys_written: vec![],
            has_acceptance_invariants: false,
            profile: organism_domain::pack::PackProfile::default(),
        });
        // legal is NOT registered

        let probe = PackProbe::new(&registry);
        let report = check(&binding, &[&probe]);

        assert!(!report.ready);
        assert_eq!(report.confirmed.len(), 1);
        assert_eq!(report.confirmed[0].resource, "customers");
        assert_eq!(report.gaps.len(), 1);
        assert_eq!(report.gaps[0].resource, "legal");
    }

    #[test]
    fn budget_probe_blocks_on_zero_budget() {
        let binding = DeclarativeBinding::new()
            .capability("vision", "scene analysis")
            .build();

        let probe = BudgetProbe::new().with_token_budget(0);
        let report = check(&binding, &[&probe]);

        assert!(!report.ready);
        assert!(report.gaps.iter().any(|g| g.resource == "token_budget"));
    }

    #[test]
    fn budget_probe_confirms_available_budget() {
        let binding = DeclarativeBinding::new()
            .capability("ocr", "document reading")
            .build();

        let probe = BudgetProbe::new()
            .with_token_budget(100_000)
            .with_spend_budget(5.0);
        let report = check(&binding, &[&probe]);

        assert!(report.ready);
        assert_eq!(report.confirmed.len(), 2);
    }
}