cliban-core 0.13.0

cliban storage + domain layer: rusqlite store + writer thread + domain contexts
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
//! Port of `backend/lib/loom/milestones.ex` + `Loom.Schema.Milestone`.

use chrono::{DateTime, NaiveDate, Utc};
use rusqlite::{params, Connection, OptionalExtension};

use crate::contexts::projects;
use crate::error::{Error, Result};
use crate::rows;
use crate::schema::{Milestone, DONE_STATUS, MILESTONE_STATUSES};
use crate::time;

#[derive(Debug, Clone)]
pub struct CreateMilestone {
    /// Project key (resolved to project_id). Mirrors the `%{project: key}`
    /// create clause.
    pub project: String,
    pub name: String,
    pub description: Option<String>,
    pub target_date: Option<NaiveDate>,
    pub status: Option<String>,
}

pub fn create(conn: &Connection, attrs: CreateMilestone) -> Result<Milestone> {
    let project = match projects::get_by_key(conn, &attrs.project)? {
        Some(p) => p,
        None => {
            return Err(Error::validation(
                "project",
                &format!("project not found: {}", attrs.project),
            ))
        }
    };

    if attrs.name.is_empty() {
        return Err(Error::validation("name", "can't be blank"));
    }
    let status = attrs.status.clone().unwrap_or_else(|| "open".to_string());
    if !MILESTONE_STATUSES.contains(&status.as_str()) {
        return Err(Error::validation("status", "is invalid"));
    }
    // unique_constraint([:project_id, :name])
    if get_row(conn, project.id, &attrs.name)?.is_some() {
        return Err(Error::validation("name", "already exists in this project"));
    }

    let now = time::format_usec(time::now_usec());
    let desc = attrs.description.unwrap_or_default();
    let target = attrs.target_date.map(time::format_date);
    conn.execute(
        "INSERT INTO milestones (project_id, name, description, target_date, \
         status, archived, inserted_at, updated_at) \
         VALUES (?1, ?2, ?3, ?4, ?5, 0, ?6, ?6)",
        params![project.id, attrs.name, desc, target, status, now],
    )?;
    let id = conn.last_insert_rowid();
    Ok(get_by_id(conn, id)?.expect("inserted"))
}

#[derive(Debug, Default, Clone)]
pub struct UpdateMilestone {
    pub name: Option<String>,
    pub description: Option<String>,
    pub target_date: Option<Option<NaiveDate>>,
    pub status: Option<String>,
    pub archived: Option<bool>,
}

pub fn update(conn: &Connection, m: &Milestone, attrs: UpdateMilestone) -> Result<Milestone> {
    if let Some(name) = &attrs.name {
        if name.is_empty() {
            return Err(Error::validation("name", "can't be blank"));
        }
    }
    if let Some(status) = &attrs.status {
        if !MILESTONE_STATUSES.contains(&status.as_str()) {
            return Err(Error::validation("status", "is invalid"));
        }
    }
    let name = attrs.name.clone().unwrap_or_else(|| m.name.clone());
    // unique within project, if name changed
    if name != m.name {
        if let Some(existing) = get_row(conn, m.project_id, &name)? {
            if existing.id != m.id {
                return Err(Error::validation("name", "already exists in this project"));
            }
        }
    }
    let description = attrs
        .description
        .clone()
        .unwrap_or_else(|| m.description.clone());
    let target = match attrs.target_date {
        Some(v) => v,
        None => m.target_date,
    };
    let status = attrs.status.clone().unwrap_or_else(|| m.status.clone());
    let archived = attrs.archived.unwrap_or(m.archived);
    let now = time::format_usec(time::now_usec());

    conn.execute(
        "UPDATE milestones SET name = ?1, description = ?2, target_date = ?3, \
         status = ?4, archived = ?5, updated_at = ?6 WHERE id = ?7",
        params![
            name,
            description,
            target.map(time::format_date),
            status,
            archived as i64,
            now,
            m.id
        ],
    )?;
    Ok(get_by_id(conn, m.id)?.expect("updated"))
}

