klieo-ops 3.3.0

Operational layer above klieo-core: supervisor, governor, gates, escalation, worklog, handoff.
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
//! KV-backed WorkLog impl. KV is the single source of truth for items,
//! adjacency, and status indexes — enabling correct multi-process operation
//! (spec § 1.10). No in-process DashMap cache; every read goes to KV.
//!
//! Bucket layout:
//! - `ops.worklog.items/<id>`          — JSON-serialised `WorkItem`
//! - `ops.worklog.parents/<id>`        — JSON-encoded `HashSet<WorkId>`
//! - `ops.worklog.children/<id>`       — JSON-encoded `HashSet<WorkId>`
//! - `ops.worklog.status/<status_key>` — JSON-encoded `HashSet<WorkId>`
//! - `ops.worklog.meta/count`          — u64 item count (CAS-maintained)
//!
//! Status-index buckets (one per `WorkStatus` variant) enable correct
//! `ready()` and `list_by_status()` without a KV listing primitive.
//! Each transition updates the old-status index (remove id) and the
//! new-status index (add id) via CAS-retry (up to 5 attempts with backoff).
//!
//! `dag()` performs BFS over parents/children via KV reads. Cycle
//! detection in `would_cycle()` does the same upward BFS from `on`.
//! Dependencies satisfied check reads each parent's item status from KV.
//!
//! Phase B M7 cap-enforcement reads the count key; the count is
//! incremented on `plan` and never decremented (items are not deleted in
//! this phase — orphan TTL is operator-cron territory per design spec § 2.5).

use super::trait_::{WorkDag, WorkId, WorkItem, WorkLog, WorkLogError, WorkStatus};
use crate::audit::OpsAuditSink;
use crate::ops_event::OpsEvent;
use async_trait::async_trait;
use bytes::Bytes;
use chrono::Utc;
use futures::future::try_join_all;
use futures::stream;
use futures_core::stream::BoxStream;
use klieo_core::error::BusError;
use klieo_core::ids::RunId;
use klieo_core::memory::EpisodicMemory;
use klieo_core::KvStore;
use std::collections::{HashSet, VecDeque};
use std::sync::Arc;
use tokio::sync::broadcast;
use tokio_stream::wrappers::BroadcastStream;
use tokio_stream::StreamExt;
use ulid::Ulid;

const BUCKET_ITEMS: &str = "ops.worklog.items";
const BUCKET_PARENTS: &str = "ops.worklog.parents";
const BUCKET_CHILDREN: &str = "ops.worklog.children";
const BUCKET_STATUS: &str = "ops.worklog.status";
const BUCKET_META: &str = "ops.worklog.meta";

const META_COUNT_KEY: &str = "count";
const CAS_MAX_RETRIES: u32 = 5;
const DEFAULT_MAX_ITEMS: usize = 10_000;
/// Number of shards for the status-index hot keys. Each status variant is
/// distributed across `STATUS_INDEX_SHARDS` KV keys instead of one, so
/// concurrent transitions to the same status do not contend on a single CAS
/// key. `list_by_status` reads all shards (16 reads) and unions the results.
const STATUS_INDEX_SHARDS: usize = 16;

/// KV-backed worklog. All state lives in KV; correct across processes
/// sharing the same `Arc<dyn KvStore>`.
pub struct KvWorkLog {
    kv: Arc<dyn KvStore>,
    cap: usize,
    ready_tx: broadcast::Sender<WorkId>,
    audit: Option<OpsAuditSink>,
}

// ── Construction ────────────────────────────────────────────────────────────

impl KvWorkLog {
    /// Build with the default 10 000-item cap.
    #[must_use]
    pub fn new(kv: Arc<dyn KvStore>) -> Self {
        Self::with_cap(kv, DEFAULT_MAX_ITEMS)
    }

    /// Build with a custom DAG size cap.
    #[must_use]
    pub fn with_cap(kv: Arc<dyn KvStore>, cap: usize) -> Self {
        let (tx, _rx) = broadcast::channel(1024);
        Self {
            kv,
            cap,
            ready_tx: tx,
            audit: None,
        }
    }

    /// Wire an audit sink.
    #[must_use]
    pub fn with_audit(mut self, episodic: Arc<dyn EpisodicMemory>, run_id: RunId) -> Self {
        self.audit = Some(OpsAuditSink::new(
            episodic,
            run_id,
            "klieo.ops.worklog.audit",
        ));
        self
    }
}

// ── Internal helpers — KV reads ──────────────────────────────────────────────

