loopflow 0.12.4

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
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
use std::io::{self, BufRead, BufReader, Write};
#[cfg(unix)]
use std::os::unix::process::CommandExt;
use std::process::{Child, ChildStdin, Command, ExitStatus, Stdio};
use std::time::Duration;

use anyhow::{anyhow, Context};
use fs2::FileExt;
use serde::{Deserialize, Serialize};

use crate::durable::{
    AuthenticatedRequest, Basis, ControlCtx, EpochId, EpochReceipt, Feedback, InterruptReceipt,
    LaunchId, Placement, ProjectId, Run, SteerReceipt, TaskId, UserFeedback, WorkRef, WorkStatus,
};
use crate::id::WaveId;
use crate::lf::WorkCommand;
use crate::store::{open_store, storage_config_from_env, Store, StoreError};

#[derive(Debug, Serialize)]
struct WorkProjection {
    work: WorkRef,
    basis: crate::durable::Basis,
    status: WorkStatus,
    run: Option<Run>,
    feedback: Option<Feedback>,
}

#[derive(Debug, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum WorkReceipt {
    Placed(Placement),
    Steer(SteerReceipt),
    FeedbackContinued { status: WorkStatus },
    FeedbackEscalated { feedback: Feedback },
    Interrupted(InterruptReceipt),
    Abandoned(EpochReceipt),
}

pub fn run(command: &WorkCommand) -> anyhow::Result<()> {
    tokio::runtime::Runtime::new()?.block_on(run_async(command))
}

async fn run_async(command: &WorkCommand) -> anyhow::Result<()> {
    let store = open_shared_store().await?;
    match command {
        WorkCommand::Status { kind, id, json } => {
            let work = parse_work(kind, id)?;
            let projection = projection(&store, &work).await?;
            print_projection(&projection, *json)?;
        }
        WorkCommand::Place {
            kind,
            id,
            home_id,
            json,
        } => {
            let work = parse_work(kind, id)?;
            if !matches!(work, WorkRef::Wave(_)) {
                return Err(anyhow!(
                    "only Wave Work can move until Project and Task execution uses the shared Run supervisor"
                ));
            }
            let placement = store.place_work(&work, home_id).await?;
            print_receipt(&WorkReceipt::Placed(placement), *json)?;
        }
        WorkCommand::Steer {
            kind,
            id,
            message,
            json,
        } => {
            let work = parse_work(kind, id)?;
            let receipt = if let Some(lease) = crate::ops::ambient_run_lease(&store).await? {
                store
                    .steer(&ControlCtx::Run(&lease), &work, message, None)
                    .await?
            } else {
                let request = AuthenticatedRequest::cli();
                store
                    .steer(&ControlCtx::User(&request), &work, message, None)
                    .await?
            };
            print_receipt(&WorkReceipt::Steer(receipt), *json)?;
        }
        WorkCommand::Feedback {
            kind,
            id,
            continue_on_success,
            continue_on_exit,
        } => {
            let work = parse_work(kind, id)?;
            let policy = if *continue_on_exit {
                FeedbackExitPolicy::AnyExit
            } else if *continue_on_success {
                FeedbackExitPolicy::Success
            } else {
                FeedbackExitPolicy::Explicit
            };
            run_feedback(&store, &work, policy).await?;
        }
        WorkCommand::Continue { kind, id, json } => {
            let work = parse_work(kind, id)?;
            let feedback = store
                .feedback(&work)
                .await?
                .ok_or_else(|| anyhow!("{} {} has no current Feedback", work.kind(), work.id()))?;
            let status = if let Some(lease) = crate::ops::ambient_run_lease(&store).await? {
                store
                    .continue_feedback(&ControlCtx::Run(&lease), &work, &feedback.basis)
                    .await?
            } else {
                let request = AuthenticatedRequest::cli();
                store
                    .continue_feedback(&ControlCtx::User(&request), &work, &feedback.basis)
                    .await?
            };
            print_receipt(&WorkReceipt::FeedbackContinued { status }, *json)?;
        }
        WorkCommand::Escalate { kind, id, json } => {
            let work = parse_work(kind, id)?;
            let lease = crate::ops::ambient_run_lease(&store)
                .await?
                .ok_or_else(|| anyhow!("Feedback escalation requires an active parent Run"))?;
            let feedback = store
                .feedback(&work)
                .await?
                .ok_or_else(|| anyhow!("{} {} has no current Feedback", work.kind(), work.id()))?;
            let feedback = store
                .escalate_feedback(&lease, &work, &feedback.basis)
                .await?;
            print_receipt(&WorkReceipt::FeedbackEscalated { feedback }, *json)?;
        }
        WorkCommand::Interrupt { kind, id, json } => {
            let work = parse_work(kind, id)?;
            let run = store
                .current_run(&work)
                .await?
                .ok_or_else(|| anyhow!("{} {} has no active Run", work.kind(), work.id()))?;
            let receipt = if let Some(lease) = crate::ops::ambient_run_lease(&store).await? {
                store
                    .interrupt(&ControlCtx::Run(&lease), &work, &run.id)
                    .await?
            } else {
                let request = AuthenticatedRequest::cli();
                store
                    .interrupt(&ControlCtx::User(&request), &work, &run.id)
                    .await?
            };
            print_receipt(&WorkReceipt::Interrupted(receipt), *json)?;
        }
        WorkCommand::Abandon {
            kind,
            id,
            reason,
            json,
        } => {
            let work = parse_work(kind, id)?;
            if crate::ops::ambient_run_lease(&store).await?.is_some() {
                return Err(anyhow!(
                    "Run callers cannot abandon Work; use the authenticated User surface"
                ));
            }
            let basis = store.current_epoch(&work).await?.current_basis;
            let receipt = store.abandon(&work, reason, &basis).await?;
            print_receipt(&WorkReceipt::Abandoned(receipt), *json)?;
        }
    }
    Ok(())
}

