lean-ctx-cloud 3.12.10

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
// SPDX-License-Identifier: Apache-2.0
//! The network half of knowledge sync, run by the scheduler or `lean-ctx
//! cloud sync`, never inside a tool call:
//! 1. send queued drafts (rebased onto the newest base when possible),
//! 2. pull new revisions of known projects into project knowledge.

use std::path::Path;

use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as B64;
use lean_ctx_time::UtcDateTime;

use super::doc::rebase_ops;
use super::draft::{QueuedDraft, queued};
use super::learn::sync_into_knowledge;
use super::{BaseRevision, load_base, save_base};
use crate::CloudError;
use crate::auth::Session;
use crate::config::CloudConfig;
use crate::mapping::{MapError, map_root};
use crate::outbox::{CHANNEL_KNOWLEDGE, Outbox};
use crate::vault::{VaultMap, VaultRecord};
use lean_ctx_protocol::cloud::knowledge::{
    KnowledgeRevisionV1, MAX_KNOWLEDGE_BODY_BYTES, ProposalAckV1, RevisionState,
};
use lean_ctx_protocol::cloud::vault::OrgSaltV1;

/// Seconds before a draft that waits for the person's first-share yes is
/// looked at again.
const CONSENT_RECHECK_SECONDS: u64 = 300;

/// What one sync pass did.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SyncReport {
    pub drafts_sent: Vec<u64>,
    pub drafts_pending: usize,
    pub drafts_failed: usize,
    /// `(ns/name, revision, facts loaded)` per project that moved.
    pub pulled: Vec<(String, u64, usize)>,
    pub problems: Vec<String>,
}

/// `GET /org/salt`: the salt id and bytes identity digests are made with.
pub fn org_salt(session: &Session) -> Result<(String, Vec<u8>), CloudError> {
    let body = session.with_client(|c| c.get("/org/salt"))?;
    let salt: OrgSaltV1 =
        serde_json::from_value(body).map_err(|e| CloudError::Protocol(format!("org salt: {e}")))?;
    salt.validate()
        .map_err(|e| CloudError::Protocol(e.to_string()))?;
    let bytes = B64
        .decode(&salt.salt)
        .map_err(|_| CloudError::Protocol("org salt is not base64".into()))?;
    Ok((salt.org_salt_id, bytes))
}

struct Resolver<'a> {
    session: &'a Session,
    salt: Option<(String, Vec<u8>)>,
    map: VaultMap,
    config: &'a CloudConfig,
    /// The share of an explicit `cloud link`, which may map a folder the
    /// person unlinked; its opt-out is lifted only after the share (bd 40060).
    explicit_link: bool,
}

