organism-runtime 1.9.3

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
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
//! Registry — the runtime's catalog of available packs, capabilities, and invariants.
//!
//! Intent resolution queries the registry to find what's available.
//! Apps register what they've wired up; the resolver searches across it.
//! Standard pack catalogs (e.g. `organism-domain::register_standard_packs`)
//! sit on top, registering domain content into a `Registry`.

use organism_pack::{
    AgentMeta, CapabilityRequirement, ContextKey, IntentBinding, IntentPacket, IntentResolver,
    InvariantClass, InvariantMeta, PackProfile, PackRequirement, ResolutionLevel, Reversibility,
};

// ── Registered Pack ────────────────────────────────────────────────

#[derive(Debug, Clone)]
pub struct RegisteredPack {
    pub name: String,
    pub description: String,
    pub fact_prefixes: Vec<String>,
    pub agent_names: Vec<String>,
    pub invariant_names: Vec<String>,
    pub agent_count: usize,
    pub invariant_count: usize,
    pub context_keys_read: Vec<ContextKey>,
    pub context_keys_written: Vec<ContextKey>,
    pub has_acceptance_invariants: bool,
    pub profile: PackProfile,
}

#[derive(Debug, Clone)]
pub struct RegisteredCapability {
    pub name: String,
    pub description: String,
}

// ── Registry ───────────────────────────────────────────────────────

#[derive(Debug, Clone, Default)]
pub struct Registry {
    packs: Vec<RegisteredPack>,
    capabilities: Vec<RegisteredCapability>,
}

impl Registry {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a domain pack only if a pack with the same name is not already
    /// registered. Used by standard-pack catalogs (e.g. `organism-domain`) to
    /// be safely callable multiple times.
    pub fn register_pack_with_profile_if_missing(
        &mut self,
        name: &'static str,
        agents: &[AgentMeta],
        invariants: &[InvariantMeta],
        profile: &PackProfile,
    ) {
        if self.packs.iter().any(|pack| pack.name == name) {
            return;
        }

        self.register_pack_with_profile(name, agents, invariants, profile);
    }

    /// Register a domain pack with full metadata and profile.
    pub fn register_pack_with_profile(
        &mut self,
        name: impl Into<String>,
        agents: &[AgentMeta],
        invariants: &[InvariantMeta],
        profile: &PackProfile,
    ) {
        let name = name.into();
        let fact_prefixes: Vec<String> = agents
            .iter()
            .map(|a| a.fact_prefix.to_string())
            .collect::<std::collections::HashSet<_>>()
            .into_iter()
            .collect();
        let agent_names = agents.iter().map(|a| a.name.to_string()).collect();
        let invariant_names = invariants.iter().map(|i| i.name.to_string()).collect();
        let description = agents
            .iter()
            .map(|a| a.description)
            .collect::<Vec<_>>()
            .join("; ");

        let context_keys_read: Vec<ContextKey> = agents
            .iter()
            .flat_map(|a| a.dependencies.iter().copied())
            .collect::<std::collections::HashSet<_>>()
            .into_iter()
            .collect();
        let context_keys_written: Vec<ContextKey> = agents
            .iter()
            .map(|a| a.target_key)
            .collect::<std::collections::HashSet<_>>()
            .into_iter()
            .collect();
        let has_acceptance_invariants = invariants
            .iter()
            .any(|i| i.class == InvariantClass::Acceptance);

        self.packs.push(RegisteredPack {
            name,
            description,
            fact_prefixes,
            agent_names,
            invariant_names,
            agent_count: agents.len(),
            invariant_count: invariants.len(),
            context_keys_read,
            context_keys_written,
            has_acceptance_invariants,
            profile: profile.clone(),
        });
    }

    /// Register a domain pack (without profile — uses default).
    pub fn register_pack(
        &mut self,
        name: impl Into<String>,
        agents: &[AgentMeta],
        invariants: &[InvariantMeta],
    ) {
        self.register_pack_with_profile(name, agents, invariants, &PackProfile::default());
    }

