loopflow 0.12.26

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
//! Parse the mutable route observed for a stable Home identity.
//!
//! A route is either this process's machine (`local`) or one SSH destination:
//!
//! - `local` — the stable local marker.
//! - `ssh://jack@host[:port]` — the canonical remote form, reachable over SSH.
//! - `jack@host` — readable shorthand that normalizes to `ssh://jack@host`.
//!
//! The route is observation, never identity; `HomeId` remains stable when it
//! changes. Reachability is operational evidence (see [`HomeState`]).

use std::fmt;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::path::Path;
use std::str::FromStr;

use serde::{Deserialize, Serialize};

pub(crate) const SSH_CONNECT_TIMEOUT_SECS: u32 = 10;
const SSH_SERVER_ALIVE_INTERVAL_SECS: u32 = 10;
const SSH_SERVER_ALIVE_COUNT_MAX: u32 = 3;

pub(crate) fn bounded_ssh_args(dest: &str, port: Option<u16>) -> Vec<String> {
    let mut args = Vec::new();
    if let Some(port) = port {
        args.extend(["-p".to_string(), port.to_string()]);
    }
    args.extend([
        "-o".to_string(),
        "BatchMode=yes".to_string(),
        "-o".to_string(),
        format!("ConnectTimeout={SSH_CONNECT_TIMEOUT_SECS}"),
        "-o".to_string(),
        format!("ServerAliveInterval={SSH_SERVER_ALIVE_INTERVAL_SECS}"),
        "-o".to_string(),
        format!("ServerAliveCountMax={SSH_SERVER_ALIVE_COUNT_MAX}"),
        dest.to_string(),
    ]);
    args
}

pub(crate) fn resolve_home_relative_repo(repo: &Path) -> Result<String, String> {
    let home = dirs::home_dir().ok_or_else(|| "cannot resolve home directory".to_string())?;
    repo.strip_prefix(&home)
        .map_err(|_| {
            format!(
                "repo {} is outside {}; remote Home routing needs a home-relative path",
                repo.display(),
                home.display()
            )
        })?
        .to_str()
        .map(str::to_string)
        .ok_or_else(|| format!("repo path {} is not UTF-8", repo.display()))
}

/// The current transport route to one Home.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HomeRoute {
    Local,
    Ssh {
        user: String,
        host: HomeHost,
        port: Option<u16>,
    },
}

/// A remote location's host: a DNS name or a numeric IP. IPv6 is stored numeric
/// and always rendered bracketed in the canonical URI.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HomeHost {
    Name(String),
    Ip(IpAddr),
}

impl HomeHost {
    /// The bare host as `ssh` wants it in a `user@host` destination — no
    /// brackets, since the ssh CLI takes an unbracketed IPv6 there.
    fn as_ssh_host(&self) -> String {
        match self {
            Self::Name(name) => name.clone(),
            Self::Ip(ip) => ip.to_string(),
        }
    }

    /// The host as it appears in the canonical URI — IPv6 bracketed.
    fn as_uri_host(&self) -> String {
        match self {
            Self::Name(name) => name.clone(),
            Self::Ip(IpAddr::V4(v4)) => v4.to_string(),
            Self::Ip(IpAddr::V6(v6)) => format!("[{v6}]"),
        }
    }
}

impl HomeRoute {
    /// Parse a durable route or SSH shorthand. `None` for anything unrecognized, so a
    /// typo fails loudly at the read site rather than silently routing wrong.
    pub fn parse(raw: &str) -> Option<Self> {
        let raw = raw.trim();
        if raw.is_empty() {
            return None;
        }
        if raw == "local" {
            return Some(Self::Local);
        }
        // The `ssh://` scheme is optional on input; it is always emitted on
        // output for the remote form.
        let body = raw.strip_prefix("ssh://").unwrap_or(raw);
        let (user, rest) = body.split_once('@')?;
        let user = valid_user(user)?;
        let (host, port) = parse_host_port(rest)?;
        Some(Self::Ssh { user, host, port })
    }

    pub fn is_remote(&self) -> bool {
        matches!(self, Self::Ssh { .. })
    }

    /// The `user@host` destination for `ssh`, when remote.
    pub fn ssh_destination(&self) -> Option<String> {
        match self {
            Self::Local => None,
            Self::Ssh { user, host, .. } => Some(format!("{user}@{}", host.as_ssh_host())),
        }
    }