pub fn run_queue(json: bool) -> anyhow::Result<()> {
    tokio::runtime::Runtime::new()?.block_on(async move {
        let store = open_shared_store().await?;
        let feedback = store.user_attention().await?;
        if json {
            println!("{}", serde_json::to_string_pretty(&feedback)?);
        } else if feedback.is_empty() {
            println!("No Work needs your attention.");
        } else {
            for item in feedback {
                let feedback = &item.feedback;
                println!(
                    "{} {}  {}:{}  {}",
                    feedback.work.kind(),
                    feedback.work.id(),
                    feedback.basis.epoch_id,
                    feedback.basis.revision,
                    feedback.position.step,
                );
            }
        }
        Ok(())
    })
}

pub fn run_exit_guard(
    kind: &str,
    id: &str,
    launch_id: &str,
    epoch_id: &str,
    revision: u64,
) -> anyhow::Result<()> {
    let work = parse_work(kind, id)?;
    let launch_id = LaunchId::parse(launch_id)?;
    let epoch_id = EpochId::parse(epoch_id)?;
    let basis = Basis { epoch_id, revision };
    tokio::runtime::Runtime::new()?.block_on(run_exit_guard_async(work, launch_id, basis))
}

async fn run_exit_guard_async(
    work: WorkRef,
    launch_id: LaunchId,
    basis: Basis,
) -> anyhow::Result<()> {
    let stdout = io::stdout();
    let mut output = stdout.lock();
    let _lock = match feedback_guard_lock(&launch_id) {
        Ok(lock) => lock,
        Err(error) => {
            write_guard_reply(
                &mut output,
                &FeedbackGuardReply::Error {
                    message: error.to_string(),
                },
            )?;
            return Ok(());
        }
    };
    let store = match open_exit_guard_store().await {
        Ok(store) => store,
        Err(error) => {
            write_guard_reply(
                &mut output,
                &FeedbackGuardReply::Error {
                    message: error.to_string(),
                },
            )?;
            return Ok(());
        }
    };
    write_guard_reply(&mut output, &FeedbackGuardReply::Ready)?;
    drop(output);
    io::copy(&mut io::stdin().lock(), &mut io::sink())?;
    continue_guarded_feedback(&store, &work, &launch_id, &basis).await
}

fn feedback_guard_lock(launch_id: &LaunchId) -> anyhow::Result<std::fs::File> {
    let lock_directory = std::env::temp_dir().join("loopflow-feedback-guards");
    std::fs::create_dir_all(&lock_directory)?;
    let lock = std::fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .read(true)
        .write(true)
        .open(lock_directory.join(format!("{}.lock", launch_id.as_str())))?;
    lock.try_lock_exclusive().map_err(|error| {
        anyhow!("another --continue-on-exit client already owns this Feedback: {error}")
    })?;
    Ok(lock)
}

async fn open_exit_guard_store() -> anyhow::Result<Store> {
    for attempt in 0..20 {
        match open_shared_store().await {
            Ok(store) => return Ok(store),
            Err(error) if attempt < 19 => {
                tracing::debug!(%error, "Feedback exit guard is retrying store open");
                tokio::time::sleep(Duration::from_millis(250)).await;
            }
            Err(error) => return Err(error),
        }
    }
    unreachable!("Feedback exit guard store loop returns on its last attempt")
}

