exochain-catapult 0.2.0-beta

EXOCHAIN Catapult — franchise business incubator with FM 3-05 operational doctrine
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
// Copyright 2026 Exochain Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

//! Newco — an instantiated franchise company governed by ExoChain.

use exo_core::{Did, Hash256, Timestamp};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::{
    agent::{AgentRoster, CatapultAgent},
    budget::BudgetLedger,
    error::{CatapultError, Result},
    goal::GoalTree,
    oda::OdaSlot,
    phase::OperationalPhase,
    receipt::ReceiptChain,
};

/// Operational status of a newco.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum NewcoStatus {
    /// Being set up — tenant provisioning in progress.
    Provisioning,
    /// Fully operational.
    Active,
    /// Temporarily suspended (governance action or budget halt).
    Suspended,
    /// Transitioning — scaling, pivoting, or closing.
    Transitioning,
    /// Orderly close completed.
    Closed,
}

/// A newco — a franchised company instantiated from a blueprint.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Newco {
    pub id: Uuid,
    pub name: String,
    /// Back-reference to the franchise blueprint.
    pub franchise_id: Uuid,
    /// Tenant isolation boundary (exo-tenant).
    pub tenant_id: Uuid,
    /// Snapshot of the constitution at creation.
    pub constitution_hash: Hash256,
    /// Current FM 3-05 operational phase.
    pub phase: OperationalPhase,
    /// The ODA roster.
    pub roster: AgentRoster,
    /// Budget tracking.
    pub budget: BudgetLedger,
    /// Goal hierarchy.
    pub goals: GoalTree,
    /// Root of the ODA authority chain.
    pub authority_chain_root: Did,
    /// Anchor into the exo-dag provenance layer.
    pub dag_anchor: Hash256,
    /// When this newco was created.
    pub created: Timestamp,
    /// Last heartbeat from any agent.
    pub last_heartbeat: Timestamp,
    /// Current operational status.
    pub status: NewcoStatus,
}

/// Caller-supplied deterministic metadata for creating a newco.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewcoInput {
    pub id: Uuid,
    pub name: String,
    pub franchise_id: Uuid,
    pub tenant_id: Uuid,
    pub constitution_hash: Hash256,
    pub authority_chain_root: Did,
    pub dag_anchor: Hash256,
    pub created: Timestamp,
}

impl Newco {
    /// Create a new newco in Assessment phase.
    ///
    /// # Errors
    /// Returns [`CatapultError`] if the input contains placeholder metadata.
    pub fn new(input: NewcoInput) -> Result<Self> {
        validate_newco_input(&input)?;
        Ok(Self {
            id: input.id,
            name: input.name,
            franchise_id: input.franchise_id,
            tenant_id: input.tenant_id,
            constitution_hash: input.constitution_hash,
            phase: OperationalPhase::Assessment,
            roster: AgentRoster::new(),
            budget: BudgetLedger::new(),
            goals: GoalTree::new(),
            authority_chain_root: input.authority_chain_root,
            dag_anchor: input.dag_anchor,
            created: input.created,
            last_heartbeat: input.created,
            status: NewcoStatus::Provisioning,
        })
    }

    /// Validate externally supplied or deserialized newco metadata.
    ///
    /// # Errors
    /// Returns [`CatapultError`] when the newco contains placeholder identity,
    /// timestamp, or provenance metadata.
    pub fn validate(&self) -> Result<()> {
        validate_newco_input(&NewcoInput {
            id: self.id,
            name: self.name.clone(),
            franchise_id: self.franchise_id,
            tenant_id: self.tenant_id,
            constitution_hash: self.constitution_hash,
            authority_chain_root: self.authority_chain_root.clone(),
            dag_anchor: self.dag_anchor,
            created: self.created,
        })?;
        if self.last_heartbeat == Timestamp::ZERO {
            return Err(CatapultError::InvalidNewco {
                reason: "newco last heartbeat must not be zero".into(),
            });
        }
        if self.last_heartbeat < self.created {
            return Err(CatapultError::InvalidNewco {
                reason: "newco last heartbeat must not precede creation timestamp".into(),
            });
        }
        self.roster.validate()?;
        self.budget.validate()?;
        self.goals.validate()?;
        Ok(())
    }

