decapod 0.56.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
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
//! Documentation CLI for accessing embedded constitution.
//!
//! This module implements the `decapod docs` command family for querying
//! Decapod's embedded methodology documents.

use crate::core::{assets, docs, error};
use clap::Subcommand;
use sha2::{Digest, Sha256};
use std::path::{Path, PathBuf};

/// CLI structure for `decapod docs` command
#[derive(clap::Args, Debug)]
pub struct DocsCli {
    #[clap(subcommand)]
    pub command: DocsCommand,
}

/// Document source selector for viewing constitution docs
#[derive(Debug, Clone, clap::ValueEnum)]
pub enum DocumentSource {
    /// Show only the embedded content (from the binary)
    Embedded,
    /// Show only the override content (from .decapod/OVERRIDE.md sections)
    Override,
    /// Show merged content (embedded base + project override appended)
    Merged,
}

/// Subcommands for the `decapod docs` CLI
#[derive(Subcommand, Debug)]
pub enum DocsCommand {
    /// List all embedded Decapod methodology documents.
    List,
    /// Display the content of a specific embedded document.
    Show {
        #[clap(value_parser)]
        path: String,
        /// Source to display: embedded (binary), override (.decapod), or merged (default)
        #[clap(long, short, value_enum, default_value = "merged")]
        source: DocumentSource,
    },
    /// Dump all embedded constitution for agentic ingestion.
    Ingest,
    /// Return scoped constitution fragments relevant to a concrete query.
    Search {
        /// Problem/query text to scope against constitution docs.
        #[clap(long)]
        query: String,
        /// Optional operation context (e.g. workspace.ensure, store.upsert).
        #[clap(long)]
        op: Option<String>,
        /// Optional touched paths (repeatable).
        #[clap(long = "path")]
        path: Vec<String>,
        /// Optional intent tags (repeatable).
        #[clap(long = "tag")]
        tag: Vec<String>,
        /// Max fragments to return.
        #[clap(long, default_value_t = 5)]
        limit: usize,
        /// Output format: text or json.
        #[clap(long, default_value = "text")]
        format: String,
    },
    /// Validate and cache OVERRIDE.md checksum.
    Override {
        /// Force re-cache even if unchanged
        #[clap(long, short)]
        force: bool,
    },
    /// Autogenerate/Sync documentation from code implementation.
    Build {
        /// Only update docs for specific files that were touched.
        #[clap(long, num_args(1..), value_delimiter = ' ')]
        touched: Option<Vec<PathBuf>>,
    },
}

