lean-ctx-cloud 3.12.12

The LeanCTX connector: enrollment, bus, knowledge sync, tasks and policy on top of LeanCTX | OSS.
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
// SPDX-License-Identifier: Apache-2.0
//! One engine-metrics pass: sharing state, gate, sample, build, buffer,
//! sign, send (`POST /v1/metrics/hours`), plus the local views (`cloud
//! status`, `cloud metrics preview`, `cloud metrics delete`) and the
//! person's confirmation (`cloud metrics confirm`).
//!
//! **Release switch (owner sequencing).** Until the lead's go after the
//! privacy block K1–K6, nothing is collected or sent to a real Cloud:
//! [`released`] is false except for a loopback Cloud (the fake wire of the
//! tests) with `LEAN_CTX_CLOUD_ENGINE_METRICS=fake-wire`. The preview and the
//! status work regardless; they never send.

use std::path::Path;

use ed25519_dalek::Signer as _;
use lean_ctx_time::{Duration, OffsetDateTime, UtcDateTime};

use super::buffer::{self, Buffer, Item, Refusal, State};
use super::collect::{self, Scope, Sources};
use super::gate::{self, OffReason, Sharing};
use crate::CloudError;
use crate::auth::Session;
use crate::config::CloudConfig;
use crate::instance_key::InstanceKeys;
use crate::state::{CloudStore, InstanceRecord};
use crate::vault::VaultMap;
use lean_ctx_protocol::cloud::lease::CloudLeaseV1;
use lean_ctx_protocol::cloud::metrics_v2::{
    BucketV2, EngineOs, EngineV2, EngineVersion, HOURS_ROUTE, HourStamp, HoursAckV2, HoursBodyV2,
    HoursRequestV2, HoursSchema, KeyId, MAX_BUCKETS, MAX_HOURS_BODY_BYTES, PolicyLevel,
    SHARING_CONFIRM_ROUTE, SHARING_ROUTE, SharingStateV2, SharingValue, SignatureHex,
};

/// Whether instance metrics (and receipts v2) are released for real sends:
/// owner go 03.11.2026 for 3.12.1. Sharing stays consent-gated.
const RELEASED: bool = true;
/// Test switch: only a loopback Cloud may receive before the release.
pub const TEST_SWITCH_ENV: &str = "LEAN_CTX_CLOUD_ENGINE_METRICS";
/// Days the first period may reach back (and never before `since`).
const BACKFILL_DAYS: i64 = 30;
/// Minimum seconds between two regular passes.
const DEBOUNCE_SECS: i64 = 3_600;
const BACKOFF_START: i64 = 60;
const BACKOFF_MAX: i64 = 3_600;
/// Seconds until a 404 for the hours upload is tried again.
const NOT_FOUND_BACKOFF: i64 = 6 * 3_600;

/// Whether this engine may collect and send to the Cloud at `origin`.
pub fn released(origin: &str) -> bool {
    let switch = std::env::var(TEST_SWITCH_ENV);
    RELEASED || (switch.as_deref() == Ok("fake-wire") && crate::is_loopback(origin))
}

/// What a pass did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MetricsV2Run {
    /// Held back until the release (owner sequencing).
    NotReleased,
    NotDue,
    Off(Sharing),
    /// Waiting for the back-off after 429/5xx.
    Waiting,
    Sent {
        buckets: u64,
        refused: u64,
    },
    Empty,
}

fn engine() -> EngineV2 {
    let os = match std::env::consts::OS {
        "macos" => EngineOs::Macos,
        "windows" => EngineOs::Windows,
        _ => EngineOs::Linux,
    };
    EngineV2 {
        instance_version: EngineVersion::new(env!("CARGO_PKG_VERSION"))
            .or_else(|| EngineVersion::new("0.0.0"))
            .expect("version"),
        os,
    }
}

fn hours_between(from: &HourStamp, to: &HourStamp) -> Vec<HourStamp> {
    let mut out = Vec::new();
    let mut at = from.start();
    let end = to.start();
    while at <= end {
        out.push(HourStamp::of(at));
        at += Duration::hours(1);
    }
    out
}

/// The vaults allowed and whether unattributed work goes.
pub(crate) struct Allowed<'a> {
    pub(crate) vaults_off: &'a std::collections::BTreeSet<String>,
    pub(crate) unattributed: bool,
}

