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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
pub mod linear;

use std::str::FromStr;
use std::time::Duration;

use serde::{Deserialize, Serialize};
use thiserror::Error;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum PmProviderKind {
    Linear,
}

impl PmProviderKind {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Linear => "linear",
        }
    }

    pub fn initiative_key(self) -> &'static str {
        match self {
            Self::Linear => "linear_initiative",
        }
    }

    /// GOAL.md frontmatter key binding a wave to its provider team — the team
    /// whose key prefixes every Task identifier (`PRD-*`, `INF-*`, …).
    pub fn team_key(self) -> &'static str {
        match self {
            Self::Linear => "linear_team",
        }
    }
}

/// The result of adopting or creating a provider team for a wave. The stable
/// `id` owns identity; `key` is mutable presentation (the Task prefix).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TeamBinding {
    pub id: String,
    pub key: String,
    pub created: bool,
}

impl std::fmt::Display for PmProviderKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for PmProviderKind {
    type Err = PmError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value.trim().to_ascii_lowercase().as_str() {
            "linear" => Ok(Self::Linear),
            other => Err(PmError::Message(format!(
                "unsupported PM provider {other:?}; expected \"linear\""
            ))),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PmKr {
    pub text: String,
    pub holds: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProjectFlowPlan {
    pub first: Option<String>,
    #[serde(rename = "loop")]
    pub loop_: Option<String>,
    pub finally: Option<String>,
}

impl ProjectFlowPlan {
    pub fn empty() -> Self {
        Self {
            first: None,
            loop_: None,
            finally: None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectContent {
    pub definition: String,
    pub flows: ProjectFlowPlan,
    pub krs: Vec<PmKr>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PmProject {
    pub id: String,
    pub slug: String,
    pub name: String,
    pub summary: String,
    pub definition: String,
    /// `None` means this provider snapshot predates Project flow configuration.
    /// Fresh provider reads always resolve it to `Some`, including an empty plan.
    pub flows: Option<ProjectFlowPlan>,
    pub krs: Vec<PmKr>,
    pub initiative_ids: Vec<String>,
    /// Stable ids of the Linear teams this Project belongs to. `None` when the
    /// read did not resolve teams (a snapshot written before the field existed);
    /// `Some(vec)` is authoritative. Team ownership drives `doctor`/`reteam`
    /// repair; a Project's team is otherwise invisible to the team-agnostic read
    /// path. Optional so an older cached snapshot still decodes.
    pub team_ids: Option<Vec<String>>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PmWave {
    pub id: String,
    pub name: String,
    pub summary: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PmItem {
    pub id: String,
    pub identifier: String,
    /// Provider-owned issue URL captured during PM sync. `None` stays explicit
    /// when the provider did not return one; status and roadmap reads never
    /// fetch it on demand.
    pub url: Option<String>,
    pub name: String,
    pub description: String,
    pub rank: u32,
    pub completed: bool,
    pub project: Option<String>,
    /// Provider user ID of the assignee, if any.
    pub assignee: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PmItemCreate {
    pub name: String,
    pub description: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct PmItemUpdate {
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub description: Option<String>,
}

/// A read of one issue's human-editable content plus its comments, taken to
/// stream Linear edits into a Task. `revision` is the provider's
/// last-updated marker (Linear `updatedAt`), monotonic per issue, and is
/// compared — not trusted as identity — so out-of-order responses never move
/// the cursor backward.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IssueObservation {
    pub revision: String,
    pub title: String,
    pub description: String,
    pub comments: Vec<IssueComment>,
}

/// One issue comment, with just enough authorship to tell a human's direction
/// from Loopflow's own writeback. `author_id` is the provider user id; `None`
/// for an integration/bot actor with no backing user, which is never treated
/// as human direction.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IssueComment {
    pub id: String,
    pub body: String,
    pub author_id: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct PmTextUpdate<'a> {
    pub(crate) name: Option<&'a str>,
    pub(crate) description: Option<&'a str>,
}

impl PmItemUpdate {
    pub(crate) fn text_update(&self) -> Option<PmTextUpdate<'_>> {
        if self.name.is_none() && self.description.is_none() {
            return None;
        }

        Some(PmTextUpdate {
            name: self.name.as_deref(),
            description: self.description.as_deref(),
        })
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum PmError {
    #[error("{0}")]
    Message(String),
}

pub type PmResult<T> = Result<T, PmError>;

pub fn project_slug(name: &str) -> String {
    let mut slug = String::new();
    let mut separator = false;
    for character in name.chars().flat_map(char::to_lowercase) {
        if character.is_ascii_alphanumeric() {
            if separator && !slug.is_empty() {
                slug.push('-');
            }
            slug.push(character);
            separator = false;
        } else if !slug.is_empty() {
            separator = true;
        }
    }
    slug
}

pub fn parse_project_content(content: &str) -> ProjectContent {
    enum Section {
        None,
        Definition,
        Flows,
        Krs,
    }

    let mut section = Section::None;
    let mut definition = Vec::new();
    let mut flows = ProjectFlowPlan::empty();
    let mut krs = Vec::new();
    let mut current_kr: Option<PmKr> = None;
    for line in content.lines() {
        let trimmed = line.trim();
        match trimmed {
            "## Definition" => {
                if let Some(kr) = current_kr.take() {
                    krs.push(kr);
                }
                section = Section::Definition;
                continue;
            }
            "## KRs" => {
                if let Some(kr) = current_kr.take() {
                    krs.push(kr);
                }
                section = Section::Krs;
                continue;
            }
            "## Flows" => {
                if let Some(kr) = current_kr.take() {
                    krs.push(kr);
                }
                section = Section::Flows;
                continue;
            }
            _ => {}
        }

        if matches!(section, Section::None)
            && trimmed.starts_with("# ")
            && !trimmed.starts_with("## ")
        {
            section = Section::Definition;
            continue;
        }

        match section {
            Section::Definition => definition.push(line),
            Section::Flows => {
                let Some((name, value)) = trimmed.split_once(':') else {
                    continue;
                };
                let value = match value.trim() {
                    "" => None,
                    value => Some(value.to_string()),
                };
                match name.trim() {
                    "first" => flows.first = value,
                    "loop" => flows.loop_ = value,
                    "finally" => flows.finally = value,
                    _ => {}
                }
            }
            Section::Krs => {
                let item = if let Some(text) = trimmed.strip_prefix("- [x] ") {
                    Some((true, text))
                } else if let Some(text) = trimmed.strip_prefix("- [X] ") {
                    Some((true, text))
                } else if let Some(text) = trimmed.strip_prefix("- [ ] ") {
                    Some((false, text))
                } else {
                    trimmed.strip_prefix("- ").map(|text| (false, text))
                };

                if let Some((holds, text)) = item {
                    if let Some(kr) = current_kr.take() {
                        krs.push(kr);
                    }
                    if !text.trim().is_empty() {
                        current_kr = Some(PmKr {
                            text: text.trim().to_string(),
                            holds,
                        });
                    }
                } else if !trimmed.is_empty() {
                    if let Some(kr) = current_kr.as_mut() {
                        kr.text.push(' ');
                        kr.text.push_str(trimmed);
                    }
                }
            }
            Section::None => {}
        }
    }
    if let Some(kr) = current_kr {
        krs.push(kr);
    }

    ProjectContent {
        definition: definition.join("\n").trim().to_string(),
        flows,
        krs,
    }
}

pub fn render_project_content(project: &ProjectContent) -> String {
    let mut content = format!("## Definition\n\n{}", project.definition.trim());
    if project.flows != ProjectFlowPlan::empty() {
        content.push_str("\n\n## Flows\n");
        if let Some(flow) = &project.flows.first {
            content.push_str(&format!("\nfirst: {}", flow.trim()));
        }
        if let Some(flow) = &project.flows.loop_ {
            content.push_str(&format!("\nloop: {}", flow.trim()));
        }
        if let Some(flow) = &project.flows.finally {
            content.push_str(&format!("\nfinally: {}", flow.trim()));
        }
    }
    content.push_str("\n\n## KRs");
    for kr in &project.krs {
        let marker = if kr.holds { "x" } else { " " };
        content.push_str(&format!("\n\n- [{marker}] {}", kr.text.trim()));
    }
    content.push('\n');
    content
}

pub(crate) const RATE_LIMIT_RETRIES: u8 = 3;
const RETRY_AFTER_FALLBACK: Duration = Duration::from_secs(60);

pub(crate) fn retry_after_delay(headers: &reqwest::header::HeaderMap) -> Duration {
    headers
        .get(reqwest::header::RETRY_AFTER)
        .and_then(|value| value.to_str().ok())
        .and_then(|value| value.parse::<u64>().ok())
        .map(Duration::from_secs)
        .unwrap_or(RETRY_AFTER_FALLBACK)
}

#[cfg(test)]
pub(crate) mod test_server {
    use std::collections::VecDeque;
    use std::sync::Arc;

    use axum::body::Bytes;
    use axum::extract::State;
    use axum::http::{HeaderMap, Method, StatusCode, Uri};
    use axum::response::Response;
    use axum::routing::any;
    use axum::Router;
    use serde_json::{json, Value};
    use tokio::net::TcpListener;
    use tokio::sync::Mutex;

    #[derive(Debug, Clone, PartialEq, Eq)]
    pub struct CapturedRequest {
        pub method: String,
        pub path: String,
        pub query: Option<String>,
        pub authorization: Option<String>,
        pub body: String,
    }

    #[derive(Debug, Clone)]
    pub struct QueuedResponse {
        pub status: StatusCode,
        pub headers: Vec<(String, String)>,
        pub body: String,
    }

    #[derive(Clone)]
    struct ServerState {
        requests: Arc<Mutex<Vec<CapturedRequest>>>,
        responses: Arc<Mutex<VecDeque<QueuedResponse>>>,
    }

    pub async fn spawn(
        responses: Vec<QueuedResponse>,
    ) -> (String, Arc<Mutex<Vec<CapturedRequest>>>) {
        let state = ServerState {
            requests: Arc::new(Mutex::new(Vec::new())),
            responses: Arc::new(Mutex::new(VecDeque::from(responses))),
        };
        let requests = state.requests.clone();
        let app = Router::new()
            .route("/", any(handle_request))
            .route("/{*path}", any(handle_request))
            .with_state(state);
        let listener = TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind listener");
        let addr = listener.local_addr().expect("listener addr");
        tokio::spawn(async move {
            axum::serve(listener, app).await.expect("serve test app");
        });
        (format!("http://{addr}"), requests)
    }

    async fn handle_request(
        State(state): State<ServerState>,
        method: Method,
        uri: Uri,
        headers: HeaderMap,
        body: Bytes,
    ) -> Response {
        state.requests.lock().await.push(CapturedRequest {
            method: method.to_string(),
            path: uri.path().to_string(),
            query: uri.query().map(str::to_string),
            authorization: headers
                .get(reqwest::header::AUTHORIZATION)
                .and_then(|value| value.to_str().ok())
                .map(str::to_string),
            body: String::from_utf8(body.to_vec()).expect("utf8 body"),
        });

        let response = state.responses.lock().await.pop_front().unwrap_or_else(|| {
            json_response(
                StatusCode::INTERNAL_SERVER_ERROR,
                json!({ "errors": [{ "message": "unexpected request" }] }),
            )
        });

        let mut builder = Response::builder().status(response.status);
        for (name, value) in response.headers {
            builder = builder.header(name, value);
        }
        builder.body(response.body.into()).expect("build response")
    }

    pub fn json_response(status: StatusCode, body: Value) -> QueuedResponse {
        response(
            status,
            vec![("content-type", "application/json")],
            body.to_string(),
        )
    }

    pub fn response(
        status: StatusCode,
        headers: Vec<(&str, &str)>,
        body: String,
    ) -> QueuedResponse {
        QueuedResponse {
            status,
            headers: headers
                .into_iter()
                .map(|(name, value)| (name.to_string(), value.to_string()))
                .collect(),
            body,
        }
    }
}

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

    #[test]
    fn pm_item_update_text_update_skips_empty_changes() {
        let update = PmItemUpdate::default();

        assert_eq!(update.text_update(), None);
    }

    #[test]
    fn pm_item_update_text_update_preserves_name_and_description() {
        let update = PmItemUpdate {
            name: Some("Ship roadmap".to_string()),
            description: Some("Build the roadmap client".to_string()),
        };

        assert_eq!(
            update.text_update(),
            Some(PmTextUpdate {
                name: Some("Ship roadmap"),
                description: Some("Build the roadmap client"),
            })
        );
    }

    #[test]
    fn project_slug_is_deterministic() {
        assert_eq!(project_slug("Mac Surface UX"), "mac-surface-ux");
        assert_eq!(project_slug("  API / Auditability  "), "api-auditability");
    }

    #[test]
    fn project_snapshot_without_flows_remains_readable() {
        let project: PmProject = serde_json::from_str(
            r#"{
                "id":"project-1",
                "slug":"incident-management",
                "name":"Incident Management",
                "summary":"Restore service and prevent recurrence.",
                "definition":"Incidents are resolved at every causal layer.",
                "krs":[],
                "initiative_ids":["initiative-1"],
                "team_ids":null
            }"#,
        )
        .expect("legacy project snapshot");

        assert_eq!(project.flows, None);
    }

    #[test]
    fn project_content_round_trips_linear_markdown() {
        let krs = vec![
            PmKr {
                text: "One proof holds".to_string(),
                holds: true,
            },
            PmKr {
                text: "Another remains".to_string(),
                holds: false,
            },
        ];
        let project = ProjectContent {
            definition: "A measured bet.".to_string(),
            flows: ProjectFlowPlan {
                first: Some("incident".to_string()),
                loop_: Some("ship-5whys".to_string()),
                finally: Some("ship".to_string()),
            },
            krs: krs.clone(),
        };
        let rendered = render_project_content(&project);
        assert_eq!(parse_project_content(&rendered), project);

        let local = "# Project Name\n\nA measured bet.\n\n## KRs\n\n- One proof holds\n  across wrapped lines.\n";
        assert_eq!(
            parse_project_content(local),
            ProjectContent {
                definition: "A measured bet.".to_string(),
                flows: ProjectFlowPlan::empty(),
                krs: vec![PmKr {
                    text: "One proof holds across wrapped lines.".to_string(),
                    holds: false,
                }],
            }
        );
    }
}