aingle_cortex 0.7.5

Córtex API - REST/GraphQL/SPARQL interface for AIngle semantic graphs
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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
// Copyright 2019-2026 Apilium Technologies OÜ. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR Commercial

//! DAG introspection REST endpoints.
//!
//! ## Endpoints
//!
//! - `GET /api/v1/dag/tips` — Current DAG tip hashes and count
//! - `GET /api/v1/dag/action/:hash` — Single DagAction by hash
//! - `GET /api/v1/dag/history` — Mutations affecting a subject
//! - `GET /api/v1/dag/chain` — Author's action chain
//! - `GET /api/v1/dag/stats` — Action count, tip count, depth estimate

use axum::{
    extract::{Path, Query, State},
    routing::{get, post},
    Json, Router,
};
use serde::{Deserialize, Serialize};

use crate::error::{Error, Result};
use crate::state::AppState;

// ============================================================================
// DTOs
// ============================================================================

#[derive(Debug, Serialize)]
pub struct DagTipsResponse {
    pub tips: Vec<String>,
    pub count: usize,
}

#[derive(Debug, Serialize)]
#[cfg_attr(feature = "mcp", derive(schemars::JsonSchema))]
pub struct DagActionDto {
    pub hash: String,
    pub parents: Vec<String>,
    pub author: String,
    pub seq: u64,
    pub timestamp: String,
    pub payload_type: String,
    pub payload_summary: String,
    pub signed: bool,
    /// Blake3 hex content hash of the source file, if present in the action's
    /// provenance. Extracted from the first provenanced triple in a
    /// `TripleInsert` (or the first `TripleInsert` inside a `Batch`).
    pub content_hash: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct DagStatsResponse {
    pub action_count: usize,
    pub tip_count: usize,
}

#[derive(Debug, Deserialize)]
pub struct HistoryQuery {
    pub subject: Option<String>,
    pub triple_id: Option<String>,
    #[serde(default = "default_limit")]
    pub limit: usize,
}

#[derive(Debug, Deserialize)]
pub struct ChainQuery {
    pub author: String,
    #[serde(default = "default_limit")]
    pub limit: usize,
}

#[derive(Debug, Deserialize)]
#[cfg_attr(feature = "mcp", derive(schemars::JsonSchema))]
pub struct PruneRequest {
    /// "keep_all", "keep_since", "keep_last", or "keep_depth"
    pub policy: String,
    /// The numeric argument for the policy (seconds / count / depth).
    #[serde(default)]
    pub value: u64,
    /// Whether to create a Compact checkpoint action after pruning.
    #[serde(default)]
    pub create_checkpoint: bool,
}

#[derive(Debug, Serialize)]
pub struct PruneResponse {
    pub pruned_count: usize,
    pub retained_count: usize,
    pub checkpoint_hash: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct TimeTravelResponse {
    pub target_hash: String,
    pub target_timestamp: String,
    pub actions_replayed: usize,
    pub triple_count: usize,
    pub triples: Vec<TimeTravelTriple>,
}

#[derive(Debug, Serialize)]
pub struct TimeTravelTriple {
    pub subject: String,
    pub predicate: String,
    pub object: serde_json::Value,
}

#[derive(Debug, Deserialize)]
pub struct DiffQuery {
    pub from: String,
    pub to: String,
}

#[derive(Debug, Deserialize)]
pub struct PullRequest {
    /// The peer URL to pull from (e.g. "http://node2:19090").
    pub peer_url: String,
}

#[derive(Debug, Serialize)]
pub struct PullResponse {
    pub ingested: usize,
    pub already_had: usize,
    pub remote_tips: Vec<String>,
}

#[derive(Debug, Serialize)]
pub struct DiffResponse {
    pub from: String,
    pub to: String,
    pub action_count: usize,
    pub actions: Vec<DagActionDto>,
}

#[derive(Debug, Deserialize)]
pub struct ExportQuery {
    /// "dot", "mermaid", or "json" (default: "json").
    #[serde(default = "default_export_format")]
    pub format: String,
}

fn default_export_format() -> String {
    "json".into()
}

#[cfg(feature = "dag")]
#[derive(Debug, Deserialize)]
pub struct VerifyQuery {
    /// Hex-encoded Ed25519 public key (64 chars).
    pub public_key: String,
}

/// Request body for POST /api/v1/dag/actions.
#[derive(Debug, Deserialize)]
pub struct CreateDagActionRequest {
    /// Author identity. Defaults to the node's configured DAG author.
    pub author: Option<String>,
    /// A descriptive type tag (e.g., "checkpoint", "decision", "annotation").
    pub payload_type: String,
    /// A human-readable summary.
    pub payload_summary: String,
    /// Optional arbitrary payload data.
    pub payload: Option<serde_json::Value>,
    /// Optional subject for indexing in DAG history.
    pub subject: Option<String>,
    /// Whether to sign the action. Defaults to true if a signing key is configured.
    pub sign: Option<bool>,
}

/// Response for POST /api/v1/dag/actions.
#[derive(Debug, Serialize)]
pub struct CreateDagActionResponse {
    pub hash: String,
    pub seq: u64,
    pub timestamp: String,
    pub signed: bool,
}

fn default_limit() -> usize {
    crate::service::dag::DEFAULT_HISTORY_LIMIT
}

// ============================================================================
// Handlers
// ============================================================================

/// GET /api/v1/dag/tips
pub async fn get_dag_tips(State(state): State<AppState>) -> Result<Json<DagTipsResponse>> {
    Ok(Json(crate::service::dag::tips(&state).await?))
}

/// GET /api/v1/dag/action/:hash
pub async fn get_dag_action(
    State(state): State<AppState>,
    Path(hash): Path<String>,
) -> Result<Json<DagActionDto>> {
    Ok(Json(crate::service::dag::action(&state, &hash).await?))
}

/// GET /api/v1/dag/history?subject=X&triple_id=X&limit=N
pub async fn get_dag_history(
    State(state): State<AppState>,
    Query(query): Query<HistoryQuery>,
) -> Result<Json<Vec<DagActionDto>>> {
    // Subject-based lookup uses the dedicated subject index (shared service logic)
    if let Some(ref subject) = query.subject {
        let actions = crate::service::dag::history_by_subject(&state, subject, query.limit).await?;
        return Ok(Json(actions));
    }

    let graph = state.graph.read().await;

    // Triple-ID-based lookup uses the affected index
    if let Some(ref tid_hex) = query.triple_id {
        let bytes = parse_hex32(tid_hex)
            .ok_or_else(|| Error::InvalidInput("triple_id must be 64 valid hex chars".into()))?;

        let actions = graph
            .dag_history(&bytes, query.limit)
            .map_err(|e| Error::Internal(e.to_string()))?;
        return Ok(Json(actions.iter().map(action_to_dto).collect()));
    }

    Err(Error::InvalidInput(
        "Either 'subject' or 'triple_id' query parameter is required".into(),
    ))
}

/// GET /api/v1/dag/chain?author=X&limit=N
pub async fn get_dag_chain(
    State(state): State<AppState>,
    Query(query): Query<ChainQuery>,
) -> Result<Json<Vec<DagActionDto>>> {
    Ok(Json(
        crate::service::dag::chain(&state, &query.author, query.limit).await?,
    ))
}

/// GET /api/v1/dag/stats
pub async fn get_dag_stats(State(state): State<AppState>) -> Result<Json<DagStatsResponse>> {
    Ok(Json(crate::service::dag::stats(&state).await?))
}

/// POST /api/v1/dag/prune
pub async fn post_dag_prune(
    State(state): State<AppState>,
    Json(req): Json<PruneRequest>,
) -> Result<Json<PruneResponse>> {
    Ok(Json(crate::service::dag::prune(&state, req).await?))
}

/// GET /api/v1/dag/export?format=dot|mermaid|json
pub async fn get_dag_export(
    State(state): State<AppState>,
    Query(query): Query<ExportQuery>,
) -> Result<axum::response::Response> {
    use axum::response::IntoResponse;

    let format = aingle_graph::dag::ExportFormat::from_str(&query.format).ok_or_else(|| {
        Error::InvalidInput(format!(
            "Unknown format '{}'. Use: dot, mermaid, json",
            query.format
        ))
    })?;

    let graph = state.graph.read().await;
    let dag_graph = graph
        .dag_export()
        .map_err(|e| Error::Internal(e.to_string()))?;

    let body = dag_graph
        .export(format)
        .map_err(|e| Error::Internal(e.to_string()))?;

    let content_type = match format {
        aingle_graph::dag::ExportFormat::Dot => "text/vnd.graphviz",
        aingle_graph::dag::ExportFormat::Mermaid => "text/plain",
        aingle_graph::dag::ExportFormat::Json => "application/json",
    };

    Ok(([(axum::http::header::CONTENT_TYPE, content_type)], body).into_response())
}

/// GET /api/v1/dag/verify/:hash?public_key=X — verify an action's Ed25519 signature
#[cfg(feature = "dag")]
pub async fn get_dag_verify(
    State(state): State<AppState>,
    Path(hash): Path<String>,
    Query(query): Query<VerifyQuery>,
) -> Result<Json<aingle_graph::dag::VerifyResult>> {
    let action_hash = aingle_graph::dag::DagActionHash::from_hex(&hash)
        .ok_or_else(|| Error::InvalidInput(format!("Invalid hash: {}", hash)))?;

    let pk_bytes = parse_hex32(&query.public_key)
        .ok_or_else(|| Error::InvalidInput("public_key must be 64 valid hex chars".into()))?;

    let graph = state.graph.read().await;
    let action = graph
        .dag_action(&action_hash)
        .map_err(|e| Error::Internal(e.to_string()))?
        .ok_or_else(|| Error::NotFound(format!("DAG action {} not found", hash)))?;

    let result = graph
        .dag_verify(&action, &pk_bytes)
        .map_err(|e| Error::Internal(e.to_string()))?;

    Ok(Json(result))
}

/// POST /api/v1/dag/sync — serve missing actions to a peer
pub async fn post_dag_sync(
    State(state): State<AppState>,
    Json(req): Json<aingle_graph::dag::SyncRequest>,
) -> Result<Json<aingle_graph::dag::SyncResponse>> {
    let graph = state.graph.read().await;

    let actions = if !req.want.is_empty() {
        // Serve specific requested actions
        let dag_store = graph
            .dag_store()
            .ok_or_else(|| Error::Internal("DAG not enabled".into()))?;
        req.want
            .iter()
            .filter_map(|h| dag_store.get(h).ok().flatten())
            .collect()
    } else {
        // Compute what the requester is missing
        graph
            .dag_compute_missing(&req.local_tips)
            .map_err(|e| Error::Internal(e.to_string()))?
    };

    let tips = graph
        .dag_tips()
        .map_err(|e| Error::Internal(e.to_string()))?;

    let action_count = actions.len();

    Ok(Json(aingle_graph::dag::SyncResponse {
        actions,
        remote_tips: tips,
        action_count,
    }))
}

/// POST /api/v1/dag/sync/pull — pull missing DAG actions from a peer
pub async fn post_dag_pull(
    State(state): State<AppState>,
    Json(req): Json<PullRequest>,
) -> Result<Json<PullResponse>> {
    // Read our current tips
    let local_tips = {
        let graph = state.graph.read().await;
        graph
            .dag_tips()
            .map_err(|e| Error::Internal(e.to_string()))?
    };

    // Send sync request to peer
    let sync_req = aingle_graph::dag::SyncRequest {
        local_tips,
        want: vec![],
    };

    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(30))
        .build()
        .map_err(|e| Error::Internal(format!("HTTP client error: {}", e)))?;

