decapod 0.47.37

Decapod is the daemonless, local-first control plane that agents call on demand to align intent, enforce boundaries, and produce proof-backed completion across concurrent multi-agent work. 🦀
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
//! Integration tests for entrypoint correctness.
//!
//! These tests ensure that `decapod init` creates correct entrypoint files
//! and that `decapod validate` enforces invariants and detects tampering.

use decapod::core::assets;
use std::fs;
use std::path::PathBuf;
use std::process::{Command, Output};
use tempfile::TempDir;

/// Helper to run decapod command in a temp directory
fn run_decapod(temp_dir: &PathBuf, args: &[&str]) -> (bool, String) {
    run_decapod_with_env(temp_dir, args, &[("DECAPOD_VALIDATE_SKIP_GIT_GATES", "1")])
}

fn run_decapod_with_env(
    temp_dir: &PathBuf,
    args: &[&str],
    envs: &[(&str, &str)],
) -> (bool, String) {
    let mut cmd = Command::new(env!("CARGO_BIN_EXE_decapod"));
    cmd.current_dir(temp_dir).args(args);
    for (k, v) in envs {
        cmd.env(k, v);
    }
    let output = cmd.output().expect("Failed to execute decapod");

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    let combined = format!("{}\n{}", stdout, stderr);

    (output.status.success(), combined)
}

fn run_raw(temp_dir: &PathBuf, args: &[&str], envs: &[(&str, &str)]) -> Output {
    let mut cmd = Command::new(env!("CARGO_BIN_EXE_decapod"));
    cmd.current_dir(temp_dir).args(args);
    for (k, v) in envs {
        cmd.env(k, v);
    }
    cmd.output().expect("Failed to execute decapod")
}

fn acquire_session(temp_path: &PathBuf) {
    let (success, output) = run_decapod(temp_path, &["session", "acquire"]);
    assert!(
        success,
        "decapod session acquire should succeed. Output:\n{}",
        output
    );
}

fn extract_password(output: &str) -> Option<String> {
    for line in output.lines() {
        if let Some(rest) = line.strip_prefix("Password: ") {
            return Some(rest.trim().to_string());
        }
    }
    None
}

#[test]
fn test_init_creates_all_entrypoints() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let temp_path = temp_dir.path().to_path_buf();

    // Run decapod init
    let (success, _output) = run_decapod(&temp_path, &["init", "--force"]);
    assert!(success, "decapod init should succeed");

    // Check that all 5 entrypoint files exist
    let expected_files = ["AGENTS.md", "CLAUDE.md", "GEMINI.md", "CODEX.md"];

    for file in expected_files {
        let file_path = temp_path.join(file);
        assert!(
            file_path.exists(),
            "Entrypoint file {} should exist after init",
            file
        );

        // Check that file is non-empty
        let content =
            fs::read_to_string(&file_path).unwrap_or_else(|_| panic!("Failed to read {}", file));
        assert!(!content.is_empty(), "{} should not be empty", file);
    }
}

#[test]
fn test_validate_passes_after_init() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let temp_path = temp_dir.path().to_path_buf();

    // Run decapod init
    let (success, _) = run_decapod(&temp_path, &["init", "--force"]);
    assert!(success, "decapod init should succeed");
    acquire_session(&temp_path);

    // Run decapod validate
    let (success, output) = run_decapod(&temp_path, &["validate"]);
    assert!(
        success,
        "decapod validate should pass after init. Output:\n{}",
        output
    );

    // Check that Four Invariants Gate is mentioned
    assert!(
        output.contains("Four Invariants Gate"),
        "Validation should check Four Invariants Gate"
    );
}

