loopflow 0.12.25

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
409
410
411
412
413
414
//! Inspect Home identity and connect local Wave chat without changing placement.

use std::path::Path;

use anyhow::anyhow;

use crate::engine::wave_home::{HomeActionDto, HomeRuntimeDto, HomeState};
use crate::lf::HomeCommand;
use crate::work::wave::context::resolve_managed_wave_sync;

/// `lf home <id|observe>` — inspect durable Home identity and reachability.
pub fn run(cmd: &HomeCommand) -> anyhow::Result<()> {
    match cmd {
        HomeCommand::Id { json } => id_cmd(*json),
        HomeCommand::Observe {
            home_id,
            route,
            json,
        } => observe_cmd(home_id, route, *json),
    }
}

fn id_cmd(json: bool) -> anyhow::Result<()> {
    let runtime = tokio::runtime::Runtime::new()?;
    let home = runtime.block_on(async {
        crate::store::open_existing_store()
            .await
            .ok_or_else(|| anyhow!("lf home id needs an initialized local store"))?
            .local_home()
            .await
            .map_err(anyhow::Error::from)
    })?;
    if json {
        println!("{}", serde_json::to_string(&home)?);
    } else {
        println!("{}", home.id);
    }
    Ok(())
}

fn observe_cmd(home_id: &crate::durable::HomeId, route: &str, json: bool) -> anyhow::Result<()> {
    let parsed = crate::engine::wave_home::HomeRoute::parse(route)
        .ok_or_else(|| anyhow!("invalid Home route: {route:?}"))?;
    if !parsed.is_remote() {
        return Err(anyhow!(
            "the local Home route is managed by `lf home id`; observe only remote SSH routes"
        ));
    }
    let route = parsed.to_string();
    let runtime = tokio::runtime::Runtime::new()?;
    let home = runtime.block_on(async {
        crate::store::open_existing_store()
            .await
            .ok_or_else(|| anyhow!("lf home observe needs an initialized local store"))?
            .observe_home(home_id, &route)
            .await
            .map_err(anyhow::Error::from)
    })?;
    if json {
        println!("{}", serde_json::to_string(&home)?);
    } else {
        println!("{}  {}", home.id, home.route);
    }
    Ok(())
}

pub fn probe_cmd(wave: Option<&str>, json: bool, repo: Option<&Path>) -> anyhow::Result<()> {
    let selected = resolve_managed_wave_sync(repo, wave).map_err(|err| anyhow!("{err}"))?;
    let wave_id = selected.id().clone();
    let rt = tokio::runtime::Runtime::new()?;
    let (wave, runtime) = rt.block_on(async {
        let store = crate::store::open_existing_store()
            .await
            .ok_or_else(|| anyhow!("lf wave probe needs an initialized local store"))?;
        let wave = store
            .get_wave(&wave_id)
            .await?
            .ok_or_else(|| anyhow!("Wave {wave_id} was not found"))?;
        let placement = store
            .placement(&crate::durable::WorkRef::Wave(wave.id().clone()))
            .await?;
        let home = store
            .home_by_id(&placement.home_id)
            .await?
            .ok_or_else(|| anyhow!("Home {} was not found", placement.home_id))?;
        let runtime =
            crate::ops::home::probe_home(wave.name(), &home, Path::new(wave.repo())).await;
        Ok::<_, anyhow::Error>((wave, runtime))
    })?;
    if json {
        println!("{}", serde_json::to_string(&runtime)?);
    } else {
        print_runtime(wave.name(), &runtime);
    }
    Ok(())
}

pub fn connect_chat(
    waves: &[String],
    wave_ids: &[String],
    json: bool,
    repo: &Path,
) -> anyhow::Result<()> {
    let runtime = tokio::runtime::Runtime::new()?;
    let responses = runtime.block_on(connect_chat_inner(waves, wave_ids, repo))?;
    if json {
        println!("{}", serde_json::to_string(&responses)?);
        return Ok(());
    }
    for wave in responses {
        let state = if wave.live { "running" } else { "starting" };
        println!("{}  {state} on {}", wave.name, wave.home.id);
    }
    Ok(())
}