/// The first hour that may be built: the sharing period's start, at most
/// 30 days back, never before the person agreed, and never before this
/// engine's own on period began (`local`, after an engine-side off; it may
/// lie in the next hour, which then is the first one built).
fn first_hour(
    since: Option<UtcDateTime>,
    local: Option<UtcDateTime>,
    now: UtcDateTime,
) -> HourStamp {
    let floor = now - Duration::days(BACKFILL_DAYS);
    let start = since.unwrap_or(now).max(floor).min(now);
    HourStamp::of(local.map_or(start, |local| start.max(local)))
}

/// Sample the cumulative counters, close the open hour, and (re)build the
/// buckets that may change: hours never built, the previous and the
/// current hour. Closed hours stay as they are.
pub(crate) fn build(
    sources: &Sources<'_>,
    scope: &Scope,
    state: &mut State,
    buffer: &Buffer,
    allowed: &Allowed<'_>,
    since: Option<UtcDateTime>,
    now: UtcDateTime,
) -> Result<(), CloudError> {
    let now_hour = HourStamp::of(now);
    let prev_hour = HourStamp::of(now - Duration::hours(1));
    let snap = collect::snapshot(sources, scope);
    match state.open_hour.clone() {
        None => {
            let local = sources
                .cloud
                .and_then(|cloud| super::buffer::local_on_since(cloud, now));
            state.collect_from = Some(first_hour(since, local, now));
            state.open_hour = Some(now_hour.clone());
            state.open_start = snap.clone();
        }
        Some(open) if open != now_hour => {
            let mut item = buffer.get(&open).unwrap_or_else(|| Item {
                hour: Some(open.clone()),
                ..Item::default()
            });
            item.sampled = collect::sampled(&state.open_start, &snap);
            if !item.sampled.is_empty() || item.bucket.is_some() {
                buffer.put(&item)?;
            }
            state.open_hour = Some(now_hour.clone());
            state.open_start = snap.clone();
        }
        Some(_) => {}
    }
    let current = collect::sampled(&state.open_start, &snap);
    let collect_from = state
        .collect_from
        .clone()
        .unwrap_or_else(|| now_hour.clone());
    let first = state
        .built_until
        .clone()
        .unwrap_or_else(|| collect_from.clone())
        .min(prev_hour.clone())
        .max(collect_from);
    let exact = collect::exact(
        sources,
        scope,
        first.start(),
        now_hour.start() + Duration::hours(1),
        prev_hour.start(),
    );
    for hour in hours_between(&first, &now_hour) {
        let mut item = buffer.get(&hour).unwrap_or_else(|| Item {
            hour: Some(hour.clone()),
            ..Item::default()
        });
        if hour == now_hour {
            item.sampled = current.clone();
        }
        let slices = collect::slices(
            scope,
            &hour,
            &exact,
            &item.sampled,
            allowed.vaults_off,
            allowed.unattributed,
        );
        if slices.is_empty() {
            if item.bucket.is_some() || !item.sampled.is_empty() {
                buffer.put(&item)?;
            }
            continue;
        }
        if item.bucket.as_ref().is_none_or(|b| b.slices != slices) {
            item.bucket = Some(BucketV2 {
                hour: hour.clone(),
                rev: state.rev(),
                slices,
            });
        }
        buffer.put(&item)?;
    }
    state.built_until = Some(now_hour);
    state.dropped_buckets = state
        .dropped_buckets
        .saturating_add(buffer.enforce_cap(buffer::MAX_ITEMS, buffer::MAX_BYTES));
    if let Some(cloud) = sources.cloud {
        super::secrets::prune(cloud, prev_hour.start());
        super::signals::prune(cloud, prev_hour.start());
    }
    Ok(())
}

/// The pending buckets, oldest first, without slices the gate no longer
/// allows (a vault turned off after the hour was built).
fn pending(buffer: &Buffer, allowed: &Allowed<'_>) -> Vec<BucketV2> {
    buffer
        .items()
        .into_iter()
        .filter(Item::pending)
        .filter_map(|item| {
            let mut bucket = item.bucket?;
            bucket.slices.retain(|s| match &s.vault {
                Some(v) => !allowed.vaults_off.contains(v.as_str()),
                None => allowed.unattributed,
            });
            (!bucket.slices.is_empty()).then_some(bucket)
        })
        .collect()
}

fn body(buckets: Vec<BucketV2>) -> HoursBodyV2 {
    HoursBodyV2 {
        schema: HoursSchema,
        instance: engine(),
        buckets,
    }
}

