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(session.store.data_dir(), record, root)?;
335    let now = lean_ctx_time::UtcDateTime::now();
336    if let Err(held) = throttle::check(&session.store, Scope::Sync, now) {
337        // A used-up transfer still delivers deletions (protected capacity):
338        // apply and ack them, then keep waiting, unless the answer shows
339        // the quota is back (E2E-FINAL: purges stayed `propagating`).
340        if !throttle::quota_holds(&session.store, Scope::Sync, now) {
341            return Err(held);
342        }
343        match sync_vault_once(session, record, root, screen, true) {
344            Ok(done) if done.quota_back => throttle::quota_lifted(&session.store, Scope::Sync),
345            Ok(done) => {
346                if done.purge_acks > 0 {
347                    tracing::info!(
348                        "cloud: {} purge tombstones of {} applied and acknowledged while transfer is used up",
349                        done.purge_acks,
350                        record.vault_id
351                    );
352                }
353                return Err(held);
354            }
355            Err(e) => {
356                tracing::warn!(
357                    "cloud: deletions of {} not applied yet: {e}",
358                    record.vault_id
359                );
360                return Err(held);
361            }
362        }
363    }
364    // A used-up transfer quota holds sync; a policy refusal of this vault
365    // is this vault's alone and holds nothing else.
366    let done = sync_vault_once(session, record, root, screen, false).map_err(|e| {
367        throttle::note_on(&session.store, None, e, lean_ctx_time::UtcDateTime::now())
368    })?;
369    throttle::passed(&session.store, Scope::Sync);
370    Ok(done)
371}
372
373fn sync_vault_once(
374    session: &Session,
375    record: &VaultRecord,
376    root: &Path,
377    screen: &mut Screen,
378    deletions_only: bool,
379) -> Result<VaultSync, CloudError> {
380    let store = &session.store;
381    let place_ref = format!("vault:{}", place_id(&record.vault_id));
382    let (mk, _) = crypt::master_key(store.config_dir(), false)?;
383    let (mut replica, _) = Replica::open(store.data_dir(), &record.vault_id, &mk)?;
384    // Fresh Cloud keys when we can; the last verified set otherwise.
385    if keyset_v3::refresh(session).is_err() && keyset_v3::load(store, session.root_key()).is_none()
386    {
387        return Err(CloudError::Protocol(
388            "no verified LeanCTX Cloud key set v3".into(),
389        ));
390    }
391    let now = lean_ctx_time::UtcDateTime::now()
392        .timestamp_millis()
393        .unsigned_abs();
394    let snapshot_keys: Vec<[u8; 32]> =
395        keyset_v3::cloud_keys(store, session.root_key(), Purpose::Snapshot, now)
396            .into_iter()
397            .map(|(_, k)| k)
398            .collect();
399    let check = |e: &Value| signature_ok(session, &place_ref, e);
400    let verifier = Verifier {
401        snapshot_keys: &snapshot_keys,
402        signature_ok: &check,
403    };
404    let api = SessionApi(session);
405    let mut report = VaultSync::default();
406    if deletions_only {
407        let Some(graph) = driver::deletions(&api, &mut replica, &place_ref, &verifier)? else {
408            report.quota_back = true;
409            return Ok(report);
410        };
411        let applied = super::purge::apply(&mut replica, &graph, now)?;
412        report.purged_local =
413            super::purge::purge_local_store(&replica, &graph, &root.to_string_lossy())?;
414        report.purge_acks = applied.new_acks;
415        let writer = super::writer::VaultWriter::open(session, CAPTURE_ROLE)?;
416        let acks = super::purge::signed_pending(&replica, &place_ref, writer.keys.signing_key())?;
417        driver::push_acks(&api, &place_ref, &acks)?;
418        super::purge::mark_sent(&replica, &acks)?;
419        return Ok(report);
420    }
421    let (first, seen_before_pull) = pull(&api, &mut replica, &place_ref, &verifier)?;
422    report.cloned = first.cloned;
423    report.stored = first.stored;
424    // Events stored unverified get one more check against current keys
425    // (a signer's worker can register after its key was first cached).
426    if let Some(pk) = replica.id_salt()? {
427        for (id, event) in replica.unverified()? {
428            if super::records::event_verifies(&event, &pk, &check) {
429                replica.mark_verified(&id)?;
430            }
431        }
432    }
433    // V4.10 / §3.16: the vault is now delivered from its replica; the facts
434    // its 1.x revisions copied into the project knowledge go, and the local
435    // relations that named them move to the replica nodes.
436    if first.cloned {
437        report.legacy_removed = crate::migrate::retire_on_clone(store, &replica, record, root)?;
438    }
439
440    // Purges (§3.4.6): deny purged statements, remove own local text, queue
441    // one ack per tombstone.
442    let graph = replica.refold()?;
443    let applied = super::purge::apply(&mut replica, &graph, now)?;
444    report.purged_local =
445        super::purge::purge_local_store(&replica, &graph, &root.to_string_lossy())?;
446    report.purge_acks = applied.new_acks;
447
448    // Capture: what the gate lets through becomes signed node.add events.
449    let pk_id = replica
450        .id_salt()?
451        .ok_or_else(|| CloudError::Local("replica has no id_salt".into()))?;
452    // Worker ids and hlc.node are derived from the instance UUID as C0 2.0
453    // names it (the server recomputes the worker id from it).
454    let writer = super::writer::VaultWriter::open(session, CAPTURE_ROLE)?;
455    let keys = &writer.keys;
456    // E2E 27.10. E5: `[cloud] auto_capture = false` (or a "not shared"
457    // answer, which writes it) means nothing new leaves this machine.
458    let capture_on = capture_allowed(&lean_ctx::core::config::Config::load().cloud);
459    if !capture_on {
460        tracing::info!("cloud: capture is off on this machine (`cloud.auto_capture`)");
461    }
462    // The HLC of the last event this run queued, continued by the doc re-check.
463    let mut run_clock = Stamp::default();
464    if let Some(knowledge) = capture_on
465        .then(|| lean_ctx::core::knowledge::ProjectKnowledge::load(&root.to_string_lossy()))
466        .flatten()
467    {
468        let (mut run, place_name) = capture::open_run(
469            store.data_dir(),
470            &crate::vault::project_identity(root)
471                .map(|i| lean_ctx_protocol::cloud::vault::stable_identity(&i))
472                .unwrap_or_default(),
473            root,
474            screen,
475            lean_ctx_time::UtcDateTime::now().timestamp_millis(),
476        );
477        run.pk_id = pk_id;
478        let mark = |key: &str| -> Result<Option<lean_ctx_time::UtcDateTime>, CloudError> {
479            Ok(replica
480                .meta(key)?
481                .and_then(|v| String::from_utf8(v.to_vec()).ok())
482                .and_then(|s| lean_ctx_time::OffsetDateTime::parse_from_rfc3339(&s).ok())
483                .map(lean_ctx_time::OffsetDateTime::to_utc))
484        };
485        let (since, import_since) = (mark(CAPTURE_SINCE)?, mark(IMPORT_SINCE)?);
486        let (plan, import_mark) = plan_capture(&knowledge, since, import_since, &mut run, &graph);
487        // What the gate kept local, per fact, for the sync status (local).
488        capture::sharing::record_rejected(
489            store.data_dir(),
490            &place_id(&record.vault_id),
491            &plan.dropped,
492            lean_ctx_time::UtcDateTime::now(),
493        );
494        let place = super::writer::vault_place(record, &replica)?;
495        let signer = writer.signer();
496        // The checkout's name in `own_sources` (never shared): what the
497        // capture lifecycle finds this checkout's own nodes by.
498        let project_hash =
499            blake3::hash(root.to_string_lossy().as_bytes()).to_hex()[..16].to_owned();
500        // #286: a fact's save names the log position its author could have
501        // seen when it wrote the fact: what this Instance had folded before
502        // this sync's pull. Another Instance's value pulled just now was not
503        // seen, so the two are concurrent (a conflict), not an edit.
504        let fact_place = Place {
505            causal_base: seen_before_pull,
506            ..place.clone()
507        };
508        // V9: sessions only for a Cloud that announced it accepts them.
509        let sessions = crate::session_ref::SessionRefs::for_store(&session.store);
510        let target = emit::Target {
511            replica: &replica,
512            place: &fact_place,
513            signer: &signer,
514            project_hash: &project_hash,
515            decision_anchors: crate::bus::relay_v2::speaks_2_2(&session.store),
516            sessions: sessions.as_ref(),
517        };
518        let emitted = emit::emit(
519            &target,
520            &mut run.checkout,
521            &plan.captured,
522            Stamp::default(),
523            now,
524        )?;
525        report.captured = emitted.queued.len();
526        // V1.4: the checkout's sessions that ended become episodes.
527        let ended = capture::episode::emit_ended(
528            &target,
529            root,
530            store.data_dir(),
531            &mut run,
532            emitted.clock,
533            now,
534        )?;
535        // Without the local key no episode names a session; the sync goes
536        // on and `cloud status` says why.
537        if let Some(error) = &ended.withheld {
538            store.record_error(&format!("episodes not queued: {error}"));
539        }
540        let clock = ended.clock;
541        report.episodes = ended.queued;
542        // v5 2.2.1: every sync re-checks the anchored claims against this
543        // checkout (`cloud maintain --stale`, automatically): a changed
544        // anchor makes the claim `outdated` until a person confirms it
545        // (`--confirm`). A failed re-check never fails the sync.
546        let (rechecked, clock) =
547            recheck_anchors(&replica, &place, &signer, &mut run.checkout, now, clock);
548        report.rechecked = rechecked;
549        // What the agent superseded, withdrew or re-pinned since capture
550        // (the knowledge journal gates it; a failure never fails the sync).
551        let maintain_target = crate::review::maintain::Target {
552            replica: &replica,
553            place: &place,
554            signer: &signer,
555        };
556        run_clock = clock;
557        match lifecycle(
558            &maintain_target,
559            &graph,
560            &mut run.checkout,
561            root,
562            &project_hash,
563            report.stored > 0,
564            now,
565            clock,
566        ) {
567            Ok(queued) => {
568                report.superseded = queued.superseded;
569                report.retracted = queued.retracted;
570                report.confirmed = queued.confirmed;
571                run_clock = queued.clock;
572            }
573            Err(e) => tracing::warn!("cloud: knowledge lifecycle skipped: {e}"),
574        }
575        capture::finish_run(store.data_dir(), &place_name, &run)?;
576        report.counts = run.counts.clone();
577        if let Some(mark) = plan.watermark {
578            replica.set_meta(CAPTURE_SINCE, mark.to_rfc3339().as_bytes())?;
579        }
580        if let Some(mark) = import_mark {
581            replica.set_meta(IMPORT_SINCE, mark.to_rfc3339().as_bytes())?;
582        }
583    }
584    // Docs (C0 2.2): a page whose derived anchors moved gets its
585    // `anchor_state` and `drift`, also in a checkout without project
586    // knowledge; a failure never fails the sync.
587    if capture_on {
588        let docs = crate::docs::require_docs_protocol(store)
589            .and_then(|()| crate::docs::space(&replica))
590            .and_then(|space| {
591                let specs = crate::docs::recheck(&root.to_string_lossy(), &space);
592                let pages = specs.len() / 2;
593                let place = super::writer::vault_place(record, &replica)?;
594                let signer = writer.signer();
595                let target = crate::review::maintain::Target {
596                    replica: &replica,
597                    place: &place,
598                    signer: &signer,
599                };
600                let mut screen = crate::knowledge::screening::Screen::for_installation();
601                crate::docs::queue_specs_at(&target, specs, &mut screen, now, run_clock)
602                    .map(|(_, clock)| (pages, clock))
603            });
604        match docs {
605            Ok((pages, clock)) => {
606                report.docs_behind = pages;
607                // The conflict edges below continue after the doc events.
608                run_clock = clock;
609            }
610            Err(e) => tracing::warn!("cloud: doc anchor re-check skipped: {e}"),
611        }
612    }
613
614    let acks = super::purge::signed_pending(&replica, &place_ref, keys.signing_key())?;
615    let pushed = driver::push_pending(&api, &replica, &place_ref, &acks)?;
616    if pushed.acked {
617        super::purge::mark_sent(&replica, &acks)?;
618    }
619    report.pushed = pushed.logged;
620    report.failed = pushed.failed;
621    let after = driver::tail(&api, &mut replica, &place_ref, &verifier)?;
622    report.stored += after.stored;
623
624    // #286: two Instances' values for one shared fact are linked (a
625    // sequential edit `supersedes`, concurrent values `contradicts`), the
626    // edge written by the one Instance the resolution names and pushed at
627    // once so every Instance serves the same state. Detected on
628    // the graph after the tail (own and other Instances' latest nodes); a
629    // failure never fails the sync.
630    if capture_on {
631        match detect_conflicts(record, &replica, &writer, &pk_id, run_clock, now) {
632            Ok(0) => {}
633            Ok(queued) => {
634                report.fact_links = queued;
635                let pushed = driver::push_pending(&api, &replica, &place_ref, &[])?;
636                report.pushed += pushed.logged;
637                report.failed.extend(pushed.failed);
638                report.stored += driver::tail(&api, &mut replica, &place_ref, &verifier)?.stored;
639            }
640            Err(e) => tracing::warn!("cloud: conflict detection skipped: {e}"),
641        }
642    }
643    Ok(report)
644}
645
646/// Pull the place: a clone on the first sync, a tail otherwise. Also
647/// returns the log position this Instance had folded before the pull (0
648/// before its first clone): the most its facts written since its last sync
649/// could have seen, which their saves carry as `causal_base` (#286).
650pub(super) fn pull(
651    api: &dyn PlaceApi,
652    replica: &mut Replica,
653    place_ref: &str,
654    verifier: &Verifier<'_>,
655) -> Result<(driver::SyncReport, u64), CloudError> {
656    let seen = replica.cursor()?;
657    let report = match seen {
658        None => driver::clone_place(api, replica, place_ref, verifier)?,
659        Some(_) => driver::tail(api, replica, place_ref, verifier)?,
660    };
661    Ok((report, seen.unwrap_or(0)))
662}
663
664/// Queue this Instance's fact links ([`capture::conflicts`]); how many.
665fn detect_conflicts(
666    record: &VaultRecord,
667    replica: &Replica,
668    writer: &super::writer::VaultWriter,
669    pk_id: &[u8; 32],
670    clock: Stamp,
671    now: u64,
672) -> Result<usize, CloudError> {
673    let place = super::writer::vault_place(record, replica)?;
674    let signer = writer.signer();
675    let target = crate::review::maintain::Target {
676        replica,
677        place: &place,
678        signer: &signer,
679    };
680    capture::conflicts::detect(&target, pk_id, clock, now).map(|(queued, _)| queued)
681}
682
683#[cfg(test)]
684mod capture_tests {
685    use ed25519_dalek::SigningKey;
686
687    use super::*;
688    use crate::replica::fold::{FoldEvent, Graph};
689
690    /// A live node of engine A, as B's replica folded it.
691    const A_NODE: &str = "n_q7zk2m4xv3bt6yhw5rn2jc7dpa";
692    /// A well-formed id the place does not hold.
693    const UNKNOWN: &str = "n_aaaaaaaaaaaaaaaaaaaaaacab4";
694
695    fn graph() -> Graph {
696        let mut g = Graph::default();
697        g.fold(&[FoldEvent {
698            seq: 1,
699            event_id: format!("E{:025}", 1),
700            op: "node.add".into(),
701            target: Some(A_NODE.into()),
702            node_type: Some("fact".into()),
703            body: Some(serde_json::json!({
704                "statement": "The ledger close holds advisory lock 42.",
705                "applies_to": []
706            })),
707            sig_invalid: false,
708            provenance: Some("workspace".into()),
709            review_state: Some("confirmed".into()),
710        }])
711        .unwrap();
712        g
713    }
714
715    /// Dogfood 02.11.: `lean-ctx import docs` made 515 facts and the 2.x
716    /// sync captured none of them (only the v1 draft path planned imports).
717    /// An imported doc fact passes the gate with its file as the reference,
718    /// and its own mark keeps the next sync from planning it again.
719    #[test]
720    fn imported_doc_facts_are_captured_with_their_file_on_sync() {
721        let repo = capture::tests::repo();
722        std::fs::create_dir_all(repo.path().join("docs")).unwrap();
723        std::fs::write(
724            repo.path().join("docs/guide.md"),
725            "# Retry\n\n## Budget\n\nPayments retry a failed charge at most three times.\n",
726        )
727        .unwrap();
728        for args in [&["add", "."][..], &["commit", "-q", "-m", "docs"]] {
729            let ok = std::process::Command::new("git")
730                .args(["-c", "user.name=LC", "-c", "user.email=lc@cloud.local"])
731                .args(args)
732                .current_dir(repo.path())
733                .status()
734                .unwrap()
735                .success();
736            assert!(ok, "git {args:?}");
737        }
738        let mut f = capture::tests::fact(
739            "arch",
740            "Payments retry a failed charge at most three times before they give up.",
741        );
742        f.imported_from = Some("docs".into());
743        f.key = "docs/guide.md#retry/budget/1".into();
744        let mut knowledge =
745            lean_ctx::core::knowledge::ProjectKnowledge::new(&repo.path().to_string_lossy());
746        knowledge.facts.push(f.clone());
747
748        let mut screen =
749            Screen::with_rules(Vec::new(), std::sync::Arc::new(Vec::new()), Vec::new());
750        let mut run = capture::CaptureRun::new(&mut screen, repo.path(), [9; 32], Vec::new(), 0);
751        let (plan, mark) = plan_capture(&knowledge, None, None, &mut run, &graph());
752        assert_eq!(plan.captured.len(), 1, "{:?}", plan.dropped);
753        assert!(
754            plan.captured[0]
755                .refs
756                .iter()
757                .any(|r| r == "file:docs/guide.md"),
758            "{:?}",
759            plan.captured[0].refs
760        );
761        assert_eq!(
762            plan.import_sources,
763            ["import:docs:docs/guide.md#retry-budget"]
764        );
765        assert_eq!(mark, Some(f.created_at.max(f.last_confirmed)));
766        assert_eq!(plan.watermark, None, "no learned fact moved the learn mark");
767
768        let mut screen =
769            Screen::with_rules(Vec::new(), std::sync::Arc::new(Vec::new()), Vec::new());
770        let mut run = capture::CaptureRun::new(&mut screen, repo.path(), [9; 32], Vec::new(), 0);
771        let (again, _) = plan_capture(&knowledge, None, mark, &mut run, &graph());
772        assert!(again.captured.is_empty(), "{:?}", again.import_sources);
773    }
774
775    /// Dogfood e2e scenario 2: B remembers a claim with `--ref file:… --ref
776    /// node:<A's live node>` and syncs. The sync's capture step must keep
777    /// the node reference and queue a `derived_from` edge after the claim;
778    /// before the fix the gate knew no node ids and dropped it.
779    #[test]
780    fn a_remembered_node_reference_becomes_a_derived_from_edge_on_sync() {
781        let repo = capture::tests::repo();
782        let mut f = capture::tests::fact(
783            "arch",
784            "The nightly export waits for advisory lock 42 before the ledger close.",
785        );
786        f.capture.refs = vec![
787            "file:src/lib.rs".into(),
788            format!("node:{A_NODE}"),
789            format!("node:{UNKNOWN}"),
790        ];
791        let mut knowledge =
792            lean_ctx::core::knowledge::ProjectKnowledge::new(&repo.path().to_string_lossy());
793        knowledge.facts.push(f);
794
795        let mut screen =
796            Screen::with_rules(Vec::new(), std::sync::Arc::new(Vec::new()), Vec::new());
797        let mut run = capture::CaptureRun::new(&mut screen, repo.path(), [9; 32], Vec::new(), 0);
798        let graph = graph();
799        let (plan, _) = plan_capture(&knowledge, None, None, &mut run, &graph);
800        assert_eq!(plan.captured.len(), 1, "{:?}", plan.dropped);
801        assert_eq!(plan.captured[0].derived_from, [A_NODE]);
802        assert!(
803            !plan.captured[0].refs.iter().any(|r| r.contains(UNKNOWN)),
804            "a node the place does not hold is no reference"
805        );
806
807        let data = tempfile::tempdir().unwrap();
808        let (replica, _) = Replica::open(data.path(), "pl_sync_derive", &[3; 32]).unwrap();
809        let key = SigningKey::from_bytes(&[0x49; 32]);
810        let place = Place {
811            kind: "vault".into(),
812            id: "3f1c2b6a-8d4e-4a7b-9c10-5e2f6a7b8c01".into(),
813            pk_id: [9; 32],
814            causal_base: 1,
815        };
816        let signer = Signer {
817            key: &key,
818            hlc_node: "6f2b9c4e-1a3d-4e5f-8a7b-0c1d2e3f4a5b".into(),
819            worker_id: "wkr_vk4oelpv5lzjmev44hun".into(),
820        };
821        let target = emit::Target {
822            replica: &replica,
823            place: &place,
824            signer: &signer,
825            project_hash: "ph",
826            decision_anchors: false,
827            sessions: None,
828        };
829        let out = emit::emit(
830            &target,
831            &mut run.checkout,
832            &plan.captured,
833            Stamp::default(),
834            1_792_800_000_000,
835        )
836        .unwrap();
837        assert_eq!(out.queued.len(), 1);
838        let pending: Vec<Value> = replica
839            .pending()
840            .unwrap()
841            .iter()
842            .map(|(_, b)| serde_json::from_slice(b).unwrap())
843            .collect();
844        let ops: Vec<&str> = pending.iter().map(|e| e["op"].as_str().unwrap()).collect();
845        assert_eq!(ops, ["node.add", "edge.add"]);
846        let applies_to = pending[0]["body"]["applies_to"].as_array().unwrap();
847        assert!(
848            applies_to.iter().any(|a| *a == format!("node:{A_NODE}")),
849            "the claim body names the node the server counts: {applies_to:?}"
850        );
851        assert_eq!(pending[1]["body"]["kind"], "derived_from");
852        assert_eq!(pending[1]["body"]["from"], out.queued[0].1.as_str());
853        assert_eq!(pending[1]["body"]["to"], A_NODE);
854    }
855}
856
857#[cfg(test)]
858mod tests {
859    /// E2E 27.10. E5: `knowledge remember` said "switched off" while the
860    /// next sync captured anyway; both read this one switch now.
861    #[test]
862    fn capture_follows_auto_capture_and_the_off_switch() {
863        use crate::CloudConfig;
864        assert!(super::capture_allowed(&CloudConfig::default()));
865        let mut off = CloudConfig::default();
866        crate::connect::without_sharing(&mut off);
867        assert!(!super::capture_allowed(&off), "a \"not shared\" answer");
868        let disabled = CloudConfig {
869            enabled: Some(false),
870            ..CloudConfig::default()
871        };
872        assert!(!super::capture_allowed(&disabled));
873    }
874
875    /// Found on the dogfood Cloud: a 1.x link stores the vault id as plain
876    /// hex, the C0 2.0 place name is the hyphenated UUID.
877    #[test]
878    fn place_ids_are_hyphenated_uuids() {
879        assert_eq!(
880            super::place_id("8b1ba534f3284cc1b939dafd92863522"),
881            "8b1ba534-f328-4cc1-b939-dafd92863522"
882        );
883        assert_eq!(
884            super::place_id("8b1ba534-f328-4cc1-b939-dafd92863522"),
885            "8b1ba534-f328-4cc1-b939-dafd92863522"
886        );
887        assert_eq!(super::place_id("not-a-uuid"), "not-a-uuid");
888        assert_eq!(
889            super::canonical_instance_id("inst_a164e846e1ad4d7fb66e4fed4e28b2aa"),
890            "a164e846-e1ad-4d7f-b66e-4fed4e28b2aa"
891        );
892    }
893}