pub(crate) async fn connect_chat_inner(
    names: &[String],
    raw_wave_ids: &[String],
    repo: &Path,
) -> anyhow::Result<Vec<crate::lf::commands::waves::WaveSnapshot>> {
    let store = std::sync::Arc::new(
        crate::store::open_store(&crate::store::storage_config_from_env()?)
            .await
            .map_err(|error| anyhow!("chat cannot open this Home registry: {error}"))?,
    );
    let local = store.local_home().await?;
    validate_expected_home(&local.id)?;
    let repo = crate::repository::CanonicalRepo::discover(repo)?;
    let wave_ids = parse_wave_ids(raw_wave_ids)?;
    let normalized_names = names
        .iter()
        .map(|raw| {
            crate::ops::util::normalize_wave_name(raw)
                .ok_or_else(|| anyhow!("invalid wave name: '{raw}'"))
        })
        .collect::<anyhow::Result<Vec<_>>>()?;
    let unique_names = normalized_names
        .iter()
        .collect::<std::collections::BTreeSet<_>>();
    if unique_names.len() != normalized_names.len() {
        return Err(anyhow!("duplicate Wave name in chat connection"));
    }
    for name in wave_ids.keys() {
        if !normalized_names.contains(name) {
            return Err(anyhow!("--wave-id names unselected Wave '{name}'"));
        }
    }
    let selected = if names.is_empty() {
        if !wave_ids.is_empty() {
            return Err(anyhow!("--wave-id requires explicit Wave names"));
        }
        let repo_name = repo.to_string();
        let known = store.list_waves(Some(&repo_name)).await?;
        if known.is_empty() {
            return Err(anyhow!(
                "no Waves found in {}; author one in wave/<name>/GOAL.md",
                repo
            ));
        }
        crate::wave_host::waves_for_home(&store, &local.id, Some(&repo_name))
            .await?
            .into_iter()
            .map(|wave| ChatSelection {
                wave,
                created: false,
            })
            .collect()
    } else {
        let mut candidates = Vec::with_capacity(normalized_names.len());
        for name in &normalized_names {
            let locator = crate::work::wave::WaveLocator::new(repo.clone(), name)?;
            let existing_wave = store.get_wave_at(&locator).await?;
            let prior_home = match existing_wave.as_ref() {
                Some(wave) => Some(
                    store
                        .placement(&crate::durable::WorkRef::Wave(wave.id().clone()))
                        .await?
                        .home_id,
                ),
                None => None,
            };
            if let Some(home_id) = prior_home.as_ref().filter(|id| **id != local.id) {
                return Err(anyhow!("Wave {name} belongs to Home {home_id}; connect there with `lf ssh {home_id} chat --follow -w {name}`"));
            }
            candidates.push((name.clone(), existing_wave));
        }
        let mut selected = Vec::with_capacity(candidates.len());
        for (name, existing_wave) in candidates {
            let created = existing_wave.is_none();
            let wave_result = match wave_ids.get(&name) {
                Some(id) => {
                    crate::controller::wave::registry::ensure_wave_row_with_id(
                        &store,
                        repo.as_path(),
                        &name,
                        id,
                    )
                    .await
                }
                None => {
                    crate::controller::wave::registry::ensure_wave_row(
                        &store,
                        repo.as_path(),
                        &name,
                    )
                    .await
                }
            };
            let wave = match wave_result {
                Ok(wave) => wave,
                Err(error) => {
                    let rollback = rollback_selections(&store, &selected).await;
                    return match rollback {
                        Ok(()) => Err(error.into()),
                        Err(rollback) => Err(anyhow!(
                            "Wave registration failed: {error}; registry rollback failed: {rollback}"
                        )),
                    };
                }
            };
            selected.push(ChatSelection { wave, created });
        }
        selected
    };
    if selected.is_empty() {
        return Ok(Vec::new());
    }

    let wave_ids = selected
        .iter()
        .map(|selection| selection.wave.id().clone())
        .collect::<Vec<_>>();
    if let Err(error) = crate::lfd::ensure(&local.id, repo.as_path()).await {
        rollback_selections(&store, &selected).await?;
        return Err(error);
    }
    let outcomes = match crate::lfd::start_waves(&local.id, wave_ids).await {
        Ok(outcomes) => outcomes,
        Err(error) => {
            let mut outcomes = Vec::with_capacity(selected.len());
            for selection in &selected {
                let state = match crate::controller::wave::server::live_endpoint(
                    Path::new(selection.wave.repo()),
                    selection.wave.name(),
                )
                .await
                {
                    Some(endpoint) => crate::wave_host::WaveStartState::Live { endpoint },
                    None => crate::wave_host::WaveStartState::Failed {
                        reason: error.to_string(),
                    },
                };
                outcomes.push(crate::wave_host::WaveStartOutcome {
                    wave_id: selection.wave.id().clone(),
                    state,
                });
            }
            outcomes
        }
    };

    let mut failures = Vec::new();
    for selection in &selected {
        let outcome = outcomes
            .iter()
            .find(|outcome| outcome.wave_id == *selection.wave.id());
        let reason = match outcome.map(|outcome| &outcome.state) {
            Some(crate::wave_host::WaveStartState::Live { .. }) => continue,
            Some(crate::wave_host::WaveStartState::Failed { reason }) => reason.clone(),
            None => "lfd returned no startup outcome".to_string(),
        };
        if let Err(rollback) = rollback_selection(&store, selection).await {
            failures.push(format!(
                "Wave {} failed to start: {reason}; registry rollback failed: {rollback}",
                selection.wave.name()
            ));
        } else {
            failures.push(format!(
                "Wave {} failed to start: {reason}",
                selection.wave.name()
            ));
        }
    }
    if !failures.is_empty() {
        return Err(anyhow!(failures.join("; ")));
    }
    let mut responses = Vec::with_capacity(selected.len());
    for selection in &selected {
        let wave = store
            .get_wave(selection.wave.id())
            .await?
            .ok_or_else(|| anyhow!("Wave '{}' disappeared after start", selection.wave.name()))?;
        let snapshot = crate::lf::commands::waves::snapshot_wave(&store, &wave).await?;
        if !snapshot.live {
            let reason = format!(
                "Wave {} reported a live startup outcome but its endpoint is not answering",
                wave.name()
            );
            if let Err(rollback) = rollback_selection(&store, selection).await {
                failures.push(format!("{reason}; registry rollback failed: {rollback}"));
            } else {
                failures.push(reason);
            }
            continue;
        }
        responses.push(snapshot);
    }
    if !failures.is_empty() {
        return Err(anyhow!(failures.join("; ")));
    }
    Ok(responses)
}