/// Batches of at most 168 buckets and 512 KiB (signature included).
pub(crate) fn batches(buckets: Vec<BucketV2>) -> Vec<HoursBodyV2> {
    // `key_id` and `signature` with their JSON framing.
    const SIGNED_EXTRA: usize = 200;
    let size = |b: &[BucketV2]| {
        serde_json::to_vec(&body(b.to_vec())).map_or(usize::MAX, |v| v.len() + SIGNED_EXTRA)
    };
    let mut out = Vec::new();
    let mut current: Vec<BucketV2> = Vec::new();
    for bucket in buckets {
        current.push(bucket);
        if current.len() > MAX_BUCKETS || size(&current) > MAX_HOURS_BODY_BYTES {
            let last = current.pop().expect("just pushed");
            if !current.is_empty() {
                out.push(body(std::mem::take(&mut current)));
            }
            current.push(last);
        }
    }
    if !current.is_empty() {
        out.push(body(current));
    }
    out
}

/// Sign a batch with the instance key (as `worker_register`).
pub(crate) fn sign(keys: &InstanceKeys, body: HoursBodyV2) -> Result<HoursRequestV2, CloudError> {
    let signer = keys.signing_key();
    let key_id = KeyId::new(&crate::workers::key_id(signer))
        .ok_or_else(|| CloudError::Local("instance key id".into()))?;
    let input = body
        .signing_input(&key_id)
        .map_err(|e| CloudError::Local(e.to_string()))?;
    let signature = SignatureHex::new(&hex::encode(signer.sign(&input).to_bytes()))
        .ok_or_else(|| CloudError::Local("signature".into()))?;
    Ok(body.signed(key_id, signature))
}

/// The same batch always carries the same key, so a retry is idempotent.
fn idempotency_key(bytes: &[u8]) -> String {
    use sha2::Digest;
    hex::encode(&sha2::Sha256::digest(bytes)[..16])
}

fn level_of(raw: Option<&str>) -> Option<PolicyLevel> {
    raw.and_then(PolicyLevel::from_wire)
}

/// Whether this pass sends nothing yet: a back-off after 429/5xx (a manual
/// sync tries anyway), or a feature Cloud switched off, which a manual sync
/// does not retry either (it would only print the same refusal each time).
pub(super) fn held_back(state: &State, now: UtcDateTime, force: bool) -> Option<MetricsV2Run> {
    if state.retry_at.is_none_or(|at| now.timestamp() >= at) {
        return None;
    }
    if state.switched_off.is_some() {
        Some(MetricsV2Run::NotDue)
    } else {
        (!force).then_some(MetricsV2Run::Waiting)
    }
}

/// Cloud switched the feature off (`404 feature_disabled`): keep the hours
/// (they stay valid once the operator switches it on), try again after
/// [`BACKOFF_MAX`], and stay quiet; `cloud status` says it.
pub(super) fn switched_off(
    cloud_data: &Path,
    state: &mut State,
    feature: Option<String>,
    now: UtcDateTime,
) -> Result<MetricsV2Run, CloudError> {
    if state.switched_off.is_none() {
        tracing::info!(
            "cloud: {}; retried in {} min",
            CloudError::FeatureDisabled {
                feature: feature.clone()
            },
            BACKOFF_MAX / 60
        );
    }
    state.switched_off = Some(feature.unwrap_or_else(|| "instance_metrics".into()));
    state.retry_at = Some(now.timestamp().saturating_add(BACKOFF_MAX));
    state.store(cloud_data)?;
    Ok(MetricsV2Run::NotDue)
}

/// Stop: record the refusal and drop everything buffered.
fn refused(
    cloud_data: &Path,
    state: &mut State,
    refusal: Refusal,
) -> Result<MetricsV2Run, CloudError> {
    let (reason, level) = match &refusal {
        Refusal::Policy { level, .. } => (OffReason::Policy, *level),
        Refusal::Lease { reason, .. } => (*reason, None),
    };
    state.refusal = Some(refusal);
    state.store(cloud_data)?;
    buffer::drop_all(cloud_data)?;
    Ok(MetricsV2Run::Off(Sharing::Off { reason, level }))
}

/// The vault map the hourly upload attributes to, `None` when it belongs
/// to another Cloud or account than `scope` (the session's).
pub(crate) fn vault_map_of(cloud_data: &Path, scope: &str) -> Option<VaultMap> {
    crate::vault::map_in(cloud_data, scope)
}

