ggen-core 26.6.25

Core graph-aware code generation engine
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
use crate::parts_execution::{ExecutionPacket, ExecutionStatus, PartExecutor, VectorClock};
use crate::utils::error::Result;
use async_trait::async_trait;
use blake3;
use chrono::Utc;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

/// Stewardship Part: WelcomeOneAnotherPart
///
/// Scripture: Romans 15:7 - "Welcome one another, therefore, as Christ has welcomed you, for the glory of God."
/// AA Structure: Agent(Steward), Activity(WelcomeActivity), Object(Visitor)
/// Owner: StewardshipCell
/// Timer: 24h
/// Terminal State: ReceivedAndRemembered
pub struct WelcomeOneAnotherPart {
    pub part_id: String,
    pub owner: String,
}

impl WelcomeOneAnotherPart {
    pub fn new(part_id: String, owner: String) -> Self {
        Self { part_id, owner }
    }

    /// Event-to-obligation mapping for the initial "arrival" event.
    pub fn identifies_obligation(&self, event_type: &str) -> bool {
        event_type == "VisitorArrival"
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct WelcomeInput {
    pub visitor_id: String,
    pub arrival_timestamp: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct WelcomeOutput {
    pub status: String,
    pub scripture_basis: String,
    pub terminal_state: String,
    pub owner: String,
    pub welcome_timestamp: String,
    pub prov_receipt: ProvReceipt,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ProvReceipt {
    pub activity_id: String,
    pub agent_id: String,
    pub entity_id: String,
    pub generated_at_time: String,
    pub scripture: String,
}

#[async_trait]
impl PartExecutor for WelcomeOneAnotherPart {
    async fn execute(&self, input: Vec<u8>) -> Result<(Vec<u8>, ExecutionPacket)> {
        let input_json: WelcomeInput = serde_json::from_slice(&input)
            .map_err(|e| crate::utils::error::Error::new(&format!("Invalid input JSON: {}", e)))?;

        let now = Utc::now();
        let activity_id = format!("welcome-{}", Uuid::new_v4());

        let prov_receipt = ProvReceipt {
            activity_id: activity_id.clone(),
            agent_id: self.owner.clone(), // The cell acts as the agent/steward
            entity_id: input_json.visitor_id.clone(),
            generated_at_time: now.to_rfc3339(),
            scripture: "Romans 15:7".to_string(),
        };

        let output = WelcomeOutput {
            status: "Success".to_string(),
            scripture_basis: "Romans 15:7".to_string(),
            terminal_state: "ReceivedAndRemembered".to_string(),
            owner: self.owner.clone(),
            welcome_timestamp: now.to_rfc3339(),
            prov_receipt,
        };

        let output_bytes = serde_json::to_vec(&output).map_err(|e| {
            crate::utils::error::Error::new(&format!("JSON serialization failed: {}", e))
        })?;

        let input_hash = blake3::hash(&input).into();
        let output_hash = blake3::hash(&output_bytes).into();

        let mut clock = VectorClock::new(self.part_id.clone());
        clock.tick(&self.part_id);

        let packet = ExecutionPacket::new(
            Uuid::new_v4().to_string(),
            self.part_id.clone(),
            input_hash,
            output_hash,
            clock,
            ExecutionStatus::Success,
            1,
        );

        Ok((output_bytes, packet))
    }
}

/// Stewardship Part: ConsentGatePart
///
/// Scripture: Galatians 6:2 - "Carry each other’s burdens, and in this way you will fulfill the law of Christ."
/// Refusal Law: No follow-up activity is admitted without an explicit stpnt:ConsentReceived event.
/// Terminal State: ConsentAdmitted | ConsentRefused
pub struct ConsentGatePart {
    pub part_id: String,
    pub owner: String,
}

impl ConsentGatePart {
    pub fn new(part_id: String, owner: String) -> Self {
        Self { part_id, owner }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ConsentInput {
    pub person_id: String,
    pub follow_up_activity: String,
    pub has_consent_receipt: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ConsentOutput {
    pub status: String,
    pub scripture_basis: String,
    pub refusal_evidence: Option<String>,
    pub terminal_state: String,
    pub owner: String,
    pub prov_receipt: ProvReceipt,
}

#[async_trait]
impl PartExecutor for ConsentGatePart {
    async fn execute(&self, input: Vec<u8>) -> Result<(Vec<u8>, ExecutionPacket)> {
        let input_json: ConsentInput = serde_json::from_slice(&input)
            .map_err(|e| crate::utils::error::Error::new(&format!("Invalid input: {}", e)))?;

        let now = Utc::now();
        let activity_id = format!("consent-gate-{}", Uuid::new_v4());

        let (status, terminal_state, refusal_evidence, execution_status) = if input_json
            .has_consent_receipt
        {
            (
                "Admitted".to_string(),
                "ConsentAdmitted".to_string(),
                None,
                ExecutionStatus::Success,
            )
        } else {
            (
                "Refused".to_string(),
                "ConsentRefused".to_string(),
                Some("Refusal: No stpnt:ConsentReceived found for follow-up attempt.".to_string()),
                ExecutionStatus::Refused,
            )
        };

        let output = ConsentOutput {
            status,
            scripture_basis: "Galatians 6:2".to_string(),
            refusal_evidence,
            terminal_state,
            owner: self.owner.clone(),
            prov_receipt: ProvReceipt {
                activity_id,
                agent_id: self.owner.clone(),
                entity_id: input_json.person_id.clone(),
                generated_at_time: now.to_rfc3339(),
                scripture: "Galatians 6:2".to_string(),
            },
        };

        let output_bytes = serde_json::to_vec(&output).map_err(|e| {
            crate::utils::error::Error::new(&format!("JSON serialization failed: {}", e))
        })?;
        let input_hash = blake3::hash(&input).into();
        let output_hash = blake3::hash(&output_bytes).into();

        let mut clock = VectorClock::new(self.part_id.clone());
        clock.tick(&self.part_id);

        let packet = ExecutionPacket::new(
            Uuid::new_v4().to_string(),
            self.part_id.clone(),
            input_hash,
            output_hash,
            clock,
            execution_status,
            1,
        );

        Ok((output_bytes, packet))
    }
}

/// Stewardship Part: AssignStewardPart
///
/// Scripture: 1 Corinthians 4:2 - "Moreover it is required in stewards, that a man be found faithful."
pub struct AssignStewardPart {
    pub part_id: String,
    pub owner: String,
}

impl AssignStewardPart {
    pub fn new(part_id: String, owner: String) -> Self {
        Self { part_id, owner }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AssignInput {
    pub obligation_id: String,
    pub steward_uri: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AssignOutput {
    pub status: String,
    pub terminal_state: String,
    pub prov_receipt: ProvReceipt,
}

#[async_trait]
impl PartExecutor for AssignStewardPart {
    async fn execute(&self, input: Vec<u8>) -> Result<(Vec<u8>, ExecutionPacket)> {
        let input_json: AssignInput = serde_json::from_slice(&input)
            .map_err(|e| crate::utils::error::Error::new(&format!("Invalid input: {}", e)))?;

        let now = Utc::now();
        let output = AssignOutput {
            status: "Assigned".to_string(),
            terminal_state: "StewardBound".to_string(),
            prov_receipt: ProvReceipt {
                activity_id: format!("assign-{}", Uuid::new_v4()),
                agent_id: self.owner.clone(),
                entity_id: input_json.obligation_id.clone(),
                generated_at_time: now.to_rfc3339(),
                scripture: "1 Corinthians 4:2".to_string(),
            },
        };

        let output_bytes = serde_json::to_vec(&output).map_err(|e| {
            crate::utils::error::Error::new(&format!("JSON serialization failed: {}", e))
        })?;
        let packet = ExecutionPacket::new(
            Uuid::new_v4().to_string(),
            self.part_id.clone(),
            blake3::hash(&input).into(),
            blake3::hash(&output_bytes).into(),
            VectorClock::new(self.part_id.clone()),
            ExecutionStatus::Success,
            1,
        );
        Ok((output_bytes, packet))
    }
}

/// Stewardship Part: FollowUpObligationPart
///
/// Scripture: 1 Corinthians 4:2 - "Moreover it is required in stewards, that a man be found faithful."
pub struct FollowUpObligationPart {
    pub part_id: String,
    pub owner: String,
}

impl FollowUpObligationPart {
    pub fn new(part_id: String, owner: String) -> Self {
        Self { part_id, owner }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FollowUpInput {
    pub obligation_id: String,
    pub deadline: String, // ISO8601
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FollowUpOutput {
    pub status: String,
    pub terminal_state: String,
}

#[async_trait]
impl PartExecutor for FollowUpObligationPart {
    async fn execute(&self, input: Vec<u8>) -> Result<(Vec<u8>, ExecutionPacket)> {
        let input_json: FollowUpInput = serde_json::from_slice(&input)
            .map_err(|e| crate::utils::error::Error::new(&format!("Invalid input JSON: {}", e)))?;
        let deadline = chrono::DateTime::parse_from_rfc3339(&input_json.deadline).map_err(|e| {
            crate::utils::error::Error::new(&format!("Invalid deadline timestamp: {}", e))
        })?;

        let (status, terminal_state, execution_status) = if Utc::now() > deadline {
            (
                "Escalated".to_string(),
                "Overdue".to_string(),
                ExecutionStatus::Refused,
            )
        } else {
            (
                "Pending".to_string(),
                "InProgress".to_string(),
                ExecutionStatus::Success,
            )
        };

        let output = FollowUpOutput {
            status: status.to_string(),
            terminal_state: terminal_state.to_string(),
        };
        let output_bytes = serde_json::to_vec(&output).map_err(|e| {
            crate::utils::error::Error::new(&format!("JSON serialization failed: {}", e))
        })?;
        let packet = ExecutionPacket::new(
            Uuid::new_v4().to_string(),
            self.part_id.clone(),
            blake3::hash(&input).into(),
            blake3::hash(&output_bytes).into(),
            VectorClock::new(self.part_id.clone()),
            execution_status,
            1,
        );
        Ok((output_bytes, packet))
    }
}

/// Stewardship Part: PentecostInvitationPart
///
/// Scripture: 1 Corinthians 12 - Distributed Gifts
pub struct PentecostInvitationPart {
    pub part_id: String,
    pub owner: String,
}

impl PentecostInvitationPart {
    pub fn new(part_id: String, owner: String) -> Self {
        Self { part_id, owner }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct InvitationInput {
    pub person_id: String,
    pub is_capable_of_receiving_another: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct InvitationOutput {
    pub status: String,
    pub terminal_state: String,
}

#[async_trait]
impl PartExecutor for PentecostInvitationPart {
    async fn execute(&self, input: Vec<u8>) -> Result<(Vec<u8>, ExecutionPacket)> {
        let input_json: InvitationInput = serde_json::from_slice(&input)
            .map_err(|e| crate::utils::error::Error::new(&format!("Invalid input JSON: {}", e)))?;

        let (status, terminal_state) = if input_json.is_capable_of_receiving_another {
            (
                "Incorporated".to_string(),
                "IncorporatedAndServing".to_string(),
            )
        } else {
            ("Developing".to_string(), "FormationPending".to_string())
        };

        let output = InvitationOutput {
            status: status.to_string(),
            terminal_state: terminal_state.to_string(),
        };
        let output_bytes = serde_json::to_vec(&output).map_err(|e| {
            crate::utils::error::Error::new(&format!("JSON serialization failed: {}", e))
        })?;
        let packet = ExecutionPacket::new(
            Uuid::new_v4().to_string(),
            self.part_id.clone(),
            blake3::hash(&input).into(),
            blake3::hash(&output_bytes).into(),
            VectorClock::new(self.part_id.clone()),
            ExecutionStatus::Success,
            1,
        );
        Ok((output_bytes, packet))
    }
}

/// Stewardship Part: ContinuityWatchPart
///
/// Scripture: Hebrews 13:17 - "keeping watch over your souls"
pub struct ContinuityWatchPart {
    pub part_id: String,
    pub owner: String,
}

impl ContinuityWatchPart {
    pub fn new(part_id: String, owner: String) -> Self {
        Self { part_id, owner }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ContinuityInput {
    pub last_activity: String, // ISO8601
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ContinuityOutput {
    pub alert: bool,
    pub message: String,
}

#[async_trait]
impl PartExecutor for ContinuityWatchPart {
    async fn execute(&self, input: Vec<u8>) -> Result<(Vec<u8>, ExecutionPacket)> {
        let input_json: ContinuityInput = serde_json::from_slice(&input)
            .map_err(|e| crate::utils::error::Error::new(&format!("Invalid input JSON: {}", e)))?;
        let last_act =
            chrono::DateTime::parse_from_rfc3339(&input_json.last_activity).map_err(|e| {
                crate::utils::error::Error::new(&format!("Invalid last_activity timestamp: {}", e))
            })?;

        let alert = Utc::now() - last_act.with_timezone(&Utc) > chrono::Duration::days(7);
        let output = ContinuityOutput {
            alert,
            message: if alert {
                "Alert: Silent disappearance detected."
            } else {
                "Continuity verified."
            }
            .to_string(),
        };

        let output_bytes = serde_json::to_vec(&output).map_err(|e| {
            crate::utils::error::Error::new(&format!("JSON serialization failed: {}", e))
        })?;
        let packet = ExecutionPacket::new(
            Uuid::new_v4().to_string(),
            self.part_id.clone(),
            blake3::hash(&input).into(),
            blake3::hash(&output_bytes).into(),
            VectorClock::new(self.part_id.clone()),
            ExecutionStatus::Success,
            1,
        );
        Ok((output_bytes, packet))
    }
}

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

    #[tokio::test]
    async fn test_welcome_one_another_part_execution() {
        let part = WelcomeOneAnotherPart::new(
            "WelcomeOneAnotherPart-001".to_string(),
            "StewardshipCell-Alpha".to_string(),
        );

        assert!(part.identifies_obligation("VisitorArrival"));

        let input = WelcomeInput {
            visitor_id: "visitor-123".to_string(),
            arrival_timestamp: Utc::now().to_rfc3339(),
        };

        let input_bytes = serde_json::to_vec(&input).unwrap();
        let (output_bytes, packet) = part.execute(input_bytes).await.expect("Execution failed");
        let output: WelcomeOutput =
            serde_json::from_slice(&output_bytes).expect("Invalid output JSON");

        assert_eq!(output.scripture_basis, "Romans 15:7");
        assert_eq!(output.terminal_state, "ReceivedAndRemembered");
        assert_eq!(packet.status, ExecutionStatus::Success);
    }

    #[tokio::test]
    async fn test_consent_gate_part_refusal() {
        let part =
            ConsentGatePart::new("ConsentGate-001".to_string(), "StewardshipCell".to_string());
        let input = ConsentInput {
            person_id: "person-456".to_string(),
            follow_up_activity: "phone-call".to_string(),
            has_consent_receipt: false,
        };
        let input_bytes = serde_json::to_vec(&input).unwrap();
        let (output_bytes, packet) = part.execute(input_bytes).await.unwrap();
        let output: ConsentOutput = serde_json::from_slice(&output_bytes).unwrap();

        assert_eq!(output.status, "Refused");
        assert_eq!(packet.status, ExecutionStatus::Refused);
    }

    #[tokio::test]
    async fn test_assign_steward_part() {
        let part = AssignStewardPart::new("Assign-001".to_string(), "StewardshipCell".to_string());
        let input = AssignInput {
            obligation_id: "obl-789".to_string(),
            steward_uri: "canon:Paul".to_string(),
        };
        let input_bytes = serde_json::to_vec(&input).unwrap();
        let (output_bytes, _packet) = part.execute(input_bytes).await.unwrap();
        let output: AssignOutput = serde_json::from_slice(&output_bytes).unwrap();

        assert_eq!(output.terminal_state, "StewardBound");
        assert_eq!(output.prov_receipt.scripture, "1 Corinthians 4:2");
    }

    #[tokio::test]
    async fn test_follow_up_escalation() {
        let part =
            FollowUpObligationPart::new("FollowUp-001".to_string(), "StewardshipCell".to_string());
        let input = FollowUpInput {
            obligation_id: "obl-789".to_string(),
            deadline: (Utc::now() - chrono::Duration::days(1)).to_rfc3339(),
        };
        let input_bytes = serde_json::to_vec(&input).unwrap();
        let (output_bytes, packet) = part.execute(input_bytes).await.unwrap();
        let output: FollowUpOutput = serde_json::from_slice(&output_bytes).unwrap();

        assert_eq!(output.status, "Escalated");
        assert_eq!(packet.status, ExecutionStatus::Refused);
    }

    #[tokio::test]
    async fn test_pentecost_incorporation() {
        let part = PentecostInvitationPart::new(
            "Pentecost-001".to_string(),
            "StewardshipCell".to_string(),
        );
        let input = InvitationInput {
            person_id: "person-123".to_string(),
            is_capable_of_receiving_another: true,
        };
        let input_bytes = serde_json::to_vec(&input).unwrap();
        let (output_bytes, _packet) = part.execute(input_bytes).await.unwrap();
        let output: InvitationOutput = serde_json::from_slice(&output_bytes).unwrap();

        assert_eq!(output.status, "Incorporated");
        assert_eq!(output.terminal_state, "IncorporatedAndServing");
    }

    #[tokio::test]
    async fn test_continuity_watch_alert() {
        let part = ContinuityWatchPart::new("Watch-001".to_string(), "StewardshipCell".to_string());
        let input = ContinuityInput {
            last_activity: (Utc::now() - chrono::Duration::days(10)).to_rfc3339(),
        };
        let input_bytes = serde_json::to_vec(&input).unwrap();
        let (output_bytes, _packet) = part.execute(input_bytes).await.unwrap();
        let output: ContinuityOutput = serde_json::from_slice(&output_bytes).unwrap();

        assert!(output.alert);
        assert!(output.message.contains("Silent disappearance"));
    }
}