async fn continue_guarded_feedback(
    store: &Store,
    work: &WorkRef,
    launch_id: &LaunchId,
    basis: &Basis,
) -> anyhow::Result<()> {
    for attempt in 0..20 {
        match store
            .continue_feedback_if_current(work, launch_id, basis)
            .await
        {
            Ok(_) | Err(StoreError::NotFound | StoreError::InvalidAuthority(_)) => return Ok(()),
            Err(StoreError::StaleBasis { .. }) => return Ok(()),
            Err(StoreError::Sqlite(error)) if attempt < 19 => {
                tracing::debug!(%error, "Feedback exit guard is retrying SQLite");
                tokio::time::sleep(Duration::from_millis(250)).await;
            }
            Err(error) => return Err(anyhow!(error)),
        }
    }
    unreachable!("Feedback exit guard retry loop returns on its last attempt")
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FeedbackExitPolicy {
    Explicit,
    Success,
    AnyExit,
}

impl FeedbackExitPolicy {
    fn continues(self, presentation_succeeded: bool) -> bool {
        match self {
            Self::Explicit => false,
            Self::Success => presentation_succeeded,
            Self::AnyExit => true,
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum FeedbackGuardReply {
    Ready,
    Error { message: String },
}

struct FeedbackExitGuard {
    input: ChildStdin,
    child: Child,
}

impl FeedbackExitGuard {
    fn spawn(work: &WorkRef, feedback: &Feedback) -> anyhow::Result<Self> {
        let mut command = Command::new(std::env::current_exe()?);
        command
            .arg("__feedback-exit-guard")
            .arg(work.kind())
            .arg(work.id())
            .arg(feedback.launch_id.as_str())
            .arg(feedback.basis.epoch_id.as_str())
            .arg(feedback.basis.revision.to_string())
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::inherit());
        #[cfg(unix)]
        // SAFETY: the closure only starts a new session before exec and does not
        // touch memory shared with the parent process.
        unsafe {
            command.pre_exec(|| {
                if libc::setsid() == -1 {
                    return Err(io::Error::last_os_error());
                }
                Ok(())
            });
        }
        let mut child = command.spawn().context("start Feedback exit guard")?;
        let input = child
            .stdin
            .take()
            .ok_or_else(|| anyhow!("Feedback exit guard did not open stdin"))?;
        let output = child
            .stdout
            .take()
            .ok_or_else(|| anyhow!("Feedback exit guard did not open stdout"))?;
        let mut output = BufReader::new(output);
        let mut line = String::new();
        if output.read_line(&mut line)? == 0 {
            return Err(anyhow!("Feedback exit guard exited unexpectedly"));
        }
        match serde_json::from_str(&line).context("parse Feedback exit guard reply")? {
            FeedbackGuardReply::Ready => Ok(Self { input, child }),
            FeedbackGuardReply::Error { message } => Err(anyhow!(message)),
        }
    }

    fn continue_now(self) -> anyhow::Result<()> {
        let Self { input, mut child } = self;
        drop(input);
        let status = child.wait().context("wait for Feedback exit guard")?;
        if status.success() {
            Ok(())
        } else {
            Err(anyhow!("Feedback exit guard exited with {status}"))
        }
    }
}

fn write_guard_reply(output: &mut impl Write, reply: &FeedbackGuardReply) -> anyhow::Result<()> {
    serde_json::to_writer(&mut *output, reply)?;
    output.write_all(b"\n")?;
    output.flush()?;
    Ok(())
}

async fn run_feedback(
    store: &Store,
    work: &WorkRef,
    policy: FeedbackExitPolicy,
) -> anyhow::Result<()> {
    let item = find_user_feedback(store, work)
        .await?
        .ok_or_else(|| anyhow!("{} {} has no current User Feedback", work.kind(), work.id()))?;
    let guard = if policy == FeedbackExitPolicy::AnyExit {
        Some(FeedbackExitGuard::spawn(work, &item.feedback)?)
    } else {
        None
    };
    println!(
        "Opening Feedback for {} {} at {}:{} ({})",
        item.feedback.work.kind(),
        item.feedback.work.id(),
        item.feedback.basis.epoch_id,
        item.feedback.basis.revision,
        item.feedback.position.step,
    );
    let status = present_feedback(&item.feedback)?;
    let should_continue = policy.continues(status.success());
    if should_continue {
        if let Some(guard) = guard {
            guard.continue_now()?;
        } else {
            continue_guarded_feedback(store, work, &item.feedback.launch_id, &item.feedback.basis)
                .await?;
        }
        println!("Continued Feedback.");
    }
    if status.success() {
        Ok(())
    } else {
        Err(anyhow!("Feedback presentation exited with {status}"))
    }
}

fn present_feedback(feedback: &Feedback) -> anyhow::Result<ExitStatus> {
    Command::new(std::env::current_exe()?)
        .arg("launch")
        .arg("present")
        .arg(feedback.launch_id.as_str())
        .status()
        .context("present Feedback Launch")
}

async fn find_user_feedback(store: &Store, work: &WorkRef) -> anyhow::Result<Option<UserFeedback>> {
    Ok(store
        .user_attention()
        .await?
        .into_iter()
        .find(|item| &item.feedback.work == work))
}

async fn open_shared_store() -> anyhow::Result<Store> {
    let config = storage_config_from_env().context("resolve the shared Loopflow store")?;
    open_store(&config)
        .await
        .context("open the shared Loopflow store")
}

async fn projection(store: &Store, work: &WorkRef) -> anyhow::Result<WorkProjection> {
    Ok(WorkProjection {
        work: work.clone(),
        basis: store.current_epoch(work).await?.current_basis,
        status: store.work_status(work).await?,
        run: store.current_run(work).await?,
        feedback: store.feedback(work).await?,
    })
}

fn parse_work(kind: &str, id: &str) -> anyhow::Result<WorkRef> {
    match kind {
        "wave" => Ok(WorkRef::Wave(WaveId::parse(id)?)),
        "project" => Ok(WorkRef::Project(ProjectId::parse(id)?)),
        "task" => Ok(WorkRef::Task(TaskId::parse(id)?)),
        value => Err(anyhow!("invalid Work kind {value:?}")),
    }
}

fn print_projection(projection: &WorkProjection, json: bool) -> anyhow::Result<()> {
    if json {
        println!("{}", serde_json::to_string_pretty(projection)?);
    } else {
        println!(
            "{} {}  {:?}\n  basis: {}:{}\n  run: {}\n  attention: {}",
            projection.work.kind(),
            projection.work.id(),
            projection.status,
            projection.basis.epoch_id,
            projection.basis.revision,
            projection
                .run
                .as_ref()
                .map_or("none", |run| run.id.as_str()),
            projection.feedback.as_ref().map_or("none", |feedback| {
                match (&feedback.attention, feedback.attention_at.is_some()) {
                    (crate::durable::AttentionRoute::User, true) => "user (pending)",
                    (crate::durable::AttentionRoute::User, false) => "user (parked)",
                    (crate::durable::AttentionRoute::Parent(_), true) => "parent (pending)",
                    (crate::durable::AttentionRoute::Parent(_), false) => "parent (parked)",
                }
            }),
        );
    }
    Ok(())
}

fn print_receipt(receipt: &WorkReceipt, json: bool) -> anyhow::Result<()> {
    if json {
        println!("{}", serde_json::to_string_pretty(receipt)?);
    } else {
        match receipt {
            WorkReceipt::Placed(placement) => println!(
                "{} {}  ->  {}",
                placement.work.kind(),
                placement.work.id(),
                placement.home_id
            ),
            WorkReceipt::Steer(receipt) => println!("steered {}", receipt.steer.id),
            WorkReceipt::FeedbackContinued { status } => println!("continued Feedback: {status:?}"),
            WorkReceipt::FeedbackEscalated { feedback } => println!(
                "escalated {} {} Feedback to User attention",
                feedback.work.kind(),
                feedback.work.id()
            ),
            WorkReceipt::Interrupted(receipt) => println!("interrupted {}", receipt.run_id),
            WorkReceipt::Abandoned(receipt) => println!("abandoned {}", receipt.epoch.id),
        }
    }
    Ok(())
}

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

    #[test]
    fn feedback_exit_policies_match_the_presentation_contract() {
        assert!(!FeedbackExitPolicy::Explicit.continues(true));
        assert!(!FeedbackExitPolicy::Explicit.continues(false));
        assert!(FeedbackExitPolicy::Success.continues(true));
        assert!(!FeedbackExitPolicy::Success.continues(false));
        assert!(FeedbackExitPolicy::AnyExit.continues(true));
        assert!(FeedbackExitPolicy::AnyExit.continues(false));
    }
}