    /// Register a pack directly from a raw struct.
    pub fn register_pack_raw(&mut self, pack: RegisteredPack) {
        self.packs.push(pack);
    }

    /// Register an available capability.
    pub fn register_capability(&mut self, name: impl Into<String>, description: impl Into<String>) {
        self.capabilities.push(RegisteredCapability {
            name: name.into(),
            description: description.into(),
        });
    }

    #[must_use]
    pub fn packs_for_prefix(&self, prefix: &str) -> Vec<&RegisteredPack> {
        self.packs
            .iter()
            .filter(|p| p.fact_prefixes.iter().any(|fp| fp == prefix))
            .collect()
    }

    #[must_use]
    pub fn packs_for_prefixes(&self, prefixes: &[&str]) -> Vec<&RegisteredPack> {
        self.packs
            .iter()
            .filter(|p| {
                p.fact_prefixes
                    .iter()
                    .any(|fp| prefixes.contains(&fp.as_str()))
            })
            .collect()
    }

    #[must_use]
    pub fn packs_for_entity(&self, entity: &str) -> Vec<&RegisteredPack> {
        let entity = entity.to_lowercase();
        self.packs
            .iter()
            .filter(|p| p.profile.entities.iter().any(|e| *e == entity))
            .collect()
    }

    #[must_use]
    pub fn packs_for_keyword(&self, keyword: &str) -> Vec<&RegisteredPack> {
        let keyword = keyword.to_lowercase();
        self.packs
            .iter()
            .filter(|p| p.profile.keywords.iter().any(|k| *k == keyword))
            .collect()
    }

    #[must_use]
    pub fn packs_writing_key(&self, key: ContextKey) -> Vec<&RegisteredPack> {
        self.packs
            .iter()
            .filter(|p| p.context_keys_written.contains(&key))
            .collect()
    }

    #[must_use]
    pub fn packs_handling_irreversible(&self) -> Vec<&RegisteredPack> {
        self.packs
            .iter()
            .filter(|p| p.profile.handles_irreversible && p.has_acceptance_invariants)
            .collect()
    }

    #[must_use]
    pub fn packs_requiring_capability(&self, capability: &str) -> Vec<&RegisteredPack> {
        self.packs
            .iter()
            .filter(|p| p.profile.required_capabilities.contains(&capability))
            .collect()
    }

    #[must_use]
    pub fn search_packs(&self, query: &str) -> Vec<&RegisteredPack> {
        let query = query.to_lowercase();
        self.packs
            .iter()
            .filter(|p| {
                p.name.to_lowercase().contains(&query)
                    || p.description.to_lowercase().contains(&query)
                    || p.profile.keywords.iter().any(|k| k.contains(&query))
                    || p.profile.entities.iter().any(|e| e.contains(&query))
            })
            .collect()
    }

    #[must_use]
    pub fn has_capability(&self, name: &str) -> bool {
        self.capabilities.iter().any(|c| c.name == name)
    }

    #[must_use]
    pub fn search_capabilities(&self, query: &str) -> Vec<&RegisteredCapability> {
        let query = query.to_lowercase();
        self.capabilities
            .iter()
            .filter(|c| {
                c.name.to_lowercase().contains(&query)
                    || c.description.to_lowercase().contains(&query)
            })
            .collect()
    }

    #[must_use]
    pub fn packs(&self) -> &[RegisteredPack] {
        &self.packs
    }

    #[must_use]
    pub fn capabilities(&self) -> &[RegisteredCapability] {
        &self.capabilities
    }
}

// ── Structural Resolver (multi-dimension) ──────────────────────────

/// Level 2 resolver with 10 matching dimensions:
///
/// 1. Fact prefix matching
/// 2. Constraint → invariant matching
/// 3. Context key flow matching
/// 4. Domain entity matching
/// 5. Keyword matching
/// 6. Reversibility matching
/// 7. Forbidden action filtering
/// 8. Capability affinity
/// 9. HITL requirement matching
/// 10. Blueprint expansion (TODO)
pub struct StructuralResolver<'a> {
    registry: &'a Registry,
}