impl KvWorkLog {
    async fn fetch_item(&self, id: &WorkId) -> Result<Option<WorkItem>, WorkLogError> {
        let entry = self
            .kv
            .get(BUCKET_ITEMS, &id.0)
            .await
            .map_err(|e| WorkLogError::Storage {
                message: e.to_string(),
                source: Some(Box::new(e)),
            })?;
        match entry {
            None => Ok(None),
            Some(e) => {
                let item = serde_json::from_slice::<WorkItem>(&e.value)
                    .map_err(|e| WorkLogError::Internal(format!("deserialise item: {e}")))?;
                Ok(Some(item))
            }
        }
    }

    async fn require_item(&self, id: &WorkId) -> Result<WorkItem, WorkLogError> {
        self.fetch_item(id)
            .await?
            .ok_or_else(|| WorkLogError::UnknownWorkItem(id.clone()))
    }

    /// So a caller can CAS-write the item back conditioned on the revision
    /// being unchanged since this read.
    async fn fetch_item_with_rev(
        &self,
        id: &WorkId,
    ) -> Result<Option<(WorkItem, u64)>, WorkLogError> {
        let entry = self
            .kv
            .get(BUCKET_ITEMS, &id.0)
            .await
            .map_err(|e| WorkLogError::Storage {
                message: e.to_string(),
                source: Some(Box::new(e)),
            })?;
        match entry {
            None => Ok(None),
            Some(e) => {
                let item = serde_json::from_slice::<WorkItem>(&e.value)
                    .map_err(|e| WorkLogError::Internal(format!("deserialise item: {e}")))?;
                Ok(Some((item, e.revision)))
            }
        }
    }

    async fn fetch_id_set(
        &self,
        bucket: &str,
        key: &str,
    ) -> Result<(HashSet<WorkId>, Option<u64>), WorkLogError> {
        let entry = self
            .kv
            .get(bucket, key)
            .await
            .map_err(|e| WorkLogError::Storage {
                message: e.to_string(),
                source: Some(Box::new(e)),
            })?;
        match entry {
            None => Ok((HashSet::new(), None)),
            Some(e) => {
                let set = serde_json::from_slice::<HashSet<WorkId>>(&e.value)
                    .map_err(|e| WorkLogError::Internal(format!("deserialise id set: {e}")))?;
                Ok((set, Some(e.revision)))
            }
        }
    }

    async fn fetch_parents(&self, id: &WorkId) -> Result<HashSet<WorkId>, WorkLogError> {
        let (set, _) = self.fetch_id_set(BUCKET_PARENTS, &id.0).await?;
        Ok(set)
    }

    async fn fetch_children(&self, id: &WorkId) -> Result<HashSet<WorkId>, WorkLogError> {
        let (set, _) = self.fetch_id_set(BUCKET_CHILDREN, &id.0).await?;
        Ok(set)
    }

    /// Read all shards for `status` and union the id sets. The returned
    /// revision is `None` because it spans multiple KV keys; callers that
    /// need per-shard CAS use `fetch_status_shard` directly.
    async fn fetch_status_index(
        &self,
        status: WorkStatus,
    ) -> Result<(HashSet<WorkId>, Option<u64>), WorkLogError> {
        let shard_reads: Vec<_> = (0..STATUS_INDEX_SHARDS)
            .map(|i| {
                let key = status_shard_key(status, i);
                async move { self.fetch_id_set(BUCKET_STATUS, &key).await }
            })
            .collect();
        let shards = try_join_all(shard_reads).await?;
        let union = shards
            .into_iter()
            .flat_map(|(set, _)| set)
            .collect::<HashSet<WorkId>>();
        Ok((union, None))
    }

    /// Short-circuit variant of [`fetch_status_index`]: fetches shard indexes
    /// sequentially in batches of 4 (via `buffer_unordered`) and stops once the
    /// collected unique-id count reaches `limit`. Avoids the full 16-read fan-out
    /// when the caller only needs a bounded sample (e.g. the `ready()` poll).
    async fn fetch_status_index_bounded(
        &self,
        status: WorkStatus,
        limit: usize,
    ) -> Result<HashSet<WorkId>, WorkLogError> {
        const CONCURRENCY: usize = 4;
        let mut collected: HashSet<WorkId> = HashSet::new();

        // Use UFCS to avoid ambiguity with tokio_stream::StreamExt which is
        // also in scope via tokio_stream imports elsewhere in the file.
        let raw = futures::StreamExt::map(stream::iter(0..STATUS_INDEX_SHARDS), |i| {
            let key = status_shard_key(status, i);
            async move { self.fetch_id_set(BUCKET_STATUS, &key).await }
        });
        let mut shard_stream = futures::StreamExt::buffer_unordered(raw, CONCURRENCY);

        while let Some(result) = futures::StreamExt::next(&mut shard_stream).await {
            let (shard_ids, _) = result?;
            collected.extend(shard_ids);
            if collected.len() >= limit {
                break;
            }
        }
        Ok(collected)
    }