/// `GET /v1/metrics/sharing`.
fn fetch_sharing(session: &Session) -> Result<SharingStateV2, CloudError> {
    let answer = session.with_client(|client| client.get(SHARING_ROUTE))?;
    serde_json::from_value(answer)
        .map_err(|e| CloudError::Protocol(format!("instance metrics sharing: {e}")))
}

/// Let the redaction path count redactions per detector (sharing is on).
fn ensure_secret_counting(session: &Session) -> Result<(), CloudError> {
    let cloud = session.store.data_dir();
    if super::secrets::enabled(cloud) {
        return Ok(());
    }
    super::secrets::enable(cloud)
}

/// One pass at `now`; `force` skips the hourly debounce (`cloud sync`).
pub fn run(
    session: &Session,
    config: &CloudConfig,
    now: UtcDateTime,
    force: bool,
) -> Result<MetricsV2Run, CloudError> {
    if !released(&session.instance.url) {
        return Ok(MetricsV2Run::NotReleased);
    }
    let store = &session.store;
    let cloud_data = store.data_dir();
    let lease = &session.lease.lease;
    let _lock = crate::state::lock_state(&buffer::dir_in(cloud_data), "state.json")?;
    let mut state = State::load(cloud_data);
    if state.org_id != session.instance.org_id {
        // Another workspace: nothing of the old one goes to the new one.
        buffer::forget(cloud_data);
        state = State {
            org_id: session.instance.org_id.clone(),
            ..State::default()
        };
    }
    // K2 (L2): an off switch applies at once, on every pass, not only on
    // the hourly one: nothing stays buffered once any switch says off.
    if !gate::decide_with(
        store,
        config,
        &session.instance,
        lease,
        state.sharing.as_ref(),
        now,
    )
    .is_on()
    {
        buffer::drop_all(cloud_data)?;
        state = State::load(cloud_data);
        state.org_id.clone_from(&session.instance.org_id);
    }
    let due = force
        || state
            .last_run
            .is_none_or(|last| now.timestamp() < last || now.timestamp() - last >= DEBOUNCE_SECS)
        || state
            .open_hour
            .as_ref()
            .is_some_and(|open| *open != HourStamp::of(now));
    if !due {
        return Ok(MetricsV2Run::NotDue);
    }
    // The workspace's word first: nothing is collected unless it says on.
    if config.metrics_upload {
        match fetch_sharing(session) {
            Ok(sharing) => state.sharing = Some(sharing),
            Err(error) if error.is_transient() => {}
            Err(error) => {
                state.store(cloud_data)?;
                return Err(error);
            }
        }
    }
    state.store(cloud_data)?;
    let sharing = gate::decide_with(
        store,
        config,
        &session.instance,
        lease,
        state.sharing.as_ref(),
        now,
    );
    let Sharing::On {
        vaults_off,
        unattributed,
        policy_version,
        since,
        ..
    } = &sharing
    else {
        buffer::drop_all(cloud_data)?;
        return Ok(MetricsV2Run::Off(sharing));
    };
    state.refusal = None;
    if let Err(error) = ensure_secret_counting(session) {
        store.record_error(&format!("instance metrics redaction counter: {error}"));
    }
    let data = lean_ctx::core::data_dir::lean_ctx_data_dir().map_err(CloudError::Local)?;
    let home = dirs::home_dir();
    let sources = Sources {
        data: &data,
        home: home.as_deref(),
        cloud: Some(cloud_data),
    };
    let scope_since = state
        .open_hour
        .as_ref()
        .map_or(now - Duration::days(BACKFILL_DAYS), |h| {
            h.start().min(now - Duration::days(3))
        });
    // The vaults of this session's Cloud and account (rc3-81, bd 39791 M2):
    // after an enrollment elsewhere nothing is collected or sent here.
    let Some(map) = vault_map_of(cloud_data, &session.instance.vault_scope()) else {
        return Ok(MetricsV2Run::Empty);
    };
    let scope = Scope::load(&data, &map, scope_since);
    let buffer = Buffer::at(cloud_data);
    let allowed = Allowed {
        vaults_off,
        unattributed: *unattributed,
    };
    build(&sources, &scope, &mut state, &buffer, &allowed, *since, now)?;
    state.last_run = Some(now.timestamp());
    state.store(cloud_data)?;

    if let Some(held) = held_back(&state, now, force) {
        return Ok(held);
    }
    let requests = batches(pending(&buffer, &allowed));
    if requests.is_empty() {
        return Ok(MetricsV2Run::Empty);
    }
    let keys = InstanceKeys::load(store)?;
    let (mut sent, mut refused_slices) = (0u64, 0u64);
    for body in requests {
        body.validate()
            .map_err(|e| CloudError::Local(format!("instance metrics withheld: {e}")))?;
        let request = sign(&keys, body)?;
        let bytes = serde_json::to_vec(&request).map_err(|e| CloudError::Local(e.to_string()))?;
        let wire: serde_json::Value =
            serde_json::from_slice(&bytes).map_err(|e| CloudError::Local(e.to_string()))?;
        let key = idempotency_key(&bytes);
        match session.with_client(|client| client.post_idempotent(HOURS_ROUTE, &wire, &key)) {
            Ok(answer) => {
                let ack: HoursAckV2 = serde_json::from_value(answer)
                    .map_err(|e| CloudError::Protocol(format!("instance metrics ack: {e}")))?;
                for bucket in &request.buckets {
                    if let Some(mut item) = buffer.get(&bucket.hour) {
                        item.acked_rev = bucket.rev;
                        buffer.put(&item)?;
                    }
                }
                sent += u64::from(ack.accepted);
                refused_slices += ack.refused.len() as u64;
                state.last_sent_at =
                    Some(now.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true));
                state.retry_at = None;
                state.attempts = 0;
                state.switched_off = None;
                let off = ack.sharing.state != SharingValue::On;
                state.sharing = Some(ack.sharing);
                if off {
                    state.store(cloud_data)?;
                    buffer::drop_all(cloud_data)?;
                    return Ok(MetricsV2Run::Off(gate::decide(
                        store,
                        config,
                        &session.instance,
                        lease,
                        now,
                    )));
                }
            }
            Err(CloudError::PolicyDenied(denial)) => {
                return refused(
                    cloud_data,
                    &mut state,
                    Refusal::Policy {
                        policy_version: *policy_version,
                        level: level_of(denial.level.as_deref()),
                    },
                );
            }
            Err(CloudError::UploadDisabled(_)) => {
                return refused(
                    cloud_data,
                    &mut state,
                    Refusal::Lease {
                        lease_id: lease.lease_id.clone(),
                        reason: OffReason::Workspace,
                    },
                );
            }
            Err(CloudError::Forbidden) => {
                return refused(
                    cloud_data,
                    &mut state,
                    Refusal::Lease {
                        lease_id: lease.lease_id.clone(),
                        reason: OffReason::Lease,
                    },
                );
            }
            Err(CloudError::Server { status: 403, .. }) => {
                // `sharing_not_confirmed` (or a newer refusal): ask again and stop.
                state.sharing = fetch_sharing(session).ok().or(state.sharing.take());
                state.store(cloud_data)?;
                buffer::drop_all(cloud_data)?;
                return Ok(MetricsV2Run::Off(gate::decide(
                    store,
                    config,
                    &session.instance,
                    lease,
                    now,
                )));
            }
            // A Cloud without the route (or one that does not know this
            // instance's slice) answers 404: not an error of this sync. The
            // hours stay buffered and are offered again much later, quietly.
            Err(CloudError::NotFound) => {
                if state.retry_at.is_none() {
                    tracing::info!(
                        "cloud: instance metrics route not served by this Cloud server; retried in {}h",
                        NOT_FOUND_BACKOFF / 3_600
                    );
                }
                state.retry_at = Some(now.timestamp().saturating_add(NOT_FOUND_BACKOFF));
                state.store(cloud_data)?;
                return Ok(MetricsV2Run::Waiting);
            }
            Err(CloudError::FeatureDisabled { feature }) => {
                return switched_off(cloud_data, &mut state, feature, now);
            }
            Err(error) if error.is_transient() => {
                state.attempts = state.attempts.saturating_add(1);
                let backoff = BACKOFF_START
                    .saturating_mul(1 << state.attempts.min(10))
                    .min(BACKOFF_MAX);
                let wait = error
                    .retry_after_at(now)
                    .and_then(|s| i64::try_from(s).ok())
                    .unwrap_or(backoff);
                state.retry_at = Some(now.timestamp().saturating_add(wait));
                state.store(cloud_data)?;
                return Err(error);
            }
            Err(
                error @ (CloudError::Server {
                    status: 400 | 413, ..
                }
                | CloudError::Protocol(_)),
            ) => {
                // These hours would be refused again: give them up, counted.
                for bucket in &request.buckets {
                    buffer.remove(&bucket.hour);
                    state.dropped_buckets = state.dropped_buckets.saturating_add(1);
                }
                state.store(cloud_data)?;
                return Err(error);
            }
            Err(error) => {
                state.store(cloud_data)?;
                return Err(error);
            }
        }
    }
    // Acked hours older than the previous one are done.
    let prev = HourStamp::of(now - Duration::hours(1));
    for item in buffer.items() {
        if let Some(hour) = &item.hour
            && !item.pending()
            && *hour < prev
        {
            buffer.remove(hour);
        }
    }
    state.refused_slices = state.refused_slices.saturating_add(refused_slices);
    state.store(cloud_data)?;
    Ok(MetricsV2Run::Sent {
        buckets: sent,
        refused: refused_slices,
    })
}

