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