const STRONG_CONTEXT_FLOW_ANCHOR_CONFIDENCE: f64 = 0.75;

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

#[allow(clippy::too_many_lines)]
impl IntentResolver for StructuralResolver<'_> {
    fn level(&self) -> ResolutionLevel {
        ResolutionLevel::Structural
    }

    fn resolve(&self, intent: &IntentPacket, current: &IntentBinding) -> IntentBinding {
        let mut binding = current.clone();
        let already_bound: std::collections::HashSet<String> =
            binding.packs.iter().map(|p| p.pack_name.clone()).collect();

        let mut matched: Vec<(String, String, f64)> = Vec::new(); // (pack, reason, confidence)

        // ── Dimension 1: Fact prefix matching ──────────────────────
        let prefixes = extract_fact_prefixes(&intent.context);
        for prefix in &prefixes {
            for pack in self.registry.packs_for_prefix(prefix) {
                if !already_bound.contains(&pack.name) {
                    matched.push((
                        pack.name.clone(),
                        format!("fact prefix '{prefix}' → pack '{}'", pack.name),
                        0.9,
                    ));
                }
            }
        }

        // ── Dimension 2: Constraint → invariant matching ───────────
        for constraint in &intent.constraints {
            for pack in &self.registry.packs {
                if pack.invariant_names.iter().any(|i| constraint.contains(i))
                    && !already_bound.contains(&pack.name)
                {
                    matched.push((
                        pack.name.clone(),
                        format!("constraint '{constraint}' → invariant in '{}'", pack.name),
                        0.85,
                    ));
                }
            }
        }

        // ── Dimension 4: Domain entity matching ────────────────────
        let entities = extract_entities(&intent.outcome);
        for entity in &entities {
            for pack in self.registry.packs_for_entity(entity) {
                if !already_bound.contains(&pack.name) {
                    matched.push((
                        pack.name.clone(),
                        format!("entity '{entity}' → pack '{}'", pack.name),
                        0.75,
                    ));
                }
            }
        }

        // ── Dimension 5: Keyword matching ──────────────────────────
        let keywords = extract_keywords(&intent.outcome);
        for keyword in &keywords {
            for pack in self.registry.packs_for_keyword(keyword) {
                if !already_bound.contains(&pack.name) {
                    matched.push((
                        pack.name.clone(),
                        format!("keyword '{keyword}' → pack '{}'", pack.name),
                        0.65,
                    ));
                }
            }
        }

        // ── Dimension 6: Reversibility matching ────────────────────
        if intent.reversibility == Reversibility::Irreversible {
            for pack in self.registry.packs_handling_irreversible() {
                if !already_bound.contains(&pack.name) {
                    matched.push((
                        pack.name.clone(),
                        format!(
                            "irreversible intent → pack '{}' has Acceptance invariants",
                            pack.name
                        ),
                        0.7,
                    ));
                }
            }
        }

        // ── Dimension 3: Context key flow matching ─────────────────
        // Context keys are useful only when they extend a stronger anchor.
        // Avoid global fan-out like "all packs writing Evaluations".
        let needed_keys = extract_context_keys(&intent.context);
        let anchored_pack_names = already_bound
            .iter()
            .cloned()
            .chain(
                matched
                    .iter()
                    .filter(|(_, _, confidence)| {
                        *confidence >= STRONG_CONTEXT_FLOW_ANCHOR_CONFIDENCE
                    })
                    .map(|(pack_name, _, _)| pack_name.clone()),
            )
            .collect::<std::collections::HashSet<_>>();
        let anchored_packs = anchored_pack_names
            .iter()
            .filter_map(|pack_name| {
                self.registry
                    .packs
                    .iter()
                    .find(|pack| &pack.name == pack_name)
            })
            .collect::<Vec<_>>();

        let anchor_written_keys = anchored_packs
            .iter()
            .flat_map(|pack| pack.context_keys_written.iter().copied())
            .filter(|key| needed_keys.contains(key))
            .collect::<std::collections::HashSet<_>>();

        for pack in &anchored_packs {
            for key in pack
                .context_keys_written
                .iter()
                .filter(|key| needed_keys.contains(key))
            {
                if !already_bound.contains(&pack.name) {
                    matched.push((
                        pack.name.clone(),
                        format!(
                            "anchored context flow → pack '{}' writes needed {key:?}",
                            pack.name
                        ),
                        0.78,
                    ));
                }
            }
        }

        if needed_keys.len() >= 2 && !anchor_written_keys.is_empty() {
            for pack in &self.registry.packs {
                if already_bound.contains(&pack.name) || anchored_pack_names.contains(&pack.name) {
                    continue;
                }

                let Some(read_key) = pack
                    .context_keys_read
                    .iter()
                    .copied()
                    .find(|key| anchor_written_keys.contains(key))
                else {
                    continue;
                };
                let Some(write_key) = pack
                    .context_keys_written
                    .iter()
                    .copied()
                    .find(|key| needed_keys.contains(key) && *key != read_key)
                else {
                    continue;
                };

                matched.push((
                    pack.name.clone(),
                    format!("context flow bridge {read_key:?}{write_key:?} from anchored packs"),
                    0.72,
                ));
            }
        }

        // ── Dimension 7: Forbidden action filtering ────────────────
        let forbidden_keywords: Vec<String> = intent
            .forbidden
            .iter()
            .map(|f| f.action.to_lowercase())
            .collect();
        matched.retain(|(pack_name, _, _)| {
            if let Some(pack) = self.registry.packs.iter().find(|p| &p.name == pack_name) {
                !pack.profile.keywords.iter().any(|k| {
                    forbidden_keywords
                        .iter()
                        .any(|f| f.contains(k) || k.contains(f.as_str()))
                })
            } else {
                true
            }
        });

        // ── Dimension 8: Capability affinity ───────────────────────
        // If ANY bound pack (declarative or matched) requires capabilities, add them.
        let mut needed_capabilities: Vec<(String, String)> = Vec::new();
        let all_pack_names: Vec<String> = already_bound
            .iter()
            .chain(matched.iter().map(|(name, _, _)| name))
            .cloned()
            .collect();
        for pack_name in &all_pack_names {
            if let Some(pack) = self.registry.packs.iter().find(|p| &p.name == pack_name) {
                for cap in pack.profile.required_capabilities {
                    if !binding.capabilities.iter().any(|c| c.capability == *cap)
                        && !needed_capabilities.iter().any(|(c, _)| c == *cap)
                    {
                        needed_capabilities.push((
                            (*cap).to_string(),
                            format!("required by pack '{pack_name}'"),
                        ));
                    }
                }
            }
        }

        // Deduplicate: keep highest confidence per pack
        let mut best: std::collections::HashMap<String, (String, f64)> =
            std::collections::HashMap::new();
        for (pack_name, reason, confidence) in matched {
            let entry = best
                .entry(pack_name.clone())
                .or_insert((reason.clone(), 0.0));
            if confidence > entry.1 {
                *entry = (reason, confidence);
            }
        }

        for (pack_name, (reason, confidence)) in best {
            binding.packs.push(PackRequirement {
                pack_name,
                reason,
                confidence: converge_pack::UnitInterval::clamped(confidence),
                source: ResolutionLevel::Structural,
            });
        }

        for (cap, reason) in needed_capabilities {
            binding.capabilities.push(CapabilityRequirement {
                capability: cap.into(),
                reason,
                confidence: converge_pack::UnitInterval::clamped(0.85),
                source: ResolutionLevel::Structural,
            });
        }

        if !binding
            .resolution
            .levels_attempted
            .contains(&ResolutionLevel::Structural)
        {
            binding
                .resolution
                .levels_attempted
                .push(ResolutionLevel::Structural);
            binding
                .resolution
                .levels_contributed
                .push(ResolutionLevel::Structural);
        }

        binding
    }
}