/// Ask the workspace for its sharing state now and keep it for
/// `gate::decide` (connect: an off set in Settings must be known before
/// anything is confirmed, also right after a new enrollment).
pub fn refresh_sharing(session: &Session) -> Result<SharingStateV2, CloudError> {
    let sharing = fetch_sharing(session)?;
    let cloud = session.store.data_dir();
    let mut state = State::load(cloud);
    if state.org_id != session.instance.org_id {
        state = State {
            org_id: session.instance.org_id.clone(),
            ..State::default()
        };
    }
    state.sharing = Some(sharing.clone());
    state.store(cloud)?;
    Ok(sharing)
}

/// Cloud's answer to a confirmation it does not need (`409 invalid_state`,
/// reason `not_required`): the plan shares by default.
pub(super) fn not_required(error: &CloudError) -> bool {
    matches!(error, CloudError::Server { status: 409, code } if code == "invalid_state")
}

/// The state after a `not_required` answer: the one Cloud sent last
/// (a team rule that turned sharing off, say), else the plan default. A
/// stored `needs_confirmation` is stale (Cloud no longer waits), so the
/// plan default replaces it.
pub(super) fn nothing_to_confirm(
    known: Option<&SharingStateV2>,
    plan: lean_ctx_protocol::cloud::lease::CloudPlan,
) -> SharingStateV2 {
    match known {
        Some(known) if known.state != SharingValue::NeedsConfirmation => known.clone(),
        _ => gate::plan_state(plan),
    }
}