/// `list/1` — ordered by name; optionally scoped to a project key. An unknown
/// project key yields an empty list (mirrors `where: false`).
pub fn list(conn: &Connection, project: Option<&str>) -> Result<Vec<Milestone>> {
    let (where_clause, project_id) = match project {
        None => (String::new(), None),
        Some(key) => match projects::get_by_key(conn, key)? {
            Some(p) => ("WHERE project_id = ?1".to_string(), Some(p.id)),
            None => return Ok(vec![]),
        },
    };
    let sql = format!(
        "SELECT {} FROM milestones {} ORDER BY name ASC",
        rows::MILESTONE_COLS,
        where_clause
    );
    let mut stmt = conn.prepare(&sql)?;
    let out = match project_id {
        Some(pid) => stmt
            .query_map(params![pid], rows::milestone)?
            .collect::<rusqlite::Result<Vec<_>>>()?,
        None => stmt
            .query_map([], rows::milestone)?
            .collect::<rusqlite::Result<Vec<_>>>()?,
    };
    Ok(out)
}

/// A milestone plus the rollups a milestone-centric view needs: the owning
/// project's key, non-archived issue counts, and when the milestone was last
/// *worked on* (as opposed to last edited).
#[derive(Debug, Clone)]
pub struct MilestoneSummary {
    pub milestone: Milestone,
    pub project_key: String,
    /// Non-archived issues carrying this milestone.
    pub total: i64,
    /// …of which are `done`.
    pub done: i64,
    /// When the milestone was last *worked on*: the newest of any activity-log
    /// entry on its issues, any issue's `updated_at`, and the milestone row's
    /// own `updated_at`. Issue `updated_at` carries the weight in practice —
    /// every move/edit bumps it, while `activity_log_entries` is only written
    /// by callers that use the log API directly.
    pub last_activity: DateTime<Utc>,
}

impl MilestoneSummary {
    /// Completion as a 0.0–1.0 fraction; an empty milestone reads as 0.
    pub fn progress(&self) -> f64 {
        if self.total == 0 {
            0.0
        } else {
            self.done as f64 / self.total as f64
        }
    }
}

/// Orderings for [`summaries`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Sort {
    /// Most recently worked on first — the milestone page's default.
    #[default]
    Activity,
    Name,
    /// Soonest target first; undated milestones sort last.
    Target,
}

impl Sort {
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "activity" => Some(Self::Activity),
            "name" => Some(Self::Name),
            "target" => Some(Self::Target),
            _ => None,
        }
    }

    fn order_by(self) -> &'static str {
        match self {
            // `last_activity` is the SELECT alias below.
            Self::Activity => "last_activity DESC, m.name ASC",
            Self::Name => "p.key ASC, m.name ASC",
            Self::Target => "m.target_date IS NULL, m.target_date ASC, m.name ASC",
        }
    }
}

#[derive(Debug, Default, Clone, Copy)]
pub struct SummaryOpts<'a> {
    /// Project key; `None` spans every project.
    pub project: Option<&'a str>,
    /// Exact `status` filter; `None` keeps all statuses.
    pub status: Option<&'a str>,
    pub sort: Sort,
}

/// `list/1` with rollups. An unknown project key yields an empty list, same as
/// [`list`].
pub fn summaries(conn: &Connection, opts: SummaryOpts) -> Result<Vec<MilestoneSummary>> {
    let project_id = match opts.project {
        None => None,
        Some(key) => match projects::get_by_key(conn, key)? {
            Some(p) => Some(p.id),
            None => return Ok(vec![]),
        },
    };

    // The counts are correlated subqueries rather than joins: joining both
    // `issues` and `activity_log_entries` would multiply rows and inflate the
    // counts. Both filters are always bound and no-op on NULL so the statement
    // shape (and its param set) stays constant.
    let sql = format!(
        "SELECT {cols}, p.key, \
           (SELECT COUNT(*) FROM issues i \
              WHERE i.milestone_id = m.id AND i.archived = 0) AS total, \
           (SELECT COUNT(*) FROM issues i \
              WHERE i.milestone_id = m.id AND i.archived = 0 AND i.status = '{done}') AS done_count, \
           MAX(COALESCE((SELECT MAX(a.ts) FROM activity_log_entries a \
                 JOIN issues i ON i.id = a.issue_id \
                 WHERE i.milestone_id = m.id AND i.archived = 0), ''), \
               COALESCE((SELECT MAX(i.updated_at) FROM issues i \
                 WHERE i.milestone_id = m.id AND i.archived = 0), ''), \
               m.updated_at) AS last_activity \
         FROM milestones m JOIN projects p ON p.id = m.project_id \
         WHERE (?1 IS NULL OR m.project_id = ?1) AND (?2 IS NULL OR m.status = ?2) \
         ORDER BY {order}",
        cols = rows::milestone_cols_as("m"),
        done = DONE_STATUS,
        order = opts.sort.order_by(),
    );

    let mut stmt = conn.prepare(&sql)?;
    let out = stmt
        .query_map(params![project_id, opts.status], |row| {
            let milestone = rows::milestone(row)?;
            let last: String = row.get(12)?;
            Ok(MilestoneSummary {
                last_activity: time::parse_ts(&last).unwrap_or(milestone.updated_at),
                milestone,
                project_key: row.get(9)?,
                total: row.get(10)?,
                done: row.get(11)?,
            })
        })?
        .collect::<rusqlite::Result<Vec<_>>>()?;
    Ok(out)
}