impl Resolver<'_> {
    fn salt(&mut self) -> Result<&(String, Vec<u8>), CloudError> {
        if self.salt.is_none() {
            self.salt = Some(org_salt(self.session)?);
        }
        Ok(self.salt.as_ref().expect("set above"))
    }

    /// Apply `change` to `projects.json` as it is on disk now, under its
    /// lock, for the Cloud and account this session is connected to (rc3-81,
    /// rc4-2): the map is stamped with them, and a map of another Cloud or
    /// account (an enrollment elsewhere since this session loaded) is left
    /// alone and refused (fail closed).
    fn write(&mut self, change: impl FnOnce(&mut VaultMap)) -> Result<(), CloudError> {
        let scope = self.session.instance.vault_scope();
        let (claimed, map) = crate::vault::update_map(self.session.store.data_dir(), |map| {
            let claimed = map.claim(&scope);
            if claimed {
                change(map);
            }
            claimed
        })?;
        self.map = map.for_scope(&scope);
        if claimed {
            Ok(())
        } else {
            Err(CloudError::Local(
                "this machine's vault records belong to another Cloud or account now; nothing was recorded"
                    .into(),
            ))
        }
    }

    /// The project for `root`, mapped in Cloud when unknown
    /// ([`crate::mapping`]: match, first-share consent, resolve).
    fn resolve(&mut self, stable: &str, root: &Path) -> Result<VaultRecord, MapError> {
        // A folder the person stopped sharing (`cloud unlink`) is never
        // mapped again on its own, also not through a kept link file.
        if !self.explicit_link && crate::unlinked::contains(self.session.store.data_dir(), root) {
            let reason = crate::unlinked::refusal(self.session.store.data_dir());
            return Err(CloudError::Refused(reason).into());
        }
        // A resolution the link file or the identity no longer backs is
        // never used: it is dropped and the checkout resolves again.
        if let Some(stale) = crate::resolution::forget_stale(&mut self.map, root) {
            tracing::info!("cloud: resolving again: {}", stale.describe());
            self.write(|map| {
                crate::resolution::forget_stale(map, root);
            })?;
        }
        if let Some(record) = self.map.vaults.get(stable)
            && record.roots.iter().any(|r| Path::new(r) == root)
        {
            crate::mapping::close_satisfied(self.session, self.config, stable, record);
            return Ok(record.clone());
        }
        let salt = self.salt()?.clone();
        let known = self.map.vaults.get(stable).cloned();
        let project = map_root(
            self.session,
            self.config,
            &salt,
            stable,
            root,
            known.as_ref(),
        )?;
        // Cloud keeps an identity's first binding: an answer that is not the
        // linked vault is refused, never recorded (fail closed).
        crate::resolution::refuse_unlinked(root, &project.vault)?;
        self.write(|map| map.record(stable, &project, root))?;
        // A first-share request opened before the vault existed (another
        // engine's sync created it) is satisfied now: never left waiting.
        let mapped =
            self.map.vaults.get(stable).cloned().ok_or_else(|| {
                CloudError::Local("the vault record was not kept; sync again".into())
            })?;
        crate::mapping::close_satisfied(self.session, self.config, stable, &mapped);
        Ok(mapped)
    }
}

/// The vault the checkout at `root` is linked to, resolved in Cloud (and
/// remembered) when this machine has no record of it yet, e.g. on the
/// first sync after `cloud link`. A first share that waits for the
/// person's yes is `MapError::Consent`.
pub fn resolve_project(
    session: &Session,
    config: &CloudConfig,
    root: &Path,
) -> Result<VaultRecord, MapError> {
    resolve_with(session, config, root, false)
}

fn resolve_with(
    session: &Session,
    config: &CloudConfig,
    root: &Path,
    explicit_link: bool,
) -> Result<VaultRecord, MapError> {
    let identity = crate::vault::project_identity(root)
        .ok_or_else(|| CloudError::Config("not inside a git repository".into()))?;
    let stable = lean_ctx_protocol::cloud::vault::stable_identity(&identity);
    let mut resolver = Resolver {
        session,
        salt: None,
        map: VaultMap::load(session.store.data_dir()).for_scope(&session.instance.vault_scope()),
        config,
        explicit_link,
    };
    resolver.resolve(&stable, root)
}

/// [`resolve_project`] for the share of an explicit `cloud link`: a folder
/// the person unlinked is mapped too, while its opt-out still keeps every
/// sender quiet; `cloud link` lifts it only once Cloud took the share
/// (bd 40060). A damaged opt-out store still refuses.
pub fn resolve_for_link(
    session: &Session,
    config: &CloudConfig,
    root: &Path,
) -> Result<VaultRecord, MapError> {
    crate::unlinked::check(session.store.data_dir(), root)?;
    resolve_with(session, config, root, true)
}

/// Cloud refused mapping a checkout to `vault` (`<ws>/<vault>`): it is not
/// one this account may use (rc4-57). Said in the person's words, with the
/// way forward.
pub fn foreign_vault_refusal(vault: &str) -> String {
    format!(
        "your account may not use {vault}: it belongs to another account, or your role \
         there does not allow it. With a Personal plan you use only your own vaults; to \
         work in a vault together, its owner invites you to their team (Team plan)."
    )
}

/// The `<ws>/<vault>` the checkout at `root` is linked to, for a refusal.
fn linked_vault(root: &Path) -> String {
    match crate::link::read_link(root) {
        Ok(Some(link)) => format!("{}/{}", link.vault.ns, link.vault.name),
        _ => "This project's vault".to_owned(),
    }
}

