loopflow 0.12.2

Run steps and flows with coding agents
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
//! `lf status` is an audit surface, so its contract is user-facing: the JSON it
//! promises must be the JSON it emits, and the wave you are standing in must be
//! the wave it reports. Drives the real binary against a seeded `LF_HOME`.

use std::path::Path;
use std::process::Command;

use loopflow::id::WaveId;
use loopflow::store::sqlite::SqliteStore;
use loopflow::store::RunEventRow;
use loopflow::trace::{AgentLaunchRow, AgentTurnRow};
use loopflow::wave::Wave;

/// A machine home holding one wave with lookup noise, a flow, and a skill. The
/// registry and the ledgers are the same database.
fn seed(home: &Path, wave_name: &str) -> Wave {
    std::fs::create_dir_all(home).expect("home");
    let db = home.join("loopflow.db");
    let store = SqliteStore::new(&db).expect("open store");
    let wave = Wave::new(
        WaveId::new(),
        wave_name.to_string(),
        home.join("repo").display().to_string(),
    );
    store.create_wave(&wave).expect("register wave");

    let now = chrono::Utc::now().timestamp();
    let event = |seq: i64, ts: i64, event: &str| RunEventRow {
        run_id: "run-1".to_string(),
        process_id: "proc-lookup".to_string(),
        parent_process_id: None,
        seq,
        ts,
        repo: Some(home.join("repo").display().to_string()),
        worktree: None,
        wave: Some(wave_name.to_string()),
        node: "run".to_string(),
        event: event.to_string(),
        command: Some(r#"["lf","pm","sync"]"#.to_string()),
        flow: None,
        skill: None,
        step_index: None,
        error: None,
    };
    store
        .insert_run_event(&event(0, now - 120, "started"))
        .expect("seed run start");
    store
        .insert_run_event(&event(1, now - 60, "completed"))
        .expect("seed run end");

    let mut flow_start = event(1, now - 50, "started");
    flow_start.run_id = "run-flow".to_string();
    flow_start.process_id = "proc-flow".to_string();
    flow_start.node = "flow".to_string();
    flow_start.command = Some(r#"["lf","build"]"#.to_string());
    flow_start.flow = Some("build".to_string());
    store
        .insert_run_event(&flow_start)
        .expect("seed flow start");
    let mut flow_end = flow_start.clone();
    flow_end.seq = 2;
    flow_end.ts = now - 40;
    flow_end.event = "completed".to_string();
    store.insert_run_event(&flow_end).expect("seed flow end");

    // The run boundary the resident launch below rides on. A real agent launch
    // always sits inside a run, so its trace is reachable by process or run id.
    let mut resident_start = event(0, now - 30, "started");
    resident_start.run_id = "run-resident".to_string();
    resident_start.process_id = "proc-resident".to_string();
    resident_start.command = Some(r#"["lf","__resident"]"#.to_string());
    store
        .insert_run_event(&resident_start)
        .expect("seed resident start");
    let mut resident_end = resident_start.clone();
    resident_end.seq = 1;
    resident_end.ts = now - 20;
    resident_end.event = "completed".to_string();
    store
        .insert_run_event(&resident_end)
        .expect("seed resident end");

    let launch = AgentLaunchRow {
        id: "launch-wave-mutate".to_string(),
        run_id: "run-resident".to_string(),
        process_id: "proc-resident".to_string(),
        started_at: now - 30,
        ended_at: Some(now - 20),
        repo: home.join("repo").display().to_string(),
        worktree: home.join("repo").display().to_string(),
        wave: Some(wave_name.to_string()),
        flow: Some("wave".to_string()),
        skill: Some("wave_mutate".to_string()),
        project: Some("auditability".to_string()),
        task: Some("W2-122".to_string()),
        provider: "codex".to_string(),
        model: Some("gpt-5".to_string()),
        surface: "headless".to_string(),
        capture_status: "complete".to_string(),
        incomplete_reason: None,
        outcome: "completed".to_string(),
        artifact_dir: "traces/launch-wave-mutate".to_string(),
        conversation_path: "traces/launch-wave-mutate/conversation.jsonl".to_string(),
        provider_events_path: None,
        provider_session_id: None,
        provider_session_path: None,
        conversation_event_count: 2,
        conversation_bytes: 10,
        control: None,
    };
    let turn = AgentTurnRow {
        id: "turn-wave-mutate".to_string(),
        launch_id: launch.id.clone(),
        ordinal: 1,
        provider_turn_id: None,
        started_at: now - 30,
        ended_at: Some(now - 20),
        status: "completed".to_string(),
        input_op: "initial".to_string(),
        context_coverage: "assembled".to_string(),
        tokenizer: "o200k_base".to_string(),
        system_prompt_path: None,
        task_prompt_path: "traces/launch-wave-mutate/task.md".to_string(),
        system_tokens: 0,
        task_tokens: 10,
        supplied_context_tokens: 10,
        provider_input_tokens: Some(10),
        provider_total_input_tokens: Some(10),
        peak_input_tokens: Some(10),
        context_window_tokens: Some(100),
        provider_output_tokens: Some(5),
        reasoning_tokens: None,
        cache_read_tokens: Some(0),
        cache_write_tokens: None,
        cost_usd: Some(0.01),
        context_gather_ms: 1,
        context_render_ms: 1,
        context_persist_ms: 1,
        first_event_seq: None,
        last_event_seq: None,
        root_output: None,
        basis: None,
    };
    store
        .insert_trace_capture(&launch, &turn, &[], &[])
        .expect("seed skill launch");
    wave
}

/// `lf status --json` in a clean environment, optionally standing inside a wave.
fn status_json(home: &Path, args: &[&str], ambient_wave_id: Option<&str>) -> serde_json::Value {
    let mut command = Command::new(env!("CARGO_BIN_EXE_lf"));
    command
        .arg("status")
        .args(args)
        .arg("--json")
        .env("LF_HOME", home)
        .env_remove("LF_DB_PATH")
        .env_remove("LF_CONTROL_HOME")
        .env_remove("LF_CONTROL_DB_PATH")
        .env_remove("LF_TRACE_ID")
        .env_remove("LF_CHANNEL")
        .env_remove("LF_WAVE_ID");
    if let Some(id) = ambient_wave_id {
        command.env("LF_WAVE_ID", id);
    }
    let output = command.output().expect("lf status runs");
    assert!(
        output.status.success(),
        "lf status failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8(output.stdout).expect("utf8");
    serde_json::from_str(stdout.trim()).unwrap_or_else(|err| panic!("not JSON: {err}\n{stdout}"))
}

fn status_human(home: &Path, wave: &str) -> String {
    let output = Command::new(env!("CARGO_BIN_EXE_lf"))
        .args(["status", wave])
        .env("LF_HOME", home)
        .env_remove("LF_DB_PATH")
        .output()
        .expect("lf status runs");
    assert!(
        output.status.success(),
        "lf status failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    String::from_utf8(output.stdout).expect("status is utf8")
}

fn execs_json(home: &Path) -> serde_json::Value {
    let output = Command::new(env!("CARGO_BIN_EXE_lf"))
        .args(["execs", "--json"])
        .env("LF_HOME", home)
        .env_remove("LF_DB_PATH")
        .output()
        .expect("lf execs runs");
    assert!(
        output.status.success(),
        "lf execs failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    serde_json::from_slice(&output.stdout).expect("lf execs emits JSON")
}

fn runs_json(home: &Path) -> serde_json::Value {
    let output = Command::new(env!("CARGO_BIN_EXE_lf"))
        .args(["runs", "--json"])
        .env("LF_HOME", home)
        .env_remove("LF_DB_PATH")
        .output()
        .expect("lf runs runs");
    assert!(
        output.status.success(),
        "lf runs failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    serde_json::from_slice(&output.stdout).expect("lf runs emits JSON")
}

fn runs_json_filtered(home: &Path, filter: &[&str]) -> serde_json::Value {
    let output = Command::new(env!("CARGO_BIN_EXE_lf"))
        .arg("runs")
        .args(filter)
        .arg("--json")
        .env("LF_HOME", home)
        .env_remove("LF_DB_PATH")
        .output()
        .expect("lf runs runs");
    assert!(
        output.status.success(),
        "lf runs failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    serde_json::from_slice(&output.stdout).expect("lf runs emits JSON")
}

fn trace_json(home: &Path, exec_id: &str) -> serde_json::Value {
    let output = Command::new(env!("CARGO_BIN_EXE_lf"))
        .args(["trace", exec_id, "--json"])
        .env("LF_HOME", home)
        .env_remove("LF_DB_PATH")
        .output()
        .expect("lf trace runs");
    assert!(
        output.status.success(),
        "lf trace failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    serde_json::from_slice(&output.stdout).expect("lf trace emits JSON")
}

#[test]
fn status_reports_skill_runs_without_lookup_or_flow_processes() {
    let home = tempfile::tempdir().expect("tempdir");
    seed(home.path(), "audit-a");

    let status = status_json(home.path(), &["audit-a"], None);

    assert_eq!(status["wave"]["name"], "audit-a");
    assert_eq!(status["runs"]["state"], "ok");
    let runs = status["runs"]["items"].as_array().expect("runs array");
    assert_eq!(runs.len(), 1);
    let skill = runs
        .iter()
        .find(|run| run["skill"] == "wave_mutate")
        .expect("the wave's skill is in its status");
    assert_eq!(skill["flow"], "wave");
    assert_eq!(skill["provider"], "codex");
    assert_eq!(skill["supplied_context_tokens"], 10);
    assert_eq!(skill["input_tokens"], 10);
    assert_eq!(skill["output_tokens"], 5);

    let human = status_human(home.path(), "audit-a");
    assert!(human.contains("wave/wave_mutate"));
    assert!(human.contains("ctx      10"));
    assert!(human.contains("tok      15"));
    assert!(!human.contains("pm sync"));
    assert!(!human.contains("build"));

    // Nothing is waiting, and the snapshot says so — it does not omit the field.
    assert_eq!(status["attention"]["state"], "ok");
    assert_eq!(status["attention"]["items"], serde_json::json!([]));
}

#[test]
fn execs_keep_the_lookup_process_ledger() {
    let home = tempfile::tempdir().expect("tempdir");
    seed(home.path(), "audit-execs");

    let execs = execs_json(home.path());
    let execs = execs.as_array().expect("exec array");
    let lookup = execs
        .iter()
        .find(|exec| exec["label"] == "pm sync")
        .expect("lookup stays available as an exec");
    assert_eq!(lookup["status"], "ok");
    assert_eq!(lookup["trace_id"], "run-1");

    let trace = trace_json(home.path(), "proc-lookup");
    assert_eq!(trace["spans"][0]["process_id"], "proc-lookup");
}

#[test]
fn runs_are_skill_launches_with_context_and_token_evidence() {
    let home = tempfile::tempdir().expect("tempdir");
    seed(home.path(), "audit-runs");

    let runs = runs_json(home.path());
    let runs = runs.as_array().expect("run array");
    assert_eq!(runs.len(), 1);
    let run = &runs[0];
    assert_eq!(run["id"], "launch-wave-mutate");
    assert_eq!(run["trace_id"], "run-resident");
    assert_eq!(run["exec_id"], "proc-resident");
    assert_eq!(run["skill"], "wave_mutate");
    assert_eq!(run["supplied_context_tokens"], 10);
    assert_eq!(run["input_tokens"], 10);
    assert_eq!(run["output_tokens"], 5);
    // A run declares the roadmap Project/Task that owns it — the foreign key a
    // roadmap row drills through to reach its runs.
    assert_eq!(run["project"], "auditability");
    assert_eq!(run["task"], "W2-122");
}

/// The drill: `lf runs --task <id>` joins a roadmap Task to exactly the runs it
/// produced, by the Linear issue identifier. A non-matching identifier finds
/// nothing rather than guessing.
#[test]
fn runs_drill_to_one_task_by_issue_identifier() {
    let home = tempfile::tempdir().expect("tempdir");
    seed(home.path(), "audit-drill");

    let matched = runs_json_filtered(home.path(), &["--task", "W2-122"]);
    let matched = matched.as_array().expect("run array");
    assert_eq!(matched.len(), 1);
    assert_eq!(matched[0]["task"], "W2-122");
    assert_eq!(matched[0]["trace_id"], "run-resident");

    let missed = runs_json_filtered(home.path(), &["--task", "W2-999"]);
    assert_eq!(missed.as_array().expect("run array").len(), 0);
}

/// The wave drill mirrors the internal scoping `lf status` uses.
#[test]
fn runs_drill_to_one_wave_by_name() {
    let home = tempfile::tempdir().expect("tempdir");
    seed(home.path(), "audit-wave-drill");

    let matched = runs_json_filtered(home.path(), &["--wave", "audit-wave-drill"]);
    assert_eq!(matched.as_array().expect("run array").len(), 1);

    let missed = runs_json_filtered(home.path(), &["--wave", "no-such-wave"]);
    assert_eq!(missed.as_array().expect("run array").len(), 0);
}

/// The drill loop closes: `lf trace` accepts the launch id `lf runs` prints,
/// resolving it to the complete trace.
#[test]
fn trace_opens_from_the_launch_id_lf_runs_prints() {
    let home = tempfile::tempdir().expect("tempdir");
    seed(home.path(), "audit-trace-launch");

    let trace = trace_json(home.path(), "launch-wave-mutate");
    assert_eq!(trace["trace_id"], "run-resident");
    let spans = trace["spans"].as_array().expect("span array");
    assert!(spans
        .iter()
        .any(|span| span["process_id"] == "proc-resident"));
}

/// The reproduced break: inside a resident wave, `LF_WAVE_ID` is a wave id, and
/// bare `lf status` read it as a name.
#[test]
fn ambient_wave_id_resolves_the_wave_it_names() {
    let home = tempfile::tempdir().expect("tempdir");
    let wave = seed(home.path(), "audit-b");

    let status = status_json(home.path(), &[], Some(wave.id().as_str()));

    assert_eq!(status["wave"]["id"], wave.id().as_str());
    assert_eq!(status["wave"]["name"], "audit-b");
    assert_eq!(status["runs"]["state"], "ok");
}

/// A wave that has done nothing reports an empty reading, not a missing one:
/// "we looked and found nothing" is a claim a client can trust.
#[test]
fn a_wave_with_no_runs_reports_an_empty_reading_not_a_missing_one() {
    let home = tempfile::tempdir().expect("tempdir");
    std::fs::create_dir_all(home.path()).expect("home");
    let store = SqliteStore::new(&home.path().join("loopflow.db")).expect("open store");
    let wave = Wave::new(
        WaveId::new(),
        "audit-c".to_string(),
        home.path().join("repo").display().to_string(),
    );
    store.create_wave(&wave).expect("register wave");

    let status = status_json(home.path(), &["audit-c"], None);

    assert_eq!(status["wave"]["status"], "ready");
    assert_eq!(status["runs"]["state"], "ok");
    assert_eq!(status["runs"]["items"], serde_json::json!([]));
    assert_eq!(status["runs"]["truncated"], false);
}