    async fn fetch_item_count(&self) -> Result<(usize, Option<u64>), WorkLogError> {
        let entry = self
            .kv
            .get(BUCKET_META, META_COUNT_KEY)
            .await
            .map_err(|e| WorkLogError::Storage {
                message: e.to_string(),
                source: Some(Box::new(e)),
            })?;
        match entry {
            None => Ok((0, None)),
            Some(e) => {
                let n = serde_json::from_slice::<u64>(&e.value)
                    .map_err(|e| WorkLogError::Internal(format!("deserialise count: {e}")))?;
                Ok((n as usize, Some(e.revision)))
            }
        }
    }
}

// ── Internal helpers — KV writes ─────────────────────────────────────────────

impl KvWorkLog {
    async fn persist_item(&self, item: &WorkItem) -> Result<(), WorkLogError> {
        let body = serde_json::to_vec(item)
            .map_err(|e| WorkLogError::Internal(format!("serialise item: {e}")))?;
        self.kv
            .put(BUCKET_ITEMS, &item.id.0, Bytes::from(body))
            .await
            .map(|_| ())
            .map_err(|e| WorkLogError::Storage {
                message: e.to_string(),
                source: Some(Box::new(e)),
            })
    }

    /// CAS-retry: add `id` to the set stored at `(bucket, key)`.
    async fn cas_add_to_set(
        &self,
        bucket: &str,
        key: &str,
        id: WorkId,
    ) -> Result<(), WorkLogError> {
        for attempt in 0..CAS_MAX_RETRIES {
            let (mut set, rev) = self.fetch_id_set(bucket, key).await?;
            set.insert(id.clone());
            let encoded = encode_id_set(&set)?;
            match self.kv.cas(bucket, key, encoded, rev).await {
                Ok(_) => return Ok(()),
                Err(BusError::CasConflict { .. }) => {
                    if attempt + 1 < CAS_MAX_RETRIES {
                        backoff_delay(attempt).await;
                        continue;
                    }
                    return Err(WorkLogError::Storage {
                        message: "cas_add_to_set: too many CAS conflicts".into(),
                        source: None,
                    });
                }
                Err(e) => {
                    return Err(WorkLogError::Storage {
                        message: e.to_string(),
                        source: Some(Box::new(e)),
                    })
                }
            }
        }
        unreachable!()
    }

    /// CAS-retry: remove `id` from the set stored at `(bucket, key)`.
    async fn cas_remove_from_set(
        &self,
        bucket: &str,
        key: &str,
        id: &WorkId,
    ) -> Result<(), WorkLogError> {
        for attempt in 0..CAS_MAX_RETRIES {
            let (mut set, rev) = self.fetch_id_set(bucket, key).await?;
            if !set.remove(id) {
                // Already absent — idempotent success.
                return Ok(());
            }
            let encoded = encode_id_set(&set)?;
            match self.kv.cas(bucket, key, encoded, rev).await {
                Ok(_) => return Ok(()),
                Err(BusError::CasConflict { .. }) => {
                    if attempt + 1 < CAS_MAX_RETRIES {
                        backoff_delay(attempt).await;
                        continue;
                    }
                    return Err(WorkLogError::Storage {
                        message: "cas_remove_from_set: too many CAS conflicts".into(),
                        source: None,
                    });
                }
                Err(e) => {
                    return Err(WorkLogError::Storage {
                        message: e.to_string(),
                        source: Some(Box::new(e)),
                    })
                }
            }
        }
        unreachable!()
    }