    /// The SSH port, when remote and explicitly set.
    pub fn ssh_port(&self) -> Option<u16> {
        match self {
            Self::Ssh { port, .. } => *port,
            Self::Local => None,
        }
    }
}

fn valid_user(user: &str) -> Option<String> {
    let user = user.trim();
    if user.is_empty() {
        return None;
    }
    let ok = user
        .chars()
        .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '.' | '_' | '-'));
    ok.then(|| user.to_string())
}

/// Parse the `host[:port]` (or `[ipv6][:port]`) location tail. Bracketed IPv6 is
/// the only accepted IPv6 form — an unbracketed multi-colon token is ambiguous
/// with a port and is rejected.
fn parse_host_port(rest: &str) -> Option<(HomeHost, Option<u16>)> {
    if let Some(inner) = rest.strip_prefix('[') {
        let (v6, after) = inner.split_once(']')?;
        let ip: Ipv6Addr = v6.parse().ok()?;
        let port = match after {
            "" => None,
            _ => Some(after.strip_prefix(':')?.parse::<u16>().ok()?),
        };
        return Some((HomeHost::Ip(IpAddr::V6(ip)), port));
    }
    match rest.matches(':').count() {
        0 => Some((parse_host(rest)?, None)),
        1 => {
            let (host, port) = rest.rsplit_once(':')?;
            Some((parse_host(host)?, Some(port.parse::<u16>().ok()?)))
        }
        // Unbracketed IPv6 is ambiguous with host:port — require brackets.
        _ => None,
    }
}

/// A host token: an IPv4 literal or a DNS name. (Bracketed IPv6 is handled by
/// the caller.)
fn parse_host(token: &str) -> Option<HomeHost> {
    let token = token.trim();
    if token.is_empty() {
        return None;
    }
    if let Ok(v4) = token.parse::<Ipv4Addr>() {
        return Some(HomeHost::Ip(IpAddr::V4(v4)));
    }
    let ok = token
        .chars()
        .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '.' | '-' | '_'));
    ok.then(|| HomeHost::Name(token.to_string()))
}

impl fmt::Display for HomeRoute {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Local => f.write_str("local"),
            Self::Ssh { user, host, port } => {
                write!(f, "ssh://{user}@{}", host.as_uri_host())?;
                if let Some(port) = port {
                    write!(f, ":{port}")?;
                }
                Ok(())
            }
        }
    }
}

impl FromStr for HomeRoute {
    type Err = String;

    fn from_str(raw: &str) -> Result<Self, Self::Err> {
        Self::parse(raw).ok_or_else(|| format!("invalid Home route: {raw:?}"))
    }
}

/// A Home's observed liveness, with evidence living alongside in
/// [`HomeRuntimeDto::reason`]. `Unreachable` and `Unknown` are different facts:
/// the Home did not answer at all versus it answered but its state could not be
/// read.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HomeState {
    /// The Home could not be reached over its address.
    Unreachable,
    /// The Home is reachable but no resident is serving the Wave.
    Stopped,
    /// A resident is serving the Wave on the Home.
    Running,
    /// The Home answered but its state could not be determined.
    Unknown,
}

/// The one contextual action a surface should offer for a Home, derived from its
/// state so the UI never has to branch on `HomeState` itself.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum HomeActionDto {
    /// Running: open/attach to the resident at `endpoint`.
    Attach { endpoint: String },
    /// Reachable but stopped: start the Wave on its stable Home identity.
    Connect { home_id: crate::durable::HomeId },
    /// Unreachable or unknown: show `message`, the actionable reason.
    Reason { message: String },
}

/// A Wave's Home plus the evidence of what is happening there — the shared
/// contract a conductor surface renders. `home` carries authority and route; `state`+`reason`
/// are the probe's evidence; `endpoint` is the attach identity when running; and
/// `action` is the single button to show.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HomeRuntimeDto {
    pub home: crate::durable::Home,
    pub state: HomeState,
    pub reason: String,
    /// Attach identity when running (the resident endpoint), else `null`.
    pub endpoint: Option<String>,
    pub action: HomeActionDto,
}