#[test]
fn test_validate_passes_after_init_without_git_repo() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let temp_path = temp_dir.path().to_path_buf();

    let init = run_raw(&temp_path, &["init", "--force"], &[]);
    assert!(
        init.status.success(),
        "decapod init should succeed. Output:\n{}{}",
        String::from_utf8_lossy(&init.stdout),
        String::from_utf8_lossy(&init.stderr)
    );

    let validate = run_raw(&temp_path, &["validate"], &[]);
    let output = format!(
        "{}{}",
        String::from_utf8_lossy(&validate.stdout),
        String::from_utf8_lossy(&validate.stderr)
    );
    assert!(
        validate.status.success(),
        "decapod validate should pass immediately after init in a non-git directory. Output:\n{}",
        output
    );
    assert!(
        output.contains("validation passed"),
        "validate should emit a clean success marker. Output:\n{}",
        output
    );
    assert!(
        !output.contains("Error:"),
        "validate should not emit an error while succeeding. Output:\n{}",
        output
    );
    assert!(
        !output.contains("warn:"),
        "validate should not emit warnings after fresh init. Output:\n{}",
        output
    );
    assert!(
        !output.contains("repair"),
        "validate should not require self-heal/repair after fresh init. Output:\n{}",
        output
    );
    assert!(
        !output.contains("self-heal"),
        "validate should not report self-heal after fresh init. Output:\n{}",
        output
    );
    assert!(
        !output.contains("requires isolated git worktree"),
        "fresh non-git validation should not be rejected by workspace preflight. Output:\n{}",
        output
    );
}

#[test]
fn test_agent_session_requires_password() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let temp_path = temp_dir.path().to_path_buf();

    let (success, _) = run_decapod(&temp_path, &["init", "--force"]);
    assert!(success, "decapod init should succeed");

    let (success, acquire_out) = run_decapod_with_env(
        &temp_path,
        &["session", "acquire"],
        &[("DECAPOD_AGENT_ID", "agent-secure")],
    );
    assert!(success, "session acquire should succeed: {}", acquire_out);
    let password = extract_password(&acquire_out).expect("acquire output should include password");

    let (ok_missing, out_missing) = run_decapod_with_env(
        &temp_path,
        &["validate"],
        &[("DECAPOD_AGENT_ID", "agent-secure")],
    );
    // With auto-acquire funnel, validate may auto-create session
    // but workspace requirement still applies first
    assert!(
        !ok_missing || out_missing.contains("worktree") || out_missing.contains("session"),
        "validate should either fail on workspace or auto-acquire session: {}",
        out_missing
    );

    let (ok_wrong, out_wrong) = run_decapod_with_env(
        &temp_path,
        &["validate"],
        &[
            ("DECAPOD_AGENT_ID", "agent-secure"),
            ("DECAPOD_SESSION_PASSWORD", "wrong"),
        ],
    );
    // With auto-acquire funnel, wrong password triggers auto-recovery
    // but workspace requirement still applies first
    assert!(
        !ok_wrong || out_wrong.contains("worktree") || out_wrong.contains("session"),
        "validate should either fail on workspace or auto-acquire session: {}",
        out_wrong
    );

    let (ok_good, out_good) = run_decapod_with_env(
        &temp_path,
        &["validate"],
        &[
            ("DECAPOD_AGENT_ID", "agent-secure"),
            ("DECAPOD_SESSION_PASSWORD", &password),
            ("DECAPOD_VALIDATE_SKIP_GIT_GATES", "1"),
        ],
    );
    assert!(
        ok_good,
        "validate should pass with correct agent+password: {}",
        out_good
    );
}