#[derive(Debug, Default)]
pub struct DocsRunResult {
    pub ingested_core_constitution: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OverrideChecksumStatus {
    MissingOverride,
    Cached,
    Updated,
    Unchanged,
}

pub fn sync_override_checksum(
    repo_root: &Path,
    force: bool,
) -> Result<OverrideChecksumStatus, error::DecapodError> {
    let override_path = repo_root.join(".decapod").join("OVERRIDE.md");

    if !override_path.exists() {
        return Ok(OverrideChecksumStatus::MissingOverride);
    }

    let current_checksum = calculate_sha256(&override_path)?;
    if force {
        cache_checksum(repo_root, &current_checksum)?;
        return Ok(OverrideChecksumStatus::Cached);
    }

    match get_cached_checksum(repo_root) {
        Some(cached_checksum) if cached_checksum == current_checksum => {
            Ok(OverrideChecksumStatus::Unchanged)
        }
        Some(_) => {
            cache_checksum(repo_root, &current_checksum)?;
            Ok(OverrideChecksumStatus::Updated)
        }
        None => {
            cache_checksum(repo_root, &current_checksum)?;
            Ok(OverrideChecksumStatus::Cached)
        }
    }
}

pub fn run_docs_cli(cli: DocsCli) -> Result<DocsRunResult, error::DecapodError> {
    match cli.command {
        DocsCommand::List => {
            let all_docs = assets::list_docs();
            let (docs, constitution): (Vec<_>, Vec<_>) =
                all_docs.into_iter().partition(|d| d.starts_with("docs/"));

            if !docs.is_empty() {
                println!("Decapod Documentation:");
                for doc in docs {
                    println!("- embedded/{}", doc);
                }
                println!();
            }

            println!("Embedded Decapod Constitution Sections:");
            for doc in constitution {
                println!("- embedded/constitution.json#{}", doc);
            }

            if let Ok(current_dir) = std::env::current_dir()
                && let Ok(repo_root) = find_repo_root(&current_dir)
            {
                let override_sections = assets::list_override_sections(&repo_root);
                if !override_sections.is_empty() {
                    println!("\nProject Override Sections:");
                    for section in override_sections {
                        println!("- {}", section);
                    }
                }
            }
            Ok(DocsRunResult::default())
        }
        DocsCommand::Show { path, source } => {
            let normalized_path = path.strip_prefix("embedded/").unwrap_or(&path).to_string();

            if normalized_path.starts_with("docs/") {
                // It's a direct document, not a constitution section
                let content = assets::get_embedded_doc(&normalized_path);
                match content {
                    Some(content) => {
                        println!("{}", content);
                        Ok(DocsRunResult::default())
                    }
                    None => Err(error::DecapodError::NotFound(format!(
                        "Document not found: {}",
                        path
                    ))),
                }
            } else {
                let normalized_path = normalized_path
                    .strip_prefix("constitution.json#")
                    .unwrap_or(&normalized_path)
                    .to_string();

                // Split path and anchor
                let (relative_path, anchor) = if let Some(pos) = normalized_path.find('#') {
                    (&normalized_path[..pos], Some(&normalized_path[pos + 1..]))
                } else {
                    (normalized_path.as_str(), None)
                };

                let relative_path = if relative_path.is_empty() {
                    "constitution.json"
                } else {
                    relative_path
                };

                if let Some(a) = anchor {
                    let current_dir =
                        std::env::current_dir().map_err(error::DecapodError::IoError)?;
                    let repo_root = find_repo_root(&current_dir)?;
                    if let Some(fragment) = docs::get_fragment(&repo_root, relative_path, Some(a)) {
                        println!("--- {} ---", fragment.title);
                        println!("{}", fragment.excerpt);
                        Ok(DocsRunResult::default())
                    } else {
                        Err(error::DecapodError::NotFound(format!(
                            "Section not found: {} in {}",
                            a, relative_path
                        )))
                    }
                } else {
                    let content = match source {
                        DocumentSource::Embedded => assets::get_embedded_doc(relative_path),
                        DocumentSource::Override => {
                            let current_dir =
                                std::env::current_dir().map_err(error::DecapodError::IoError)?;
                            let repo_root = find_repo_root(&current_dir)?;
                            assets::get_override_doc(&repo_root, relative_path)
                        }
                        DocumentSource::Merged => {
                            let current_dir =
                                std::env::current_dir().map_err(error::DecapodError::IoError)?;
                            let repo_root = find_repo_root(&current_dir)?;
                            assets::get_merged_doc(&repo_root, relative_path)
                        }
                    };

                    match content {
                        Some(content) => {
                            println!("{}", content);
                            Ok(DocsRunResult::default())
                        }
                        None => Err(error::DecapodError::NotFound(format!(
                            "Document not found: {} (source: {:?})",
                            path, source
                        ))),
                    }
                }
            }
        }
        DocsCommand::Build { touched } => {
            build_docs(touched.unwrap_or_default())?;
            Ok(DocsRunResult::default())
        }

        DocsCommand::Ingest => {
            let docs = assets::list_docs();
            // Determine repo root for override merging
            let current_dir = std::env::current_dir().map_err(error::DecapodError::IoError)?;
            let repo_root = find_repo_root(&current_dir)?;
            let mut ingested_core_constitution = false;

            for doc_path in docs {
                // Convert embedded path to relative path for override merging
                let relative_path = doc_path.strip_prefix("embedded/").unwrap_or(&doc_path);
                if relative_path.starts_with("core/") {
                    ingested_core_constitution = true;
                }

                if let Some(content) = assets::get_merged_doc(&repo_root, relative_path) {
                    println!("--- BEGIN embedded/constitution.json#{} ---", doc_path);
                    println!("{}", content);
                    println!("--- END embedded/constitution.json#{} ---", doc_path);
                }
            }
            Ok(DocsRunResult {
                ingested_core_constitution,
            })
        }
        DocsCommand::Search {
            query,
            op,
            path,
            tag,
            limit,
            format,
        } => {
            let current_dir = std::env::current_dir().map_err(error::DecapodError::IoError)?;
            let repo_root = find_repo_root(&current_dir)?;
            let fragments = docs::resolve_scoped_fragments(
                &repo_root,
                Some(&query),
                op.as_deref(),
                &path,
                &tag,
                limit,
            );

            if format.eq_ignore_ascii_case("json") {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&serde_json::json!({
                        "query": query,
                        "op": op,
                        "paths": path,
                        "tags": tag,
                        "fragments": fragments,
                    }))
                    .map_err(|e| error::DecapodError::ValidationError(e.to_string()))?
                );
            } else {
                println!("Scoped constitution context:");
                for (idx, fragment) in fragments.iter().enumerate() {
                    println!("\n{}. {} ({})", idx + 1, fragment.title, fragment.r#ref);
                    println!("{}", fragment.excerpt);
                }
            }
            Ok(DocsRunResult::default())
        }
        DocsCommand::Override { force } => {
            let current_dir = std::env::current_dir().map_err(error::DecapodError::IoError)?;
            let repo_root = find_repo_root(&current_dir)?;
            let override_path = repo_root.join(".decapod").join("OVERRIDE.md");
            match sync_override_checksum(&repo_root, force)? {
                OverrideChecksumStatus::MissingOverride => {
                    println!("ℹ No OVERRIDE.md found at {}", override_path.display());
                    println!("  Run `decapod init` to create one.");
                }
                OverrideChecksumStatus::Cached => {
                    println!("✓ OVERRIDE.md checksum cached");
                }
                OverrideChecksumStatus::Updated => {
                    println!("📝 OVERRIDE.md checksum refreshed");
                }
                OverrideChecksumStatus::Unchanged => {
                    println!("✓ OVERRIDE.md unchanged");
                }
            }

            Ok(DocsRunResult::default())
        }
    }
}