/// Send drafts, then pull. `cwd_root` adds the current project to the pull
/// even if it never drafted (for `lean-ctx cloud sync` in a project).
pub fn sync(session: &Session, config: &CloudConfig, cwd_root: Option<&Path>) -> SyncReport {
    let data = session.store.data_dir().to_path_buf();
    let mut report = SyncReport::default();
    // A used-up transfer quota or a policy hold: drafts stay queued, no
    // request goes out until it ends (never a busy loop).
    if let Some(held) = crate::throttle::holding(
        &session.store,
        crate::throttle::Scope::Sync,
        UtcDateTime::now(),
    ) {
        let depth = Outbox::at(&data).depth(CHANNEL_KNOWLEDGE);
        report.drafts_pending = depth.pending;
        report.drafts_failed = depth.failed;
        report.problems.push(held.refusal().to_string());
        return report;
    }
    // Every checkout whose recorded vault its link file or identity no
    // longer backs is dropped before anything is sent or pulled.
    let scope = session.instance.vault_scope();
    let map = match crate::resolution::load_current(&data, Some(&scope)) {
        Ok((map, _)) => map,
        Err(error) => {
            report.problems.push(error.to_string());
            return report;
        }
    };
    let mut resolver = Resolver {
        session,
        salt: None,
        map,
        config,
        explicit_link: false,
    };
    if let Some(root) = cwd_root
        // A folder the person stopped sharing is not mapped (rc4-6).
        && !crate::unlinked::contains(&data, root)
        && let Some(identity) = crate::vault::project_identity(root)
    {
        let stable = lean_ctx_protocol::cloud::vault::stable_identity(&identity);
        if let Err(error) = resolver.resolve(&stable, root) {
            report.problems.push(match error {
                MapError::Cloud(CloudError::Forbidden) => {
                    foreign_vault_refusal(&linked_vault(root))
                }
                error => format!("{}: {error}", root.display()),
            });
        }
    }
    // A C0 2.0 Cloud takes no 1.x draft: capture sends the same knowledge
    // as signed events, so a draft still queued from before is dropped.
    if crate::bus::relay_v2::speaks_v2(&session.store) {
        drop_drafts(&data);
    } else {
        send_drafts(&mut resolver, &mut report);
    }
    pull_all(&resolver, &mut report);
    let outbox = Outbox::at(&data);
    let depth = outbox.depth(CHANNEL_KNOWLEDGE);
    report.drafts_pending = depth.pending;
    report.drafts_failed = depth.failed;
    let now = session.lease.service_time(UtcDateTime::now()).to_utc();
    let stamp = now.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true);
    if report.problems.is_empty() {
        session.store.record_success("knowledge", &stamp);
    } else {
        session.store.record_error(&report.problems.join("; "));
    }
    report
}

fn drop_drafts(data: &Path) {
    let outbox = Outbox::at(data);
    for item in outbox.list(CHANNEL_KNOWLEDGE) {
        let _ = outbox.remove(&item);
    }
}