    /// CAS-retry increment of the item count. Returns the new count.
    async fn cas_increment_count(&self) -> Result<usize, WorkLogError> {
        for attempt in 0..CAS_MAX_RETRIES {
            let (current, rev) = self.fetch_item_count().await?;
            let next = current + 1;
            let encoded = serde_json::to_vec(&(next as u64))
                .map_err(|e| WorkLogError::Internal(format!("serialise count: {e}")))?;
            match self
                .kv
                .cas(BUCKET_META, META_COUNT_KEY, Bytes::from(encoded), rev)
                .await
            {
                Ok(_) => return Ok(next),
                Err(BusError::CasConflict { .. }) => {
                    if attempt + 1 < CAS_MAX_RETRIES {
                        backoff_delay(attempt).await;
                        continue;
                    }
                    return Err(WorkLogError::Storage {
                        message: "cas_increment_count: too many CAS conflicts".into(),
                        source: None,
                    });
                }
                Err(e) => {
                    return Err(WorkLogError::Storage {
                        message: e.to_string(),
                        source: Some(Box::new(e)),
                    })
                }
            }
        }
        unreachable!()
    }

    /// Move `id` from the old-status shard to the new-status shard in KV.
    /// Each id is consistently mapped to one shard by `shard_for_id` so
    /// the item lands in and is removed from the same shard on every call.
    async fn update_status_index(
        &self,
        id: &WorkId,
        from: WorkStatus,
        to: WorkStatus,
    ) -> Result<(), WorkLogError> {
        if from == to {
            return Ok(());
        }
        let shard = shard_for_id(id);
        let from_key = status_shard_key(from, shard);
        let to_key = status_shard_key(to, shard);
        let remove = self.cas_remove_from_set(BUCKET_STATUS, &from_key, id);
        let add = self.cas_add_to_set(BUCKET_STATUS, &to_key, id.clone());
        // Independent shards — run concurrently.
        let (r, a) = tokio::join!(remove, add);
        r?;
        a
    }

    async fn emit(&self, event: OpsEvent) {
        if let Some(sink) = &self.audit {
            sink.emit(event).await;
        }
    }

    fn announce_ready(&self, id: WorkId) {
        if let Err(err) = self.ready_tx.send(id) {
            tracing::debug!(
                target: "klieo.ops.worklog",
                work_id = %err.0,
                "ready-stream has no live receivers; dropping notification"
            );
        }
    }
}

// ── Cross-process graph algorithms ───────────────────────────────────────────

impl KvWorkLog {
    /// BFS upward from `on` along KV-stored parents; returns true if `child`
    /// is reachable (which would form a cycle).
    async fn would_cycle(&self, child: &WorkId, on: &WorkId) -> Result<bool, WorkLogError> {
        let mut queue: VecDeque<WorkId> = VecDeque::new();
        let mut visited: HashSet<WorkId> = HashSet::new();
        queue.push_back(on.clone());
        while let Some(node) = queue.pop_front() {
            if &node == child {
                return Ok(true);
            }
            if !visited.insert(node.clone()) {
                continue;
            }
            for parent in self.fetch_parents(&node).await? {
                queue.push_back(parent);
            }
        }
        Ok(false)
    }

    /// Returns true when all parents of `id` are in status `Done` per KV.
    async fn dependencies_satisfied(&self, id: &WorkId) -> Result<bool, WorkLogError> {
        let parents = self.fetch_parents(id).await?;
        for parent_id in &parents {
            match self.fetch_item(parent_id).await? {
                Some(item) if item.status == WorkStatus::Done => continue,
                _ => return Ok(false),
            }
        }
        Ok(true)
    }
}

// ── WorkLog impl ─────────────────────────────────────────────────────────────

#[async_trait]
impl WorkLog for KvWorkLog {
    async fn plan(&self, mut item: WorkItem) -> Result<WorkId, WorkLogError> {
        // Cap check via KV count (cross-process correct).
        let count = self.fetch_item_count().await?.0;
        if count >= self.cap {
            return Err(WorkLogError::CapExceeded { cap: self.cap });
        }

        let id = WorkId(format!("wrk_{}", Ulid::new()));
        item.id = id.clone();
        item.last_transition_at = Utc::now().to_rfc3339();

        let initial_deps = std::mem::take(&mut item.depends_on);

        for parent in &initial_deps {
            if self.fetch_item(parent).await?.is_none() {
                return Err(WorkLogError::UnknownWorkItem(parent.clone()));
            }
        }

        // A freshly-minted id cannot appear in any existing parent chain,
        // so we skip cycle-checking for initial deps.
        item.status = if initial_deps.is_empty() {
            WorkStatus::Ready
        } else {
            WorkStatus::Planned
        };

        // Persist item first so other processes can see it immediately.
        self.persist_item(&item).await?;
        self.cas_increment_count().await?;

        let edge_futures: Vec<_> = initial_deps
            .iter()
            .map(|parent| {
                let parent_id = parent.clone();
                let child_id = id.clone();
                async move {
                    let add_parent =
                        self.cas_add_to_set(BUCKET_PARENTS, &child_id.0, parent_id.clone());
                    let add_child =
                        self.cas_add_to_set(BUCKET_CHILDREN, &parent_id.0, child_id.clone());
                    let (r1, r2) = tokio::join!(add_parent, add_child);
                    r1?;
                    r2
                }
            })
            .collect();
        for fut in edge_futures {
            fut.await?;
        }

        let shard = shard_for_id(&id);
        self.cas_add_to_set(
            BUCKET_STATUS,
            &status_shard_key(item.status, shard),
            id.clone(),
        )
        .await?;

        self.emit(OpsEvent::WorkPlanned {
            tenant: item.tenant.clone(),
            work_id: id.0.clone(),
            title: item.title.clone(),
            depends_on: initial_deps.iter().map(|p| p.0.clone()).collect(),
        })
        .await;

        if item.status == WorkStatus::Ready {
            self.announce_ready(id.clone());
        }
        Ok(id)
    }