/// Helper function to find the .decapod repo root
/// (This is a simplified version; a real implementation might be more robust)
fn find_repo_root(start_dir: &Path) -> Result<PathBuf, error::DecapodError> {
    // Check for developer override first
    let override_root = std::env::var("DECAPOD_DEV_OVERRIDE")
        .map(PathBuf::from)
        .unwrap_or_else(|_| start_dir.to_path_buf());

    let mut current_dir = override_root;
    loop {
        if current_dir.join(".decapod").exists() {
            return Ok(current_dir);
        }
        if !current_dir.pop() {
            return Err(error::DecapodError::NotFound(
                "'.decapod' directory not found in current or parent directories.".to_string(),
            ));
        }
    }
}

/// Calculate SHA256 checksum of a file
use clap::CommandFactory;
use std::io::Write;

fn build_docs(touched: Vec<PathBuf>) -> Result<(), error::DecapodError> {
    let current_dir = std::env::current_dir().map_err(error::DecapodError::IoError)?;
    let repo_root = find_repo_root(&current_dir)?;

    let contracts_path = repo_root.join("docs/agent/command-contracts.md");
    let _schema_path = repo_root.join("docs/agent/config-schema.md");

    // Only update if relevant files are touched, or if touched is empty (full build)
    let update_contracts = touched.is_empty()
        || touched.iter().any(|p| {
            let p_str = p.to_string_lossy();
            p_str.contains("src/cli.rs") || p_str.contains("src/core/docs_cli.rs")
        });

    let update_schema = touched.is_empty()
        || touched.iter().any(|p| {
            let p_str = p.to_string_lossy();
            p_str.contains("src/cli.rs")
        });

    if update_contracts {
        println!("Updating docs/agent/command-contracts.md...");
        let mut file = std::fs::File::create(&contracts_path)?;
        writeln!(file, "# Command Contracts\n")?;
        writeln!(
            file,
            "This document defines the normative operational contracts for the Decapod CLI.\n"
        )?;

        let cmd = crate::cli::Cli::command();
        for sub in cmd.get_subcommands() {
            if sub.is_hide_set() {
                continue;
            }
            let name = sub.get_name();
            let about = sub.get_about().map(|a| a.to_string()).unwrap_or_default();

            writeln!(file, "## `decapod {}`", name)?;
            writeln!(file, "- **Intent:** {}", about)?;

            // Extract more info if it's a known core command
            match name {
                "todo" => {
                    writeln!(
                        file,
                        "- **Preconditions:** Agent must have an active session."
                    )?;
                    writeln!(file, "- **State Transition:** Managed via `todo.db`.")?;
                }
                "workspace" => {
                    writeln!(file, "- **Preconditions:** Task must be claimed.")?;
                    writeln!(
                        file,
                        "- **State Transition:** Creates git worktrees/containers."
                    )?;
                }
                "validate" => {
                    writeln!(file, "- **Intent:** Verify methodology compliance.")?;
                    writeln!(file, "- **Outcome:** Exit code 0 on success, 1 on failure.")?;
                }
                _ => {}
            }
            writeln!(file)?;
        }

        // Auto-scan for RPCs
        writeln!(file, "# RPC Operations (Auto-generated)\n")?;
        let rpc_src =
            std::fs::read_to_string(repo_root.join("src/core/rpc.rs")).unwrap_or_default();
        for line in rpc_src.lines() {
            if line.contains("pub struct ") && line.contains("Params {") {
                let rpc_name = line
                    .split("pub struct ")
                    .nth(1)
                    .unwrap_or("")
                    .split("Params")
                    .next()
                    .unwrap_or("");
                if !rpc_name.is_empty() {
                    writeln!(file, "### Operation: `{}`", rpc_name)?;
                }
            }
        }
    }

    if update_schema {
        println!("Updating docs/agent/config-schema.md...");
        let schema_path = repo_root.join("docs/agent/config-schema.md");
        let mut file = std::fs::File::create(&schema_path)?;
        writeln!(file, "# Configuration Schema (Auto-generated)\n")?;

        let config_src = std::fs::read_to_string(repo_root.join("src/cli.rs")).unwrap_or_default();
        if let Some(start) = config_src.find("pub struct DecapodProjectConfig {") {
            let end = config_src[start..].find('}').unwrap_or(0);
            let fields = &config_src[start..start + end + 1];
            writeln!(file, "```rust\n{}\n```", fields)?;
        }
    }

    Ok(())
}