/// `cloud metrics confirm`: the person agrees (Personal). Callers
/// make sure a person answered in a terminal; MCP tools never call this.
pub fn confirm(session: &Session) -> Result<SharingStateV2, CloudError> {
    if !released(&session.instance.url) {
        return Err(CloudError::Refused(
            "instance metrics are not released yet; nothing is shared".into(),
        ));
    }
    let answer =
        session.with_client(|client| client.post(SHARING_CONFIRM_ROUTE, &serde_json::json!({})));
    let cloud = session.store.data_dir();
    let mut state = State::load(cloud);
    if state.org_id != session.instance.org_id {
        state = State {
            org_id: session.instance.org_id.clone(),
            ..State::default()
        };
    }
    let sharing: SharingStateV2 = match answer {
        Ok(answer) => serde_json::from_value(answer)
            .map_err(|e| CloudError::Protocol(format!("instance metrics sharing: {e}")))?,
        // `409 invalid_state` (`not_required`): nothing to confirm. A state
        // Cloud sent earlier (a team rule that turned it off, say) stays as
        // it is; a stale `needs_confirmation` or none at all gives way to the
        // plan default until the next answer.
        Err(error) if not_required(&error) => {
            let settled = nothing_to_confirm(state.sharing.as_ref(), session.lease.lease.plan);
            if state.sharing.as_ref() == Some(&settled) {
                return Ok(settled);
            }
            settled
        }
        Err(error) => return Err(error),
    };
    state.sharing = Some(sharing.clone());
    state.store(cloud)?;
    Ok(sharing)
}

// ── local views ──────────────────────────────────────────────────────────────