fn send_drafts(resolver: &mut Resolver<'_>, report: &mut SyncReport) {
    let data = resolver.session.store.data_dir().to_path_buf();
    let outbox = Outbox::at(&data);
    let now = UtcDateTime::now();
    for mut item in outbox.list(CHANNEL_KNOWLEDGE) {
        if !item.due(now) {
            continue;
        }
        let Some(mut queued_draft) = queued(&item.payload) else {
            let _ = outbox.fail(&mut item, "damaged draft");
            continue;
        };
        let record = match resolver
            .resolve(&queued_draft.stable_identity, Path::new(&queued_draft.root))
        {
            Ok(record) => record,
            Err(error) => {
                report.problems.push(format!("draft {}: {error}", item.id));
                // A first share waits for the person: look again soon,
                // without the growing backoff of a failure.
                let wait = matches!(error, MapError::Consent(_)).then_some(CONSENT_RECHECK_SECONDS);
                let _ = outbox.retry_later(&mut item, &error.to_string(), wait, now);
                if matches!(
                    error,
                    MapError::Cloud(CloudError::Unauthorized | CloudError::LeaseLapsed)
                ) {
                    return;
                }
                continue;
            }
        };
        let base = load_base(&data, &record.vault_id);
        if !rebase_onto(&mut queued_draft, &base) {
            let _ = outbox.remove(&item);
            continue;
        }
        // A draft queued before refs were keyed carries the unsalted digest:
        // keyed now, or kept queued while the local key is unavailable.
        if let Err(error) = queued_draft.rekey_legacy_ref(&data) {
            report.problems.push(format!("draft {}: {error}", item.id));
            let _ = outbox.retry_later(&mut item, &error.to_string(), None, now);
            continue;
        }
        if let Ok(payload) = serde_json::to_value(&queued_draft) {
            item.payload = payload;
            let _ = outbox.update(&item);
        }
        let body = match serde_json::to_value(&queued_draft.draft) {
            Ok(body) => body,
            Err(error) => {
                let _ = outbox.fail(&mut item, &error.to_string());
                continue;
            }
        };
        let path = format!("/vaults/{}/proposals", record.vault_id);
        let result = resolver
            .session
            .with_client(|c| c.post_idempotent(&path, &body, &item.id));
        match result {
            Ok(answer) => {
                if let Ok(ack) = serde_json::from_value::<ProposalAckV1>(answer) {
                    report.drafts_sent.push(ack.number);
                }
                let _ = outbox.remove(&item);
            }
            Err(error @ (CloudError::Unauthorized | CloudError::LeaseLapsed)) => {
                report.problems.push(error.to_string());
                let _ = outbox.retry_later(&mut item, &error.to_string(), None, now);
                return;
            }
            Err(CloudError::RateLimited { retry_after }) => {
                let _ = outbox.retry_later(&mut item, "rate limited", retry_after, now);
            }
            // A used-up quota: this draft and the rest wait in the outbox and
            // the throttle holds sync until it ends. A policy refusal holds
            // this draft only, until a newer policy is in force or the
            // hold's time is up (an admin may change the policy).
            Err(error @ (CloudError::QuotaExceeded(_) | CloudError::PolicyDenied(_))) => {
                let quota = matches!(error, CloudError::QuotaExceeded(_));
                let wait = error
                    .retry_after_at(now)
                    .or(Some(crate::throttle::POLICY_HOLD_S.unsigned_abs()));
                report.problems.push(format!("draft {}: {error}", item.id));
                let _ = if quota {
                    outbox.retry_later(&mut item, &error.to_string(), wait, now)
                } else {
                    outbox.hold_for_policy(&mut item, &error.to_string(), wait, now)
                };
                if quota {
                    let _ = crate::throttle::note(
                        &resolver.session.store,
                        crate::throttle::Scope::Sync,
                        error,
                        now,
                    );
                    return;
                }
            }
            Err(error) if error.is_transient() => {
                let _ = outbox.retry_later(&mut item, &error.to_string(), None, now);
            }
            Err(
                error
                @ (CloudError::Conflict { .. } | CloudError::Forbidden | CloudError::NotFound),
            ) => {
                // The base moved or the right/project changed: try again after the next pull.
                report.problems.push(format!("draft {}: {error}", item.id));
                let _ = outbox.retry_later(&mut item, &error.to_string(), Some(900), now);
            }
            Err(error) => {
                report.problems.push(format!("draft {}: {error}", item.id));
                let _ = outbox.fail(&mut item, &error.to_string());
            }
        }
    }
}

/// Rebase a queued draft onto `base` when it is newer. Returns `false` when
/// every op is already in the base (nothing left to propose). A draft whose
/// ops clash with the newer base keeps its old base.
fn rebase_onto(queued_draft: &mut QueuedDraft, base: &BaseRevision) -> bool {
    let patch = &mut queued_draft.draft.context_patch;
    if base.revision <= patch.base_revision {
        return true;
    }
    match rebase_ops(&base.document, &patch.ops) {
        Ok(kept) if kept.is_empty() => false,
        Ok(kept) => {
            patch.ops = kept;
            patch.base_revision = base.revision;
            true
        }
        Err(_) => true,
    }
}