/// `get/2` — by project key + name.
pub fn get(conn: &Connection, project_key: &str, name: &str) -> Result<Option<Milestone>> {
    match projects::get_by_key(conn, project_key)? {
        None => Ok(None),
        Some(p) => get_row(conn, p.id, name),
    }
}

pub fn get_by_id(conn: &Connection, id: i64) -> Result<Option<Milestone>> {
    let sql = format!(
        "SELECT {} FROM milestones WHERE id = ?1",
        rows::MILESTONE_COLS
    );
    Ok(conn
        .query_row(&sql, params![id], rows::milestone)
        .optional()?)
}

fn get_row(conn: &Connection, project_id: i64, name: &str) -> Result<Option<Milestone>> {
    let sql = format!(
        "SELECT {} FROM milestones WHERE project_id = ?1 AND name = ?2",
        rows::MILESTONE_COLS
    );
    Ok(conn
        .query_row(&sql, params![project_id, name], rows::milestone)
        .optional()?)
}

// ---- waves ----

/// The dependency-wave partition of a milestone, for orchestration: wave N is
/// safe to start once waves 0..N have finished. Derived from the `blocks`
/// edges among the milestone's own open issues; done issues count as satisfied
/// dependencies and are listed separately.
/// One path that more than one ticket in the same wave predicts touching.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Collision {
    pub path: String,
    /// The colliding tickets, sorted.
    pub keys: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Waves {
    /// Layers of issue keys: everything in `waves[n]` has all its blockers in
    /// `done` or in earlier waves.
    pub waves: Vec<Vec<String>>,
    /// The milestone's issues already done (their dependents may schedule).
    pub done: Vec<String>,
    /// Open issues gated — directly or transitively — by open work outside
    /// this milestone. They cannot be scheduled by finishing the milestone's
    /// own waves.
    pub external_blocked: Vec<String>,
    /// Advisory same-implementer groups: `related_to` components (sorted),
    /// linear runs of the intra-milestone blocking graph (in dependency order),
    /// and same-wave tickets predicted to touch one path (sorted).
    /// Never scheduling edges; `waves` alone decides what may start.
    pub chains: Vec<Vec<String>>,
    /// Why some tickets were joined: one entry per path that more than one
    /// ticket in a single wave predicts touching, in its `## Files` section.
    pub collisions: Vec<Collision>,
}