#[test]
fn test_expired_session_releases_assigned_tasks() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let temp_path = temp_dir.path().to_path_buf();

    let (success, _) = run_decapod(&temp_path, &["init", "--force"]);
    assert!(success, "decapod init should succeed");

    let (success, acquire_out) = run_decapod_with_env(
        &temp_path,
        &["session", "acquire"],
        &[("DECAPOD_AGENT_ID", "agent-expire")],
    );
    assert!(success, "session acquire should succeed: {}", acquire_out);
    let password = extract_password(&acquire_out).expect("acquire output should include password");
    let auth_env = [
        ("DECAPOD_AGENT_ID", "agent-expire"),
        ("DECAPOD_SESSION_PASSWORD", password.as_str()),
        ("DECAPOD_GROUP_BROKER_INTERNAL", "1"),
    ];

    let add_out = run_raw(
        &temp_path,
        &["todo", "--format", "json", "add", "session cleanup target"],
        &auth_env,
    );
    assert!(
        add_out.status.success(),
        "todo add should succeed: {}",
        String::from_utf8_lossy(&add_out.stderr)
    );
    let add_json: serde_json::Value =
        serde_json::from_slice(&add_out.stdout).expect("todo add should return json");
    let task_id = add_json["id"]
        .as_str()
        .expect("todo add json should include id")
        .to_string();

    let claim_out = run_raw(
        &temp_path,
        &["todo", "--format", "json", "claim", "--id", &task_id],
        &auth_env,
    );
    assert!(
        claim_out.status.success(),
        "todo claim should succeed: {}",
        String::from_utf8_lossy(&claim_out.stderr)
    );

    let session_path = temp_path
        .join(".decapod")
        .join("generated")
        .join("sessions")
        .join("agent-expire.json");
    let mut session_json: serde_json::Value =
        serde_json::from_str(&fs::read_to_string(&session_path).expect("session file"))
            .expect("session json");
    session_json["expires_at_epoch_secs"] = serde_json::json!(0);
    fs::write(
        &session_path,
        serde_json::to_string_pretty(&session_json).expect("serialize"),
    )
    .expect("write expired session");

    let status_out = run_raw(
        &temp_path,
        &["session", "status"],
        &[("DECAPOD_AGENT_ID", "agent-expire")],
    );
    assert!(
        status_out.status.success(),
        "session status should run cleanup: {}",
        String::from_utf8_lossy(&status_out.stderr)
    );

    let (ok_unknown_acquire, out_unknown_acquire) =
        run_decapod(&temp_path, &["session", "acquire"]);
    assert!(
        ok_unknown_acquire,
        "unknown session acquire should succeed: {}",
        out_unknown_acquire
    );

    let todo_db = temp_path.join(".decapod").join("data").join("todo.db");
    let conn = rusqlite::Connection::open(todo_db).expect("open todo db");
    let assigned_to: String = conn
        .query_row(
            "SELECT assigned_to FROM tasks WHERE id = ?1",
            [task_id.as_str()],
            |row| row.get(0),
        )
        .expect("query task owner");
    assert_eq!(
        assigned_to, "",
        "expired session cleanup should unassign task"
    );
}

#[test]
fn test_entrypoints_are_thin() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let temp_path = temp_dir.path().to_path_buf();

    // Run decapod init
    let (success, _) = run_decapod(&temp_path, &["init", "--force"]);
    assert!(success, "decapod init should succeed");

    // Check AGENTS.md line count (should be ≤ 100)
    let agents_content =
        fs::read_to_string(temp_path.join("AGENTS.md")).expect("Failed to read AGENTS.md");
    let agents_lines = agents_content.lines().count();
    assert!(
        agents_lines <= 100,
        "AGENTS.md should be ≤ 100 lines (got {})",
        agents_lines
    );

    // Check agent-specific files (should be ≤ 70)
    for file in ["CLAUDE.md", "GEMINI.md", "CODEX.md"] {
        let content = fs::read_to_string(temp_path.join(file))
            .unwrap_or_else(|_| panic!("Failed to read {}", file));
        let line_count = content.lines().count();
        assert!(
            line_count <= 70,
            "{} should be ≤ 70 lines (got {})",
            file,
            line_count
        );
    }
}

#[test]
fn test_entrypoints_contain_canonical_router() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let temp_path = temp_dir.path().to_path_buf();

    // Run decapod init
    let (success, _) = run_decapod(&temp_path, &["init", "--force"]);
    assert!(success, "decapod init should succeed");

    // Check that all entrypoints reference core/DECAPOD.md
    let files = ["AGENTS.md", "CLAUDE.md", "GEMINI.md", "CODEX.md"];

    for file in files {
        let content = fs::read_to_string(temp_path.join(file))
            .unwrap_or_else(|_| panic!("Failed to read {}", file));
        assert!(
            content.contains("core/DECAPOD.md"),
            "{} should reference canonical router (core/DECAPOD.md)",
            file
        );
    }
}

#[test]
fn test_entrypoints_contain_four_invariants() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let temp_path = temp_dir.path().to_path_buf();

    // Run decapod init
    let (success, _) = run_decapod(&temp_path, &["init", "--force"]);
    assert!(success, "decapod init should succeed");

    // Check that AGENTS.md contains the 4 invariants
    let agents_content =
        fs::read_to_string(temp_path.join("AGENTS.md")).expect("Failed to read AGENTS.md");

    let invariant_markers = ["core/DECAPOD.md", "decapod validate", "stop if", "✅"];

    for marker in invariant_markers {
        assert!(
            agents_content.contains(marker),
            "AGENTS.md should contain invariant marker: {}",
            marker
        );
    }
}