/// What `cloud status` shows about engine metrics.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MetricsV2Status {
    pub sharing: Sharing,
    pub state: SharingStateV2,
    pub released: bool,
    pub last_sent_at: Option<String>,
    pub buffered: u64,
    pub dropped: u64,
    /// The feature Cloud switched off (`feature_disabled`), shown once here
    /// instead of on every sync.
    pub switched_off: Option<String>,
}

impl MetricsV2Status {
    /// `Sharing engine metrics with <workspace>: on (plan default) · counts only, incl. full
    /// re-fetches and unregulated program names · last sent 17:05 UTC · 2 hours buffered`.
    pub fn line(&self, workspace: &str) -> String {
        let mut line = format!(
            "Sharing instance metrics with {workspace}: {}",
            self.sharing.describe()
        );
        if !self.released {
            line.push_str(" · not released yet, nothing is sent");
        }
        // K4: what the counts include, beyond the obvious.
        line.push_str(" · counts only, incl. full re-fetches and unregulated program names");
        if self.sharing.is_on() {
            if let Some(at) = self
                .last_sent_at
                .as_deref()
                .and_then(|t| OffsetDateTime::parse_from_rfc3339(t).ok())
            {
                line.push_str(&format!(" · last sent {} UTC", at.format("%H:%M")));
            }
            line.push_str(&format!(" · {} hours buffered", self.buffered));
        }
        if self.dropped > 0 {
            line.push_str(&format!(" · {} hours dropped (buffer full)", self.dropped));
        }
        if let Some(feature) = &self.switched_off {
            line.push_str(&format!(
                " · {} (hours kept until it is on)",
                crate::CloudError::FeatureDisabled {
                    feature: Some(feature.clone())
                }
            ));
        }
        line
    }

    pub fn wire(&self) -> lean_ctx_protocol::cloud::status::CloudStatusMetricsV2 {
        let mut sharing = self.state.clone();
        // This engine sends nothing whatever the workspace says: say off.
        if !self.sharing.is_on() && sharing.state == SharingValue::On {
            sharing.state = SharingValue::Off;
        }
        lean_ctx_protocol::cloud::status::CloudStatusMetricsV2 {
            sharing,
            last_sent_at: self.last_sent_at.clone(),
            buffered_buckets: self.buffered,
            dropped_buckets: self.dropped,
            released: Some(self.released),
        }
    }
}

/// Engine metrics as `cloud status` reports them (local only).
pub fn status(
    store: &CloudStore,
    config: &CloudConfig,
    instance: &InstanceRecord,
    lease: &CloudLeaseV1,
    now: UtcDateTime,
) -> MetricsV2Status {
    let state = State::load(store.data_dir());
    let known = state
        .sharing
        .clone()
        .filter(|_| state.org_id == instance.org_id);
    MetricsV2Status {
        sharing: gate::decide(store, config, instance, lease, now),
        state: known.unwrap_or_else(|| gate::plan_state(lease.plan)),
        released: released(&instance.url),
        last_sent_at: state.last_sent_at,
        buffered: Buffer::at(store.data_dir()).pending() as u64,
        dropped: state.dropped_buckets,
        switched_off: state.switched_off,
    }
}

/// The buckets of `hours` (oldest first) from the same collector that
/// uploads: exact counters from the local stores now, the sampled part and
/// the `rev` as buffered (rev 1 for an hour never built). Local only.
fn local_buckets(
    store: &CloudStore,
    instance: &InstanceRecord,
    sharing: &Sharing,
    hours: &[HourStamp],
    now: UtcDateTime,
) -> Result<Vec<BucketV2>, CloudError> {
    let (Some(first), Some(last)) = (hours.first(), hours.last()) else {
        return Ok(Vec::new());
    };
    let (vaults_off, unattributed) = match sharing {
        Sharing::On {
            vaults_off,
            unattributed,
            ..
        } => (vaults_off.clone(), *unattributed),
        Sharing::Off { .. } => (
            gate::policy(store.data_dir(), now)
                .map(|(off, _)| off)
                .unwrap_or_default(),
            instance.org_kind.as_deref() == Some("personal"),
        ),
    };
    let data = lean_ctx::core::data_dir::lean_ctx_data_dir().map_err(CloudError::Local)?;
    let home = dirs::home_dir();
    let sources = Sources {
        data: &data,
        home: home.as_deref(),
        cloud: Some(store.data_dir()),
    };
    let scope = Scope::load(
        &data,
        &crate::vault::connected_map(store),
        first.start() - Duration::days(3),
    );
    let end = last.start() + Duration::hours(1);
    // Spend is read by minute per hour: the last two hours, as uploads do.
    let exact = collect::exact(
        &sources,
        &scope,
        first.start(),
        end,
        end - Duration::hours(2),
    );
    let buffer = Buffer::at(store.data_dir());
    let mut out = Vec::new();
    for hour in hours {
        let buffered = buffer.get(hour);
        let sampled = buffered
            .as_ref()
            .map(|i| i.sampled.clone())
            .unwrap_or_default();
        let rev = buffered.and_then(|i| i.bucket.map(|b| b.rev)).unwrap_or(1);
        let slices = collect::slices(&scope, hour, &exact, &sampled, &vaults_off, unattributed);
        if !slices.is_empty() {
            out.push(BucketV2 {
                hour: hour.clone(),
                rev,
                slices,
            });
        }
    }
    Ok(out)
}