    /// Advance to the next operational phase.
    ///
    /// Validates both the phase transition and roster sufficiency.
    pub fn advance_phase(&mut self, target: OperationalPhase) -> Result<()> {
        self.validate()?;
        // Validate the phase transition
        if !self.phase.can_transition_to(target) {
            return Err(CatapultError::InvalidPhaseTransition {
                from: self.phase,
                to: target,
            });
        }

        // Validate roster sufficiency for the target phase
        let required = target.min_roster();
        if !self.roster.has_slots(required) {
            return Err(CatapultError::RosterIncomplete {
                phase: target,
                needed: required.len(),
                have: self.roster.filled_count(),
            });
        }

        self.phase = target;

        // Update status based on phase
        self.status = match target {
            OperationalPhase::Assessment | OperationalPhase::Selection => NewcoStatus::Provisioning,
            OperationalPhase::Preparation
            | OperationalPhase::Execution
            | OperationalPhase::Sustainment => NewcoStatus::Active,
            OperationalPhase::Transition => NewcoStatus::Transitioning,
        };

        Ok(())
    }

    /// Hire an agent into an ODA slot.
    pub fn hire_agent(&mut self, agent: CatapultAgent) -> Result<()> {
        self.validate()?;
        self.roster.fill_slot(agent)
    }

    /// Release an agent from an ODA slot.
    pub fn release_agent(&mut self, slot: &OdaSlot) -> Result<CatapultAgent> {
        self.roster.release_slot(slot)
    }

    /// Suspend the newco (governance or budget action).
    pub fn suspend(&mut self) {
        self.status = NewcoStatus::Suspended;
    }

    /// Reactivate a suspended newco.
    pub fn reactivate(&mut self) {
        if self.status == NewcoStatus::Suspended {
            self.status = NewcoStatus::Active;
        }
    }

    /// Close the newco.
    pub fn close(&mut self) {
        self.status = NewcoStatus::Closed;
    }

    /// Whether the ODA roster is fully staffed.
    #[must_use]
    pub fn is_fully_staffed(&self) -> bool {
        self.roster.is_complete()
    }

    /// Whether the newco has its founding agents.
    #[must_use]
    pub fn has_founders(&self) -> bool {
        self.roster.has_slots(&OdaSlot::FOUNDERS)
    }
}

/// Registry of all newcos managed by Catapult.
#[derive(Debug, Clone, Default)]
pub struct NewcoRegistry {
    pub newcos: std::collections::BTreeMap<Uuid, Newco>,
    pub receipt_chains: std::collections::BTreeMap<Uuid, ReceiptChain>,
}

impl NewcoRegistry {
    /// Create an empty newco registry.
    #[must_use]
    pub fn new() -> Self {
        Self {
            newcos: std::collections::BTreeMap::new(),
            receipt_chains: std::collections::BTreeMap::new(),
        }
    }

    /// Register a new newco.
    pub fn register(&mut self, newco: Newco) -> Result<Uuid> {
        newco.validate()?;
        let id = newco.id;
        if self.newcos.contains_key(&id) {
            return Err(CatapultError::NewcoAlreadyExists(id));
        }
        self.newcos.insert(id, newco);
        self.receipt_chains.insert(id, ReceiptChain::new());
        Ok(id)
    }

    /// Look up a newco by ID.
    #[must_use]
    pub fn get(&self, id: &Uuid) -> Option<&Newco> {
        self.newcos.get(id)
    }

    /// Look up a newco by ID (mutable).
    #[must_use]
    pub fn get_mut(&mut self, id: &Uuid) -> Option<&mut Newco> {
        self.newcos.get_mut(id)
    }

    /// Get the receipt chain for a newco.
    #[must_use]
    pub fn receipts(&self, id: &Uuid) -> Option<&ReceiptChain> {
        self.receipt_chains.get(id)
    }

    /// Get the receipt chain for a newco (mutable).
    #[must_use]
    pub fn receipts_mut(&mut self, id: &Uuid) -> Option<&mut ReceiptChain> {
        self.receipt_chains.get_mut(id)
    }

    /// List all newcos.
    #[must_use]
    pub fn list(&self) -> Vec<&Newco> {
        self.newcos.values().collect()
    }

    /// Number of registered newcos.
    #[must_use]
    pub fn len(&self) -> usize {
        self.newcos.len()
    }

    /// Whether the registry is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.newcos.is_empty()
    }
}