#[test]
fn test_validate_fails_on_missing_invariant() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let temp_path = temp_dir.path().to_path_buf();

    // Run decapod init
    let (success, _) = run_decapod(&temp_path, &["init", "--force"]);
    assert!(success, "decapod init should succeed");
    acquire_session(&temp_path);

    // Tamper with AGENTS.md - remove canonical router reference
    let agents_path = temp_path.join("AGENTS.md");
    let content = fs::read_to_string(&agents_path).expect("Failed to read AGENTS.md");
    let tampered = content.replace("core/DECAPOD.md", "core/LEGACY.md");
    fs::write(&agents_path, tampered).expect("Failed to write tampered AGENTS.md");

    // Run decapod validate (should fail)
    let (success, output) = run_decapod(&temp_path, &["validate"]);
    assert!(
        !success,
        "decapod validate should fail after tampering. Output:\n{}",
        output
    );

    // Check that it detected the missing invariant
    assert!(
        output.contains("Invariant missing: Router pointer to core/DECAPOD.md"),
        "Validation should detect missing router invariant"
    );
}

#[test]
fn test_validate_fails_on_bloated_entrypoint() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let temp_path = temp_dir.path().to_path_buf();

    // Run decapod init
    let (success, _) = run_decapod(&temp_path, &["init", "--force"]);
    assert!(success, "decapod init should succeed");
    acquire_session(&temp_path);

    // Bloat CLAUDE.md beyond 50 lines
    let claude_path = temp_path.join("CLAUDE.md");
    let content = fs::read_to_string(&claude_path).expect("Failed to read CLAUDE.md");
    let bloated = format!("{}\n{}", content, "# Extra\n".repeat(50));
    fs::write(&claude_path, bloated).expect("Failed to write bloated CLAUDE.md");

    // Run decapod validate (should fail)
    let (success, output) = run_decapod(&temp_path, &["validate"]);
    assert!(
        !success,
        "decapod validate should fail on bloated entrypoint. Output:\n{}",
        output
    );

    // Check that it detected the line limit violation
    assert!(
        output.contains("CLAUDE.md exceeds line limit"),
        "Validation should detect bloated entrypoint"
    );
}

#[test]
fn test_agent_specific_files_defer_to_agents() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let temp_path = temp_dir.path().to_path_buf();

    // Run decapod init
    let (success, _) = run_decapod(&temp_path, &["init", "--force"]);
    assert!(success, "decapod init should succeed");

    // Check that agent-specific files reference AGENTS.md
    for file in ["CLAUDE.md", "GEMINI.md", "CODEX.md"] {
        let content = fs::read_to_string(temp_path.join(file))
            .unwrap_or_else(|_| panic!("Failed to read {}", file));
        assert!(
            content.contains("AGENTS.md"),
            "{} should defer to AGENTS.md",
            file
        );
    }
}

#[test]
fn test_root_entrypoints_match_scaffold_generators() {
    let repo_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    for file in ["AGENTS.md", "CLAUDE.md", "GEMINI.md", "CODEX.md"] {
        let root_path = repo_root.join(file);
        let root_content =
            fs::read_to_string(&root_path).unwrap_or_else(|_| panic!("Failed to read {}", file));
        let template_content =
            assets::get_template(file).unwrap_or_else(|| panic!("Missing generated {}", file));

        assert_eq!(
            root_content, template_content,
            "Entrypoint drift detected: {} differs from Rust scaffold generator output.",
            file
        );
    }
}