fn pull_all(resolver: &Resolver<'_>, report: &mut SyncReport) {
    let data = resolver.session.store.data_dir().to_path_buf();
    for record in resolver.map.vaults.values() {
        match pull_project(resolver.session, &data, record) {
            Ok(Some((revision, loaded))) => {
                report
                    .pulled
                    .push((format!("{}/{}", record.ns, record.name), revision, loaded));
            }
            Ok(None) => {}
            Err(error) => report
                .problems
                .push(format!("pull {}/{}: {error}", record.ns, record.name)),
        }
        // rc4-69: the team rules sent to agents reach every agent here.
        if let Err(error) = crate::team_decisions::pull(resolver.session, &data, record) {
            report
                .problems
                .push(format!("team rules {}/{}: {error}", record.ns, record.name));
        }
    }
}

/// Pull one project; `Some((revision, facts loaded))` when it moved.
fn pull_project(
    session: &Session,
    data: &Path,
    record: &VaultRecord,
) -> Result<Option<(u64, usize)>, CloudError> {
    let base = load_base(data, &record.vault_id);
    let path = format!("/vaults/{}/knowledge", record.vault_id);
    let etag = base
        .etag
        .clone()
        .unwrap_or_else(|| format!("\"{}\"", base.revision));
    let answer = session.with_client(|c| {
        c.send(
            "GET",
            &path,
            None,
            &[("If-None-Match", &etag)],
            MAX_KNOWLEDGE_BODY_BYTES,
        )
    })?;
    if answer.status == 304 {
        return Ok(None);
    }
    let revision: KnowledgeRevisionV1 = serde_json::from_value(answer.body)
        .map_err(|e| CloudError::Protocol(format!("knowledge: {e}")))?;
    revision
        .validate()
        .map_err(|e| CloudError::Protocol(e.to_string()))?;
    if revision.vault_id != record.vault_id {
        return Err(CloudError::Protocol("knowledge for another project".into()));
    }
    // Only a released revision is ever delivered to agents (C0 1.9 §3).
    if revision.state != RevisionState::Released {
        return Err(CloudError::Protocol(
            "The Cloud delivered a revision that is not released".into(),
        ));
    }
    // `validate` refused a revision without its document.
    let Some(document) = revision.document else {
        return Ok(None);
    };
    if revision.revision == base.revision && document == base.document {
        if revision.quarantined_after != base.quarantined_after {
            save_base(
                data,
                &record.vault_id,
                &BaseRevision {
                    quarantined_after: revision.quarantined_after,
                    etag: answer.etag,
                    ..base
                },
            )?;
        }
        return Ok(None);
    }
    let mut loaded = 0;
    for root in &record.roots {
        if Path::new(root).is_dir() {
            let (count, _) =
                sync_into_knowledge(root, &record.ns, &record.name, revision.revision, &document)
                    .map_err(CloudError::Local)?;
            loaded = loaded.max(count);
        }
    }
    save_base(
        data,
        &record.vault_id,
        &BaseRevision {
            revision: revision.revision,
            etag: answer.etag,
            document,
            quarantined_after: revision.quarantined_after,
        },
    )?;
    Ok(Some((revision.revision, loaded)))
}

/// A draft as `cloud status` lists it: `(outbox id, summary, last error)`.
pub type DraftLine = (String, String, Option<String>);