impl HomeRuntimeDto {
    /// Assemble the runtime evidence and derive the single contextual action.
    pub fn new(
        home: &crate::durable::Home,
        state: HomeState,
        reason: String,
        endpoint: Option<String>,
    ) -> Self {
        let action = match (state, &endpoint) {
            (HomeState::Running, Some(endpoint)) => HomeActionDto::Attach {
                endpoint: endpoint.clone(),
            },
            (HomeState::Stopped, _) => HomeActionDto::Connect {
                home_id: home.id.clone(),
            },
            // Running-without-endpoint is a state we could not fully read.
            (HomeState::Running, None) | (HomeState::Unknown, _) | (HomeState::Unreachable, _) => {
                HomeActionDto::Reason {
                    message: reason.clone(),
                }
            }
        };
        Self {
            home: home.clone(),
            state,
            reason,
            endpoint,
            action,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn home(raw: &str) -> HomeRoute {
        HomeRoute::parse(raw).unwrap_or_else(|| panic!("parse {raw:?}"))
    }

    #[test]
    fn canonical_forms_round_trip() {
        for raw in [
            "local",
            "ssh://jack@mini-heart",
            "ssh://jack@mini.example.com:2222",
            "ssh://jack@10.0.0.5",
            "ssh://jack@10.0.0.5:22",
            "ssh://jack@[2001:db8::1]",
            "ssh://jack@[::1]:22",
        ] {
            assert_eq!(home(raw).to_string(), raw, "canonical {raw}");
        }
    }

    #[test]
    fn shorthand_normalizes_to_ssh_uri() {
        assert_eq!(home("jack@mini-heart").to_string(), "ssh://jack@mini-heart");
        assert_eq!(
            home("jack@10.0.0.5:22").to_string(),
            "ssh://jack@10.0.0.5:22"
        );
        assert_eq!(home("ssh://jack@local").to_string(), "ssh://jack@local");
    }

    #[test]
    fn ssh_user_is_required() {
        assert_eq!(home("local"), HomeRoute::Local);
        assert_eq!(HomeRoute::parse("ssh://mini-heart"), None);
        assert_eq!(HomeRoute::parse("mini-heart"), None);
        assert_eq!(HomeRoute::parse("@host"), None);
        assert_eq!(HomeRoute::parse(""), None);
    }

    #[test]
    fn ipv6_must_be_bracketed_and_ports_parse() {
        // bracketed ok
        assert!(home("ssh://jack@[fe80::1]").is_remote());
        // unbracketed ipv6 is ambiguous with a port and is rejected
        assert_eq!(HomeRoute::parse("ssh://jack@2001:db8::1"), None);
        // bad port
        assert_eq!(HomeRoute::parse("ssh://jack@host:notaport"), None);
        assert_eq!(HomeRoute::parse("ssh://jack@host:99999"), None);
    }

    #[test]
    fn ssh_destination_and_port_feed_the_transport() {
        let h = home("ssh://jack@[::1]:2222");
        assert_eq!(h.ssh_destination().as_deref(), Some("jack@::1"));
        assert_eq!(h.ssh_port(), Some(2222));

        let h = home("ssh://deploy@box.tail.ts.net");
        assert_eq!(
            h.ssh_destination().as_deref(),
            Some("deploy@box.tail.ts.net")
        );
        assert_eq!(h.ssh_port(), None);

        assert_eq!(home("local").ssh_destination(), None);
    }

    #[test]
    fn runtime_action_follows_state() {
        let now = time::OffsetDateTime::UNIX_EPOCH;
        let h = crate::durable::Home {
            id: crate::durable::HomeId::parse("home_00000000000000000000000000000001").unwrap(),
            route: "ssh://jack@host".into(),
            created_at: now,
            observed_at: now,
        };
        let running = HomeRuntimeDto::new(
            &h,
            HomeState::Running,
            "resident serving".into(),
            Some("127.0.0.1:7777".into()),
        );
        assert_eq!(
            running.action,
            HomeActionDto::Attach {
                endpoint: "127.0.0.1:7777".into()
            }
        );

        let stopped = HomeRuntimeDto::new(
            &h,
            HomeState::Stopped,
            "reachable, no resident".into(),
            None,
        );
        assert_eq!(
            stopped.action,
            HomeActionDto::Connect {
                home_id: h.id.clone()
            }
        );

        let unreachable = HomeRuntimeDto::new(
            &h,
            HomeState::Unreachable,
            "ssh could not connect".into(),
            None,
        );
        assert_eq!(
            unreachable.action,
            HomeActionDto::Reason {
                message: "ssh could not connect".into()
            }
        );
    }
}