Skip to main content

lean_ctx_cloud/knowledge/
pull.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The network half of knowledge sync, run by the scheduler or `lean-ctx
3//! cloud sync`, never inside a tool call:
4//! 1. send queued drafts (rebased onto the newest base when possible),
5//! 2. pull new revisions of known projects into project knowledge.
6
7use std::path::Path;
8
9use base64::Engine as _;
10use base64::engine::general_purpose::STANDARD as B64;
11use lean_ctx_time::UtcDateTime;
12
13use super::doc::rebase_ops;
14use super::draft::{QueuedDraft, queued};
15use super::learn::sync_into_knowledge;
16use super::{BaseRevision, load_base, save_base};
17use crate::CloudError;
18use crate::auth::Session;
19use crate::config::CloudConfig;
20use crate::mapping::{MapError, map_root};
21use crate::outbox::{CHANNEL_KNOWLEDGE, Outbox};
22use crate::vault::{VaultMap, VaultRecord};
23use lean_ctx_protocol::cloud::knowledge::{
24    KnowledgeRevisionV1, MAX_KNOWLEDGE_BODY_BYTES, ProposalAckV1, RevisionState,
25};
26use lean_ctx_protocol::cloud::vault::OrgSaltV1;
27
28/// Seconds before a draft that waits for the person's first-share yes is
29/// looked at again.
30const CONSENT_RECHECK_SECONDS: u64 = 300;
31
32/// What one sync pass did.
33#[derive(Debug, Clone, Default, PartialEq, Eq)]
34pub struct SyncReport {
35    pub drafts_sent: Vec<u64>,
36    pub drafts_pending: usize,
37    pub drafts_failed: usize,
38    /// `(ns/name, revision, facts loaded)` per project that moved.
39    pub pulled: Vec<(String, u64, usize)>,
40    pub problems: Vec<String>,
41}
42
43/// `GET /org/salt`: the salt id and bytes identity digests are made with.
44pub fn org_salt(session: &Session) -> Result<(String, Vec<u8>), CloudError> {
45    let body = session.with_client(|c| c.get("/org/salt"))?;
46    let salt: OrgSaltV1 =
47        serde_json::from_value(body).map_err(|e| CloudError::Protocol(format!("org salt: {e}")))?;
48    salt.validate()
49        .map_err(|e| CloudError::Protocol(e.to_string()))?;
50    let bytes = B64
51        .decode(&salt.salt)
52        .map_err(|_| CloudError::Protocol("org salt is not base64".into()))?;
53    Ok((salt.org_salt_id, bytes))
54}
55
56struct Resolver<'a> {
57    session: &'a Session,
58    salt: Option<(String, Vec<u8>)>,
59    map: VaultMap,
60    config: &'a CloudConfig,
61    /// The share of an explicit `cloud link`, which may map a folder the
62    /// person unlinked; its opt-out is lifted only after the share (bd 40060).
63    explicit_link: bool,
64}
65
66impl Resolver<'_> {
67    fn salt(&mut self) -> Result<&(String, Vec<u8>), CloudError> {
68        if self.salt.is_none() {
69            self.salt = Some(org_salt(self.session)?);
70        }
71        Ok(self.salt.as_ref().expect("set above"))
72    }
73
74    /// The project for `root`, mapped in Cloud when unknown
75    /// ([`crate::mapping`]: match, first-share consent, resolve).
76    fn resolve(&mut self, stable: &str, root: &Path) -> Result<VaultRecord, MapError> {
77        // A folder the person stopped sharing (`cloud unlink`) is never
78        // mapped again on its own, also not through a kept link file.
79        if !self.explicit_link && crate::unlinked::contains(self.session.store.data_dir(), root) {
80            let reason = crate::unlinked::refusal(self.session.store.data_dir());
81            return Err(CloudError::Refused(reason).into());
82        }
83        // A resolution the link file or the identity no longer backs is
84        // never used: it is dropped and the checkout resolves again.
85        if let Some(stale) = crate::resolution::forget_stale(&mut self.map, root) {
86            tracing::info!("cloud: resolving again: {}", stale.describe());
87            self.map
88                .save(self.session.store.data_dir())
89                .map_err(|e| CloudError::Local(e.to_string()))?;
90        }
91        if let Some(record) = self.map.vaults.get(stable)
92            && record.roots.iter().any(|r| Path::new(r) == root)
93        {
94            crate::mapping::close_satisfied(self.session, self.config, stable, record);
95            return Ok(record.clone());
96        }
97        let salt = self.salt()?.clone();
98        let known = self.map.vaults.get(stable).cloned();
99        let project = map_root(
100            self.session,
101            self.config,
102            &salt,
103            stable,
104            root,
105            known.as_ref(),
106        )?;
107        // Cloud keeps an identity's first binding: an answer that is not the
108        // linked vault is refused, never recorded (fail closed).
109        crate::resolution::refuse_unlinked(root, &project.vault)?;
110        self.map.record(stable, &project, root);
111        self.map
112            .save(self.session.store.data_dir())
113            .map_err(|e| CloudError::Local(e.to_string()))?;
114        // A first-share request opened before the vault existed (another
115        // engine's sync created it) is satisfied now: never left waiting.
116        let mapped = self.map.vaults[stable].clone();
117        crate::mapping::close_satisfied(self.session, self.config, stable, &mapped);
118        Ok(mapped)
119    }
120}
121
122/// The vault the checkout at `root` is linked to, resolved in Cloud (and
123/// remembered) when this machine has no record of it yet, e.g. on the
124/// first sync after `cloud link`. A first share that waits for the
125/// person's yes is `MapError::Consent`.
126pub fn resolve_project(
127    session: &Session,
128    config: &CloudConfig,
129    root: &Path,
130) -> Result<VaultRecord, MapError> {
131    resolve_with(session, config, root, false)
132}
133
134fn resolve_with(
135    session: &Session,
136    config: &CloudConfig,
137    root: &Path,
138    explicit_link: bool,
139) -> Result<VaultRecord, MapError> {
140    let identity = crate::vault::project_identity(root)
141        .ok_or_else(|| CloudError::Config("not inside a git repository".into()))?;
142    let stable = lean_ctx_protocol::cloud::vault::stable_identity(&identity);
143    let mut resolver = Resolver {
144        session,
145        salt: None,
146        map: VaultMap::load(session.store.data_dir()),
147        config,
148        explicit_link,
149    };
150    resolver.resolve(&stable, root)
151}
152
153/// [`resolve_project`] for the share of an explicit `cloud link`: a folder
154/// the person unlinked is mapped too, while its opt-out still keeps every
155/// sender quiet; `cloud link` lifts it only once Cloud took the share
156/// (bd 40060). A damaged opt-out store still refuses.
157pub fn resolve_for_link(
158    session: &Session,
159    config: &CloudConfig,
160    root: &Path,
161) -> Result<VaultRecord, MapError> {
162    crate::unlinked::check(session.store.data_dir(), root)?;
163    resolve_with(session, config, root, true)
164}
165
166/// Cloud refused mapping a checkout to `vault` (`<ws>/<vault>`): it is not
167/// one this account may use (rc4-57). Said in the person's words, with the
168/// way forward.
169pub fn foreign_vault_refusal(vault: &str) -> String {
170    format!(
171        "your account may not use {vault}: it belongs to another account, or your role \
172         there does not allow it. With a Personal plan you use only your own vaults; to \
173         work in a vault together, its owner invites you to their team (Team plan)."
174    )
175}
176
177/// The `<ws>/<vault>` the checkout at `root` is linked to, for a refusal.
178fn linked_vault(root: &Path) -> String {
179    match crate::link::read_link(root) {
180        Ok(Some(link)) => format!("{}/{}", link.vault.ns, link.vault.name),
181        _ => "This project's vault".to_owned(),
182    }
183}
184
185/// Send drafts, then pull. `cwd_root` adds the current project to the pull
186/// even if it never drafted (for `lean-ctx cloud sync` in a project).
187pub fn sync(session: &Session, config: &CloudConfig, cwd_root: Option<&Path>) -> SyncReport {
188    let data = session.store.data_dir().to_path_buf();
189    let mut report = SyncReport::default();
190    // A used-up transfer quota or a policy hold: drafts stay queued, no
191    // request goes out until it ends (never a busy loop).
192    if let Some(held) = crate::throttle::holding(
193        &session.store,
194        crate::throttle::Scope::Sync,
195        UtcDateTime::now(),
196    ) {
197        let depth = Outbox::at(&data).depth(CHANNEL_KNOWLEDGE);
198        report.drafts_pending = depth.pending;
199        report.drafts_failed = depth.failed;
200        report.problems.push(held.refusal().to_string());
201        return report;
202    }
203    // Every checkout whose recorded vault its link file or identity no
204    // longer backs is dropped before anything is sent or pulled.
205    let map = match crate::resolution::load_current(&data) {
206        Ok((map, _)) => map,
207        Err(error) => {
208            report.problems.push(error.to_string());
209            return report;
210        }
211    };
212    let mut resolver = Resolver {
213        session,
214        salt: None,
215        map,
216        config,
217        explicit_link: false,
218    };
219    if let Some(root) = cwd_root
220        // A folder the person stopped sharing is not mapped (rc4-6).
221        && !crate::unlinked::contains(&data, root)
222        && let Some(identity) = crate::vault::project_identity(root)
223    {
224        let stable = lean_ctx_protocol::cloud::vault::stable_identity(&identity);
225        if let Err(error) = resolver.resolve(&stable, root) {
226            report.problems.push(match error {
227                MapError::Cloud(CloudError::Forbidden) => {
228                    foreign_vault_refusal(&linked_vault(root))
229                }
230                error => format!("{}: {error}", root.display()),
231            });
232        }
233    }
234    // A C0 2.0 Cloud takes no 1.x draft: capture sends the same knowledge
235    // as signed events, so a draft still queued from before is dropped.
236    if crate::bus::relay_v2::speaks_v2(&session.store) {
237        drop_drafts(&data);
238    } else {
239        send_drafts(&mut resolver, &mut report);
240    }
241    pull_all(&resolver, &mut report);
242    let outbox = Outbox::at(&data);
243    let depth = outbox.depth(CHANNEL_KNOWLEDGE);
244    report.drafts_pending = depth.pending;
245    report.drafts_failed = depth.failed;
246    let now = session.lease.service_time(UtcDateTime::now()).to_utc();
247    let stamp = now.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true);
248    if report.problems.is_empty() {
249        session.store.record_success("knowledge", &stamp);
250    } else {
251        session.store.record_error(&report.problems.join("; "));
252    }
253    report
254}
255
256fn drop_drafts(data: &Path) {
257    let outbox = Outbox::at(data);
258    for item in outbox.list(CHANNEL_KNOWLEDGE) {
259        let _ = outbox.remove(&item);
260    }
261}
262
263fn send_drafts(resolver: &mut Resolver<'_>, report: &mut SyncReport) {
264    let data = resolver.session.store.data_dir().to_path_buf();
265    let outbox = Outbox::at(&data);
266    let now = UtcDateTime::now();
267    for mut item in outbox.list(CHANNEL_KNOWLEDGE) {
268        if !item.due(now) {
269            continue;
270        }
271        let Some(mut queued_draft) = queued(&item.payload) else {
272            let _ = outbox.fail(&mut item, "damaged draft");
273            continue;
274        };
275        let record = match resolver
276            .resolve(&queued_draft.stable_identity, Path::new(&queued_draft.root))
277        {
278            Ok(record) => record,
279            Err(error) => {
280                report.problems.push(format!("draft {}: {error}", item.id));
281                // A first share waits for the person: look again soon,
282                // without the growing backoff of a failure.
283                let wait = matches!(error, MapError::Consent(_)).then_some(CONSENT_RECHECK_SECONDS);
284                let _ = outbox.retry_later(&mut item, &error.to_string(), wait, now);
285                if matches!(
286                    error,
287                    MapError::Cloud(CloudError::Unauthorized | CloudError::LeaseLapsed)
288                ) {
289                    return;
290                }
291                continue;
292            }
293        };
294        let base = load_base(&data, &record.vault_id);
295        if !rebase_onto(&mut queued_draft, &base) {
296            let _ = outbox.remove(&item);
297            continue;
298        }
299        // A draft queued before refs were keyed carries the unsalted digest:
300        // keyed now, or kept queued while the local key is unavailable.
301        if let Err(error) = queued_draft.rekey_legacy_ref(&data) {
302            report.problems.push(format!("draft {}: {error}", item.id));
303            let _ = outbox.retry_later(&mut item, &error.to_string(), None, now);
304            continue;
305        }
306        if let Ok(payload) = serde_json::to_value(&queued_draft) {
307            item.payload = payload;
308            let _ = outbox.update(&item);
309        }
310        let body = match serde_json::to_value(&queued_draft.draft) {
311            Ok(body) => body,
312            Err(error) => {
313                let _ = outbox.fail(&mut item, &error.to_string());
314                continue;
315            }
316        };
317        let path = format!("/vaults/{}/proposals", record.vault_id);
318        let result = resolver
319            .session
320            .with_client(|c| c.post_idempotent(&path, &body, &item.id));
321        match result {
322            Ok(answer) => {
323                if let Ok(ack) = serde_json::from_value::<ProposalAckV1>(answer) {
324                    report.drafts_sent.push(ack.number);
325                }
326                let _ = outbox.remove(&item);
327            }
328            Err(error @ (CloudError::Unauthorized | CloudError::LeaseLapsed)) => {
329                report.problems.push(error.to_string());
330                let _ = outbox.retry_later(&mut item, &error.to_string(), None, now);
331                return;
332            }
333            Err(CloudError::RateLimited { retry_after }) => {
334                let _ = outbox.retry_later(&mut item, "rate limited", retry_after, now);
335            }
336            // A used-up quota: this draft and the rest wait in the outbox and
337            // the throttle holds sync until it ends. A policy refusal holds
338            // this draft only, until a newer policy is in force or the
339            // hold's time is up (an admin may change the policy).
340            Err(error @ (CloudError::QuotaExceeded(_) | CloudError::PolicyDenied(_))) => {
341                let quota = matches!(error, CloudError::QuotaExceeded(_));
342                let wait = error
343                    .retry_after_at(now)
344                    .or(Some(crate::throttle::POLICY_HOLD_S.unsigned_abs()));
345                report.problems.push(format!("draft {}: {error}", item.id));
346                let _ = if quota {
347                    outbox.retry_later(&mut item, &error.to_string(), wait, now)
348                } else {
349                    outbox.hold_for_policy(&mut item, &error.to_string(), wait, now)
350                };
351                if quota {
352                    let _ = crate::throttle::note(
353                        &resolver.session.store,
354                        crate::throttle::Scope::Sync,
355                        error,
356                        now,
357                    );
358                    return;
359                }
360            }
361            Err(error) if error.is_transient() => {
362                let _ = outbox.retry_later(&mut item, &error.to_string(), None, now);
363            }
364            Err(
365                error
366                @ (CloudError::Conflict { .. } | CloudError::Forbidden | CloudError::NotFound),
367            ) => {
368                // The base moved or the right/project changed: try again after the next pull.
369                report.problems.push(format!("draft {}: {error}", item.id));
370                let _ = outbox.retry_later(&mut item, &error.to_string(), Some(900), now);
371            }
372            Err(error) => {
373                report.problems.push(format!("draft {}: {error}", item.id));
374                let _ = outbox.fail(&mut item, &error.to_string());
375            }
376        }
377    }
378}
379
380/// Rebase a queued draft onto `base` when it is newer. Returns `false` when
381/// every op is already in the base (nothing left to propose). A draft whose
382/// ops clash with the newer base keeps its old base.
383fn rebase_onto(queued_draft: &mut QueuedDraft, base: &BaseRevision) -> bool {
384    let patch = &mut queued_draft.draft.context_patch;
385    if base.revision <= patch.base_revision {
386        return true;
387    }
388    match rebase_ops(&base.document, &patch.ops) {
389        Ok(kept) if kept.is_empty() => false,
390        Ok(kept) => {
391            patch.ops = kept;
392            patch.base_revision = base.revision;
393            true
394        }
395        Err(_) => true,
396    }
397}
398
399fn pull_all(resolver: &Resolver<'_>, report: &mut SyncReport) {
400    let data = resolver.session.store.data_dir().to_path_buf();
401    for record in resolver.map.vaults.values() {
402        match pull_project(resolver.session, &data, record) {
403            Ok(Some((revision, loaded))) => {
404                report
405                    .pulled
406                    .push((format!("{}/{}", record.ns, record.name), revision, loaded));
407            }
408            Ok(None) => {}
409            Err(error) => report
410                .problems
411                .push(format!("pull {}/{}: {error}", record.ns, record.name)),
412        }
413        // rc4-69: the team rules sent to agents reach every agent here.
414        if let Err(error) = crate::team_decisions::pull(resolver.session, &data, record) {
415            report
416                .problems
417                .push(format!("team rules {}/{}: {error}", record.ns, record.name));
418        }
419    }
420}
421
422/// Pull one project; `Some((revision, facts loaded))` when it moved.
423fn pull_project(
424    session: &Session,
425    data: &Path,
426    record: &VaultRecord,
427) -> Result<Option<(u64, usize)>, CloudError> {
428    let base = load_base(data, &record.vault_id);
429    let path = format!("/vaults/{}/knowledge", record.vault_id);
430    let etag = base
431        .etag
432        .clone()
433        .unwrap_or_else(|| format!("\"{}\"", base.revision));
434    let answer = session.with_client(|c| {
435        c.send(
436            "GET",
437            &path,
438            None,
439            &[("If-None-Match", &etag)],
440            MAX_KNOWLEDGE_BODY_BYTES,
441        )
442    })?;
443    if answer.status == 304 {
444        return Ok(None);
445    }
446    let revision: KnowledgeRevisionV1 = serde_json::from_value(answer.body)
447        .map_err(|e| CloudError::Protocol(format!("knowledge: {e}")))?;
448    revision
449        .validate()
450        .map_err(|e| CloudError::Protocol(e.to_string()))?;
451    if revision.vault_id != record.vault_id {
452        return Err(CloudError::Protocol("knowledge for another project".into()));
453    }
454    // Only a released revision is ever delivered to agents (C0 1.9 ยง3).
455    if revision.state != RevisionState::Released {
456        return Err(CloudError::Protocol(
457            "LeanCTX Cloud delivered a revision that is not released".into(),
458        ));
459    }
460    // `validate` refused a revision without its document.
461    let Some(document) = revision.document else {
462        return Ok(None);
463    };
464    if revision.revision == base.revision && document == base.document {
465        if revision.quarantined_after != base.quarantined_after {
466            save_base(
467                data,
468                &record.vault_id,
469                &BaseRevision {
470                    quarantined_after: revision.quarantined_after,
471                    etag: answer.etag,
472                    ..base
473                },
474            )?;
475        }
476        return Ok(None);
477    }
478    let mut loaded = 0;
479    for root in &record.roots {
480        if Path::new(root).is_dir() {
481            let (count, _) =
482                sync_into_knowledge(root, &record.ns, &record.name, revision.revision, &document)
483                    .map_err(CloudError::Local)?;
484            loaded = loaded.max(count);
485        }
486    }
487    save_base(
488        data,
489        &record.vault_id,
490        &BaseRevision {
491            revision: revision.revision,
492            etag: answer.etag,
493            document,
494            quarantined_after: revision.quarantined_after,
495        },
496    )?;
497    Ok(Some((revision.revision, loaded)))
498}
499
500/// A draft as `cloud status` lists it: `(outbox id, summary, last error)`.
501pub type DraftLine = (String, String, Option<String>);
502
503/// Pending and failed drafts for `cloud status`.
504pub fn draft_listing(data: &Path) -> (Vec<DraftLine>, Vec<DraftLine>) {
505    let outbox = Outbox::at(data);
506    let describe = |items: Vec<crate::outbox::OutboxItem>| {
507        items
508            .into_iter()
509            .map(|item| {
510                let summary = queued(&item.payload).map_or_else(
511                    || "(unreadable)".to_string(),
512                    |q| q.draft.summary.unwrap_or_default(),
513                );
514                (item.id, summary, item.last_error)
515            })
516            .collect::<Vec<_>>()
517    };
518    (
519        describe(outbox.list(CHANNEL_KNOWLEDGE)),
520        describe(outbox.failed(CHANNEL_KNOWLEDGE)),
521    )
522}
523
524#[cfg(test)]
525mod tests {
526    use super::*;
527    use lean_ctx_protocol::cloud::knowledge::{
528        ContextPatchV1, DRAFT_PROPOSAL_SCHEMA, DraftProposalV1, EngineScreeningV1, FactV1,
529        PatchOpV1, ProposalState, ResearchContextDocumentV1,
530    };
531    use serde_json::Value;
532
533    fn fact(id: &str) -> FactV1 {
534        FactV1 {
535            id: id.into(),
536            statement: format!("statement {id}"),
537            kind: "decision".into(),
538            applies_to: vec![],
539            sources: vec![],
540            from_contributions: vec![],
541            anchors: vec![],
542        }
543    }
544
545    fn queued_with(ids: &[&str], base_revision: u64) -> QueuedDraft {
546        QueuedDraft {
547            stable_identity: "a".repeat(64),
548            root: "/tmp/p".into(),
549            draft: DraftProposalV1 {
550                schema: DRAFT_PROPOSAL_SCHEMA.into(),
551                state: ProposalState::Draft,
552                summary: Some("s".into()),
553                body: None,
554                sources: vec![],
555                context_patch: ContextPatchV1 {
556                    base_revision,
557                    ops: ids
558                        .iter()
559                        .map(|id| PatchOpV1::AddFact { fact: fact(id) })
560                        .collect(),
561                },
562                session_ref: "ses_1".into(),
563                engine_screening: EngineScreeningV1 {
564                    scanner_version: 1,
565                    secrets_removed: 0,
566                    pii_removed: 0,
567                    items_dropped: 0,
568                },
569                origin: None,
570            },
571            ref_keyed: true,
572        }
573    }
574
575    fn base(revision: u64, ids: &[&str]) -> BaseRevision {
576        BaseRevision {
577            revision,
578            document: ResearchContextDocumentV1 {
579                facts: ids.iter().map(|id| fact(id)).collect(),
580                ..Default::default()
581            },
582            ..Default::default()
583        }
584    }
585
586    #[test]
587    fn drafts_move_onto_newer_bases_and_vanish_when_merged() {
588        let mut q = queued_with(&["a", "b"], 1);
589        assert!(rebase_onto(&mut q, &base(2, &["a"])));
590        assert_eq!(q.draft.context_patch.base_revision, 2);
591        assert_eq!(q.draft.context_patch.ops.len(), 1);
592        let mut merged = queued_with(&["a"], 1);
593        assert!(
594            !rebase_onto(&mut merged, &base(3, &["a"])),
595            "nothing left to propose"
596        );
597    }
598
599    #[test]
600    fn clashing_drafts_keep_their_old_base() {
601        let mut q = queued_with(&["a"], 1);
602        let mut clash = base(2, &[]);
603        let mut changed = fact("a");
604        changed.statement = "someone else wrote this".into();
605        clash.document.facts.push(changed);
606        assert!(rebase_onto(&mut q, &clash));
607        assert_eq!(q.draft.context_patch.base_revision, 1);
608        let _: Value = serde_json::to_value(&q).unwrap();
609    }
610
611    /// !406 follow-up: a draft queued before refs were keyed (no
612    /// `ref_keyed`, the unsalted digest) reaches `send_drafts` with its
613    /// vault resolved, but the local key is unavailable. It is not sent: it
614    /// stays queued with its stored ref, waits with a backoff, and the run
615    /// names why.
616    #[test]
617    fn a_legacy_draft_without_a_key_stays_queued_and_is_not_sent() {
618        let (_dir, session) = crate::auth::fixture_session();
619        let data = session.store.data_dir().to_path_buf();
620        let checkout = tempfile::tempdir().unwrap();
621        let root = checkout.path().to_string_lossy().into_owned();
622        let mut legacy = serde_json::to_value(queued_with(&["a"], 0)).unwrap();
623        let unsalted = super::super::draft::session_ref("20261116-091500u123456p4242s0");
624        legacy["root"] = Value::from(root.clone());
625        legacy["draft"]["session_ref"] = Value::from(unsalted);
626        legacy.as_object_mut().unwrap().remove("ref_keyed");
627        assert!(!queued(&legacy).unwrap().ref_keyed, "a pre-!406 payload");
628        let outbox = Outbox::at(&data);
629        let id = outbox
630            .enqueue(
631                CHANNEL_KNOWLEDGE,
632                legacy.clone(),
633                lean_ctx_time::UtcDateTime::now(),
634            )
635            .unwrap();
636
637        // The vault is known for this checkout, so only the key holds the
638        // draft back (no salt lookup, no request).
639        let mut map = VaultMap::default();
640        map.vaults.insert(
641            "a".repeat(64),
642            VaultRecord {
643                vault_id: "3f1c2b6a-8d4e-4a7b-9c10-5e2f6a7b8c01".into(),
644                ns: "acme".into(),
645                name: "payments".into(),
646                sealed: false,
647                roots: vec![root],
648            },
649        );
650        let config = CloudConfig::default();
651        let mut resolver = Resolver {
652            session: &session,
653            salt: None,
654            map,
655            config: &config,
656            explicit_link: false,
657        };
658        crate::session_ref::make_keyless(&data);
659        let mut report = SyncReport::default();
660        send_drafts(&mut resolver, &mut report);
661
662        assert!(report.drafts_sent.is_empty());
663        assert_eq!(report.problems.len(), 1, "{:?}", report.problems);
664        assert!(
665            report.problems[0].contains(&format!("draft {id}"))
666                && report.problems[0].contains("receipts.hmac-key"),
667            "{:?}",
668            report.problems
669        );
670        let items = outbox.list(CHANNEL_KNOWLEDGE);
671        assert_eq!(items.len(), 1, "still queued");
672        assert_eq!(items[0].id, id);
673        assert_eq!(items[0].attempts, 1);
674        assert!(items[0].next_attempt_at.is_some(), "waits with a backoff");
675        assert!(
676            items[0]
677                .last_error
678                .as_deref()
679                .is_some_and(|e| e.contains("receipts.hmac-key"))
680        );
681        assert_eq!(
682            items[0].payload, legacy,
683            "the stored ref is kept, never marked keyed"
684        );
685        assert_eq!(outbox.depth(CHANNEL_KNOWLEDGE).failed, 0, "never failed");
686
687        // Not due yet: a second pass leaves it alone.
688        let mut again = SyncReport::default();
689        send_drafts(&mut resolver, &mut again);
690        assert!(again.problems.is_empty(), "{:?}", again.problems);
691        assert_eq!(outbox.list(CHANNEL_KNOWLEDGE)[0].attempts, 1);
692    }
693
694    /// bd 40158: only the share of an explicit `cloud link` maps a folder
695    /// the person unlinked (`explicit_link`); every other resolve is refused.
696    /// Without the bypass a relink would be refused and undone forever; with
697    /// it inverted, sync would map the unlinked folder again.
698    #[test]
699    fn unlink_is_bypassed_only_by_the_explicit_link_resolve() {
700        let (_dir, session) = crate::auth::fixture_session();
701        let data = session.store.data_dir().to_path_buf();
702        let checkout = tempfile::tempdir().unwrap();
703        let root = checkout.path().canonicalize().unwrap();
704        std::fs::write(root.join(".lean-ctx-id"), "payments-repo").unwrap();
705        let stable = lean_ctx_protocol::cloud::vault::stable_identity(
706            &crate::vault::project_identity(&root).unwrap(),
707        );
708        let mut map = VaultMap::default();
709        map.vaults.insert(
710            stable,
711            VaultRecord {
712                vault_id: "3f1c2b6a-8d4e-4a7b-9c10-5e2f6a7b8c01".into(),
713                ns: "acme".into(),
714                name: "payments".into(),
715                sealed: false,
716                roots: vec![root.to_string_lossy().into_owned()],
717            },
718        );
719        map.save(&data).unwrap();
720        let config = CloudConfig::default();
721        // Recorded here: both resolve without a request.
722        assert_eq!(
723            resolve_project(&session, &config, &root).unwrap().name,
724            "payments"
725        );
726
727        crate::unlinked::add(&data, &root).unwrap();
728        match resolve_project(&session, &config, &root) {
729            Err(MapError::Cloud(CloudError::Refused(why))) => {
730                assert_eq!(why, crate::unlinked::refusal(&data));
731            }
732            other => panic!("an unlinked folder is refused: {other:?}"),
733        }
734        let linked = resolve_for_link(&session, &config, &root)
735            .expect("the explicit link maps the unlinked folder");
736        assert_eq!(
737            (linked.ns.as_str(), linked.name.as_str()),
738            ("acme", "payments")
739        );
740        assert!(
741            crate::unlinked::contains(&data, &root),
742            "the resolve never lifts the opt-out"
743        );
744
745        // A damaged opt-out store refuses the explicit link too.
746        std::fs::write(data.join(crate::unlinked::FILE), "[").unwrap();
747        assert!(resolve_for_link(&session, &config, &root).is_err());
748    }
749}