/// The next batch exactly as it would be sent, unsigned; changes nothing.
/// Sharing on: the oldest pending batch, else the last complete hour built
/// now. Sharing not on: no buckets (nothing would be sent).
pub fn preview(
    store: &CloudStore,
    config: &CloudConfig,
    instance: &InstanceRecord,
    lease: &CloudLeaseV1,
    now: UtcDateTime,
) -> Result<(Sharing, HourStamp, HoursBodyV2), CloudError> {
    let sharing = gate::decide(store, config, instance, lease, now);
    let hour = HourStamp::of(now - Duration::hours(1));
    let buckets = match &sharing {
        Sharing::On {
            vaults_off,
            unattributed,
            ..
        } => {
            let allowed = Allowed {
                vaults_off,
                unattributed: *unattributed,
            };
            match batches(pending(&Buffer::at(store.data_dir()), &allowed))
                .into_iter()
                .next()
            {
                Some(next) => next.buckets,
                None => local_buckets(store, instance, &sharing, std::slice::from_ref(&hour), now)?,
            }
        }
        Sharing::Off { .. } => Vec::new(),
    };
    let request = body(buckets);
    if !request.buckets.is_empty() {
        request
            .validate()
            .map_err(|e| CloudError::Local(format!("instance metrics withheld: {e}")))?;
    }
    Ok((sharing, hour, request))
}

/// What `cloud metrics preview` shows for the last complete hour whatever
/// the sharing state (for people: "this is what would go when on").
pub fn sample_hour(
    store: &CloudStore,
    config: &CloudConfig,
    instance: &InstanceRecord,
    lease: &CloudLeaseV1,
    now: UtcDateTime,
) -> Result<HoursBodyV2, CloudError> {
    let sharing = gate::decide(store, config, instance, lease, now);
    let hour = HourStamp::of(now - Duration::hours(1));
    Ok(body(local_buckets(
        store,
        instance,
        &sharing,
        &[hour],
        now,
    )?))
}

/// `cloud metrics hours --range 24h|7d|30d`: this engine's own buckets for
/// the span (the current hour included, at most 720), from the same
/// collector that uploads, sent or not: the local side of the K24 parity
/// check. Local only.
pub fn hours(
    store: &CloudStore,
    config: &CloudConfig,
    instance: &InstanceRecord,
    lease: &CloudLeaseV1,
    range_hours: i64,
    now: UtcDateTime,
) -> Result<HoursBodyV2, CloudError> {
    let sharing = gate::decide(store, config, instance, lease, now);
    let count = range_hours.clamp(1, 720);
    let list: Vec<HourStamp> = (0..count)
        .rev()
        .map(|back| HourStamp::of(now - Duration::hours(back)))
        .collect();
    Ok(body(local_buckets(store, instance, &sharing, &list, now)?))
}

/// `cloud metrics delete`: everything this engine holds for the workspace
/// (buffer, state, fingerprint key and hits) is deleted locally.
pub fn delete_local(store: &CloudStore) {
    buffer::forget(store.data_dir());
    // Deleted hours are not rebuilt from the local stores (NEW-1).
    buffer::note_local_off(store.data_dir());
}

/// `cloud metrics delete`, Cloud side (C0 2.1 `DELETE /v1/metrics/hours`):
/// every bucket this engine stored. Only once released.
pub fn delete_remote(session: &Session) -> Result<bool, CloudError> {
    if !released(&session.instance.url) {
        return Ok(false);
    }
    session.with_client(|client| client.delete(HOURS_ROUTE))?;
    Ok(true)
}