    let url = format!("{}/api/v1/dag/sync", req.peer_url.trim_end_matches('/'));
    let resp = client
        .post(&url)
        .json(&sync_req)
        .send()
        .await
        .map_err(|e| Error::Internal(format!("Failed to contact peer: {}", e)))?;

    if !resp.status().is_success() {
        return Err(Error::Internal(format!(
            "Peer returned status {}",
            resp.status()
        )));
    }

    let sync_resp: aingle_graph::dag::SyncResponse = resp
        .json()
        .await
        .map_err(|e| Error::Internal(format!("Invalid peer response: {}", e)))?;

    // Ingest received actions
    let graph = state.graph.read().await;
    let mut ingested = 0;
    let mut already_had = 0;

    for action in &sync_resp.actions {
        let hash = action.compute_hash();
        let dag_store = graph
            .dag_store()
            .ok_or_else(|| Error::Internal("DAG not enabled".into()))?;

        if dag_store
            .contains(&hash)
            .map_err(|e| Error::Internal(e.to_string()))?
        {
            already_had += 1;
        } else {
            graph
                .dag_ingest(action)
                .map_err(|e| Error::Internal(e.to_string()))?;
            ingested += 1;
        }
    }

    Ok(Json(PullResponse {
        ingested,
        already_had,
        remote_tips: sync_resp.remote_tips.iter().map(|h| h.to_hex()).collect(),
    }))
}

/// GET /api/v1/dag/at/:hash — reconstruct graph state at a specific DAG action
pub async fn get_dag_at(
    State(state): State<AppState>,
    Path(hash): Path<String>,
) -> Result<Json<TimeTravelResponse>> {
    let action_hash = aingle_graph::dag::DagActionHash::from_hex(&hash)
        .ok_or_else(|| Error::InvalidInput(format!("Invalid DAG action hash: {}", hash)))?;

    let graph = state.graph.read().await;
    let (snapshot_db, info) = graph
        .dag_at(&action_hash)
        .map_err(|e| Error::Internal(e.to_string()))?;

    let triples = snapshot_db
        .find(aingle_graph::TriplePattern::any())
        .map_err(|e| Error::Internal(e.to_string()))?
        .into_iter()
        .map(|t| TimeTravelTriple {
            subject: t.subject.to_string(),
            predicate: t.predicate.to_string(),
            object: triple_value_to_json(&t.object),
        })
        .collect();

    Ok(Json(TimeTravelResponse {
        target_hash: info.target_hash.to_hex(),
        target_timestamp: info.target_timestamp.to_rfc3339(),
        actions_replayed: info.actions_replayed,
        triple_count: info.triple_count,
        triples,
    }))
}

/// GET /api/v1/dag/diff?from=X&to=Y — actions between two DAG points
pub async fn get_dag_diff(
    State(state): State<AppState>,
    Query(query): Query<DiffQuery>,
) -> Result<Json<DiffResponse>> {
    let from = aingle_graph::dag::DagActionHash::from_hex(&query.from)
        .ok_or_else(|| Error::InvalidInput(format!("Invalid 'from' hash: {}", query.from)))?;
    let to = aingle_graph::dag::DagActionHash::from_hex(&query.to)
        .ok_or_else(|| Error::InvalidInput(format!("Invalid 'to' hash: {}", query.to)))?;

    let graph = state.graph.read().await;
    let diff = graph
        .dag_diff(&from, &to)
        .map_err(|e| Error::Internal(e.to_string()))?;

    let actions: Vec<DagActionDto> = diff.actions.iter().map(action_to_dto).collect();
    let action_count = actions.len();

    Ok(Json(DiffResponse {
        from: query.from,
        to: query.to,
        action_count,
        actions,
    }))
}

/// POST /api/v1/dag/actions — create an explicit DAG action with arbitrary payload
pub async fn post_create_dag_action(
    State(state): State<AppState>,
    Json(req): Json<CreateDagActionRequest>,
) -> Result<(axum::http::StatusCode, Json<CreateDagActionResponse>)> {
    if req.payload_type.is_empty() {
        return Err(Error::InvalidInput("payload_type cannot be empty".into()));
    }

    let dag_author = if let Some(ref author) = req.author {
        aingle_graph::NodeId::named(author)
    } else {
        state
            .dag_author
            .clone()
            .unwrap_or_else(|| aingle_graph::NodeId::named("node:local"))
    };

    let dag_seq = state
        .dag_seq_counter
        .fetch_add(1, std::sync::atomic::Ordering::SeqCst);

    let graph = state.graph.read().await;
    let dag_store = graph
        .dag_store()
        .ok_or_else(|| Error::Internal("DAG not enabled".into()))?;

    let parents = dag_store
        .tips()
        .map_err(|e| Error::Internal(e.to_string()))?;

    let timestamp = chrono::Utc::now();
    let mut action = aingle_graph::dag::DagAction {
        parents,
        author: dag_author,
        seq: dag_seq,
        timestamp,
        payload: aingle_graph::dag::DagPayload::Custom {
            payload_type: req.payload_type,
            payload_summary: req.payload_summary,
            payload: req.payload,
            subject: req.subject,
        },
        signature: None,
    };

    // Sign unless explicitly disabled
    let should_sign = req.sign.unwrap_or(true);
    if should_sign {
        if let Some(ref key) = state.dag_signing_key {
            key.sign(&mut action);
        }
    }

    let signed = action.signature.is_some();
    let hash = dag_store
        .put(&action)
        .map_err(|e| Error::Internal(e.to_string()))?;

    Ok((
        axum::http::StatusCode::CREATED,
        Json(CreateDagActionResponse {
            hash: hash.to_hex(),
            seq: dag_seq,
            timestamp: timestamp.to_rfc3339(),
            signed,
        }),
    ))
}

// ============================================================================
// Router
// ============================================================================

pub fn dag_router() -> Router<AppState> {
    let router = Router::new()
        .route("/api/v1/dag/tips", get(get_dag_tips))
        .route("/api/v1/dag/action/{hash}", get(get_dag_action))
        .route("/api/v1/dag/history", get(get_dag_history))
        .route("/api/v1/dag/chain", get(get_dag_chain))
        .route("/api/v1/dag/stats", get(get_dag_stats))
        .route("/api/v1/dag/prune", post(post_dag_prune))
        .route("/api/v1/dag/at/{hash}", get(get_dag_at))
        .route("/api/v1/dag/diff", get(get_dag_diff))
        .route("/api/v1/dag/export", get(get_dag_export))
        .route("/api/v1/dag/sync", post(post_dag_sync))
        .route("/api/v1/dag/sync/pull", post(post_dag_pull))
        .route("/api/v1/dag/actions", post(post_create_dag_action));

    #[cfg(feature = "dag")]
    let router = router.route("/api/v1/dag/verify/{hash}", get(get_dag_verify));

    router
}

// ============================================================================
// Helpers
// ============================================================================

/// Convert a raw [`DagAction`] to its serializable DTO form.
///
/// Extracts the payload type, a human-readable summary, and the content hash
/// from the action's provenance (for `TripleInsert` and `Batch` payloads).
pub(crate) fn action_to_dto(action: &aingle_graph::dag::DagAction) -> DagActionDto {
    let hash = action.compute_hash().to_hex();
    let parents: Vec<String> = action.parents.iter().map(|h| h.to_hex()).collect();

    let (payload_type, payload_summary, content_hash) = match &action.payload {
        aingle_graph::dag::DagPayload::TripleInsert { triples } => {
            let summary = if triples.len() == 1 {
                let t = &triples[0];
                format!("{} -> {} -> {}", t.subject, t.predicate, t.object)
            } else {
                format!("{} triple(s)", triples.len())
            };
            // Extract content_hash from the first triple that carries provenance.
            // All triples from a single file ingest share the same content_hash.
            let content_hash = triples
                .iter()
                .find_map(|t| t.provenance.as_ref().map(|p| p.content_hash.clone()));
            ("triple:create".to_string(), summary, content_hash)
        }
        aingle_graph::dag::DagPayload::TripleDelete {
            triple_ids,
            subjects,
        } => {
            let summary = if !subjects.is_empty() {
                format!("{} triple(s) [{}]", triple_ids.len(), subjects.join(", "))
            } else {
                format!("{} triple(s)", triple_ids.len())
            };
            ("triple:delete".to_string(), summary, None)
        }
        aingle_graph::dag::DagPayload::MemoryOp { kind } => {
            let summary = match kind {
                aingle_graph::dag::MemoryOpKind::Store { entry_type, .. } => {
                    format!("Store({})", entry_type)
                }
                aingle_graph::dag::MemoryOpKind::Forget { memory_id } => {
                    format!("Forget({})", memory_id)
                }
                aingle_graph::dag::MemoryOpKind::Consolidate => "Consolidate".to_string(),
            };
            ("memory:op".to_string(), summary, None)
        }
        aingle_graph::dag::DagPayload::Batch { ops } => {
            // Search the ops for the first TripleInsert that has a provenanced triple.
            let content_hash = ops.iter().find_map(|op| {
                if let aingle_graph::dag::DagPayload::TripleInsert { triples } = op {
                    triples
                        .iter()
                        .find_map(|t| t.provenance.as_ref().map(|p| p.content_hash.clone()))
                } else {
                    None
                }
            });
            (
                "batch".to_string(),
                format!("{} ops", ops.len()),
                content_hash,
            )
        }
        aingle_graph::dag::DagPayload::Genesis {
            triple_count,
            description,
        } => (
            "genesis".to_string(),
            format!("{} triples: {}", triple_count, description),
            None,
        ),
        aingle_graph::dag::DagPayload::Compact {
            pruned_count,
            retained_count,
            ref policy,
        } => (
            "compact".to_string(),
            format!(
                "pruned {} / retained {} ({})",
                pruned_count, retained_count, policy
            ),
            None,
        ),
        aingle_graph::dag::DagPayload::Noop => ("noop".to_string(), String::new(), None),
        aingle_graph::dag::DagPayload::Custom {
            payload_type,
            payload_summary,
            ..
        } => (payload_type.clone(), payload_summary.clone(), None),
    };

    DagActionDto {
        hash,
        parents,
        author: action.author.to_string(),
        seq: action.seq,
        timestamp: action.timestamp.to_rfc3339(),
        payload_type,
        payload_summary,
        signed: action.signature.is_some(),
        content_hash,
    }
}

/// Parse a 64-character hex string into a 32-byte array.
///
/// Returns `None` if `hex` is not exactly 64 characters or contains non-hex digits.
fn parse_hex32(hex: &str) -> Option<[u8; 32]> {
    if hex.len() != 64 {
        return None;
    }
    let mut out = [0u8; 32];
    for (i, b) in out.iter_mut().enumerate() {
        *b = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16).ok()?;
    }
    Some(out)
}