    async fn depend(&self, child: WorkId, on: WorkId) -> Result<(), WorkLogError> {
        if self.fetch_item(&child).await?.is_none() {
            return Err(WorkLogError::UnknownWorkItem(child));
        }
        if self.fetch_item(&on).await?.is_none() {
            return Err(WorkLogError::UnknownWorkItem(on));
        }
        if self.would_cycle(&child, &on).await? {
            return Err(WorkLogError::CycleDetected { child, on });
        }
        let add_parent = self.cas_add_to_set(BUCKET_PARENTS, &child.0, on.clone());
        let add_child = self.cas_add_to_set(BUCKET_CHILDREN, &on.0, child.clone());
        let (r1, r2) = tokio::join!(add_parent, add_child);
        r1?;
        r2?;

        let tenant = self
            .fetch_item(&child)
            .await?
            .and_then(|i| i.tenant.clone());
        self.emit(OpsEvent::WorkDependencyAdded {
            tenant,
            child: child.0,
            on: on.0,
        })
        .await;
        Ok(())
    }

    async fn ready(&self, limit: usize) -> Vec<WorkId> {
        // Use the bounded variant to short-circuit once enough ids are
        // collected; avoids the full 16-shard fan-out when limit is small.
        match self
            .fetch_status_index_bounded(WorkStatus::Ready, limit)
            .await
        {
            Ok(set) => set.into_iter().take(limit).collect(),
            Err(e) => {
                tracing::warn!(target: "klieo.ops.worklog", error = %e, "ready() index read failed");
                vec![]
            }
        }
    }