// ── Extraction helpers ─────────────────────────────────────────────

fn extract_fact_prefixes(context: &serde_json::Value) -> Vec<String> {
    let mut prefixes = Vec::new();
    collect_prefixes(context, &mut prefixes);
    prefixes.sort();
    prefixes.dedup();
    prefixes
}

fn collect_prefixes(value: &serde_json::Value, prefixes: &mut Vec<String>) {
    match value {
        serde_json::Value::String(s) => {
            if let Some(colon) = s.find(':') {
                let candidate = &s[..=colon];
                if candidate.len() >= 3 && candidate.chars().next().is_some_and(char::is_alphabetic)
                {
                    prefixes.push(candidate.to_string());
                }
            }
        }
        serde_json::Value::Array(arr) => {
            for v in arr {
                collect_prefixes(v, prefixes);
            }
        }
        serde_json::Value::Object(map) => {
            for (key, v) in map {
                if key.ends_with(':') {
                    prefixes.push(key.clone());
                }
                collect_prefixes(v, prefixes);
            }
        }
        _ => {}
    }
}

fn extract_context_keys(context: &serde_json::Value) -> Vec<ContextKey> {
    let mut keys = Vec::new();
    // Only match explicit ContextKey references in structured fields,
    // not incidental word matches in free text.
    if let Some(obj) = context.as_object() {
        for key in obj.keys() {
            let k = key.to_lowercase();
            if k == "evaluations" || k == "evaluation" {
                keys.push(ContextKey::Evaluations);
            }
            if k == "strategies" || k == "strategy" {
                keys.push(ContextKey::Strategies);
            }
            if k == "proposals" || k == "proposal" {
                keys.push(ContextKey::Proposals);
            }
            if k == "constraints" || k == "constraint" {
                keys.push(ContextKey::Constraints);
            }
            if k == "signals" || k == "signal" {
                keys.push(ContextKey::Signals);
            }
        }
    }
    keys.dedup();
    keys
}

