Skip to main content

lean_ctx_cloud/sync/
place.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The C0 2.0 sync of one bound vault (SPEC-ENGINE §3.4.4, V1.6): clone or
3//! tail the replica, turn what the capture gate lets through into signed
4//! events, push them, tail again. Runs only when the enrolled Cloud speaks
5//! C0 2.0 ([`crate::bus::relay_v2::speaks_v2`]); against a 1.x
6//! Cloud the draft path stays as it is.
7
8use std::path::Path;
9
10use serde_json::Value;
11
12use super::driver::{self, PlaceApi, Verifier};
13use crate::auth::Session;
14use crate::capture::{self, emit};
15use crate::events::build::{Place, Signer};
16use crate::events::hlc::Stamp;
17use crate::events::sign;
18use crate::keyset_v3::{self, Purpose};
19use crate::replica::{Replica, crypt};
20use crate::vault::VaultRecord;
21use crate::workers::keys as worker_keys;
22use crate::{CloudError, knowledge::screening::Screen};
23
24/// The routes of a session, with its token refresh.
25pub struct SessionApi<'a>(pub &'a Session);
26
27impl PlaceApi for SessionApi<'_> {
28    fn get(&self, path: &str) -> Result<Value, CloudError> {
29        self.0.with_client(|c| c.get(path))
30    }
31    fn get_bytes(&self, path: &str, max: usize) -> Result<Vec<u8>, CloudError> {
32        self.0.with_client(|c| c.get_bytes(path, max))
33    }
34    fn post(&self, path: &str, body: &Value) -> Result<Value, CloudError> {
35        self.0.with_client(|c| c.post(path, body))
36    }
37}
38
39/// Host app the CLI and the session hooks capture as.
40pub(crate) const CAPTURE_HOST: &str = "lean-ctx";
41pub const CAPTURE_ROLE: &str = "capture";
42/// Replica meta key: `created_at` of the newest fact the gate considered.
43const CAPTURE_SINCE: &str = "capture_since";
44/// Replica meta: when an imported fact (`lean-ctx import docs|git`) last
45/// changed that the previous capture considered (a re-import updates facts
46/// in place, so imports keep their own mark).
47const IMPORT_SINCE: &str = "import_since";
48
49/// What one vault sync did.
50#[derive(Debug, Clone, Default, PartialEq, Eq)]
51pub struct VaultSync {
52    pub cloned: bool,
53    pub stored: usize,
54    pub captured: usize,
55    /// Episodes queued for sessions that ended (V1.4).
56    pub episodes: usize,
57    /// Own local facts removed because a purge took their text out.
58    pub purged_local: usize,
59    /// Purge tombstones newly acknowledged.
60    pub purge_acks: usize,
61    /// Facts copied in by 1.x pulls, removed once the replica serves the
62    /// vault (V4.10).
63    pub legacy_removed: usize,
64    pub pushed: usize,
65    /// Anchor states the automatic re-check queued (`to_verify`, `gone`,
66    /// or `fresh` again).
67    pub rechecked: usize,
68    /// Own nodes the capture lifecycle queued as superseded (`edge.add
69    /// supersedes` from their successor), withdrawn (`retract`) and
70    /// re-anchored after a local re-pin (`field.set anchors`).
71    pub superseded: usize,
72    pub retracted: usize,
73    pub confirmed: usize,
74    /// Links queued between two Instances' values of one shared fact:
75    /// `supersedes` for a sequential edit, `contradicts` for a conflict
76    /// (#286, [`capture::conflicts`]).
77    pub fact_links: usize,
78    /// Doc pages whose anchored code moved since this sync last looked.
79    pub docs_behind: usize,
80    /// Events the place refused for good: (event id, refusal).
81    pub failed: Vec<(String, String)>,
82    pub counts: capture::CaptureCounts,
83    /// A deletions-only pass (the month's transfer used up) found an
84    /// ordinary tail page: the quota is back.
85    pub quota_back: bool,
86}
87
88/// Whether an event's signature verifies under the signer rules of §3.3.5:
89/// a worker event by a key of this place that signs for its worker id, any
90/// other actor by a Cloud key of purpose `event` valid when received.
91pub(super) fn signature_ok(session: &Session, place_ref: &str, event: &Value) -> bool {
92    let key_id = event
93        .get("key_id")
94        .and_then(Value::as_str)
95        .unwrap_or_default();
96    let received_at = event
97        .get("received_at")
98        .and_then(Value::as_u64)
99        .unwrap_or(u64::MAX);
100    match event.pointer("/actor/kind").and_then(Value::as_str) {
101        Some("worker") => {
102            let Some(worker) = event.get("worker_id").and_then(Value::as_str) else {
103                return false;
104            };
105            let signs = |found: &Option<([u8; 32], Vec<String>)>| {
106                matches!(found, Some((key, workers))
107                    if workers.iter().any(|x| x == worker) && sign::verify(event, key))
108            };
109            let found = worker_keys::worker_key_or_fetch(session, place_ref, key_id, received_at)
110                .ok()
111                .flatten();
112            if signs(&found) {
113                return true;
114            }
115            // A key cached before its worker registered lists no (or an
116            // older set of) workers: fetch the place's keys once more.
117            found.is_some()
118                && worker_keys::fetch(session, place_ref).is_ok()
119                && signs(&worker_keys::worker_key(
120                    &session.store,
121                    place_ref,
122                    key_id,
123                    received_at,
124                ))
125        }
126        Some("person" | "server" | "legacy_import") => keyset_v3::cloud_keys(
127            &session.store,
128            session.root_key(),
129            Purpose::Event,
130            received_at,
131        )
132        .iter()
133        .any(|(id, key)| id == key_id && sign::verify(event, key)),
134        _ => false,
135    }
136}
137
138/// The C0 2.0 place id of a vault: the canonical hyphenated UUID. A 1.x
139/// link resolve may hand out the same id as 32 plain hex digits, which a
140/// C0 2.0 Cloud does not accept as its place name.
141pub fn place_id(vault_id: &str) -> String {
142    uuid::Uuid::parse_str(vault_id)
143        .map_or_else(|_| vault_id.to_string(), |u| u.hyphenated().to_string())
144}
145
146/// The instance id as C0 2.0 names it: the hyphenated UUID of the 1.x
147/// `inst_<32 hex>` id.
148pub fn canonical_instance_id(instance_id: &str) -> String {
149    place_id(instance_id.strip_prefix("inst_").unwrap_or(instance_id))
150}
151
152/// The automatic anchor re-check of one sync (v5 2.2.1): the deterministic
153/// `--stale` task of `cloud maintain`, queued after this run's capture
154/// events (continuing `clock`). Returns how many states it queued and the
155/// clock after them; an error is logged and counts as none, so the sync goes
156/// on.
157fn recheck_anchors(
158    replica: &Replica,
159    place: &Place,
160    signer: &Signer<'_>,
161    checkout: &mut capture::refs::Checkout,
162    now: u64,
163    clock: Stamp,
164) -> (usize, Stamp) {
165    use crate::review::maintain;
166    let req = maintain::Request {
167        vault: String::new(),
168        stale: true,
169        contradictions: false,
170        dedupe: false,
171        limit: maintain::DEFAULT_LIMIT,
172        confirm: None,
173    };
174    let target = maintain::Target {
175        replica,
176        place,
177        signer,
178    };
179    match maintain::run_stale_at(&target, checkout, &req, now, clock) {
180        Ok((counts, clock)) => (counts.done, clock),
181        Err(e) => {
182            tracing::warn!("cloud: anchor re-check skipped: {e}");
183            (0, clock)
184        }
185    }
186}
187
188/// Replica meta keys of the lifecycle gate, per checkout (`<key>:<project
189/// hash>`; checkouts of one vault share its replica but each has its own
190/// knowledge store): the knowledge journal's LSN and the time (unix ms) of
191/// the last lifecycle pass.
192const LIFECYCLE_LSN: &str = "lifecycle_lsn";
193const LIFECYCLE_AT: &str = "lifecycle_at";
194/// The longest a lifecycle pass is skipped while nothing moved: it covers
195/// what neither the journal nor the tail records (a store edited outside the
196/// engine).
197const LIFECYCLE_FULL_MS: u64 = 60 * 60 * 1000;
198
199/// Whether a lifecycle pass has work: the knowledge journal moved since the
200/// last pass, the place delivered new events (another engine may have marked
201/// a claim this checkout already re-pinned), or an hour passed; and the
202/// journal LSN to record.
203fn lifecycle_due(
204    replica: &Replica,
205    root: &Path,
206    project_hash: &str,
207    remote_changed: bool,
208    now: u64,
209) -> Result<(bool, u64), CloudError> {
210    let head = lean_ctx::core::knowledge::knowledge_dir_of(&root.to_string_lossy())
211        .map_or(0, |dir| lean_ctx::core::knowledge::journal::head_lsn(&dir));
212    let read = |key: &str| -> Result<Option<u64>, CloudError> {
213        Ok(replica
214            .meta(&format!("{key}:{project_hash}"))?
215            .and_then(|v| String::from_utf8(v.to_vec()).ok())
216            .and_then(|s| s.parse().ok()))
217    };
218    let due = match (read(LIFECYCLE_LSN)?, read(LIFECYCLE_AT)?) {
219        (Some(lsn), Some(at)) => {
220            remote_changed || lsn != head || now.saturating_sub(at) >= LIFECYCLE_FULL_MS
221        }
222        _ => true,
223    };
224    Ok((due, head))
225}
226
227/// The capture lifecycle of one sync ([`capture::lifecycle`]): what the
228/// agent superseded, withdrew or re-pinned since its facts were captured,
229/// queued after this run's capture and re-check events. A failure is logged
230/// and plans nothing, so the sync goes on.
231#[allow(clippy::too_many_arguments)]
232fn lifecycle(
233    target: &crate::review::maintain::Target<'_>,
234    graph: &crate::replica::fold::Graph,
235    checkout: &mut capture::refs::Checkout,
236    root: &Path,
237    project_hash: &str,
238    remote_changed: bool,
239    now: u64,
240    clock: Stamp,
241) -> Result<capture::lifecycle::Queued, CloudError> {
242    use capture::lifecycle;
243    let idle = lifecycle::Queued {
244        clock,
245        ..lifecycle::Queued::default()
246    };
247    let (due, head) = lifecycle_due(target.replica, root, project_hash, remote_changed, now)?;
248    if !due {
249        return Ok(idle);
250    }
251    let Some(store) = lifecycle::store_facts(target.replica, &root.to_string_lossy()) else {
252        tracing::debug!("cloud: lifecycle skipped, the knowledge store is not readable");
253        return Ok(idle);
254    };
255    let own = lifecycle::own_nodes(target.replica, project_hash)?;
256    let present = lifecycle::present(graph, target.replica)?;
257    let removed = lifecycle::removed_identities(&root.to_string_lossy());
258    let actions = lifecycle::plan(
259        &own,
260        &store,
261        &removed,
262        |id| present.view(graph, id),
263        &present,
264    );
265    let queued = lifecycle::queue(target, graph, checkout, &actions, clock, now)?;
266    target.replica.set_meta(
267        &format!("{LIFECYCLE_LSN}:{project_hash}"),
268        head.to_string().as_bytes(),
269    )?;
270    target.replica.set_meta(
271        &format!("{LIFECYCLE_AT}:{project_hash}"),
272        now.to_string().as_bytes(),
273    )?;
274    Ok(queued)
275}
276
277/// The claims of `knowledge` (after `since`) that pass the capture gate.
278///
279/// v5 2.6.1: a `node:<id>` reference is valid only for a live node of this
280/// place's folded `graph`, so the gate's checkout learns those ids first;
281/// without them every `node:` reference was dropped as invalid and no
282/// `derived_from` edge was ever written (dogfood e2e, scenario 2). A claim
283/// that names a live node then carries a `derived_from` edge to it, its own
284/// provenance (not telemetry).
285///
286/// K1: the facts `lean-ctx import docs|git` made from the repository pass
287/// the same gate after `import_since`, with their import source as the
288/// reference (`file:<path>`, `commit:<sha>`). The plan's `watermark` is the
289/// learned facts' mark; the imports' mark is returned next to it.
290fn plan_capture(
291    knowledge: &lean_ctx::core::knowledge::ProjectKnowledge,
292    since: Option<lean_ctx_time::UtcDateTime>,
293    import_since: Option<lean_ctx_time::UtcDateTime>,
294    run: &mut capture::CaptureRun<'_>,
295    graph: &crate::replica::fold::Graph,
296) -> (
297    crate::knowledge::learn::LearnPlan,
298    Option<lean_ctx_time::UtcDateTime>,
299) {
300    use crate::knowledge::learn::{plan_import, plan_learn};
301    run.checkout
302        .nodes
303        .extend(graph.live_nodes().map(|(id, _)| id.clone()));
304    let repo = lean_ctx_protocol::cloud::knowledge::ResearchContextDocumentV1::default();
305    let mut plan = plan_learn(knowledge, &repo, since, usize::MAX, run);
306    let imported = plan_import(knowledge, &repo, import_since, usize::MAX, run);
307    plan.added.extend(imported.added);
308    plan.dropped.extend(imported.dropped);
309    plan.merges.extend(imported.merges);
310    plan.import_sources.extend(imported.import_sources);
311    plan.captured.extend(imported.captured);
312    capture::derived::link(&mut plan.captured, graph);
313    (plan, imported.watermark)
314}
315
316/// Sync the vault `record` bound to the checkout at `root`. While a quota
317/// or policy throttle holds sync, nothing is asked of Cloud: the replica
318/// keeps its pending events and the refusal says until when.
319/// Whether sync may capture this machine's knowledge into the vault: the
320/// same switches the `knowledge remember` note reads.
321pub fn capture_allowed(config: &crate::CloudConfig) -> bool {
322    config.enabled != Some(false) && config.auto_capture
323}
324
325pub fn sync_vault(
326    session: &Session,
327    record: &VaultRecord,
328    root: &Path,
329    screen: &mut Screen,
330) -> Result<VaultSync, CloudError> {
331    use crate::throttle::{self, Scope};
332    // Never into a vault the checkout left (a pulled link file, an
333    // identity change): nothing is pulled from or pushed to it.
334    crate::resolution::refuse_stale_record(
335        session.store.data_dir(),
336        &session.instance.vault_scope(),
337        record,
338        root,
339    )?;
340    let now = lean_ctx_time::UtcDateTime::now();
341    if let Err(held) = throttle::check(&session.store, Scope::Sync, now) {
342        // A used-up transfer still delivers deletions (protected capacity):
343        // apply and ack them, then keep waiting, unless the answer shows
344        // the quota is back (E2E-FINAL: purges stayed `propagating`).
345        if !throttle::quota_holds(&session.store, Scope::Sync, now) {
346            return Err(held);
347        }
348        match sync_vault_once(session, record, root, screen, true) {
349            Ok(done) if done.quota_back => throttle::quota_lifted(&session.store, Scope::Sync),
350            Ok(done) => {
351                if done.purge_acks > 0 {
352                    tracing::info!(
353                        "cloud: {} purge tombstones of {} applied and acknowledged while transfer is used up",
354                        done.purge_acks,
355                        record.vault_id
356                    );
357                }
358                return Err(held);
359            }
360            Err(e) => {
361                tracing::warn!(
362                    "cloud: deletions of {} not applied yet: {e}",
363                    record.vault_id
364                );
365                return Err(held);
366            }
367        }
368    }
369    // A used-up transfer quota holds sync; a policy refusal of this vault
370    // is this vault's alone and holds nothing else.
371    let done = sync_vault_once(session, record, root, screen, false).map_err(|e| {
372        throttle::note_on(&session.store, None, e, lean_ctx_time::UtcDateTime::now())
373    })?;
374    throttle::passed(&session.store, Scope::Sync);
375    Ok(done)
376}
377
378fn sync_vault_once(
379    session: &Session,
380    record: &VaultRecord,
381    root: &Path,
382    screen: &mut Screen,
383    deletions_only: bool,
384) -> Result<VaultSync, CloudError> {
385    let store = &session.store;
386    let place_ref = format!("vault:{}", place_id(&record.vault_id));
387    let (mk, _) = crypt::master_key(store.config_dir(), false)?;
388    let (mut replica, _) = Replica::open(store.data_dir(), &record.vault_id, &mk)?;
389    // Fresh Cloud keys when we can; the last verified set otherwise.
390    if keyset_v3::refresh(session).is_err() && keyset_v3::load(store, session.root_key()).is_none()
391    {
392        return Err(CloudError::Protocol("no verified Cloud key set v3".into()));
393    }
394    let now = lean_ctx_time::UtcDateTime::now()
395        .timestamp_millis()
396        .unsigned_abs();
397    let snapshot_keys: Vec<[u8; 32]> =
398        keyset_v3::cloud_keys(store, session.root_key(), Purpose::Snapshot, now)
399            .into_iter()
400            .map(|(_, k)| k)
401            .collect();
402    let check = |e: &Value| signature_ok(session, &place_ref, e);
403    let verifier = Verifier {
404        snapshot_keys: &snapshot_keys,
405        signature_ok: &check,
406    };
407    let api = SessionApi(session);
408    let mut report = VaultSync::default();
409    if deletions_only {
410        let Some(graph) = driver::deletions(&api, &mut replica, &place_ref, &verifier)? else {
411            report.quota_back = true;
412            return Ok(report);
413        };
414        let applied = super::purge::apply(&mut replica, &graph, now)?;
415        report.purged_local =
416            super::purge::purge_local_store(&replica, &graph, &root.to_string_lossy())?;
417        report.purge_acks = applied.new_acks;
418        let writer = super::writer::VaultWriter::open(session, CAPTURE_ROLE)?;
419        let acks = super::purge::signed_pending(&replica, &place_ref, writer.keys.signing_key())?;
420        driver::push_acks(&api, &place_ref, &acks)?;
421        super::purge::mark_sent(&replica, &acks)?;
422        return Ok(report);
423    }
424    let (first, seen_before_pull) = pull(&api, &mut replica, &place_ref, &verifier)?;
425    report.cloned = first.cloned;
426    report.stored = first.stored;
427    // Events stored unverified get one more check against current keys
428    // (a signer's worker can register after its key was first cached).
429    if let Some(pk) = replica.id_salt()? {
430        for (id, event) in replica.unverified()? {
431            if super::records::event_verifies(&event, &pk, &check) {
432                replica.mark_verified(&id)?;
433            }
434        }
435    }
436    // V4.10 / §3.16: the vault is now delivered from its replica; the facts
437    // its 1.x revisions copied into the project knowledge go, and the local
438    // relations that named them move to the replica nodes.
439    if first.cloned {
440        report.legacy_removed = crate::migrate::retire_on_clone(store, &replica, record, root)?;
441    }
442
443    // Purges (§3.4.6): deny purged statements, remove own local text, queue
444    // one ack per tombstone.
445    let graph = replica.refold()?;
446    let applied = super::purge::apply(&mut replica, &graph, now)?;
447    report.purged_local =
448        super::purge::purge_local_store(&replica, &graph, &root.to_string_lossy())?;
449    report.purge_acks = applied.new_acks;
450
451    // Capture: what the gate lets through becomes signed node.add events.
452    let pk_id = replica
453        .id_salt()?
454        .ok_or_else(|| CloudError::Local("replica has no id_salt".into()))?;
455    // Worker ids and hlc.node are derived from the instance UUID as C0 2.0
456    // names it (the server recomputes the worker id from it).
457    let writer = super::writer::VaultWriter::open(session, CAPTURE_ROLE)?;
458    let keys = &writer.keys;
459    // E2E 27.10. E5: `[cloud] auto_capture = false` (or a "not shared"
460    // answer, which writes it) means nothing new leaves this machine.
461    let capture_on = capture_allowed(&lean_ctx::core::config::Config::load().cloud);
462    if !capture_on {
463        tracing::info!("cloud: capture is off on this machine (`cloud.auto_capture`)");
464    }
465    // The HLC of the last event this run queued, continued by the doc re-check.
466    let mut run_clock = Stamp::default();
467    if let Some(knowledge) = capture_on
468        .then(|| lean_ctx::core::knowledge::ProjectKnowledge::load(&root.to_string_lossy()))
469        .flatten()
470    {
471        let (mut run, place_name) = capture::open_run(
472            store.data_dir(),
473            &crate::vault::project_identity(root)
474                .map(|i| lean_ctx_protocol::cloud::vault::stable_identity(&i))
475                .unwrap_or_default(),
476            root,
477            screen,
478            lean_ctx_time::UtcDateTime::now().timestamp_millis(),
479        );
480        run.pk_id = pk_id;
481        let mark = |key: &str| -> Result<Option<lean_ctx_time::UtcDateTime>, CloudError> {
482            Ok(replica
483                .meta(key)?
484                .and_then(|v| String::from_utf8(v.to_vec()).ok())
485                .and_then(|s| lean_ctx_time::OffsetDateTime::parse_from_rfc3339(&s).ok())
486                .map(lean_ctx_time::OffsetDateTime::to_utc))
487        };
488        let (since, import_since) = (mark(CAPTURE_SINCE)?, mark(IMPORT_SINCE)?);
489        let (plan, import_mark) = plan_capture(&knowledge, since, import_since, &mut run, &graph);
490        // What the gate kept local, per fact, for the sync status (local).
491        capture::sharing::record_rejected(
492            store.data_dir(),
493            &place_id(&record.vault_id),
494            &plan.dropped,
495            lean_ctx_time::UtcDateTime::now(),
496        );
497        let place = super::writer::vault_place(record, &replica)?;
498        let signer = writer.signer();
499        // The checkout's name in `own_sources` (never shared): what the
500        // capture lifecycle finds this checkout's own nodes by.
501        let project_hash =
502            blake3::hash(root.to_string_lossy().as_bytes()).to_hex()[..16].to_owned();
503        // #286: a fact's save names the log position its author could have
504        // seen when it wrote the fact: what this Instance had folded before
505        // this sync's pull. Another Instance's value pulled just now was not
506        // seen, so the two are concurrent (a conflict), not an edit.
507        let fact_place = Place {
508            causal_base: seen_before_pull,
509            ..place.clone()
510        };
511        // V9: sessions only for a Cloud that announced it accepts them.
512        let sessions = crate::session_ref::SessionRefs::for_store(&session.store);
513        let target = emit::Target {
514            replica: &replica,
515            place: &fact_place,
516            signer: &signer,
517            project_hash: &project_hash,
518            decision_anchors: crate::bus::relay_v2::speaks_2_2(&session.store),
519            sessions: sessions.as_ref(),
520        };
521        let emitted = emit::emit(
522            &target,
523            &mut run.checkout,
524            &plan.captured,
525            Stamp::default(),
526            now,
527        )?;
528        report.captured = emitted.queued.len();
529        // V1.4: the checkout's sessions that ended become episodes.
530        let ended = capture::episode::emit_ended(
531            &target,
532            root,
533            store.data_dir(),
534            &mut run,
535            emitted.clock,
536            now,
537        )?;
538        // Without the local key no episode names a session; the sync goes
539        // on and `cloud status` says why.
540        if let Some(error) = &ended.withheld {
541            store.record_error(&format!("episodes not queued: {error}"));
542        }
543        let clock = ended.clock;
544        report.episodes = ended.queued;
545        // v5 2.2.1: every sync re-checks the anchored claims against this
546        // checkout (`cloud maintain --stale`, automatically): a changed
547        // anchor makes the claim `outdated` until a person confirms it
548        // (`--confirm`). A failed re-check never fails the sync.
549        let (rechecked, clock) =
550            recheck_anchors(&replica, &place, &signer, &mut run.checkout, now, clock);
551        report.rechecked = rechecked;
552        // What the agent superseded, withdrew or re-pinned since capture
553        // (the knowledge journal gates it; a failure never fails the sync).
554        let maintain_target = crate::review::maintain::Target {
555            replica: &replica,
556            place: &place,
557            signer: &signer,
558        };
559        run_clock = clock;
560        match lifecycle(
561            &maintain_target,
562            &graph,
563            &mut run.checkout,
564            root,
565            &project_hash,
566            report.stored > 0,
567            now,
568            clock,
569        ) {
570            Ok(queued) => {
571                report.superseded = queued.superseded;
572                report.retracted = queued.retracted;
573                report.confirmed = queued.confirmed;
574                run_clock = queued.clock;
575            }
576            Err(e) => tracing::warn!("cloud: knowledge lifecycle skipped: {e}"),
577        }
578        capture::finish_run(store.data_dir(), &place_name, &run)?;
579        report.counts = run.counts.clone();
580        if let Some(mark) = plan.watermark {
581            replica.set_meta(CAPTURE_SINCE, mark.to_rfc3339().as_bytes())?;
582        }
583        if let Some(mark) = import_mark {
584            replica.set_meta(IMPORT_SINCE, mark.to_rfc3339().as_bytes())?;
585        }
586    }
587    // Docs (C0 2.2): a page whose derived anchors moved gets its
588    // `anchor_state` and `drift`, also in a checkout without project
589    // knowledge; a failure never fails the sync.
590    if capture_on {
591        let docs = crate::docs::require_docs_protocol(store)
592            .and_then(|()| crate::docs::space(&replica))
593            .and_then(|space| {
594                let specs = crate::docs::recheck(&root.to_string_lossy(), &space);
595                let pages = specs.len() / 2;
596                let place = super::writer::vault_place(record, &replica)?;
597                let signer = writer.signer();
598                let target = crate::review::maintain::Target {
599                    replica: &replica,
600                    place: &place,
601                    signer: &signer,
602                };
603                let mut screen = crate::knowledge::screening::Screen::for_installation();
604                crate::docs::queue_specs_at(&target, specs, &mut screen, now, run_clock)
605                    .map(|(_, clock)| (pages, clock))
606            });
607        match docs {
608            Ok((pages, clock)) => {
609                report.docs_behind = pages;
610                // The conflict edges below continue after the doc events.
611                run_clock = clock;
612            }
613            Err(e) => tracing::warn!("cloud: doc anchor re-check skipped: {e}"),
614        }
615    }
616
617    let acks = super::purge::signed_pending(&replica, &place_ref, keys.signing_key())?;
618    let pushed = driver::push_pending(&api, &replica, &place_ref, &acks)?;
619    if pushed.acked {
620        super::purge::mark_sent(&replica, &acks)?;
621    }
622    report.pushed = pushed.logged;
623    report.failed = pushed.failed;
624    let after = driver::tail(&api, &mut replica, &place_ref, &verifier)?;
625    report.stored += after.stored;
626
627    // #286: two Instances' values for one shared fact are linked (a
628    // sequential edit `supersedes`, concurrent values `contradicts`), the
629    // edge written by the one Instance the resolution names and pushed at
630    // once so every Instance serves the same state. Detected on
631    // the graph after the tail (own and other Instances' latest nodes); a
632    // failure never fails the sync.
633    if capture_on {
634        match detect_conflicts(record, &replica, &writer, &pk_id, run_clock, now) {
635            Ok(0) => {}
636            Ok(queued) => {
637                report.fact_links = queued;
638                let pushed = driver::push_pending(&api, &replica, &place_ref, &[])?;
639                report.pushed += pushed.logged;
640                report.failed.extend(pushed.failed);
641                report.stored += driver::tail(&api, &mut replica, &place_ref, &verifier)?.stored;
642            }
643            Err(e) => tracing::warn!("cloud: conflict detection skipped: {e}"),
644        }
645    }
646    Ok(report)
647}
648
649/// Pull the place: a clone on the first sync, a tail otherwise. Also
650/// returns the log position this Instance had folded before the pull (0
651/// before its first clone): the most its facts written since its last sync
652/// could have seen, which their saves carry as `causal_base` (#286).
653pub(super) fn pull(
654    api: &dyn PlaceApi,
655    replica: &mut Replica,
656    place_ref: &str,
657    verifier: &Verifier<'_>,
658) -> Result<(driver::SyncReport, u64), CloudError> {
659    let seen = replica.cursor()?;
660    let report = match seen {
661        None => driver::clone_place(api, replica, place_ref, verifier)?,
662        Some(_) => driver::tail(api, replica, place_ref, verifier)?,
663    };
664    Ok((report, seen.unwrap_or(0)))
665}
666
667/// Queue this Instance's fact links ([`capture::conflicts`]); how many.
668fn detect_conflicts(
669    record: &VaultRecord,
670    replica: &Replica,
671    writer: &super::writer::VaultWriter,
672    pk_id: &[u8; 32],
673    clock: Stamp,
674    now: u64,
675) -> Result<usize, CloudError> {
676    let place = super::writer::vault_place(record, replica)?;
677    let signer = writer.signer();
678    let target = crate::review::maintain::Target {
679        replica,
680        place: &place,
681        signer: &signer,
682    };
683    capture::conflicts::detect(&target, pk_id, clock, now).map(|(queued, _)| queued)
684}
685
686#[cfg(test)]
687mod capture_tests {
688    use ed25519_dalek::SigningKey;
689
690    use super::*;
691    use crate::replica::fold::{FoldEvent, Graph};
692
693    /// A live node of engine A, as B's replica folded it.
694    const A_NODE: &str = "n_q7zk2m4xv3bt6yhw5rn2jc7dpa";
695    /// A well-formed id the place does not hold.
696    const UNKNOWN: &str = "n_aaaaaaaaaaaaaaaaaaaaaacab4";
697
698    fn graph() -> Graph {
699        let mut g = Graph::default();
700        g.fold(&[FoldEvent {
701            seq: 1,
702            event_id: format!("E{:025}", 1),
703            op: "node.add".into(),
704            target: Some(A_NODE.into()),
705            node_type: Some("fact".into()),
706            body: Some(serde_json::json!({
707                "statement": "The ledger close holds advisory lock 42.",
708                "applies_to": []
709            })),
710            sig_invalid: false,
711            provenance: Some("workspace".into()),
712            review_state: Some("confirmed".into()),
713        }])
714        .unwrap();
715        g
716    }
717
718    /// Dogfood 02.11.: `lean-ctx import docs` made 515 facts and the 2.x
719    /// sync captured none of them (only the v1 draft path planned imports).
720    /// An imported doc fact passes the gate with its file as the reference,
721    /// and its own mark keeps the next sync from planning it again.
722    #[test]
723    fn imported_doc_facts_are_captured_with_their_file_on_sync() {
724        let repo = capture::tests::repo();
725        std::fs::create_dir_all(repo.path().join("docs")).unwrap();
726        std::fs::write(
727            repo.path().join("docs/guide.md"),
728            "# Retry\n\n## Budget\n\nPayments retry a failed charge at most three times.\n",
729        )
730        .unwrap();
731        for args in [&["add", "."][..], &["commit", "-q", "-m", "docs"]] {
732            let ok = std::process::Command::new("git")
733                .args(["-c", "user.name=LC", "-c", "user.email=lc@cloud.local"])
734                .args(args)
735                .current_dir(repo.path())
736                .status()
737                .unwrap()
738                .success();
739            assert!(ok, "git {args:?}");
740        }
741        let mut f = capture::tests::fact(
742            "arch",
743            "Payments retry a failed charge at most three times before they give up.",
744        );
745        f.imported_from = Some("docs".into());
746        f.key = "docs/guide.md#retry/budget/1".into();
747        let mut knowledge =
748            lean_ctx::core::knowledge::ProjectKnowledge::new(&repo.path().to_string_lossy());
749        knowledge.facts.push(f.clone());
750
751        let mut screen =
752            Screen::with_rules(Vec::new(), std::sync::Arc::new(Vec::new()), Vec::new());
753        let mut run = capture::CaptureRun::new(&mut screen, repo.path(), [9; 32], Vec::new(), 0);
754        let (plan, mark) = plan_capture(&knowledge, None, None, &mut run, &graph());
755        assert_eq!(plan.captured.len(), 1, "{:?}", plan.dropped);
756        assert!(
757            plan.captured[0]
758                .refs
759                .iter()
760                .any(|r| r == "file:docs/guide.md"),
761            "{:?}",
762            plan.captured[0].refs
763        );
764        assert_eq!(
765            plan.import_sources,
766            ["import:docs:docs/guide.md#retry-budget"]
767        );
768        assert_eq!(mark, Some(f.created_at.max(f.last_confirmed)));
769        assert_eq!(plan.watermark, None, "no learned fact moved the learn mark");
770
771        let mut screen =
772            Screen::with_rules(Vec::new(), std::sync::Arc::new(Vec::new()), Vec::new());
773        let mut run = capture::CaptureRun::new(&mut screen, repo.path(), [9; 32], Vec::new(), 0);
774        let (again, _) = plan_capture(&knowledge, None, mark, &mut run, &graph());
775        assert!(again.captured.is_empty(), "{:?}", again.import_sources);
776    }
777
778    /// Dogfood e2e scenario 2: B remembers a claim with `--ref file:… --ref
779    /// node:<A's live node>` and syncs. The sync's capture step must keep
780    /// the node reference and queue a `derived_from` edge after the claim;
781    /// before the fix the gate knew no node ids and dropped it.
782    #[test]
783    fn a_remembered_node_reference_becomes_a_derived_from_edge_on_sync() {
784        let repo = capture::tests::repo();
785        let mut f = capture::tests::fact(
786            "arch",
787            "The nightly export waits for advisory lock 42 before the ledger close.",
788        );
789        f.capture.refs = vec![
790            "file:src/lib.rs".into(),
791            format!("node:{A_NODE}"),
792            format!("node:{UNKNOWN}"),
793        ];
794        let mut knowledge =
795            lean_ctx::core::knowledge::ProjectKnowledge::new(&repo.path().to_string_lossy());
796        knowledge.facts.push(f);
797
798        let mut screen =
799            Screen::with_rules(Vec::new(), std::sync::Arc::new(Vec::new()), Vec::new());
800        let mut run = capture::CaptureRun::new(&mut screen, repo.path(), [9; 32], Vec::new(), 0);
801        let graph = graph();
802        let (plan, _) = plan_capture(&knowledge, None, None, &mut run, &graph);
803        assert_eq!(plan.captured.len(), 1, "{:?}", plan.dropped);
804        assert_eq!(plan.captured[0].derived_from, [A_NODE]);
805        assert!(
806            !plan.captured[0].refs.iter().any(|r| r.contains(UNKNOWN)),
807            "a node the place does not hold is no reference"
808        );
809
810        let data = tempfile::tempdir().unwrap();
811        let (replica, _) = Replica::open(data.path(), "pl_sync_derive", &[3; 32]).unwrap();
812        let key = SigningKey::from_bytes(&[0x49; 32]);
813        let place = Place {
814            kind: "vault".into(),
815            id: "3f1c2b6a-8d4e-4a7b-9c10-5e2f6a7b8c01".into(),
816            pk_id: [9; 32],
817            causal_base: 1,
818        };
819        let signer = Signer {
820            key: &key,
821            hlc_node: "6f2b9c4e-1a3d-4e5f-8a7b-0c1d2e3f4a5b".into(),
822            worker_id: "wkr_vk4oelpv5lzjmev44hun".into(),
823        };
824        let target = emit::Target {
825            replica: &replica,
826            place: &place,
827            signer: &signer,
828            project_hash: "ph",
829            decision_anchors: false,
830            sessions: None,
831        };
832        let out = emit::emit(
833            &target,
834            &mut run.checkout,
835            &plan.captured,
836            Stamp::default(),
837            1_792_800_000_000,
838        )
839        .unwrap();
840        assert_eq!(out.queued.len(), 1);
841        let pending: Vec<Value> = replica
842            .pending()
843            .unwrap()
844            .iter()
845            .map(|(_, b)| serde_json::from_slice(b).unwrap())
846            .collect();
847        let ops: Vec<&str> = pending.iter().map(|e| e["op"].as_str().unwrap()).collect();
848        assert_eq!(ops, ["node.add", "edge.add"]);
849        let applies_to = pending[0]["body"]["applies_to"].as_array().unwrap();
850        assert!(
851            applies_to.iter().any(|a| *a == format!("node:{A_NODE}")),
852            "the claim body names the node the server counts: {applies_to:?}"
853        );
854        assert_eq!(pending[1]["body"]["kind"], "derived_from");
855        assert_eq!(pending[1]["body"]["from"], out.queued[0].1.as_str());
856        assert_eq!(pending[1]["body"]["to"], A_NODE);
857    }
858}
859
860#[cfg(test)]
861mod tests {
862    /// E2E 27.10. E5: `knowledge remember` said "switched off" while the
863    /// next sync captured anyway; both read this one switch now.
864    #[test]
865    fn capture_follows_auto_capture_and_the_off_switch() {
866        use crate::CloudConfig;
867        assert!(super::capture_allowed(&CloudConfig::default()));
868        let mut off = CloudConfig::default();
869        crate::connect::without_sharing(&mut off);
870        assert!(!super::capture_allowed(&off), "a \"not shared\" answer");
871        let disabled = CloudConfig {
872            enabled: Some(false),
873            ..CloudConfig::default()
874        };
875        assert!(!super::capture_allowed(&disabled));
876    }
877
878    /// Found on the dogfood Cloud: a 1.x link stores the vault id as plain
879    /// hex, the C0 2.0 place name is the hyphenated UUID.
880    #[test]
881    fn place_ids_are_hyphenated_uuids() {
882        assert_eq!(
883            super::place_id("8b1ba534f3284cc1b939dafd92863522"),
884            "8b1ba534-f328-4cc1-b939-dafd92863522"
885        );
886        assert_eq!(
887            super::place_id("8b1ba534-f328-4cc1-b939-dafd92863522"),
888            "8b1ba534-f328-4cc1-b939-dafd92863522"
889        );
890        assert_eq!(super::place_id("not-a-uuid"), "not-a-uuid");
891        assert_eq!(
892            super::canonical_instance_id("inst_a164e846e1ad4d7fb66e4fed4e28b2aa"),
893            "a164e846-e1ad-4d7f-b66e-4fed4e28b2aa"
894        );
895    }
896}