    async fn ready_stream(&self) -> BoxStream<'static, WorkId> {
        let rx = self.ready_tx.subscribe();
        let stream = BroadcastStream::new(rx).filter_map(|r| r.ok());
        Box::pin(stream)
    }

    async fn dispatch(&self, id: WorkId) -> Result<(), WorkLogError> {
        let item = self.require_item(&id).await?;
        if item.status != WorkStatus::Ready {
            return Err(WorkLogError::Internal(format!(
                "cannot dispatch item in status {:?}",
                item.status
            )));
        }
        let mut updated = item.clone();
        updated.status = WorkStatus::InProgress;
        updated.last_transition_at = Utc::now().to_rfc3339();
        self.persist_item(&updated).await?;
        self.update_status_index(&id, WorkStatus::Ready, WorkStatus::InProgress)
            .await?;
        self.emit(OpsEvent::WorkDispatched {
            tenant: updated.tenant.clone(),
            work_id: id.0,
        })
        .await;
        Ok(())
    }

    async fn transition(&self, id: WorkId, status: WorkStatus) -> Result<(), WorkLogError> {
        let item = self.require_item(&id).await?;
        if item.status.is_terminal() && item.status != status {
            return Err(WorkLogError::Internal(format!(
                "cannot transition from terminal status {:?} to {:?}",
                item.status, status
            )));
        }
        let prev_status = item.status;
        let mut updated = item;
        updated.status = status;
        updated.last_transition_at = Utc::now().to_rfc3339();
        self.persist_item(&updated).await?;
        self.update_status_index(&id, prev_status, status).await?;

        self.emit(OpsEvent::WorkTransition {
            tenant: updated.tenant.clone(),
            work_id: id.0.clone(),
            from: format!("{prev_status:?}").to_lowercase(),
            to: format!("{status:?}").to_lowercase(),
            reason: None,
        })
        .await;

        if status == WorkStatus::Done {
            self.cascade_ready_children(&id).await?;
        }
        Ok(())
    }

    async fn transition_if_status(
        &self,
        id: WorkId,
        from: WorkStatus,
        to: WorkStatus,
    ) -> Result<bool, WorkLogError> {
        let (item, rev) = match self.fetch_item_with_rev(&id).await? {
            Some(pair) => pair,
            None => return Err(WorkLogError::UnknownWorkItem(id)),
        };
        // A concurrent actor already moved it off `from` and won the race.
        if item.status != from {
            return Ok(false);
        }
        if item.status.is_terminal() && item.status != to {
            return Err(WorkLogError::Internal(format!(
                "cannot transition from terminal status {:?} to {:?}",
                item.status, to
            )));
        }

        let mut updated = item;
        updated.status = to;
        updated.last_transition_at = Utc::now().to_rfc3339();
        let body = serde_json::to_vec(&updated)
            .map_err(|e| WorkLogError::Internal(format!("serialise item: {e}")))?;

        // CAS the item write on the revision read above: if anyone else wrote
        // the item between the read and here, the revision moved and we lose the
        // race rather than clobbering their transition.
        match self
            .kv
            .cas(BUCKET_ITEMS, &id.0, Bytes::from(body), Some(rev))
            .await
        {
            Ok(_) => {}
            Err(BusError::CasConflict { .. }) => return Ok(false),
            Err(e) => {
                return Err(WorkLogError::Storage {
                    message: e.to_string(),
                    source: Some(Box::new(e)),
                })
            }
        }
        self.update_status_index(&id, from, to).await?;

        self.emit(OpsEvent::WorkTransition {
            tenant: updated.tenant.clone(),
            work_id: id.0.clone(),
            from: format!("{from:?}").to_lowercase(),
            to: format!("{to:?}").to_lowercase(),
            reason: None,
        })
        .await;

        if to == WorkStatus::Done {
            self.cascade_ready_children(&id).await?;
        }
        Ok(true)
    }

    async fn get(&self, id: WorkId) -> Option<WorkItem> {
        match self.fetch_item(&id).await {
            Ok(opt) => opt,
            Err(err) => {
                tracing::warn!(
                    target: "klieo.ops.worklog",
                    work_id = %id.0,
                    error = %err,
                    "WorkLog::get fetch failed; returning None which is indistinguishable from missing"
                );
                None
            }
        }
    }

    async fn list_by_status(&self, filter: WorkStatus, limit: usize) -> Vec<WorkItem> {
        let ids = match self.fetch_status_index(filter).await {
            Ok((set, _)) => set,
            Err(e) => {
                tracing::warn!(target: "klieo.ops.worklog", error = %e, "list_by_status index read failed");
                return vec![];
            }
        };
        let fetches: Vec<_> = ids
            .into_iter()
            .take(limit)
            .map(|id| async move { self.fetch_item(&id).await })
            .collect();
        let results = match try_join_all(fetches).await {
            Ok(items) => items,
            Err(err) => {
                tracing::warn!(
                    target: "klieo.ops.worklog",
                    error = %err,
                    "list_by_status fetch_item failed; returning partial results"
                );
                return Vec::new();
            }
        };
        results.into_iter().flatten().collect()
    }

    async fn dag(&self, root: WorkId) -> WorkDag {
        let mut visited: HashSet<WorkId> = HashSet::new();
        let mut queue: VecDeque<WorkId> = VecDeque::new();
        queue.push_back(root);
        let mut out: Vec<WorkItem> = Vec::new();
        while let Some(node) = queue.pop_front() {
            if !visited.insert(node.clone()) {
                continue;
            }
            match self.fetch_item(&node).await {
                Ok(Some(item)) => out.push(item),
                Ok(None) => {}
                Err(e) => {
                    tracing::warn!(target: "klieo.ops.worklog", error = %e, "dag fetch failed");
                }
            }
            match self.fetch_children(&node).await {
                Ok(children) => {
                    for c in children {
                        queue.push_back(c);
                    }
                }
                Err(e) => {
                    tracing::warn!(target: "klieo.ops.worklog", error = %e, "dag children fetch failed")
                }
            }
            match self.fetch_parents(&node).await {
                Ok(parents) => {
                    for p in parents {
                        queue.push_back(p);
                    }
                }
                Err(e) => {
                    tracing::warn!(target: "klieo.ops.worklog", error = %e, "dag parents fetch failed")
                }
            }
        }
        WorkDag { items: out }
    }
}

// ── Cascade helper ────────────────────────────────────────────────────────────