/// Pending and failed drafts for `cloud status`.
pub fn draft_listing(data: &Path) -> (Vec<DraftLine>, Vec<DraftLine>) {
    let outbox = Outbox::at(data);
    let describe = |items: Vec<crate::outbox::OutboxItem>| {
        items
            .into_iter()
            .map(|item| {
                let summary = queued(&item.payload).map_or_else(
                    || "(unreadable)".to_string(),
                    |q| q.draft.summary.unwrap_or_default(),
                );
                (item.id, summary, item.last_error)
            })
            .collect::<Vec<_>>()
    };
    (
        describe(outbox.list(CHANNEL_KNOWLEDGE)),
        describe(outbox.failed(CHANNEL_KNOWLEDGE)),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use lean_ctx_protocol::cloud::knowledge::{
        ContextPatchV1, DRAFT_PROPOSAL_SCHEMA, DraftProposalV1, EngineScreeningV1, FactV1,
        PatchOpV1, ProposalState, ResearchContextDocumentV1,
    };
    use serde_json::Value;

    fn fact(id: &str) -> FactV1 {
        FactV1 {
            id: id.into(),
            statement: format!("statement {id}"),
            kind: "decision".into(),
            applies_to: vec![],
            sources: vec![],
            from_contributions: vec![],
            anchors: vec![],
        }
    }

    fn queued_with(ids: &[&str], base_revision: u64) -> QueuedDraft {
        QueuedDraft {
            stable_identity: "a".repeat(64),
            root: "/tmp/p".into(),
            draft: DraftProposalV1 {
                schema: DRAFT_PROPOSAL_SCHEMA.into(),
                state: ProposalState::Draft,
                summary: Some("s".into()),
                body: None,
                sources: vec![],
                context_patch: ContextPatchV1 {
                    base_revision,
                    ops: ids
                        .iter()
                        .map(|id| PatchOpV1::AddFact { fact: fact(id) })
                        .collect(),
                },
                session_ref: "ses_1".into(),
                engine_screening: EngineScreeningV1 {
                    scanner_version: 1,
                    secrets_removed: 0,
                    pii_removed: 0,
                    items_dropped: 0,
                },
                origin: None,
            },
            ref_keyed: true,
        }
    }

    fn base(revision: u64, ids: &[&str]) -> BaseRevision {
        BaseRevision {
            revision,
            document: ResearchContextDocumentV1 {
                facts: ids.iter().map(|id| fact(id)).collect(),
                ..Default::default()
            },
            ..Default::default()
        }
    }

    #[test]
    fn drafts_move_onto_newer_bases_and_vanish_when_merged() {
        let mut q = queued_with(&["a", "b"], 1);
        assert!(rebase_onto(&mut q, &base(2, &["a"])));
        assert_eq!(q.draft.context_patch.base_revision, 2);
        assert_eq!(q.draft.context_patch.ops.len(), 1);
        let mut merged = queued_with(&["a"], 1);
        assert!(
            !rebase_onto(&mut merged, &base(3, &["a"])),
            "nothing left to propose"
        );
    }

    #[test]
    fn clashing_drafts_keep_their_old_base() {
        let mut q = queued_with(&["a"], 1);
        let mut clash = base(2, &[]);
        let mut changed = fact("a");
        changed.statement = "someone else wrote this".into();
        clash.document.facts.push(changed);
        assert!(rebase_onto(&mut q, &clash));
        assert_eq!(q.draft.context_patch.base_revision, 1);
        let _: Value = serde_json::to_value(&q).unwrap();
    }

    /// !406 follow-up: a draft queued before refs were keyed (no
    /// `ref_keyed`, the unsalted digest) reaches `send_drafts` with its
    /// vault resolved, but the local key is unavailable. It is not sent: it
    /// stays queued with its stored ref, waits with a backoff, and the run
    /// names why.
    #[test]
    fn a_legacy_draft_without_a_key_stays_queued_and_is_not_sent() {
        let (_dir, session) = crate::auth::fixture_session();
        let data = session.store.data_dir().to_path_buf();
        let checkout = tempfile::tempdir().unwrap();
        let root = checkout.path().to_string_lossy().into_owned();
        let mut legacy = serde_json::to_value(queued_with(&["a"], 0)).unwrap();
        let unsalted = super::super::draft::session_ref("20261116-091500u123456p4242s0");
        legacy["root"] = Value::from(root.clone());
        legacy["draft"]["session_ref"] = Value::from(unsalted);
        legacy.as_object_mut().unwrap().remove("ref_keyed");
        assert!(!queued(&legacy).unwrap().ref_keyed, "a pre-!406 payload");
        let outbox = Outbox::at(&data);
        let id = outbox
            .enqueue(
                CHANNEL_KNOWLEDGE,
                legacy.clone(),
                lean_ctx_time::UtcDateTime::now(),
            )
            .unwrap();

        // The vault is known for this checkout, so only the key holds the
        // draft back (no salt lookup, no request).
        let mut map = VaultMap::default();
        map.vaults.insert(
            "a".repeat(64),
            VaultRecord {
                vault_id: "3f1c2b6a-8d4e-4a7b-9c10-5e2f6a7b8c01".into(),
                ns: "acme".into(),
                name: "payments".into(),
                sealed: false,
                roots: vec![root],
            },
        );
        let config = CloudConfig::default();
        let mut resolver = Resolver {
            session: &session,
            salt: None,
            map,
            config: &config,
            explicit_link: false,
        };
        crate::session_ref::make_keyless(&data);
        let mut report = SyncReport::default();
        send_drafts(&mut resolver, &mut report);

        assert!(report.drafts_sent.is_empty());
        assert_eq!(report.problems.len(), 1, "{:?}", report.problems);
        assert!(
            report.problems[0].contains(&format!("draft {id}"))
                && report.problems[0].contains("receipts.hmac-key"),
            "{:?}",
            report.problems
        );
        let items = outbox.list(CHANNEL_KNOWLEDGE);
        assert_eq!(items.len(), 1, "still queued");
        assert_eq!(items[0].id, id);
        assert_eq!(items[0].attempts, 1);
        assert!(items[0].next_attempt_at.is_some(), "waits with a backoff");
        assert!(
            items[0]
                .last_error
                .as_deref()
                .is_some_and(|e| e.contains("receipts.hmac-key"))
        );
        assert_eq!(
            items[0].payload, legacy,
            "the stored ref is kept, never marked keyed"
        );
        assert_eq!(outbox.depth(CHANNEL_KNOWLEDGE).failed, 0, "never failed");

        // Not due yet: a second pass leaves it alone.
        let mut again = SyncReport::default();
        send_drafts(&mut resolver, &mut again);
        assert!(again.problems.is_empty(), "{:?}", again.problems);
        assert_eq!(outbox.list(CHANNEL_KNOWLEDGE)[0].attempts, 1);
    }

    /// bd 40158: only the share of an explicit `cloud link` maps a folder
    /// the person unlinked (`explicit_link`); every other resolve is refused.
    /// Without the bypass a relink would be refused and undone forever; with
    /// it inverted, sync would map the unlinked folder again.
    #[test]
    fn unlink_is_bypassed_only_by_the_explicit_link_resolve() {
        let (_dir, session) = crate::auth::fixture_session();
        let data = session.store.data_dir().to_path_buf();
        let checkout = tempfile::tempdir().unwrap();
        let root = checkout.path().canonicalize().unwrap();
        std::fs::write(root.join(".lean-ctx-id"), "payments-repo").unwrap();
        let stable = lean_ctx_protocol::cloud::vault::stable_identity(
            &crate::vault::project_identity(&root).unwrap(),
        );
        let mut map = VaultMap::default();
        map.vaults.insert(
            stable,
            VaultRecord {
                vault_id: "3f1c2b6a-8d4e-4a7b-9c10-5e2f6a7b8c01".into(),
                ns: "acme".into(),
                name: "payments".into(),
                sealed: false,
                roots: vec![root.to_string_lossy().into_owned()],
            },
        );
        map.save(&data).unwrap();
        let config = CloudConfig::default();
        // Recorded here: both resolve without a request.
        assert_eq!(
            resolve_project(&session, &config, &root).unwrap().name,
            "payments"
        );

        crate::unlinked::add(&data, &root).unwrap();
        match resolve_project(&session, &config, &root) {
            Err(MapError::Cloud(CloudError::Refused(why))) => {
                assert_eq!(why, crate::unlinked::refusal(&data));
            }
            other => panic!("an unlinked folder is refused: {other:?}"),
        }
        let linked = resolve_for_link(&session, &config, &root)
            .expect("the explicit link maps the unlinked folder");
        assert_eq!(
            (linked.ns.as_str(), linked.name.as_str()),
            ("acme", "payments")
        );
        assert!(
            crate::unlinked::contains(&data, &root),
            "the resolve never lifts the opt-out"
        );

        // A damaged opt-out store refuses the explicit link too.
        std::fs::write(data.join(crate::unlinked::FILE), "[").unwrap();
        assert!(resolve_for_link(&session, &config, &root).is_err());
    }
}