decapod 0.49.1

Decapod is a Rust-built governance runtime for AI agents: repo-native state, enforced workflow, proof gates, safe coordination.
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
//! Deterministic Map Operators — structured parallel processing with scope-reduction enforcement.
//!
//! Two operator modes:
//! - `map llm`: Stateless parallel processing with prompt template + schema validation.
//! - `map agentic`: Subagent delegation with mandatory scope-reduction (`--retain`).
//!
//! Both operators are *structural* — they define the contract and audit trail.
//! Actual LLM/subagent dispatch is pluggable.

use crate::core::error;
use crate::core::schemas;
use crate::core::store::Store;
use clap::Subcommand;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};

// ---------------------------------------------------------------------------
// Paths
// ---------------------------------------------------------------------------

fn map_events_path(root: &Path) -> PathBuf {
    root.join(schemas::MAP_EVENTS_NAME)
}

// ---------------------------------------------------------------------------
// Data types
// ---------------------------------------------------------------------------

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct MapEvent {
    pub event_id: String,
    pub ts: String,
    pub actor: String,
    pub op: String,
    pub item_count: usize,
    pub prompt_hash: Option<String>,
    pub schema_hash: Option<String>,
    pub delegate_hash: Option<String>,
    pub retain: Option<String>,
    pub status: String,
    pub result_hash: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
struct MapItemResult {
    index: usize,
    item_hash: String,
    status: String,
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn now_iso() -> String {
    crate::core::time::now_epoch_z()
}

fn sha256_hex(data: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(data);
    format!("{:x}", hasher.finalize())
}

fn append_jsonl(path: &Path, value: &serde_json::Value) -> Result<(), error::DecapodError> {
    let mut f = OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)
        .map_err(error::DecapodError::IoError)?;
    writeln!(f, "{}", serde_json::to_string(value).unwrap())
        .map_err(error::DecapodError::IoError)?;
    Ok(())
}

fn load_items(items_str: &str) -> Result<Vec<serde_json::Value>, error::DecapodError> {
    // Try parsing as JSON array directly
    if let Ok(arr) = serde_json::from_str::<Vec<serde_json::Value>>(items_str) {
        return Ok(arr);
    }
    // Try as file path
    let path = Path::new(items_str);
    if path.exists() {
        let content = fs::read_to_string(path).map_err(error::DecapodError::IoError)?;
        let arr: Vec<serde_json::Value> = serde_json::from_str(&content).map_err(|e| {
            error::DecapodError::ValidationError(format!("Failed to parse items file: {}", e))
        })?;
        return Ok(arr);
    }
    Err(error::DecapodError::ValidationError(
        "Items must be a valid JSON array or a path to a JSON file".to_string(),
    ))
}

// ---------------------------------------------------------------------------
// Core operations
// ---------------------------------------------------------------------------

/// Execute a stateless map-llm operation.
pub fn map_llm(
    store: &Store,
    items_str: &str,
    prompt: &str,
    schema_str: &str,
    actor: &str,
) -> Result<serde_json::Value, error::DecapodError> {
    let items = load_items(items_str)?;
    if items.is_empty() {
        return Err(error::DecapodError::ValidationError(
            "Items array must not be empty".to_string(),
        ));
    }

    let prompt_hash = sha256_hex(prompt.as_bytes());
    let schema_hash = sha256_hex(schema_str.as_bytes());

    // Validate schema is parseable JSON
    let _schema: serde_json::Value = serde_json::from_str(schema_str)
        .map_err(|e| error::DecapodError::ValidationError(format!("Invalid schema JSON: {}", e)))?;

    // Process each item structurally (contract definition, not execution)
    let mut results: Vec<MapItemResult> = Vec::new();
    for (i, item) in items.iter().enumerate() {
        let item_json = serde_json::to_string(item).unwrap();
        let item_hash = sha256_hex(item_json.as_bytes());
        results.push(MapItemResult {
            index: i,
            item_hash,
            status: "pending".to_string(),
        });
    }

    // Deterministic result hash
    let results_json = serde_json::to_string(&results).unwrap();
    let result_hash = sha256_hex(results_json.as_bytes());

    let event_id = crate::core::ulid::new_ulid();
    let ts = now_iso();

    let event = serde_json::json!({
        "event_id": event_id,
        "ts": ts,
        "actor": actor,
        "op": "map.llm",
        "item_count": items.len(),
        "prompt_hash": prompt_hash,
        "schema_hash": schema_hash,
        "status": "completed",
        "result_hash": result_hash,
    });

    append_jsonl(&map_events_path(&store.root), &event)?;

    Ok(serde_json::json!({
        "event_id": event_id,
        "op": "map.llm",
        "item_count": items.len(),
        "prompt_hash": prompt_hash,
        "schema_hash": schema_hash,
        "result_hash": result_hash,
        "items": results,
    }))
}

/// Execute a map-agentic operation with scope-reduction enforcement.
pub fn map_agentic(
    store: &Store,
    items_str: &str,
    delegate: &str,
    retain: &str,
    actor: &str,
) -> Result<serde_json::Value, error::DecapodError> {
    // Scope-reduction invariant: --retain must be non-empty
    if retain.trim().is_empty() {
        return Err(error::DecapodError::ValidationError(
            "Delegation without retention violates scope-reduction invariant".to_string(),
        ));
    }

    let items = load_items(items_str)?;
    if items.is_empty() {
        return Err(error::DecapodError::ValidationError(
            "Items array must not be empty".to_string(),
        ));
    }

    let delegate_hash = sha256_hex(delegate.as_bytes());

    // Log each item delegation
    let mut results: Vec<MapItemResult> = Vec::new();
    for (i, item) in items.iter().enumerate() {
        let item_json = serde_json::to_string(item).unwrap();
        let item_hash = sha256_hex(item_json.as_bytes());
        results.push(MapItemResult {
            index: i,
            item_hash,
            status: "delegated".to_string(),
        });
    }

    let results_json = serde_json::to_string(&results).unwrap();
    let result_hash = sha256_hex(results_json.as_bytes());

    let event_id = crate::core::ulid::new_ulid();
    let ts = now_iso();

    let event = serde_json::json!({
        "event_id": event_id,
        "ts": ts,
        "actor": actor,
        "op": "map.agentic",
        "item_count": items.len(),
        "delegate_hash": delegate_hash,
        "retain": retain,
        "status": "completed",
        "result_hash": result_hash,
    });

    append_jsonl(&map_events_path(&store.root), &event)?;

    Ok(serde_json::json!({
        "event_id": event_id,
        "op": "map.agentic",
        "item_count": items.len(),
        "delegate_hash": delegate_hash,
        "retain": retain,
        "result_hash": result_hash,
        "items": results,
    }))
}

/// Read all map events from the JSONL audit trail.
pub fn read_map_events(root: &Path) -> Result<Vec<MapEvent>, error::DecapodError> {
    let path = map_events_path(root);
    if !path.exists() {
        return Ok(Vec::new());
    }
    let content = fs::read_to_string(&path).map_err(error::DecapodError::IoError)?;
    let mut events = Vec::new();
    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        let event: MapEvent = serde_json::from_str(trimmed)
            .map_err(|e| error::DecapodError::ValidationError(e.to_string()))?;
        events.push(event);
    }
    Ok(events)
}