/// Partition the milestone's open, non-archived issues into dependency waves
/// (Kahn layers over the intra-milestone `blocks` edges). A dependency cycle is
/// an error naming the issues involved — a cyclic milestone cannot be
/// orchestrated and the board needs fixing, not a guess.
pub fn waves(conn: &Connection, project_key: &str, name: &str) -> Result<Waves> {
    use std::collections::{HashMap, HashSet};

    let milestone = get(conn, project_key, name)?
        .ok_or_else(|| Error::NamedNotFound(name.to_string()))?;

    struct Node {
        key: String,
        done: bool,
        /// Paths this ticket predicts it will touch, from its `## Files`
        /// section. Empty when it has none, which is the pre-feature default.
        predicted: Vec<String>,
    }
    let sql = "SELECT id, key, status, description FROM issues \
               WHERE milestone_id = ?1 AND archived = 0 ORDER BY position, key";
    let mut stmt = conn.prepare(sql)?;
    let nodes: HashMap<i64, Node> = stmt
        .query_map(params![milestone.id], |r| {
            let description: String = r.get::<_, Option<String>>(3)?.unwrap_or_default();
            Ok((
                r.get::<_, i64>(0)?,
                Node {
                    key: r.get(1)?,
                    done: r.get::<_, String>(2)? == crate::schema::DONE_STATUS,
                    predicted: crate::sections::predicted_changes(&description)
                        .into_iter()
                        .map(|c| c.path)
                        .collect(),
                },
            ))
        })?
        .collect::<rusqlite::Result<HashMap<_, _>>>()?;

    let done: Vec<String> = nodes
        .values()
        .filter(|n| n.done)
        .map(|n| n.key.clone())
        .collect();

    // Open blockers of every open node, split into edges inside the milestone
    // and gates from outside it.
    let mut intra: HashMap<i64, Vec<i64>> = HashMap::new();
    let mut external: HashSet<i64> = HashSet::new();
    {
        let mut stmt = conn.prepare(
            "SELECT r.to_issue_id, b.id FROM issue_relation r \
             JOIN issues b ON b.id = r.from_issue_id \
             JOIN issues i ON i.id = r.to_issue_id \
             WHERE r.type = 'blocks' AND i.milestone_id = ?1 AND i.archived = 0 \
             AND b.archived = 0 AND b.status != 'done'",
        )?;
        let edges = stmt
            .query_map(params![milestone.id], |r| {
                Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?))
            })?
            .collect::<rusqlite::Result<Vec<_>>>()?;
        for (to, blocker) in edges {
            if nodes.get(&to).is_none_or(|n| n.done) {
                continue;
            }
            if nodes.contains_key(&blocker) {
                intra.entry(to).or_default().push(blocker);
            } else {
                external.insert(to);
            }
        }
    }

    // Layered Kahn over the open nodes. External-gated nodes never schedule;
    // whatever else is left at the fixpoint is either transitively external
    // or a genuine cycle.
    let mut remaining: HashSet<i64> = nodes
        .iter()
        .filter(|(_, n)| !n.done)
        .map(|(id, _)| *id)
        .collect();
    let mut scheduled: HashSet<i64> = HashSet::new();
    let mut waves_out: Vec<Vec<String>> = Vec::new();
    loop {
        let mut wave: Vec<i64> = remaining
            .iter()
            .copied()
            .filter(|id| !external.contains(id))
            .filter(|id| {
                intra
                    .get(id)
                    .is_none_or(|blockers| blockers.iter().all(|b| scheduled.contains(b)))
            })
            .collect();
        if wave.is_empty() {
            break;
        }
        wave.sort_by(|a, b| nodes[a].key.cmp(&nodes[b].key));
        for id in &wave {
            remaining.remove(id);
            scheduled.insert(*id);
        }
        waves_out.push(wave.into_iter().map(|id| nodes[&id].key.clone()).collect());
    }

    // Drain the transitively-external tail: nodes whose unmet blockers are all
    // external-blocked themselves. What survives is a cycle.
    let mut external_blocked: HashSet<i64> = external
        .iter()
        .copied()
        .filter(|id| remaining.contains(id))
        .collect();
    loop {
        let grown: Vec<i64> = remaining
            .iter()
            .copied()
            .filter(|id| !external_blocked.contains(id))
            .filter(|id| {
                intra.get(id).is_none_or(|blockers| {
                    blockers
                        .iter()
                        .all(|b| scheduled.contains(b) || external_blocked.contains(b))
                })
            })
            .collect();
        if grown.is_empty() {
            break;
        }
        external_blocked.extend(grown);
    }
    let cyclic: Vec<&i64> = remaining
        .iter()
        .filter(|id| !external_blocked.contains(id))
        .collect();
    if !cyclic.is_empty() {
        let mut keys: Vec<String> = cyclic.iter().map(|id| nodes[id].key.clone()).collect();
        keys.sort();
        return Err(Error::validation(
            "milestone",
            &format!("dependency cycle among: {}", keys.join(", ")),
        ));
    }

    // Chains staff the schedulable work, so they are derived last, over the
    // nodes that survived: done, archived, and externally gated issues are all
    // out. Pairing a real ticket with one this milestone can never start is
    // advice nobody can take.
    let schedulable = |id: &i64| {
        nodes.get(id).is_some_and(|n| !n.done) && !external_blocked.contains(id)
    };

    let mut related: HashMap<i64, Vec<i64>> = HashMap::new();
    {
        let mut stmt = conn.prepare(
            "SELECT from_issue_id, to_issue_id FROM issue_relation WHERE type = 'related_to'",
        )?;
        for edge in stmt.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)))? {
            let (a, b) = edge?;
            if schedulable(&a) && schedulable(&b) {
                related.entry(a).or_default().push(b);
                related.entry(b).or_default().push(a);
            }
        }
    }
    // Tickets in one wave are the ones that would run at the same time, so a
    // path two of them both predict touching is the collision worth catching.
    // git marks only some of these, and the ones it does not mark — a helper
    // invented twice, a signature changed two ways — are the expensive ones.
    // Joining them is an edge in the same component walk that serves
    // `related_to`, so one implementer takes them in sequence and the second
    // starts from a tree that already contains the first.
    let mut collisions: Vec<Collision> = Vec::new();
    let by_key: HashMap<&str, i64> = nodes.iter().map(|(id, n)| (n.key.as_str(), *id)).collect();
    for layer in &waves_out {
        let mut by_path: HashMap<&str, Vec<i64>> = HashMap::new();
        for key in layer {
            let Some(id) = by_key.get(key.as_str()) else {
                continue;
            };
            for path in &nodes[id].predicted {
                let sharers = by_path.entry(path.as_str()).or_default();
                if !sharers.contains(id) {
                    sharers.push(*id);
                }
            }
        }
        let mut paths: Vec<&str> = by_path
            .iter()
            .filter(|(_, ids)| ids.len() > 1)
            .map(|(path, _)| *path)
            .collect();
        paths.sort_unstable();
        for path in paths {
            let ids = &by_path[path];
            for pair in ids.windows(2) {
                related.entry(pair[0]).or_default().push(pair[1]);
                related.entry(pair[1]).or_default().push(pair[0]);
            }
            let mut keys: Vec<String> = ids.iter().map(|id| nodes[id].key.clone()).collect();
            keys.sort();
            collisions.push(Collision {
                path: path.to_string(),
                keys,
            });
        }
    }

    let mut open: Vec<i64> = nodes.keys().copied().filter(schedulable).collect();
    open.sort_by(|a, b| nodes[a].key.cmp(&nodes[b].key));
    let mut seen = HashSet::new();
    let mut chains = Vec::new();
    let mut chained: HashSet<i64> = HashSet::new();
    for id in open {
        if !seen.insert(id) || !related.contains_key(&id) {
            continue;
        }
        let mut stack = vec![id];
        let mut members = Vec::new();
        while let Some(next) = stack.pop() {
            members.push(next);
            for neighbor in related.get(&next).into_iter().flatten() {
                if seen.insert(*neighbor) {
                    stack.push(*neighbor);
                }
            }
        }
        if members.len() > 1 {
            chained.extend(members.iter().copied());
            let mut chain: Vec<String> = members.iter().map(|id| nodes[id].key.clone()).collect();
            chain.sort();
            chains.push(chain);
        }
    }

    // A linear run of blocking edges is the strongest evidence for
    // same-implementer work: those tickets are serialised by construction and
    // land on one surface, so one implementer pays comprehension once instead
    // of once per wave. Fan-in or fan-out ends a run — that is where the work
    // genuinely parallelises. An explicit `related_to` group already claimed
    // its members, so a run splits around them rather than restating them.
    let mut dependents: HashMap<i64, Vec<i64>> = HashMap::new();
    for (to, blockers) in &intra {
        for blocker in blockers {
            dependents.entry(*blocker).or_default().push(*to);
        }
    }
    let mut next: HashMap<i64, i64> = HashMap::new();
    let mut has_prev: HashSet<i64> = HashSet::new();
    for (blocker, deps) in &dependents {
        if deps.len() != 1 || chained.contains(blocker) || !schedulable(blocker) {
            continue;
        }
        let to = deps[0];
        if chained.contains(&to)
            || !schedulable(&to)
            || intra.get(&to).is_none_or(|b| b.len() != 1)
        {
            continue;
        }
        next.insert(*blocker, to);
        has_prev.insert(to);
    }
    let mut starts: Vec<i64> = next
        .keys()
        .copied()
        .filter(|id| !has_prev.contains(id))
        .collect();
    starts.sort_by(|a, b| nodes[a].key.cmp(&nodes[b].key));
    for start in starts {
        // Dependency order, not sorted: the run is also the order to work it.
        let mut chain = vec![nodes[&start].key.clone()];
        let mut walked: HashSet<i64> = HashSet::from([start]);
        let mut cur = start;
        // Unreachable today: a cycle already returned Err above. Cheap
        // insurance so a future reordering cannot turn this into a hang.
        while let Some(step) = next.get(&cur) {
            if !walked.insert(*step) {
                break;
            }
            chain.push(nodes[step].key.clone());
            cur = *step;
        }
        chains.push(chain);
    }

    let mut external_keys: Vec<String> = external_blocked
        .iter()
        .map(|id| nodes[id].key.clone())
        .collect();
    external_keys.sort();
    let mut done_sorted = done;
    done_sorted.sort();

    Ok(Waves {
        waves: waves_out,
        done: done_sorted,
        external_blocked: external_keys,
        chains,
        collisions,
    })
}