fn extract_entities(outcome: &str) -> Vec<String> {
    let outcome = outcome.to_lowercase();
    let known_entities = [
        "lead",
        "vendor",
        "contract",
        "employee",
        "expense",
        "deal",
        "partner",
        "subscription",
        "asset",
        "ticket",
        "campaign",
        "feature",
        "release",
        "incident",
        "policy",
        "approval",
        "budget",
        "team",
        "persona",
        "skill",
        "credential",
        "patent",
        "signal",
        "hypothesis",
        "experiment",
    ];
    known_entities
        .iter()
        .filter(|e| outcome.contains(**e))
        .map(|e| (*e).to_string())
        .collect()
}

const STOP_WORDS: &[&str] = &[
    "this", "that", "with", "from", "have", "your", "into", "about", "would", "there", "their",
    "they", "them", "when", "what", "where", "which", "shall", "could", "should", "will", "been",
    "does", "done", "each", "every", "some", "than", "then", "also", "just", "only", "most",
    "such", "very", "more", "over", "under", "after", "before", "between", "through", "during",
    "without", "within", "along", "across", "against", "around", "upon", "onto", "produce",
    "process", "create", "update", "manage", "handle", "ensure", "track", "check", "verify",
    "analyze", "review", "prepare", "complete",
];

fn extract_keywords(outcome: &str) -> Vec<String> {
    outcome
        .to_lowercase()
        .split_whitespace()
        .filter(|w| w.len() >= 4)
        .map(|w| w.trim_matches(|c: char| !c.is_alphanumeric()).to_string())
        .filter(|w| !w.is_empty() && !STOP_WORDS.contains(&w.as_str()))
        .collect()
}