// ---------------------------------------------------------------------------
// CLI
// ---------------------------------------------------------------------------

#[derive(clap::Args, Debug)]
pub struct MapCli {
    #[clap(subcommand)]
    pub command: MapCommand,
}

#[derive(Subcommand, Debug)]
pub enum MapCommand {
    /// Stateless parallel processing: apply prompt+schema to each item
    Llm {
        /// JSON array or path to JSON file containing items
        #[clap(long)]
        items: String,
        /// Prompt template to apply to each item
        #[clap(long)]
        prompt: String,
        /// JSON schema for output validation
        #[clap(long)]
        schema: String,
        /// Actor identifier
        #[clap(long, default_value = "decapod")]
        actor: String,
    },
    /// Subagent map with scope-reduction enforcement
    Agentic {
        /// JSON array or path to JSON file containing items
        #[clap(long)]
        items: String,
        /// Delegation prompt for subagents
        #[clap(long)]
        delegate: String,
        /// What the caller retains responsibility for (REQUIRED for scope-reduction)
        #[clap(long)]
        retain: String,
        /// Actor identifier
        #[clap(long, default_value = "decapod")]
        actor: String,
    },
    /// Emit subsystem schema JSON
    Schema,
}

pub fn run_map_cli(store: &Store, cli: MapCli) -> Result<(), error::DecapodError> {
    match cli.command {
        MapCommand::Llm {
            items,
            prompt,
            schema,
            actor,
        } => {
            let result = map_llm(store, &items, &prompt, &schema, &actor)?;
            println!("{}", serde_json::to_string_pretty(&result).unwrap());
        }
        MapCommand::Agentic {
            items,
            delegate,
            retain,
            actor,
        } => {
            let result = map_agentic(store, &items, &delegate, &retain, &actor)?;
            println!("{}", serde_json::to_string_pretty(&result).unwrap());
        }
        MapCommand::Schema => {
            println!("{}", serde_json::to_string_pretty(&schema()).unwrap());
        }
    }
    Ok(())
}

