terraphim_agent 1.16.34

Terraphim AI Agent CLI - Command-line interface with interactive REPL and ASCII graph visualization
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
//! Integration tests for the procedural memory CLI (`learn procedure` subcommands).
//!
//! These tests exercise the full binary to verify that procedures can be created,
//! steps added, confidence updated, listed, and shown via the CLI.

use std::process::Command;

fn agent_binary() -> String {
    let output = Command::new("cargo")
        .args(["build", "-p", "terraphim_agent"])
        .output()
        .expect("cargo build should succeed");
    if !output.status.success() {
        panic!(
            "cargo build failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    let workspace_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .unwrap()
        .parent()
        .unwrap();
    workspace_root
        .join("target/debug/terraphim-agent")
        .to_string_lossy()
        .to_string()
}

/// Run a procedure subcommand, returning (stdout, stderr, success).
fn run_procedure_cmd(binary: &str, args: &[&str], env_home: &str) -> (String, String, bool) {
    let mut full_args = vec!["learn", "procedure"];
    full_args.extend_from_slice(args);

    let output = Command::new(binary)
        .args(&full_args)
        // Override HOME so procedures.jsonl is written to a temp dir
        .env("HOME", env_home)
        // Also override XDG_DATA_HOME to control where dirs::data_dir() resolves
        .env("XDG_DATA_HOME", format!("{}/data", env_home))
        .output()
        .expect("should execute procedure command");

    (
        String::from_utf8_lossy(&output.stdout).to_string(),
        String::from_utf8_lossy(&output.stderr).to_string(),
        output.status.success(),
    )
}

#[test]
fn procedure_list_empty() {
    let binary = agent_binary();
    let tmp = tempfile::tempdir().expect("create temp dir");
    let home = tmp.path().to_string_lossy().to_string();

    let (stdout, _stderr, success) = run_procedure_cmd(&binary, &["list"], &home);
    assert!(success, "list on empty store should succeed");
    assert!(
        stdout.contains("No procedures found"),
        "expected empty message, got: {}",
        stdout
    );
}

#[test]
fn procedure_record_and_show() {
    let binary = agent_binary();
    let tmp = tempfile::tempdir().expect("create temp dir");
    let home = tmp.path().to_string_lossy().to_string();

    // Record a new procedure
    let (stdout, _stderr, success) = run_procedure_cmd(
        &binary,
        &[
            "record",
            "Build Rust project",
            "--description",
            "Steps to build a Rust project from scratch",
        ],
        &home,
    );
    assert!(success, "record should succeed");
    assert!(
        stdout.contains("Created procedure:"),
        "expected creation message, got: {}",
        stdout
    );

    // Extract the procedure ID from output
    let id = stdout
        .trim()
        .strip_prefix("Created procedure: ")
        .expect("should have procedure ID")
        .to_string();

    // Show it
    let (stdout, _stderr, success) = run_procedure_cmd(&binary, &["show", &id], &home);
    assert!(success, "show should succeed");
    assert!(stdout.contains("Build Rust project"), "title in output");
    assert!(
        stdout.contains("Steps to build a Rust project from scratch"),
        "description in output"
    );
    assert!(stdout.contains("Steps (0):"), "zero steps initially");
}

#[test]
fn procedure_add_step_and_list() {
    let binary = agent_binary();
    let tmp = tempfile::tempdir().expect("create temp dir");
    let home = tmp.path().to_string_lossy().to_string();

    // Record
    let (stdout, _, _) = run_procedure_cmd(&binary, &["record", "Deploy app"], &home);
    let id = stdout
        .trim()
        .strip_prefix("Created procedure: ")
        .unwrap()
        .to_string();

    // Add steps
    let (stdout, _, success) = run_procedure_cmd(
        &binary,
        &[
            "add-step",
            &id,
            "cargo build --release",
            "--precondition",
            "Rust toolchain installed",
            "--postcondition",
            "Binary exists in target/release",
        ],
        &home,
    );
    assert!(success, "add-step should succeed");
    assert!(stdout.contains("Added step 1"), "first step added");

    let (stdout, _, success) = run_procedure_cmd(
        &binary,
        &["add-step", &id, "scp target/release/app server:/opt/"],
        &home,
    );
    assert!(success, "second add-step should succeed");
    assert!(stdout.contains("Added step 2"), "second step added");

    // Show with steps
    let (stdout, _, success) = run_procedure_cmd(&binary, &["show", &id], &home);
    assert!(success);
    assert!(stdout.contains("Steps (2):"), "two steps");
    assert!(stdout.contains("cargo build --release"));
    assert!(stdout.contains("pre: Rust toolchain installed"));
    assert!(stdout.contains("post: Binary exists in target/release"));
    assert!(stdout.contains("scp target/release/app server:/opt/"));

    // List
    let (stdout, _, success) = run_procedure_cmd(&binary, &["list"], &home);
    assert!(success);
    assert!(stdout.contains("Deploy app"));
    assert!(stdout.contains("2 steps"));
}

#[test]
fn procedure_success_and_failure_update_confidence() {
    let binary = agent_binary();
    let tmp = tempfile::tempdir().expect("create temp dir");
    let home = tmp.path().to_string_lossy().to_string();

    // Record
    let (stdout, _, _) = run_procedure_cmd(&binary, &["record", "Test procedure"], &home);
    let id = stdout
        .trim()
        .strip_prefix("Created procedure: ")
        .unwrap()
        .to_string();

    // Record successes
    let (_, _, success) = run_procedure_cmd(&binary, &["success", &id], &home);
    assert!(success);
    let (_, _, success) = run_procedure_cmd(&binary, &["success", &id], &home);
    assert!(success);

    // Record a failure
    let (_, _, success) = run_procedure_cmd(&binary, &["failure", &id], &home);
    assert!(success);

    // Show to verify confidence: 2 successes, 1 failure = 67%
    let (stdout, _, success) = run_procedure_cmd(&binary, &["show", &id], &home);
    assert!(success);
    assert!(
        stdout.contains("67%"),
        "expected 67% confidence, got: {}",
        stdout
    );
    assert!(stdout.contains("2 successes"));
    assert!(stdout.contains("1 failures"));
}

#[test]
fn procedure_success_nonexistent_fails() {
    let binary = agent_binary();
    let tmp = tempfile::tempdir().expect("create temp dir");
    let home = tmp.path().to_string_lossy().to_string();

    let (_, _stderr, success) = run_procedure_cmd(&binary, &["success", "nonexistent-id"], &home);
    assert!(!success, "success on nonexistent procedure should fail");
}

#[test]
fn procedure_replay_dry_run() {
    let binary = agent_binary();
    let tmp = tempfile::tempdir().expect("create temp dir");
    let home = tmp.path().to_string_lossy().to_string();

    // Record a procedure
    let (stdout, _, _) = run_procedure_cmd(&binary, &["record", "Echo things"], &home);
    let id = stdout
        .trim()
        .strip_prefix("Created procedure: ")
        .unwrap()
        .to_string();

    // Add two echo steps
    run_procedure_cmd(&binary, &["add-step", &id, "echo hello"], &home);
    run_procedure_cmd(&binary, &["add-step", &id, "echo world"], &home);

    // Replay with --dry-run
    let (stdout, _stderr, success) =
        run_procedure_cmd(&binary, &["replay", &id, "--dry-run"], &home);
    assert!(success, "dry-run replay should succeed");
    assert!(
        stdout.contains("[DRY RUN]"),
        "should indicate dry run, got: {}",
        stdout
    );
    assert!(
        stdout.contains("step 1: OK"),
        "step 1 should report OK, got: {}",
        stdout
    );
    assert!(
        stdout.contains("step 2: OK"),
        "step 2 should report OK, got: {}",
        stdout
    );
    assert!(
        stdout.contains("Dry run completed"),
        "should report dry run completed, got: {}",
        stdout
    );
}

#[test]
fn procedure_replay_real_execution() {
    let binary = agent_binary();
    let tmp = tempfile::tempdir().expect("create temp dir");
    let home = tmp.path().to_string_lossy().to_string();

    // Record
    let (stdout, _, _) = run_procedure_cmd(&binary, &["record", "Echo commands"], &home);
    let id = stdout
        .trim()
        .strip_prefix("Created procedure: ")
        .unwrap()
        .to_string();

    // Add echo steps
    run_procedure_cmd(&binary, &["add-step", &id, "echo hello"], &home);
    run_procedure_cmd(&binary, &["add-step", &id, "echo world"], &home);

    // Replay for real
    let (stdout, _stderr, success) = run_procedure_cmd(&binary, &["replay", &id], &home);
    assert!(success, "replay should succeed, stderr: {}", _stderr);
    assert!(
        stdout.contains("Replay completed successfully"),
        "should report success, got: {}",
        stdout
    );

    // Verify confidence was updated (1 success recorded)
    let (stdout, _, _) = run_procedure_cmd(&binary, &["show", &id], &home);
    assert!(
        stdout.contains("1 successes"),
        "should show 1 success after replay, got: {}",
        stdout
    );
}

#[test]
fn procedure_replay_failure_stops_early() {
    let binary = agent_binary();
    let tmp = tempfile::tempdir().expect("create temp dir");
    let home = tmp.path().to_string_lossy().to_string();

    // Record
    let (stdout, _, _) = run_procedure_cmd(&binary, &["record", "Failing procedure"], &home);
    let id = stdout
        .trim()
        .strip_prefix("Created procedure: ")
        .unwrap()
        .to_string();

    // Add a failing step followed by an echo step
    run_procedure_cmd(&binary, &["add-step", &id, "false"], &home);
    run_procedure_cmd(&binary, &["add-step", &id, "echo should-not-run"], &home);

    // Replay -- should fail
    let (stdout, _stderr, success) = run_procedure_cmd(&binary, &["replay", &id], &home);
    assert!(!success, "replay with failure should exit non-zero");
    assert!(
        stdout.contains("FAILED"),
        "should report failure, got: {}",
        stdout
    );
    // The second step should not appear as OK
    assert!(
        !stdout.contains("step 2: OK"),
        "step 2 should not have run, got: {}",
        stdout
    );
}

#[test]
fn procedure_replay_nonexistent_fails() {
    let binary = agent_binary();
    let tmp = tempfile::tempdir().expect("create temp dir");
    let home = tmp.path().to_string_lossy().to_string();

    let (_, _stderr, success) = run_procedure_cmd(&binary, &["replay", "nonexistent-id"], &home);
    assert!(!success, "replay of nonexistent procedure should fail");
}

#[test]
fn procedure_health_shows_critical_after_failures() {
    let binary = agent_binary();
    let tmp = tempfile::tempdir().expect("create temp dir");
    let home = tmp.path().to_string_lossy().to_string();

    // Record a procedure
    let (stdout, _, _) = run_procedure_cmd(&binary, &["record", "Fragile procedure"], &home);
    let id = stdout
        .trim()
        .strip_prefix("Created procedure: ")
        .unwrap()
        .to_string();

    // Record 5 failures (enough for auto-disable)
    for _ in 0..5 {
        let (_, _, success) = run_procedure_cmd(&binary, &["failure", &id], &home);
        assert!(success);
    }

    // Run health check
    let (stdout, _stderr, success) = run_procedure_cmd(&binary, &["health"], &home);
    assert!(
        success,
        "health command should succeed, stderr: {}",
        _stderr
    );
    assert!(
        stdout.contains("Critical"),
        "expected Critical status, got: {}",
        stdout
    );
    assert!(
        stdout.contains("auto-disabled"),
        "expected auto-disabled message, got: {}",
        stdout
    );
}

#[test]
fn procedure_disable_prevents_replay() {
    let binary = agent_binary();
    let tmp = tempfile::tempdir().expect("create temp dir");
    let home = tmp.path().to_string_lossy().to_string();

    // Record a procedure with a step
    let (stdout, _, _) = run_procedure_cmd(&binary, &["record", "Disable test"], &home);
    let id = stdout
        .trim()
        .strip_prefix("Created procedure: ")
        .unwrap()
        .to_string();

    run_procedure_cmd(&binary, &["add-step", &id, "echo hello"], &home);

    // Disable it
    let (stdout, _, success) = run_procedure_cmd(&binary, &["disable", &id], &home);
    assert!(success, "disable should succeed");
    assert!(
        stdout.contains("disabled"),
        "expected disabled message, got: {}",
        stdout
    );

    // Attempt replay -- should be refused
    let (_, stderr, success) = run_procedure_cmd(&binary, &["replay", &id], &home);
    assert!(!success, "replay of disabled procedure should fail");
    assert!(
        stderr.contains("disabled"),
        "expected disabled error, got stderr: {}",
        stderr
    );
}

#[test]
fn procedure_enable_allows_replay() {
    let binary = agent_binary();
    let tmp = tempfile::tempdir().expect("create temp dir");
    let home = tmp.path().to_string_lossy().to_string();

    // Record a procedure with a step
    let (stdout, _, _) = run_procedure_cmd(&binary, &["record", "Enable test"], &home);
    let id = stdout
        .trim()
        .strip_prefix("Created procedure: ")
        .unwrap()
        .to_string();

    run_procedure_cmd(&binary, &["add-step", &id, "echo hello"], &home);

    // Disable then re-enable
    run_procedure_cmd(&binary, &["disable", &id], &home);
    let (stdout, _, success) = run_procedure_cmd(&binary, &["enable", &id], &home);
    assert!(success, "enable should succeed");
    assert!(
        stdout.contains("enabled"),
        "expected enabled message, got: {}",
        stdout
    );

    // Replay should work now
    let (stdout, _stderr, success) = run_procedure_cmd(&binary, &["replay", &id], &home);
    assert!(
        success,
        "replay of re-enabled procedure should succeed, stderr: {}",
        _stderr
    );
    assert!(
        stdout.contains("Replay completed successfully"),
        "expected success message, got: {}",
        stdout
    );
}