impl KvWorkLog {
    /// When an item transitions to Done, check each child: if all its parents
    /// are Done, promote it from Planned → Ready and persist + announce.
    async fn cascade_ready_children(&self, done_id: &WorkId) -> Result<(), WorkLogError> {
        let children = self.fetch_children(done_id).await?;
        let mut newly_ready: Vec<WorkItem> = Vec::new();

        for child_id in children {
            let child = match self.fetch_item(&child_id).await? {
                Some(c) if c.status == WorkStatus::Planned => c,
                _ => continue,
            };
            if self.dependencies_satisfied(&child_id).await? {
                let mut updated = child;
                updated.status = WorkStatus::Ready;
                updated.last_transition_at = Utc::now().to_rfc3339();
                newly_ready.push(updated);
            }
        }

        // Persist all newly-ready items concurrently.
        let persists = newly_ready.iter().map(|snap| self.persist_item(snap));
        try_join_all(persists).await?;

        // Update status indexes concurrently.
        let index_updates = newly_ready
            .iter()
            .map(|snap| self.update_status_index(&snap.id, WorkStatus::Planned, WorkStatus::Ready));
        try_join_all(index_updates).await?;

        for snap in &newly_ready {
            self.announce_ready(snap.id.clone());
        }
        Ok(())
    }
}

// ── Utility fns ───────────────────────────────────────────────────────────────

/// Return the status prefix string for a given `WorkStatus` variant.
fn status_prefix(status: WorkStatus) -> &'static str {
    match status {
        WorkStatus::Planned => "planned",
        WorkStatus::Ready => "ready",
        WorkStatus::InProgress => "in_progress",
        WorkStatus::Done => "done",
        WorkStatus::Failed => "failed",
        WorkStatus::AwaitingApproval => "awaiting_approval",
        WorkStatus::Cancelled => "cancelled",
    }
}

/// Compute the shard index for a `WorkId` by hashing its string representation
/// modulo [`STATUS_INDEX_SHARDS`].
///
/// ## Stability contract
///
/// `SipHasher13` with fixed keys guarantees the same shard assignment across
/// Rust releases. `std::collections::hash_map::DefaultHasher` explicitly
/// provides no such guarantee (stdlib docs: "should not be relied upon over
/// releases"). The keys below are chosen to be human-readable in hex dumps:
///
/// - `k0 = 0x4b6c_6965_6f31_3300` — ASCII "klieo13\0"
/// - `k1 = 0x7368_6172_645f_6964` — ASCII "shard_id"
///
/// **Do not change these constants.** Doing so silently re-shards every
/// persisted `WorkId`, causing items to be visible in the wrong shard and
/// breaking `ready()` / `list_by_status()` on existing KV state.
fn shard_for_id(id: &WorkId) -> usize {
    use std::hash::{Hash, Hasher};
    let mut hasher = siphasher::sip::SipHasher13::new_with_keys(
        0x4b6c_6965_6f31_3300, // "klieo13\0" — readable in hex dumps
        0x7368_6172_645f_6964, // "shard_id"
    );
    id.0.hash(&mut hasher);
    (hasher.finish() % STATUS_INDEX_SHARDS as u64) as usize
}

/// Build the sharded KV key for a status index entry:
/// `<status_prefix>/shard_<N>`.
fn status_shard_key(status: WorkStatus, shard: usize) -> String {
    format!("{}/shard_{shard}", status_prefix(status))
}

fn encode_id_set(set: &HashSet<WorkId>) -> Result<Bytes, WorkLogError> {
    let body = serde_json::to_vec(set)
        .map_err(|e| WorkLogError::Internal(format!("serialise id set: {e}")))?;
    Ok(Bytes::from(body))
}