#[test]
fn test_agent_entrypoints_are_consistent_except_header() {
    let repo_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));

    let root_claude = fs::read_to_string(repo_root.join("CLAUDE.md")).expect("read CLAUDE.md");
    let root_gemini = fs::read_to_string(repo_root.join("GEMINI.md")).expect("read GEMINI.md");
    let root_codex = fs::read_to_string(repo_root.join("CODEX.md")).expect("read CODEX.md");

    assert!(
        root_claude
            .lines()
            .next()
            .is_some_and(|l| l.contains("CLAUDE.md")),
        "CLAUDE.md header should include CLAUDE.md"
    );
    assert_eq!(
        root_claude.lines().skip(1).collect::<Vec<_>>(),
        root_gemini.lines().skip(1).collect::<Vec<_>>(),
        "Root entrypoints should only differ by file-specific header: CLAUDE.md != GEMINI.md"
    );
    assert_eq!(
        root_claude.lines().skip(1).collect::<Vec<_>>(),
        root_codex.lines().skip(1).collect::<Vec<_>>(),
        "Root entrypoints should only differ by file-specific header: CLAUDE.md != CODEX.md"
    );

    let tpl_claude = assets::get_template("CLAUDE.md").expect("generated CLAUDE");
    let tpl_gemini = assets::get_template("GEMINI.md").expect("generated GEMINI");
    let tpl_codex = assets::get_template("CODEX.md").expect("generated CODEX");

    assert_eq!(
        tpl_claude.lines().skip(1).collect::<Vec<_>>(),
        tpl_gemini.lines().skip(1).collect::<Vec<_>>(),
        "Template entrypoints should only differ by file-specific header: CLAUDE.md != GEMINI.md"
    );
    assert_eq!(
        tpl_claude.lines().skip(1).collect::<Vec<_>>(),
        tpl_codex.lines().skip(1).collect::<Vec<_>>(),
        "Template entrypoints should only differ by file-specific header: CLAUDE.md != CODEX.md"
    );
}

#[test]
fn test_entrypoints_use_embedded_docs_paths_only() {
    let repo_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    for file in ["CLAUDE.md", "GEMINI.md", "CODEX.md"] {
        let content =
            fs::read_to_string(repo_root.join(file)).unwrap_or_else(|_| panic!("read {}", file));
        assert!(
            !content.contains("decapod docs show constitution/"),
            "{} must not reference direct constitution/* filesystem paths",
            file
        );
        assert!(
            content.contains("decapod docs show docs/PLAYBOOK.md"),
            "{} must reference embedded docs path for operator playbook",
            file
        );
        assert!(
            content.contains(".decapod/workspaces"),
            "{} must mandate canonical Decapod worktree root",
            file
        );
        assert!(
            content.contains("decapod todo add \"<task>\""),
            "{} must require task creation before claim",
            file
        );
        assert!(
            !content.contains(".claude/worktrees"),
            "{} must never reference non-canonical .claude/worktrees path",
            file
        );
    }
}

#[test]
fn test_top_level_docs_avoid_direct_constitution_file_links() {
    let repo_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    let readme = fs::read_to_string(repo_root.join("README.md")).expect("read README.md");
    let security = fs::read_to_string(repo_root.join("SECURITY.md")).expect("read SECURITY.md");

    assert!(
        readme.contains("(constitution/core/DECAPOD.md)"),
        "README.md should link to constitution/core/DECAPOD.md"
    );

    assert!(
        !security.contains("(constitution/"),
        "SECURITY.md should not instruct direct constitution file access"
    );
    assert!(
        security.contains("decapod docs show specs/SECURITY.md"),
        "SECURITY.md should route constitutional access through decapod docs show"
    );
}

#[test]
fn test_intent_context_spec_contract_alignment() {
    let repo_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    let readme = fs::read_to_string(repo_root.join("README.md")).expect("read README.md");
    let core_decapod = fs::read_to_string(repo_root.join("constitution/core/DECAPOD.md"))
        .expect("read constitution/core/DECAPOD.md");
    let lib_rs = fs::read_to_string(repo_root.join("src/lib.rs")).expect("read src/lib.rs");
    let cli_rs = fs::read_to_string(repo_root.join("src/cli.rs")).expect("read src/cli.rs");

    let contract_phrase =
        "turn intent into context, then context into explicit specifications before inference";

    assert!(
        readme.contains(contract_phrase),
        "README.md must state the intent->context->specifications flow"
    );
    assert!(
        core_decapod.contains(contract_phrase),
        "constitution/core/DECAPOD.md must state the intent->context->specifications flow"
    );
    assert!(
        lib_rs.contains(contract_phrase) || cli_rs.contains(contract_phrase),
        "src/lib.rs or src/cli.rs CLI about text must state the intent->context->specifications flow"
    );
}