fn calculate_sha256(path: &Path) -> Result<String, error::DecapodError> {
    let content = std::fs::read(path).map_err(error::DecapodError::IoError)?;
    let hash = Sha256::digest(&content);
    Ok(format!("{:x}", hash))
}

/// Get cached checksum for OVERRIDE.md
fn get_cached_checksum(repo_root: &Path) -> Option<String> {
    let checksum_path = repo_root
        .join(".decapod")
        .join("generated")
        .join("override.checksum");
    std::fs::read_to_string(checksum_path).ok()
}

/// Cache checksum for OVERRIDE.md
fn cache_checksum(repo_root: &Path, checksum: &str) -> Result<(), error::DecapodError> {
    let checksum_path = repo_root
        .join(".decapod")
        .join("generated")
        .join("override.checksum");
    // Ensure generated directory exists
    if let Some(parent) = checksum_path.parent() {
        std::fs::create_dir_all(parent).map_err(error::DecapodError::IoError)?;
    }
    std::fs::write(checksum_path, checksum).map_err(error::DecapodError::IoError)
}

pub fn schema() -> serde_json::Value {
    serde_json::json!({
        "name": "docs",
        "type": "object",
        "properties": {
            "list": {
                "type": "null",
                "description": "List all embedded Decapod methodology documents"
            },
            "show": {
                "type": "string",
                "description": "Display a specific embedded document"
            },
            "ingest": {
                "type": "null",
                "description": "Dump all embedded constitution for agentic ingestion"
            },
            "search": {
                "type": "object",
                "description": "Return scoped constitution fragments for a problem query",
                "properties": {
                    "query": { "type": "string" },
                    "op": { "type": "string" },
                    "path": { "type": "array", "items": { "type": "string" } },
                    "tag": { "type": "array", "items": { "type": "string" } },
                    "limit": { "type": "integer" },
                    "format": { "type": "string", "enum": ["text", "json"] }
                }
            },
            "override": {
                "type": "object",
                "description": "Validate and cache OVERRIDE.md checksum",
                "properties": {
                    "force": {
                        "type": "boolean",
                        "description": "Force re-cache even if unchanged"
                    }
                }
            }
        }
    })
}