fn validate_newco_input(input: &NewcoInput) -> Result<()> {
    if input.id.is_nil() {
        return Err(CatapultError::InvalidNewco {
            reason: "newco id must be caller-supplied and non-nil".into(),
        });
    }
    if input.name.trim().is_empty() {
        return Err(CatapultError::InvalidNewco {
            reason: "newco name must not be empty".into(),
        });
    }
    if input.franchise_id.is_nil() {
        return Err(CatapultError::InvalidNewco {
            reason: "newco franchise id must be non-nil".into(),
        });
    }
    if input.tenant_id.is_nil() {
        return Err(CatapultError::InvalidNewco {
            reason: "newco tenant id must be non-nil".into(),
        });
    }
    if input.constitution_hash == Hash256::ZERO {
        return Err(CatapultError::InvalidNewco {
            reason: "newco constitution hash must not be zero".into(),
        });
    }
    if input.dag_anchor == Hash256::ZERO {
        return Err(CatapultError::InvalidNewco {
            reason: "newco DAG anchor must not be zero".into(),
        });
    }
    if input.created == Timestamp::ZERO {
        return Err(CatapultError::InvalidNewco {
            reason: "newco created timestamp must be caller-supplied HLC".into(),
        });
    }
    Ok(())
}

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

    fn test_uuid(byte: u8) -> Uuid {
        Uuid::from_bytes([byte; 16])
    }

    fn test_hash(label: &str) -> Hash256 {
        Hash256::digest(label.as_bytes())
    }

    fn test_timestamp() -> Timestamp {
        Timestamp {
            physical_ms: 1_765_000_000_000,
            logical: 4,
        }
    }

    fn test_did() -> Did {
        Did::new("did:exo:test-root").unwrap()
    }

    fn test_newco_input() -> NewcoInput {
        NewcoInput {
            id: test_uuid(1),
            name: "Test Co".into(),
            franchise_id: test_uuid(2),
            tenant_id: test_uuid(3),
            constitution_hash: test_hash("constitution"),
            authority_chain_root: test_did(),
            dag_anchor: test_hash("dag-anchor"),
            created: test_timestamp(),
        }
    }

    fn make_newco() -> Newco {
        Newco::new(test_newco_input()).unwrap()
    }

    #[test]
    fn newco_new_requires_caller_supplied_identity_and_provenance() {
        let newco = Newco::new(test_newco_input()).unwrap();

        assert_eq!(newco.id, test_uuid(1));
        assert_eq!(newco.franchise_id, test_uuid(2));
        assert_eq!(newco.tenant_id, test_uuid(3));
        assert_ne!(newco.constitution_hash, Hash256::ZERO);
        assert_ne!(newco.dag_anchor, Hash256::ZERO);
        assert_ne!(newco.created, Timestamp::ZERO);
        assert_eq!(newco.last_heartbeat, newco.created);
    }

    #[test]
    fn newco_rejects_placeholder_metadata() {
        let mut input = test_newco_input();
        input.id = Uuid::nil();
        assert!(Newco::new(input).is_err());

        let mut input = test_newco_input();
        input.name = " ".into();
        assert!(Newco::new(input).is_err());

        let mut input = test_newco_input();
        input.franchise_id = Uuid::nil();
        assert!(Newco::new(input).is_err());

        let mut input = test_newco_input();
        input.tenant_id = Uuid::nil();
        assert!(Newco::new(input).is_err());

        let mut input = test_newco_input();
        input.constitution_hash = Hash256::ZERO;
        assert!(Newco::new(input).is_err());

        let mut input = test_newco_input();
        input.dag_anchor = Hash256::ZERO;
        assert!(Newco::new(input).is_err());

        let mut input = test_newco_input();
        input.created = Timestamp::ZERO;
        assert!(Newco::new(input).is_err());
    }

    #[test]
    fn registry_register_rejects_direct_placeholder_newco() {
        let mut reg = NewcoRegistry::new();
        let mut newco = make_newco();
        newco.dag_anchor = Hash256::ZERO;

        assert!(reg.register(newco).is_err());
    }

    #[test]
    fn newco_validate_rejects_deserialized_bad_heartbeat_state() {
        let mut newco = make_newco();
        newco.last_heartbeat = Timestamp::ZERO;
        assert!(newco.validate().is_err());

        let mut newco = make_newco();
        newco.last_heartbeat = Timestamp::new(1, 0);
        assert!(newco.validate().is_err());
    }

    fn make_agent(slot: OdaSlot) -> CatapultAgent {
        CatapultAgent {
            did: Did::new(&format!("did:exo:test-{slot:?}").to_ascii_lowercase()).unwrap(),
            slot,
            display_name: slot.display_name().into(),
            capabilities: vec![],
            status: AgentStatus::Active,
            last_heartbeat: Timestamp::new(1_765_000_000_100, 0),
            budget_spent_cents: 0,
            budget_limit_cents: 100_000,
            hired_at: Timestamp::new(1_765_000_000_000, 0),
            hired_by: test_did(),
            commandbase_profile: None,
        }
    }

    #[test]
    fn new_newco_starts_in_assessment() {
        let n = make_newco();
        assert_eq!(n.phase, OperationalPhase::Assessment);
        assert_eq!(n.status, NewcoStatus::Provisioning);
        assert!(!n.has_founders());
    }

    #[test]
    fn advance_to_selection_with_founders() {
        let mut n = make_newco();
        // Assessment → Selection requires founders
        n.hire_agent(make_agent(OdaSlot::HrPeopleOps1)).unwrap();
        n.hire_agent(make_agent(OdaSlot::DeepResearcher)).unwrap();
        n.advance_phase(OperationalPhase::Selection).unwrap();
        assert_eq!(n.phase, OperationalPhase::Selection);
    }

    #[test]
    fn cannot_skip_to_execution() {
        let mut n = make_newco();
        assert!(n.advance_phase(OperationalPhase::Execution).is_err());
    }

    #[test]
    fn roster_insufficient_for_phase() {
        let mut n = make_newco();
        // Try to enter Selection without founders
        assert!(n.advance_phase(OperationalPhase::Selection).is_err());
    }

    #[test]
    fn full_lifecycle() {
        let mut n = make_newco();

        // Hire founders
        n.hire_agent(make_agent(OdaSlot::HrPeopleOps1)).unwrap();
        n.hire_agent(make_agent(OdaSlot::DeepResearcher)).unwrap();
        n.advance_phase(OperationalPhase::Selection).unwrap();

        // Hire leadership
        n.hire_agent(make_agent(OdaSlot::VentureCommander)).unwrap();
        n.hire_agent(make_agent(OdaSlot::ProcessArchitect)).unwrap();
        n.advance_phase(OperationalPhase::Preparation).unwrap();

        // Fill remaining ODA
        n.hire_agent(make_agent(OdaSlot::OperationsDeputy)).unwrap();
        n.hire_agent(make_agent(OdaSlot::GrowthEngineer1)).unwrap();
        n.hire_agent(make_agent(OdaSlot::GrowthEngineer2)).unwrap();
        n.hire_agent(make_agent(OdaSlot::Communications1)).unwrap();
        n.hire_agent(make_agent(OdaSlot::Communications2)).unwrap();
        n.hire_agent(make_agent(OdaSlot::HrPeopleOps2)).unwrap();
        n.hire_agent(make_agent(OdaSlot::PlatformEngineer1))
            .unwrap();
        n.hire_agent(make_agent(OdaSlot::PlatformEngineer2))
            .unwrap();

        assert!(n.is_fully_staffed());
        n.advance_phase(OperationalPhase::Execution).unwrap();
        assert_eq!(n.status, NewcoStatus::Active);

        n.advance_phase(OperationalPhase::Sustainment).unwrap();
        n.advance_phase(OperationalPhase::Transition).unwrap();
        assert_eq!(n.status, NewcoStatus::Transitioning);

        // Can restart the cycle
        n.advance_phase(OperationalPhase::Assessment).unwrap();
    }

    #[test]
    fn suspend_and_reactivate() {
        let mut n = make_newco();
        n.status = NewcoStatus::Active;
        n.suspend();
        assert_eq!(n.status, NewcoStatus::Suspended);
        n.reactivate();
        assert_eq!(n.status, NewcoStatus::Active);
    }

    #[test]
    fn registry_crud() {
        let mut reg = NewcoRegistry::new();
        assert!(reg.is_empty());

        let n = make_newco();
        let id = n.id;
        reg.register(n).unwrap();

        assert_eq!(reg.len(), 1);
        assert!(reg.get(&id).is_some());
        assert!(reg.get_mut(&id).is_some());
        assert!(reg.receipts(&id).is_some());
        assert!(reg.receipts_mut(&id).is_some());
        assert_eq!(reg.list().len(), 1);
    }

    #[test]
    fn registry_duplicate_rejected() {
        let mut reg = NewcoRegistry::new();
        let n = make_newco();
        let n2 = n.clone();
        reg.register(n).unwrap();
        assert!(reg.register(n2).is_err());
    }

    #[test]
    fn status_serde() {
        let statuses = [
            NewcoStatus::Provisioning,
            NewcoStatus::Active,
            NewcoStatus::Suspended,
            NewcoStatus::Transitioning,
            NewcoStatus::Closed,
        ];
        for s in &statuses {
            let j = serde_json::to_string(s).unwrap();
            let rt: NewcoStatus = serde_json::from_str(&j).unwrap();
            assert_eq!(&rt, s);
        }
    }
}