struct ChatSelection {
    wave: crate::work::wave::Wave,
    created: bool,
}

async fn rollback_selection(
    store: &crate::store::Store,
    selection: &ChatSelection,
) -> anyhow::Result<()> {
    if selection.created {
        store.delete_wave(selection.wave.id()).await?;
    }
    Ok(())
}

async fn rollback_selections(
    store: &crate::store::Store,
    selections: &[ChatSelection],
) -> anyhow::Result<()> {
    let mut failures = Vec::new();
    for selection in selections.iter().rev() {
        if let Err(error) = rollback_selection(store, selection).await {
            failures.push(format!("{}: {error}", selection.wave.name()));
        }
    }
    if failures.is_empty() {
        Ok(())
    } else {
        Err(anyhow!(failures.join("; ")))
    }
}

fn parse_wave_ids(
    values: &[String],
) -> anyhow::Result<std::collections::BTreeMap<String, crate::id::WaveId>> {
    let mut bindings = std::collections::BTreeMap::new();
    for value in values {
        let (raw_name, raw_id) = value
            .split_once('=')
            .ok_or_else(|| anyhow!("invalid --wave-id {value:?}; expected NAME=ID"))?;
        let name = crate::ops::util::normalize_wave_name(raw_name)
            .ok_or_else(|| anyhow!("invalid Wave name in --wave-id {value:?}"))?;
        let id = crate::id::WaveId::parse(raw_id)
            .map_err(|error| anyhow!("invalid Wave id in --wave-id {value:?}: {error}"))?;
        if bindings.insert(name.clone(), id).is_some() {
            return Err(anyhow!("duplicate --wave-id binding for Wave '{name}'"));
        }
    }
    Ok(bindings)
}

fn validate_expected_home(local: &crate::durable::HomeId) -> anyhow::Result<()> {
    let Ok(raw) = std::env::var(crate::lf::commands::ssh::EXPECTED_HOME_ID_ENV) else {
        return Ok(());
    };
    let expected = crate::durable::HomeId::parse(&raw)
        .map_err(|error| anyhow!("invalid expected Home id: {error}"))?;
    if expected != *local {
        return Err(anyhow!(
            "refusing remote lifecycle command: expected Home {expected}, local Home is {local}"
        ));
    }
    Ok(())
}

fn print_runtime(name: &str, runtime: &HomeRuntimeDto) {
    let state = match runtime.state {
        HomeState::Unreachable => "unreachable",
        HomeState::Stopped => "stopped",
        HomeState::Running => "running",
        HomeState::Unknown => "unknown",
    };
    let action = match &runtime.action {
        HomeActionDto::Attach { endpoint } => format!("Attach ({endpoint})"),
        HomeActionDto::Connect { home_id } => format!("Open chat on {home_id}"),
        HomeActionDto::Reason { message } => message.clone(),
    };
    println!(
        "{name}  {} ({})  [{state}]",
        runtime.home.id, runtime.home.route
    );
    println!("  reason  {}", runtime.reason);
    println!("  action  {action}");
}

pub fn validate_expected_home_process() -> anyhow::Result<()> {
    if std::env::var_os(crate::lf::commands::ssh::EXPECTED_HOME_ID_ENV).is_none() {
        return Ok(());
    }
    let runtime = tokio::runtime::Runtime::new()?;
    let local = runtime.block_on(async {
        crate::store::open_existing_store()
            .await
            .ok_or_else(|| anyhow!("Home-addressed command needs an initialized local store"))?
            .local_home()
            .await
            .map_err(anyhow::Error::from)
    })?;
    validate_expected_home(&local.id)
}