beady-eye 0.4.0

A tree of work in flight: bead graphs annotated with the live agents working them
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
//! The rules that say a bead's claim and the pane behind it have come apart.

use chrono::{DateTime, Utc};
use serde::Serialize;

use crate::config::Anomalies;
use crate::model::join::{AgentRef, Conflict};
use crate::model::snapshot::ProviderState;
use crate::model::types::{Bead, Status};

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "rule", rename_all = "kebab-case")]
pub enum Anomaly {
    /// `in_progress` and untouched for longer than the configured window.
    StaleClaim { days: i64 },
    /// `in_progress` with no pane behind it.
    ///
    /// Where the bead named a live pane the join would not award it, that
    /// refusal is the reason and travels with the rule; where it named
    /// nothing, or nothing live, there is no reason to carry.
    OrphanClaim {
        #[serde(skip_serializing_if = "Option::is_none")]
        refused: Option<Conflict>,
    },
    /// Closed, but its pane is still there.
    StalePane,
}

/// Every anomaly rule that fires on one bead, in a fixed order.
///
/// A node carries all of them, not the first: an old claim whose agent has
/// died is both an orphan claim and a stale one, and the age is the part that
/// says whether to care. `now` is a parameter so the age rule is testable.
///
/// `agents` is how the run went for panes, because only one of these rules
/// reads bd alone. The rest need a pane, and where nothing answered for
/// panes there is no pane fact to read either way.
///
/// `pane_out_of_reach` is the same ignorance one bead at a time: the run
/// answered for panes, and the pane this bead named is in a session that did
/// not. It is asked per bead rather than per run because the sessions that
/// did answer are still worth reading — a run that fell silent about every
/// claim because one session hiccuped would throw away what it does know to
/// avoid saying what it does not.
pub fn detect(
    bead: &Bead,
    agent: Option<&AgentRef>,
    refused: Option<&Conflict>,
    agents: ProviderState,
    pane_out_of_reach: bool,
    cfg: &Anomalies,
    now: DateTime<Utc>,
) -> Vec<Anomaly> {
    if bead.status.is_closed() {
        return agent.map(|_| Anomaly::StalePane).into_iter().collect();
    }

    if bead.status != Status::InProgress {
        // An agent parked on blocked or open work is ordinary, not an anomaly.
        return Vec::new();
    }

    let mut fired = Vec::new();

    if agents.answered() && agent.is_none() && !pane_out_of_reach {
        fired.push(Anomaly::OrphanClaim {
            refused: refused.cloned(),
        });
    }

    let untouched_for = bead.updated_at.map(|updated| (now - updated).num_days());
    if let Some(days) = untouched_for.filter(|days| *days >= cfg.stale_claim_days) {
        fired.push(Anomaly::StaleClaim { days });
    }

    fired
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::collect::bd::parse_beads;
    use crate::model::join::JoinSource;
    use crate::model::types::testing::key;
    use crate::model::types::PaneStatus;
    use pretty_assertions::assert_eq;

    const NOW: &str = "2026-08-30T12:00:00Z";
    const SIXTY_DAYS_AGO: &str = "2026-07-01T12:00:00Z";
    const THIRTY_DAYS_AGO: &str = "2026-07-31T12:00:00Z";
    const TWENTY_NINE_DAYS_AGO: &str = "2026-08-01T12:00:00Z";
    const YESTERDAY: &str = "2026-08-29T12:00:00Z";

    /// A bead as bd writes it, so the fields the rules read come through the
    /// real parser rather than a struct literal that can drift from it.
    fn bead(status: &str, updated_at: &str) -> Bead {
        parse_beads(&format!(
            r#"[{{"id":"p-1","title":"work","status":"{status}",
                  "updated_at":"{updated_at}"}}]"#
        ))
        .expect("the row parses")
        .remove(0)
    }

    fn pane(pane_status: PaneStatus) -> AgentRef {
        AgentRef {
            pane: key("w:p1"),
            pane_status,
            title: None,
            source: JoinSource::AgentPane,
        }
    }

    fn live() -> AgentRef {
        pane(PaneStatus::Working)
    }

    fn now() -> DateTime<Utc> {
        NOW.parse().expect("the clock parses")
    }

    /// A claim with nothing behind it and no refusal to explain it.
    fn orphan() -> Anomaly {
        Anomaly::OrphanClaim { refused: None }
    }

    // ---- closed beads: stale-pane ---------------------------------------

    #[test]
    fn a_closed_bead_whose_pane_is_still_there_is_a_stale_pane() {
        let got = detect(
            &bead("closed", YESTERDAY),
            Some(&live()),
            None,
            ProviderState::Answering,
            false,
            &Anomalies::default(),
            now(),
        );
        assert_eq!(got, vec![Anomaly::StalePane]);
    }

    #[test]
    fn a_pane_that_has_finished_still_outlived_its_closed_bead() {
        let got = detect(
            &bead("closed", YESTERDAY),
            Some(&pane(PaneStatus::Done)),
            None,
            ProviderState::Answering,
            false,
            &Anomalies::default(),
            now(),
        );
        assert_eq!(
            got,
            vec![Anomaly::StalePane],
            "the rule keys on a pane being there, not on what it is doing"
        );
    }

    #[test]
    fn a_closed_bead_with_no_pane_is_clean() {
        let got = detect(
            &bead("closed", YESTERDAY),
            None,
            None,
            ProviderState::Answering,
            false,
            &Anomalies::default(),
            now(),
        );
        assert_eq!(got, Vec::new());
    }

    #[test]
    fn a_long_closed_bead_is_never_a_stale_claim() {
        let got = detect(
            &bead("closed", SIXTY_DAYS_AGO),
            Some(&live()),
            None,
            ProviderState::Answering,
            false,
            &Anomalies::default(),
            now(),
        );
        assert_eq!(
            got,
            vec![Anomaly::StalePane],
            "the age rule is about claims, and a closed bead holds none"
        );
    }

    // ---- claims: orphan-claim and stale-claim ---------------------------

    /// The other side of the gate: a provider that answered and awarded the
    /// bead no pane has said something, and the rule reads it.
    #[test]
    fn a_fresh_claim_with_no_pane_is_an_orphan_claim() {
        let got = detect(
            &bead("in_progress", YESTERDAY),
            None,
            None,
            ProviderState::Answering,
            false,
            &Anomalies::default(),
            now(),
        );
        assert_eq!(got, vec![orphan()]);
    }

    #[test]
    fn a_claim_untouched_past_the_window_is_a_stale_claim() {
        let got = detect(
            &bead("in_progress", SIXTY_DAYS_AGO),
            Some(&live()),
            None,
            ProviderState::Answering,
            false,
            &Anomalies::default(),
            now(),
        );
        assert_eq!(got, vec![Anomaly::StaleClaim { days: 60 }]);
    }

    #[test]
    fn an_old_claim_whose_agent_has_died_is_both_and_keeps_its_age() {
        let got = detect(
            &bead("in_progress", SIXTY_DAYS_AGO),
            None,
            None,
            ProviderState::Answering,
            false,
            &Anomalies::default(),
            now(),
        );
        assert_eq!(
            got,
            vec![orphan(), Anomaly::StaleClaim { days: 60 }],
            "reporting only the orphan throws away how long it has sat there"
        );
    }

    /// A claim whose pane the run could not ask about is not a claim whose
    /// pane is gone, and only the second is an orphan. The stale-claim rule
    /// reads bd alone, so it still fires on the same bead — a run that knows
    /// nothing about panes still knows how long the row has sat there.
    #[test]
    fn a_claim_whose_pane_is_out_of_reach_is_not_orphaned_and_is_still_aged() {
        let got = detect(
            &bead("in_progress", SIXTY_DAYS_AGO),
            None,
            None,
            ProviderState::Answering,
            true,
            &Anomalies::default(),
            now(),
        );
        assert_eq!(got, vec![Anomaly::StaleClaim { days: 60 }]);
    }

    /// The other half, on the same inputs: the run answered for the session
    /// this bead's pane was in, so the pane is gone rather than unasked.
    #[test]
    fn a_claim_whose_pane_the_run_could_ask_about_is_orphaned() {
        let got = detect(
            &bead("in_progress", SIXTY_DAYS_AGO),
            None,
            None,
            ProviderState::Answering,
            false,
            &Anomalies::default(),
            now(),
        );
        assert_eq!(got, vec![orphan(), Anomaly::StaleClaim { days: 60 }]);
    }

    #[test]
    fn a_recent_claim_with_a_pane_is_clean() {
        let got = detect(
            &bead("in_progress", YESTERDAY),
            Some(&live()),
            None,
            ProviderState::Answering,
            false,
            &Anomalies::default(),
            now(),
        );
        assert_eq!(got, Vec::new());
    }

    #[test]
    fn the_window_fires_on_the_day_it_is_reached() {
        let inside = detect(
            &bead("in_progress", TWENTY_NINE_DAYS_AGO),
            Some(&live()),
            None,
            ProviderState::Answering,
            false,
            &Anomalies::default(),
            now(),
        );
        assert_eq!(inside, Vec::new(), "29 days is inside a 30-day window");

        let reached = detect(
            &bead("in_progress", THIRTY_DAYS_AGO),
            Some(&live()),
            None,
            ProviderState::Answering,
            false,
            &Anomalies::default(),
            now(),
        );
        assert_eq!(reached, vec![Anomaly::StaleClaim { days: 30 }]);
    }

    #[test]
    fn the_window_is_configurable() {
        let wide = Anomalies {
            stale_claim_days: 90,
        };
        let got = detect(
            &bead("in_progress", SIXTY_DAYS_AGO),
            Some(&live()),
            None,
            ProviderState::Answering,
            false,
            &wide,
            now(),
        );
        assert_eq!(got, Vec::new(), "60 days is inside a 90-day window");

        let narrow = Anomalies {
            stale_claim_days: 7,
        };
        let got = detect(
            &bead("in_progress", SIXTY_DAYS_AGO),
            Some(&live()),
            None,
            ProviderState::Answering,
            false,
            &narrow,
            now(),
        );
        assert_eq!(got, vec![Anomaly::StaleClaim { days: 60 }]);
    }

    #[test]
    fn a_claim_bd_gives_no_update_time_for_has_no_age_to_judge() {
        let mut b = bead("in_progress", SIXTY_DAYS_AGO);
        b.updated_at = None;

        let got = detect(
            &b,
            Some(&live()),
            None,
            ProviderState::Answering,
            false,
            &Anomalies::default(),
            now(),
        );
        assert_eq!(got, Vec::new());
    }

    // ---- the statuses that hold no claim --------------------------------

    #[test]
    fn a_blocked_bead_with_a_live_pane_is_never_flagged() {
        let got = detect(
            &bead("blocked", SIXTY_DAYS_AGO),
            Some(&live()),
            None,
            ProviderState::Answering,
            false,
            &Anomalies::default(),
            now(),
        );
        assert_eq!(got, Vec::new(), "an agent parked on blocked work is normal");
    }

    #[test]
    fn a_blocked_bead_with_no_pane_is_never_flagged() {
        let got = detect(
            &bead("blocked", SIXTY_DAYS_AGO),
            None,
            None,
            ProviderState::Answering,
            false,
            &Anomalies::default(),
            now(),
        );
        assert_eq!(got, Vec::new());
    }

    #[test]
    fn an_open_bead_is_never_flagged() {
        let got = detect(
            &bead("open", SIXTY_DAYS_AGO),
            None,
            None,
            ProviderState::Answering,
            false,
            &Anomalies::default(),
            now(),
        );
        assert_eq!(got, Vec::new());
    }

    #[test]
    fn a_deferred_bead_is_never_flagged() {
        let got = detect(
            &bead("deferred", SIXTY_DAYS_AGO),
            Some(&live()),
            None,
            ProviderState::Answering,
            false,
            &Anomalies::default(),
            now(),
        );
        assert_eq!(got, Vec::new());
    }

    // ---- the wire ------------------------------------------------------

    #[test]
    fn the_rules_serialise_under_the_names_the_contract_publishes() {
        let json = serde_json::to_string(&vec![
            Anomaly::StalePane,
            orphan(),
            Anomaly::StaleClaim { days: 60 },
        ])
        .expect("the anomalies serialise");

        assert_eq!(
            json,
            r#"[{"rule":"stale-pane"},{"rule":"orphan-claim"},{"rule":"stale-claim","days":60}]"#
        );
    }
}