fn triple_value_to_json(v: &aingle_graph::Value) -> serde_json::Value {
    match v {
        aingle_graph::Value::String(s) => serde_json::Value::String(s.clone()),
        aingle_graph::Value::Integer(i) => serde_json::json!(*i),
        aingle_graph::Value::Float(f) => serde_json::json!(*f),
        aingle_graph::Value::Boolean(b) => serde_json::json!(*b),
        aingle_graph::Value::Json(j) => j.clone(),
        aingle_graph::Value::Node(n) => serde_json::json!({ "node": n.to_string() }),
        aingle_graph::Value::DateTime(dt) => serde_json::Value::String(dt.clone()),
        aingle_graph::Value::Null => serde_json::Value::Null,
        _ => serde_json::Value::String(format!("{:?}", v)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use aingle_graph::dag::{DagAction, DagPayload, Provenance, TripleInsertPayload};
    use aingle_graph::NodeId;
    use chrono::Utc;

    fn test_action(payload: DagPayload) -> DagAction {
        DagAction {
            parents: vec![],
            author: NodeId::named("node:test"),
            seq: 0,
            timestamp: Utc::now(),
            payload,
            signature: None,
        }
    }

    #[test]
    fn action_to_dto_extracts_content_hash_from_triple_insert() {
        let provenance = Provenance {
            source_path: "vault/note.md".into(),
            line_start: 1,
            line_end: 3,
            content_hash: "deadbeef".into(),
        };
        let action = test_action(DagPayload::TripleInsert {
            triples: vec![TripleInsertPayload {
                subject: "akashi://note".into(),
                predicate: "akashi:title".into(),
                object: serde_json::json!("Test Note"),
                provenance: Some(provenance),
            }],
        });

        let dto = action_to_dto(&action);

        assert_eq!(
            dto.content_hash,
            Some("deadbeef".into()),
            "content_hash must be extracted from TripleInsert provenance"
        );
    }

    #[test]
    fn action_to_dto_extracts_content_hash_from_batch_with_triple_insert() {
        let provenance = Provenance {
            source_path: "vault/doc.md".into(),
            line_start: 5,
            line_end: 10,
            content_hash: "cafebabe".into(),
        };
        let action = test_action(DagPayload::Batch {
            ops: vec![
                DagPayload::TripleInsert {
                    triples: vec![TripleInsertPayload {
                        subject: "akashi://doc".into(),
                        predicate: "akashi:body".into(),
                        object: serde_json::json!("content"),
                        provenance: Some(provenance),
                    }],
                },
                DagPayload::Noop,
            ],
        });

        let dto = action_to_dto(&action);

        assert_eq!(
            dto.content_hash,
            Some("cafebabe".into()),
            "content_hash must be extracted from first TripleInsert inside Batch"
        );
    }

    #[test]
    fn action_to_dto_content_hash_none_for_triple_insert_without_provenance() {
        let action = test_action(DagPayload::TripleInsert {
            triples: vec![TripleInsertPayload {
                subject: "s".into(),
                predicate: "p".into(),
                object: serde_json::json!("o"),
                provenance: None,
            }],
        });

        let dto = action_to_dto(&action);

        assert_eq!(
            dto.content_hash, None,
            "content_hash must be None when no provenance is present"
        );
    }

    #[test]
    fn action_to_dto_content_hash_none_for_genesis() {
        let action = test_action(DagPayload::Genesis {
            triple_count: 0,
            description: "root".into(),
        });

        let dto = action_to_dto(&action);

        assert_eq!(
            dto.content_hash, None,
            "Genesis actions have no content_hash"
        );
    }

    #[test]
    fn action_to_dto_content_hash_none_for_noop() {
        let action = test_action(DagPayload::Noop);

        let dto = action_to_dto(&action);

        assert_eq!(dto.content_hash, None, "Noop actions have no content_hash");
    }
}