pub fn schema() -> serde_json::Value {
    serde_json::json!({
        "name": "map",
        "version": "0.1.0",
        "description": "Deterministic map operators — structured parallel processing with scope-reduction",
        "commands": [
            { "name": "llm", "description": "Stateless parallel processing with prompt+schema" },
            { "name": "agentic", "description": "Subagent map with scope-reduction enforcement" },
            { "name": "schema", "description": "Emit subsystem schema JSON" },
        ],
        "storage": [schemas::MAP_EVENTS_NAME],
        "invariants": [
            "map agentic requires --retain (scope-reduction invariant)",
            "All operations are logged to append-only map.events.jsonl",
            "Deterministic: same items + same prompt + same schema → same result_hash",
        ],
    })
}

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

    fn test_store() -> (tempfile::TempDir, Store) {
        let tmp = tempdir().unwrap();
        let root = tmp.path().to_path_buf();
        fs::create_dir_all(&root).unwrap();
        let store = Store {
            kind: crate::core::store::StoreKind::Repo,
            root,
        };
        (tmp, store)
    }

    #[test]
    fn test_map_llm_rejects_empty_items() {
        let (_tmp, store) = test_store();
        let result = map_llm(&store, "[]", "prompt", "{}", "agent");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("must not be empty"));
    }

    #[test]
    fn test_map_agentic_rejects_empty_retain() {
        let (_tmp, store) = test_store();
        let result = map_agentic(&store, "[\"item1\"]", "delegate prompt", "", "agent");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("scope-reduction"));
    }

    #[test]
    fn test_map_agentic_logs_delegation() {
        let (_tmp, store) = test_store();
        let result = map_agentic(
            &store,
            "[\"item1\", \"item2\"]",
            "do the thing",
            "orchestration",
            "agent",
        )
        .unwrap();
        assert_eq!(result["item_count"].as_u64().unwrap(), 2);
        assert_eq!(result["retain"].as_str().unwrap(), "orchestration");

        let events = read_map_events(&store.root).unwrap();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].op, "map.agentic");
    }

    #[test]
    fn test_map_llm_produces_result() {
        let (_tmp, store) = test_store();
        let result = map_llm(
            &store,
            "[\"a\", \"b\", \"c\"]",
            "summarize: {{item}}",
            "{\"type\": \"object\"}",
            "agent",
        )
        .unwrap();
        assert_eq!(result["item_count"].as_u64().unwrap(), 3);
        assert!(result["result_hash"].as_str().is_some());
    }
}