async fn backoff_delay(attempt: u32) {
    let ms = 5u64 * (1 << attempt.min(6));
    tokio::time::sleep(std::time::Duration::from_millis(ms)).await;
}

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

    use klieo_bus_memory::MemoryBus;
    use klieo_core::{KvEntry, Lease, Revision};
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::time::Duration;

    fn stale_item(title: &str) -> WorkItem {
        WorkItem::new(title, serde_json::json!({}), None, vec![])
    }

    /// `transition_if_status` from a terminal status to a different status is a
    /// rejected transition.
    #[tokio::test]
    async fn transition_if_status_rejects_terminal_from() {
        let bus = MemoryBus::new();
        let wl = KvWorkLog::new(bus.kv.clone());
        let id = wl.plan(stale_item("done")).await.expect("plan");
        wl.transition(id.clone(), WorkStatus::Done)
            .await
            .expect("to done");

        let err = wl
            .transition_if_status(id, WorkStatus::Done, WorkStatus::Ready)
            .await
            .expect_err("terminal -> Ready must be rejected");
        assert!(matches!(err, WorkLogError::Internal(_)), "got {err:?}");
    }

    /// `transition_if_status` on an unknown id is `UnknownWorkItem`, not a
    /// silent `Ok(false)`.
    #[tokio::test]
    async fn transition_if_status_unknown_item_errors() {
        let bus = MemoryBus::new();
        let wl = KvWorkLog::new(bus.kv.clone());
        let err = wl
            .transition_if_status(
                WorkId("nope".into()),
                WorkStatus::InProgress,
                WorkStatus::Ready,
            )
            .await
            .expect_err("unknown id must error");
        assert!(
            matches!(err, WorkLogError::UnknownWorkItem(_)),
            "got {err:?}"
        );
    }

    /// Wraps a `KvStore`, injecting exactly one `CasConflict` on the next `cas`
    /// to the items bucket — simulating a concurrent writer landing between a
    /// `transition_if_status` read and its CAS write.
    struct CasConflictOnceKv {
        inner: Arc<dyn KvStore>,
        armed: AtomicBool,
    }

    #[async_trait]
    impl KvStore for CasConflictOnceKv {
        async fn get(&self, bucket: &str, key: &str) -> Result<Option<KvEntry>, BusError> {
            self.inner.get(bucket, key).await
        }
        async fn put(&self, bucket: &str, key: &str, value: Bytes) -> Result<Revision, BusError> {
            self.inner.put(bucket, key, value).await
        }
        async fn cas(
            &self,
            bucket: &str,
            key: &str,
            value: Bytes,
            expected: Option<Revision>,
        ) -> Result<Revision, BusError> {
            if bucket == BUCKET_ITEMS && self.armed.swap(false, Ordering::SeqCst) {
                return Err(BusError::CasConflict {
                    expected: expected.unwrap_or(0),
                    actual: expected.unwrap_or(0) + 1,
                });
            }
            self.inner.cas(bucket, key, value, expected).await
        }
        async fn delete(&self, bucket: &str, key: &str) -> Result<(), BusError> {
            self.inner.delete(bucket, key).await
        }
        async fn lease(&self, bucket: &str, key: &str, ttl: Duration) -> Result<Lease, BusError> {
            self.inner.lease(bucket, key, ttl).await
        }
        async fn keys(&self, bucket: &str) -> Result<Vec<String>, BusError> {
            self.inner.keys(bucket).await
        }
    }

    /// When the item write loses the CAS race (revision moved between read and
    /// write), `transition_if_status` returns `Ok(false)` — no double-dispatch.
    #[tokio::test]
    async fn transition_if_status_returns_false_on_cas_conflict() {
        let bus = MemoryBus::new();
        // Seed the item via the plain bus so plan's writes succeed un-trapped.
        let wl_seed = KvWorkLog::new(bus.kv.clone());
        let id = wl_seed.plan(stale_item("contended")).await.expect("plan");
        wl_seed.dispatch(id.clone()).await.expect("dispatch"); // -> InProgress

        let trap = Arc::new(CasConflictOnceKv {
            inner: bus.kv.clone(),
            armed: AtomicBool::new(true),
        });
        let wl = KvWorkLog::new(trap);

        let applied = wl
            .transition_if_status(id.clone(), WorkStatus::InProgress, WorkStatus::Ready)
            .await
            .expect("cas conflict is Ok(false), not Err");
        assert!(!applied, "a lost CAS race must not transition the item");
        // Status is unchanged — still InProgress.
        assert_eq!(
            wl_seed.get(id).await.unwrap().status,
            WorkStatus::InProgress
        );
    }

    /// Shard distribution sanity: 1000 synthetic WorkIds must hit at least
    /// 12 of 16 shards, confirming the SipHasher13 keys produce a reasonably
    /// uniform distribution across the shard space.
    #[test]
    fn shard_distribution_covers_at_least_12_of_16() {
        let mut hit_shards = std::collections::HashSet::new();
        for i in 0..1000usize {
            let id = WorkId(format!("wrk_{i}"));
            hit_shards.insert(shard_for_id(&id));
        }
        assert!(
            hit_shards.len() >= 12,
            "expected >= 12 shards hit out of 16; got {} — hash distribution may be degenerate",
            hit_shards.len()
        );
    }
}