lean-ctx-cloud 3.12.10

The LeanCTX connector: enrollment, bus, knowledge sync, tasks and policy on top of LeanCTX | OSS.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
// SPDX-License-Identifier: Apache-2.0
//! The C0 2.0 sync of one bound vault (SPEC-ENGINE ยง3.4.4, V1.6): clone or
//! tail the replica, turn what the capture gate lets through into signed
//! events, push them, tail again. Runs only when the enrolled Cloud speaks
//! C0 2.0 ([`crate::bus::relay_v2::speaks_v2`]); against a 1.x
//! Cloud the draft path stays as it is.

use std::path::Path;

use serde_json::Value;

use super::driver::{self, PlaceApi, Verifier};
use crate::auth::Session;
use crate::capture::{self, emit};
use crate::events::build::{Place, Signer};
use crate::events::hlc::Stamp;
use crate::events::sign;
use crate::keyset_v3::{self, Purpose};
use crate::replica::{Replica, crypt};
use crate::vault::VaultRecord;
use crate::workers::keys as worker_keys;
use crate::{CloudError, knowledge::screening::Screen};

/// The routes of a session, with its token refresh.
pub struct SessionApi<'a>(pub &'a Session);

impl PlaceApi for SessionApi<'_> {
    fn get(&self, path: &str) -> Result<Value, CloudError> {
        self.0.with_client(|c| c.get(path))
    }
    fn get_bytes(&self, path: &str, max: usize) -> Result<Vec<u8>, CloudError> {
        self.0.with_client(|c| c.get_bytes(path, max))
    }
    fn post(&self, path: &str, body: &Value) -> Result<Value, CloudError> {
        self.0.with_client(|c| c.post(path, body))
    }
}

/// Host app the CLI and the session hooks capture as.
pub(crate) const CAPTURE_HOST: &str = "lean-ctx";
pub const CAPTURE_ROLE: &str = "capture";
/// Replica meta key: `created_at` of the newest fact the gate considered.
const CAPTURE_SINCE: &str = "capture_since";
/// Replica meta: when an imported fact (`lean-ctx import docs|git`) last
/// changed that the previous capture considered (a re-import updates facts
/// in place, so imports keep their own mark).
const IMPORT_SINCE: &str = "import_since";

/// What one vault sync did.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct VaultSync {
    pub cloned: bool,
    pub stored: usize,
    pub captured: usize,
    /// Episodes queued for sessions that ended (V1.4).
    pub episodes: usize,
    /// Own local facts removed because a purge took their text out.
    pub purged_local: usize,
    /// Purge tombstones newly acknowledged.
    pub purge_acks: usize,
    /// Facts copied in by 1.x pulls, removed once the replica serves the
    /// vault (V4.10).
    pub legacy_removed: usize,
    pub pushed: usize,
    /// Anchor states the automatic re-check queued (`to_verify`, `gone`,
    /// or `fresh` again).
    pub rechecked: usize,
    /// Own nodes the capture lifecycle queued as superseded (`edge.add
    /// supersedes` from their successor), withdrawn (`retract`) and
    /// re-anchored after a local re-pin (`field.set anchors`).
    pub superseded: usize,
    pub retracted: usize,
    pub confirmed: usize,
    /// Links queued between two Instances' values of one shared fact:
    /// `supersedes` for a sequential edit, `contradicts` for a conflict
    /// (#286, [`capture::conflicts`]).
    pub fact_links: usize,
    /// Doc pages whose anchored code moved since this sync last looked.
    pub docs_behind: usize,
    /// Events the place refused for good: (event id, refusal).
    pub failed: Vec<(String, String)>,
    pub counts: capture::CaptureCounts,
    /// A deletions-only pass (the month's transfer used up) found an
    /// ordinary tail page: the quota is back.
    pub quota_back: bool,
}

/// Whether an event's signature verifies under the signer rules of ยง3.3.5:
/// a worker event by a key of this place that signs for its worker id, any
/// other actor by a Cloud key of purpose `event` valid when received.
pub(super) fn signature_ok(session: &Session, place_ref: &str, event: &Value) -> bool {
    let key_id = event
        .get("key_id")
        .and_then(Value::as_str)
        .unwrap_or_default();
    let received_at = event
        .get("received_at")
        .and_then(Value::as_u64)
        .unwrap_or(u64::MAX);
    match event.pointer("/actor/kind").and_then(Value::as_str) {
        Some("worker") => {
            let Some(worker) = event.get("worker_id").and_then(Value::as_str) else {
                return false;
            };
            let signs = |found: &Option<([u8; 32], Vec<String>)>| {
                matches!(found, Some((key, workers))
                    if workers.iter().any(|x| x == worker) && sign::verify(event, key))
            };
            let found = worker_keys::worker_key_or_fetch(session, place_ref, key_id, received_at)
                .ok()
                .flatten();
            if signs(&found) {
                return true;
            }
            // A key cached before its worker registered lists no (or an
            // older set of) workers: fetch the place's keys once more.
            found.is_some()
                && worker_keys::fetch(session, place_ref).is_ok()
                && signs(&worker_keys::worker_key(
                    &session.store,
                    place_ref,
                    key_id,
                    received_at,
                ))
        }
        Some("person" | "server" | "legacy_import") => keyset_v3::cloud_keys(
            &session.store,
            session.root_key(),
            Purpose::Event,
            received_at,
        )
        .iter()
        .any(|(id, key)| id == key_id && sign::verify(event, key)),
        _ => false,
    }
}

/// The C0 2.0 place id of a vault: the canonical hyphenated UUID. A 1.x
/// link resolve may hand out the same id as 32 plain hex digits, which a
/// C0 2.0 Cloud does not accept as its place name.
pub fn place_id(vault_id: &str) -> String {
    uuid::Uuid::parse_str(vault_id)
        .map_or_else(|_| vault_id.to_string(), |u| u.hyphenated().to_string())
}

/// The instance id as C0 2.0 names it: the hyphenated UUID of the 1.x
/// `inst_<32 hex>` id.
pub fn canonical_instance_id(instance_id: &str) -> String {
    place_id(instance_id.strip_prefix("inst_").unwrap_or(instance_id))
}

/// The automatic anchor re-check of one sync (v5 2.2.1): the deterministic
/// `--stale` task of `cloud maintain`, queued after this run's capture
/// events (continuing `clock`). Returns how many states it queued and the
/// clock after them; an error is logged and counts as none, so the sync goes
/// on.
fn recheck_anchors(
    replica: &Replica,
    place: &Place,
    signer: &Signer<'_>,
    checkout: &mut capture::refs::Checkout,
    now: u64,
    clock: Stamp,
) -> (usize, Stamp) {
    use crate::review::maintain;
    let req = maintain::Request {
        vault: String::new(),
        stale: true,
        contradictions: false,
        dedupe: false,
        limit: maintain::DEFAULT_LIMIT,
        confirm: None,
    };
    let target = maintain::Target {
        replica,
        place,
        signer,
    };
    match maintain::run_stale_at(&target, checkout, &req, now, clock) {
        Ok((counts, clock)) => (counts.done, clock),
        Err(e) => {
            tracing::warn!("cloud: anchor re-check skipped: {e}");
            (0, clock)
        }
    }
}

/// Replica meta keys of the lifecycle gate, per checkout (`<key>:<project
/// hash>`; checkouts of one vault share its replica but each has its own
/// knowledge store): the knowledge journal's LSN and the time (unix ms) of
/// the last lifecycle pass.
const LIFECYCLE_LSN: &str = "lifecycle_lsn";
const LIFECYCLE_AT: &str = "lifecycle_at";
/// The longest a lifecycle pass is skipped while nothing moved: it covers
/// what neither the journal nor the tail records (a store edited outside the
/// engine).
const LIFECYCLE_FULL_MS: u64 = 60 * 60 * 1000;

/// Whether a lifecycle pass has work: the knowledge journal moved since the
/// last pass, the place delivered new events (another engine may have marked
/// a claim this checkout already re-pinned), or an hour passed; and the
/// journal LSN to record.
fn lifecycle_due(
    replica: &Replica,
    root: &Path,
    project_hash: &str,
    remote_changed: bool,
    now: u64,
) -> Result<(bool, u64), CloudError> {
    let head = lean_ctx::core::knowledge::knowledge_dir_of(&root.to_string_lossy())
        .map_or(0, |dir| lean_ctx::core::knowledge::journal::head_lsn(&dir));
    let read = |key: &str| -> Result<Option<u64>, CloudError> {
        Ok(replica
            .meta(&format!("{key}:{project_hash}"))?
            .and_then(|v| String::from_utf8(v.to_vec()).ok())
            .and_then(|s| s.parse().ok()))
    };
    let due = match (read(LIFECYCLE_LSN)?, read(LIFECYCLE_AT)?) {
        (Some(lsn), Some(at)) => {
            remote_changed || lsn != head || now.saturating_sub(at) >= LIFECYCLE_FULL_MS
        }
        _ => true,
    };
    Ok((due, head))
}

/// The capture lifecycle of one sync ([`capture::lifecycle`]): what the
/// agent superseded, withdrew or re-pinned since its facts were captured,
/// queued after this run's capture and re-check events. A failure is logged
/// and plans nothing, so the sync goes on.
#[allow(clippy::too_many_arguments)]
fn lifecycle(
    target: &crate::review::maintain::Target<'_>,
    graph: &crate::replica::fold::Graph,
    checkout: &mut capture::refs::Checkout,
    root: &Path,
    project_hash: &str,
    remote_changed: bool,
    now: u64,
    clock: Stamp,
) -> Result<capture::lifecycle::Queued, CloudError> {
    use capture::lifecycle;
    let idle = lifecycle::Queued {
        clock,
        ..lifecycle::Queued::default()
    };
    let (due, head) = lifecycle_due(target.replica, root, project_hash, remote_changed, now)?;
    if !due {
        return Ok(idle);
    }
    let Some(store) = lifecycle::store_facts(target.replica, &root.to_string_lossy()) else {
        tracing::debug!("cloud: lifecycle skipped, the knowledge store is not readable");
        return Ok(idle);
    };
    let own = lifecycle::own_nodes(target.replica, project_hash)?;
    let present = lifecycle::present(graph, target.replica)?;
    let removed = lifecycle::removed_identities(&root.to_string_lossy());
    let actions = lifecycle::plan(
        &own,
        &store,
        &removed,
        |id| present.view(graph, id),
        &present,
    );
    let queued = lifecycle::queue(target, graph, checkout, &actions, clock, now)?;
    target.replica.set_meta(
        &format!("{LIFECYCLE_LSN}:{project_hash}"),
        head.to_string().as_bytes(),
    )?;
    target.replica.set_meta(
        &format!("{LIFECYCLE_AT}:{project_hash}"),
        now.to_string().as_bytes(),
    )?;
    Ok(queued)
}

/// The claims of `knowledge` (after `since`) that pass the capture gate.
///
/// v5 2.6.1: a `node:<id>` reference is valid only for a live node of this
/// place's folded `graph`, so the gate's checkout learns those ids first;
/// without them every `node:` reference was dropped as invalid and no
/// `derived_from` edge was ever written (dogfood e2e, scenario 2). A claim
/// that names a live node then carries a `derived_from` edge to it, its own
/// provenance (not telemetry).
///
/// K1: the facts `lean-ctx import docs|git` made from the repository pass
/// the same gate after `import_since`, with their import source as the
/// reference (`file:<path>`, `commit:<sha>`). The plan's `watermark` is the
/// learned facts' mark; the imports' mark is returned next to it.
fn plan_capture(
    knowledge: &lean_ctx::core::knowledge::ProjectKnowledge,
    since: Option<lean_ctx_time::UtcDateTime>,
    import_since: Option<lean_ctx_time::UtcDateTime>,
    run: &mut capture::CaptureRun<'_>,
    graph: &crate::replica::fold::Graph,
) -> (
    crate::knowledge::learn::LearnPlan,
    Option<lean_ctx_time::UtcDateTime>,
) {
    use crate::knowledge::learn::{plan_import, plan_learn};
    run.checkout
        .nodes
        .extend(graph.live_nodes().map(|(id, _)| id.clone()));
    let repo = lean_ctx_protocol::cloud::knowledge::ResearchContextDocumentV1::default();
    let mut plan = plan_learn(knowledge, &repo, since, usize::MAX, run);
    let imported = plan_import(knowledge, &repo, import_since, usize::MAX, run);
    plan.added.extend(imported.added);
    plan.dropped.extend(imported.dropped);
    plan.merges.extend(imported.merges);
    plan.import_sources.extend(imported.import_sources);
    plan.captured.extend(imported.captured);
    capture::derived::link(&mut plan.captured, graph);
    (plan, imported.watermark)
}

/// Sync the vault `record` bound to the checkout at `root`. While a quota
/// or policy throttle holds sync, nothing is asked of Cloud: the replica
/// keeps its pending events and the refusal says until when.
/// Whether sync may capture this machine's knowledge into the vault: the
/// same switches the `knowledge remember` note reads.
pub fn capture_allowed(config: &crate::CloudConfig) -> bool {
    config.enabled != Some(false) && config.auto_capture
}

pub fn sync_vault(
    session: &Session,
    record: &VaultRecord,
    root: &Path,
    screen: &mut Screen,
) -> Result<VaultSync, CloudError> {
    use crate::throttle::{self, Scope};
    // Never into a vault the checkout left (a pulled link file, an
    // identity change): nothing is pulled from or pushed to it.
    crate::resolution::refuse_stale_record(
        session.store.data_dir(),
        &session.instance.vault_scope(),
        record,
        root,
    )?;
    let now = lean_ctx_time::UtcDateTime::now();
    if let Err(held) = throttle::check(&session.store, Scope::Sync, now) {
        // A used-up transfer still delivers deletions (protected capacity):
        // apply and ack them, then keep waiting, unless the answer shows
        // the quota is back (E2E-FINAL: purges stayed `propagating`).
        if !throttle::quota_holds(&session.store, Scope::Sync, now) {
            return Err(held);
        }
        match sync_vault_once(session, record, root, screen, true) {
            Ok(done) if done.quota_back => throttle::quota_lifted(&session.store, Scope::Sync),
            Ok(done) => {
                if done.purge_acks > 0 {
                    tracing::info!(
                        "cloud: {} purge tombstones of {} applied and acknowledged while transfer is used up",
                        done.purge_acks,
                        record.vault_id
                    );
                }
                return Err(held);
            }
            Err(e) => {
                tracing::warn!(
                    "cloud: deletions of {} not applied yet: {e}",
                    record.vault_id
                );
                return Err(held);
            }
        }
    }
    // A used-up transfer quota holds sync; a policy refusal of this vault
    // is this vault's alone and holds nothing else.
    let done = sync_vault_once(session, record, root, screen, false).map_err(|e| {
        throttle::note_on(&session.store, None, e, lean_ctx_time::UtcDateTime::now())
    })?;
    throttle::passed(&session.store, Scope::Sync);
    Ok(done)
}

fn sync_vault_once(
    session: &Session,
    record: &VaultRecord,
    root: &Path,
    screen: &mut Screen,
    deletions_only: bool,
) -> Result<VaultSync, CloudError> {
    let store = &session.store;
    let place_ref = format!("vault:{}", place_id(&record.vault_id));
    let (mk, _) = crypt::master_key(store.config_dir(), false)?;
    let (mut replica, _) = Replica::open(store.data_dir(), &record.vault_id, &mk)?;
    // Fresh Cloud keys when we can; the last verified set otherwise.
    if keyset_v3::refresh(session).is_err() && keyset_v3::load(store, session.root_key()).is_none()
    {
        return Err(CloudError::Protocol("no verified Cloud key set v3".into()));
    }
    let now = lean_ctx_time::UtcDateTime::now()
        .timestamp_millis()
        .unsigned_abs();
    let snapshot_keys: Vec<[u8; 32]> =
        keyset_v3::cloud_keys(store, session.root_key(), Purpose::Snapshot, now)
            .into_iter()
            .map(|(_, k)| k)
            .collect();
    let check = |e: &Value| signature_ok(session, &place_ref, e);
    let verifier = Verifier {
        snapshot_keys: &snapshot_keys,
        signature_ok: &check,
    };
    let api = SessionApi(session);
    let mut report = VaultSync::default();
    if deletions_only {
        let Some(graph) = driver::deletions(&api, &mut replica, &place_ref, &verifier)? else {
            report.quota_back = true;
            return Ok(report);
        };
        let applied = super::purge::apply(&mut replica, &graph, now)?;
        report.purged_local =
            super::purge::purge_local_store(&replica, &graph, &root.to_string_lossy())?;
        report.purge_acks = applied.new_acks;
        let writer = super::writer::VaultWriter::open(session, CAPTURE_ROLE)?;
        let acks = super::purge::signed_pending(&replica, &place_ref, writer.keys.signing_key())?;
        driver::push_acks(&api, &place_ref, &acks)?;
        super::purge::mark_sent(&replica, &acks)?;
        return Ok(report);
    }
    let (first, seen_before_pull) = pull(&api, &mut replica, &place_ref, &verifier)?;
    report.cloned = first.cloned;
    report.stored = first.stored;
    // Events stored unverified get one more check against current keys
    // (a signer's worker can register after its key was first cached).
    if let Some(pk) = replica.id_salt()? {
        for (id, event) in replica.unverified()? {
            if super::records::event_verifies(&event, &pk, &check) {
                replica.mark_verified(&id)?;
            }
        }
    }
    // V4.10 / ยง3.16: the vault is now delivered from its replica; the facts
    // its 1.x revisions copied into the project knowledge go, and the local
    // relations that named them move to the replica nodes.
    if first.cloned {
        report.legacy_removed = crate::migrate::retire_on_clone(store, &replica, record, root)?;
    }

    // Purges (ยง3.4.6): deny purged statements, remove own local text, queue
    // one ack per tombstone.
    let graph = replica.refold()?;
    let applied = super::purge::apply(&mut replica, &graph, now)?;
    report.purged_local =
        super::purge::purge_local_store(&replica, &graph, &root.to_string_lossy())?;
    report.purge_acks = applied.new_acks;

    // Capture: what the gate lets through becomes signed node.add events.
    let pk_id = replica
        .id_salt()?
        .ok_or_else(|| CloudError::Local("replica has no id_salt".into()))?;
    // Worker ids and hlc.node are derived from the instance UUID as C0 2.0
    // names it (the server recomputes the worker id from it).
    let writer = super::writer::VaultWriter::open(session, CAPTURE_ROLE)?;
    let keys = &writer.keys;
    // E2E 27.10. E5: `[cloud] auto_capture = false` (or a "not shared"
    // answer, which writes it) means nothing new leaves this machine.
    let capture_on = capture_allowed(&lean_ctx::core::config::Config::load().cloud);
    if !capture_on {
        tracing::info!("cloud: capture is off on this machine (`cloud.auto_capture`)");
    }
    // The HLC of the last event this run queued, continued by the doc re-check.
    let mut run_clock = Stamp::default();
    if let Some(knowledge) = capture_on
        .then(|| lean_ctx::core::knowledge::ProjectKnowledge::load(&root.to_string_lossy()))
        .flatten()
    {
        let (mut run, place_name) = capture::open_run(
            store.data_dir(),
            &crate::vault::project_identity(root)
                .map(|i| lean_ctx_protocol::cloud::vault::stable_identity(&i))
                .unwrap_or_default(),
            root,
            screen,
            lean_ctx_time::UtcDateTime::now().timestamp_millis(),
        );
        run.pk_id = pk_id;
        let mark = |key: &str| -> Result<Option<lean_ctx_time::UtcDateTime>, CloudError> {
            Ok(replica
                .meta(key)?
                .and_then(|v| String::from_utf8(v.to_vec()).ok())
                .and_then(|s| lean_ctx_time::OffsetDateTime::parse_from_rfc3339(&s).ok())
                .map(lean_ctx_time::OffsetDateTime::to_utc))
        };
        let (since, import_since) = (mark(CAPTURE_SINCE)?, mark(IMPORT_SINCE)?);
        let (plan, import_mark) = plan_capture(&knowledge, since, import_since, &mut run, &graph);
        // What the gate kept local, per fact, for the sync status (local).
        capture::sharing::record_rejected(
            store.data_dir(),
            &place_id(&record.vault_id),
            &plan.dropped,
            lean_ctx_time::UtcDateTime::now(),
        );
        let place = super::writer::vault_place(record, &replica)?;
        let signer = writer.signer();
        // The checkout's name in `own_sources` (never shared): what the
        // capture lifecycle finds this checkout's own nodes by.
        let project_hash =
            blake3::hash(root.to_string_lossy().as_bytes()).to_hex()[..16].to_owned();
        // #286: a fact's save names the log position its author could have
        // seen when it wrote the fact: what this Instance had folded before
        // this sync's pull. Another Instance's value pulled just now was not
        // seen, so the two are concurrent (a conflict), not an edit.
        let fact_place = Place {
            causal_base: seen_before_pull,
            ..place.clone()
        };
        // V9: sessions only for a Cloud that announced it accepts them.
        let sessions = crate::session_ref::SessionRefs::for_store(&session.store);
        let target = emit::Target {
            replica: &replica,
            place: &fact_place,
            signer: &signer,
            project_hash: &project_hash,
            decision_anchors: crate::bus::relay_v2::speaks_2_2(&session.store),
            sessions: sessions.as_ref(),
        };
        let emitted = emit::emit(
            &target,
            &mut run.checkout,
            &plan.captured,
            Stamp::default(),
            now,
        )?;
        report.captured = emitted.queued.len();
        // V1.4: the checkout's sessions that ended become episodes.
        let ended = capture::episode::emit_ended(
            &target,
            root,
            store.data_dir(),
            &mut run,
            emitted.clock,
            now,
        )?;
        // Without the local key no episode names a session; the sync goes
        // on and `cloud status` says why.
        if let Some(error) = &ended.withheld {
            store.record_error(&format!("episodes not queued: {error}"));
        }
        let clock = ended.clock;
        report.episodes = ended.queued;
        // v5 2.2.1: every sync re-checks the anchored claims against this
        // checkout (`cloud maintain --stale`, automatically): a changed
        // anchor makes the claim `outdated` until a person confirms it
        // (`--confirm`). A failed re-check never fails the sync.
        let (rechecked, clock) =
            recheck_anchors(&replica, &place, &signer, &mut run.checkout, now, clock);
        report.rechecked = rechecked;
        // What the agent superseded, withdrew or re-pinned since capture
        // (the knowledge journal gates it; a failure never fails the sync).
        let maintain_target = crate::review::maintain::Target {
            replica: &replica,
            place: &place,
            signer: &signer,
        };
        run_clock = clock;
        match lifecycle(
            &maintain_target,
            &graph,
            &mut run.checkout,
            root,
            &project_hash,
            report.stored > 0,
            now,
            clock,
        ) {
            Ok(queued) => {
                report.superseded = queued.superseded;
                report.retracted = queued.retracted;
                report.confirmed = queued.confirmed;
                run_clock = queued.clock;
            }
            Err(e) => tracing::warn!("cloud: knowledge lifecycle skipped: {e}"),
        }
        capture::finish_run(store.data_dir(), &place_name, &run)?;
        report.counts = run.counts.clone();
        if let Some(mark) = plan.watermark {
            replica.set_meta(CAPTURE_SINCE, mark.to_rfc3339().as_bytes())?;
        }
        if let Some(mark) = import_mark {
            replica.set_meta(IMPORT_SINCE, mark.to_rfc3339().as_bytes())?;
        }
    }
    // Docs (C0 2.2): a page whose derived anchors moved gets its
    // `anchor_state` and `drift`, also in a checkout without project
    // knowledge; a failure never fails the sync.
    if capture_on {
        let docs = crate::docs::require_docs_protocol(store)
            .and_then(|()| crate::docs::space(&replica))
            .and_then(|space| {
                let specs = crate::docs::recheck(&root.to_string_lossy(), &space);
                let pages = specs.len() / 2;
                let place = super::writer::vault_place(record, &replica)?;
                let signer = writer.signer();
                let target = crate::review::maintain::Target {
                    replica: &replica,
                    place: &place,
                    signer: &signer,
                };
                let mut screen = crate::knowledge::screening::Screen::for_installation();
                crate::docs::queue_specs_at(&target, specs, &mut screen, now, run_clock)
                    .map(|(_, clock)| (pages, clock))
            });
        match docs {
            Ok((pages, clock)) => {
                report.docs_behind = pages;
                // The conflict edges below continue after the doc events.
                run_clock = clock;
            }
            Err(e) => tracing::warn!("cloud: doc anchor re-check skipped: {e}"),
        }
    }

    let acks = super::purge::signed_pending(&replica, &place_ref, keys.signing_key())?;
    let pushed = driver::push_pending(&api, &replica, &place_ref, &acks)?;
    if pushed.acked {
        super::purge::mark_sent(&replica, &acks)?;
    }
    report.pushed = pushed.logged;
    report.failed = pushed.failed;
    let after = driver::tail(&api, &mut replica, &place_ref, &verifier)?;
    report.stored += after.stored;

    // #286: two Instances' values for one shared fact are linked (a
    // sequential edit `supersedes`, concurrent values `contradicts`), the
    // edge written by the one Instance the resolution names and pushed at
    // once so every Instance serves the same state. Detected on
    // the graph after the tail (own and other Instances' latest nodes); a
    // failure never fails the sync.
    if capture_on {
        match detect_conflicts(record, &replica, &writer, &pk_id, run_clock, now) {
            Ok(0) => {}
            Ok(queued) => {
                report.fact_links = queued;
                let pushed = driver::push_pending(&api, &replica, &place_ref, &[])?;
                report.pushed += pushed.logged;
                report.failed.extend(pushed.failed);
                report.stored += driver::tail(&api, &mut replica, &place_ref, &verifier)?.stored;
            }
            Err(e) => tracing::warn!("cloud: conflict detection skipped: {e}"),
        }
    }
    Ok(report)
}

/// Pull the place: a clone on the first sync, a tail otherwise. Also
/// returns the log position this Instance had folded before the pull (0
/// before its first clone): the most its facts written since its last sync
/// could have seen, which their saves carry as `causal_base` (#286).
pub(super) fn pull(
    api: &dyn PlaceApi,
    replica: &mut Replica,
    place_ref: &str,
    verifier: &Verifier<'_>,
) -> Result<(driver::SyncReport, u64), CloudError> {
    let seen = replica.cursor()?;
    let report = match seen {
        None => driver::clone_place(api, replica, place_ref, verifier)?,
        Some(_) => driver::tail(api, replica, place_ref, verifier)?,
    };
    Ok((report, seen.unwrap_or(0)))
}

/// Queue this Instance's fact links ([`capture::conflicts`]); how many.
fn detect_conflicts(
    record: &VaultRecord,
    replica: &Replica,
    writer: &super::writer::VaultWriter,
    pk_id: &[u8; 32],
    clock: Stamp,
    now: u64,
) -> Result<usize, CloudError> {
    let place = super::writer::vault_place(record, replica)?;
    let signer = writer.signer();
    let target = crate::review::maintain::Target {
        replica,
        place: &place,
        signer: &signer,
    };
    capture::conflicts::detect(&target, pk_id, clock, now).map(|(queued, _)| queued)
}

#[cfg(test)]
mod capture_tests {
    use ed25519_dalek::SigningKey;

    use super::*;
    use crate::replica::fold::{FoldEvent, Graph};

    /// A live node of engine A, as B's replica folded it.
    const A_NODE: &str = "n_q7zk2m4xv3bt6yhw5rn2jc7dpa";
    /// A well-formed id the place does not hold.
    const UNKNOWN: &str = "n_aaaaaaaaaaaaaaaaaaaaaacab4";

    fn graph() -> Graph {
        let mut g = Graph::default();
        g.fold(&[FoldEvent {
            seq: 1,
            event_id: format!("E{:025}", 1),
            op: "node.add".into(),
            target: Some(A_NODE.into()),
            node_type: Some("fact".into()),
            body: Some(serde_json::json!({
                "statement": "The ledger close holds advisory lock 42.",
                "applies_to": []
            })),
            sig_invalid: false,
            provenance: Some("workspace".into()),
            review_state: Some("confirmed".into()),
        }])
        .unwrap();
        g
    }

    /// Dogfood 02.11.: `lean-ctx import docs` made 515 facts and the 2.x
    /// sync captured none of them (only the v1 draft path planned imports).
    /// An imported doc fact passes the gate with its file as the reference,
    /// and its own mark keeps the next sync from planning it again.
    #[test]
    fn imported_doc_facts_are_captured_with_their_file_on_sync() {
        let repo = capture::tests::repo();
        std::fs::create_dir_all(repo.path().join("docs")).unwrap();
        std::fs::write(
            repo.path().join("docs/guide.md"),
            "# Retry\n\n## Budget\n\nPayments retry a failed charge at most three times.\n",
        )
        .unwrap();
        for args in [&["add", "."][..], &["commit", "-q", "-m", "docs"]] {
            let ok = std::process::Command::new("git")
                .args(["-c", "user.name=LC", "-c", "user.email=lc@cloud.local"])
                .args(args)
                .current_dir(repo.path())
                .status()
                .unwrap()
                .success();
            assert!(ok, "git {args:?}");
        }
        let mut f = capture::tests::fact(
            "arch",
            "Payments retry a failed charge at most three times before they give up.",
        );
        f.imported_from = Some("docs".into());
        f.key = "docs/guide.md#retry/budget/1".into();
        let mut knowledge =
            lean_ctx::core::knowledge::ProjectKnowledge::new(&repo.path().to_string_lossy());
        knowledge.facts.push(f.clone());

        let mut screen =
            Screen::with_rules(Vec::new(), std::sync::Arc::new(Vec::new()), Vec::new());
        let mut run = capture::CaptureRun::new(&mut screen, repo.path(), [9; 32], Vec::new(), 0);
        let (plan, mark) = plan_capture(&knowledge, None, None, &mut run, &graph());
        assert_eq!(plan.captured.len(), 1, "{:?}", plan.dropped);
        assert!(
            plan.captured[0]
                .refs
                .iter()
                .any(|r| r == "file:docs/guide.md"),
            "{:?}",
            plan.captured[0].refs
        );
        assert_eq!(
            plan.import_sources,
            ["import:docs:docs/guide.md#retry-budget"]
        );
        assert_eq!(mark, Some(f.created_at.max(f.last_confirmed)));
        assert_eq!(plan.watermark, None, "no learned fact moved the learn mark");

        let mut screen =
            Screen::with_rules(Vec::new(), std::sync::Arc::new(Vec::new()), Vec::new());
        let mut run = capture::CaptureRun::new(&mut screen, repo.path(), [9; 32], Vec::new(), 0);
        let (again, _) = plan_capture(&knowledge, None, mark, &mut run, &graph());
        assert!(again.captured.is_empty(), "{:?}", again.import_sources);
    }

    /// Dogfood e2e scenario 2: B remembers a claim with `--ref file:โ€ฆ --ref
    /// node:<A's live node>` and syncs. The sync's capture step must keep
    /// the node reference and queue a `derived_from` edge after the claim;
    /// before the fix the gate knew no node ids and dropped it.
    #[test]
    fn a_remembered_node_reference_becomes_a_derived_from_edge_on_sync() {
        let repo = capture::tests::repo();
        let mut f = capture::tests::fact(
            "arch",
            "The nightly export waits for advisory lock 42 before the ledger close.",
        );
        f.capture.refs = vec![
            "file:src/lib.rs".into(),
            format!("node:{A_NODE}"),
            format!("node:{UNKNOWN}"),
        ];
        let mut knowledge =
            lean_ctx::core::knowledge::ProjectKnowledge::new(&repo.path().to_string_lossy());
        knowledge.facts.push(f);

        let mut screen =
            Screen::with_rules(Vec::new(), std::sync::Arc::new(Vec::new()), Vec::new());
        let mut run = capture::CaptureRun::new(&mut screen, repo.path(), [9; 32], Vec::new(), 0);
        let graph = graph();
        let (plan, _) = plan_capture(&knowledge, None, None, &mut run, &graph);
        assert_eq!(plan.captured.len(), 1, "{:?}", plan.dropped);
        assert_eq!(plan.captured[0].derived_from, [A_NODE]);
        assert!(
            !plan.captured[0].refs.iter().any(|r| r.contains(UNKNOWN)),
            "a node the place does not hold is no reference"
        );

        let data = tempfile::tempdir().unwrap();
        let (replica, _) = Replica::open(data.path(), "pl_sync_derive", &[3; 32]).unwrap();
        let key = SigningKey::from_bytes(&[0x49; 32]);
        let place = Place {
            kind: "vault".into(),
            id: "3f1c2b6a-8d4e-4a7b-9c10-5e2f6a7b8c01".into(),
            pk_id: [9; 32],
            causal_base: 1,
        };
        let signer = Signer {
            key: &key,
            hlc_node: "6f2b9c4e-1a3d-4e5f-8a7b-0c1d2e3f4a5b".into(),
            worker_id: "wkr_vk4oelpv5lzjmev44hun".into(),
        };
        let target = emit::Target {
            replica: &replica,
            place: &place,
            signer: &signer,
            project_hash: "ph",
            decision_anchors: false,
            sessions: None,
        };
        let out = emit::emit(
            &target,
            &mut run.checkout,
            &plan.captured,
            Stamp::default(),
            1_792_800_000_000,
        )
        .unwrap();
        assert_eq!(out.queued.len(), 1);
        let pending: Vec<Value> = replica
            .pending()
            .unwrap()
            .iter()
            .map(|(_, b)| serde_json::from_slice(b).unwrap())
            .collect();
        let ops: Vec<&str> = pending.iter().map(|e| e["op"].as_str().unwrap()).collect();
        assert_eq!(ops, ["node.add", "edge.add"]);
        let applies_to = pending[0]["body"]["applies_to"].as_array().unwrap();
        assert!(
            applies_to.iter().any(|a| *a == format!("node:{A_NODE}")),
            "the claim body names the node the server counts: {applies_to:?}"
        );
        assert_eq!(pending[1]["body"]["kind"], "derived_from");
        assert_eq!(pending[1]["body"]["from"], out.queued[0].1.as_str());
        assert_eq!(pending[1]["body"]["to"], A_NODE);
    }
}

#[cfg(test)]
mod tests {
    /// E2E 27.10. E5: `knowledge remember` said "switched off" while the
    /// next sync captured anyway; both read this one switch now.
    #[test]
    fn capture_follows_auto_capture_and_the_off_switch() {
        use crate::CloudConfig;
        assert!(super::capture_allowed(&CloudConfig::default()));
        let mut off = CloudConfig::default();
        crate::connect::without_sharing(&mut off);
        assert!(!super::capture_allowed(&off), "a \"not shared\" answer");
        let disabled = CloudConfig {
            enabled: Some(false),
            ..CloudConfig::default()
        };
        assert!(!super::capture_allowed(&disabled));
    }

    /// Found on the dogfood Cloud: a 1.x link stores the vault id as plain
    /// hex, the C0 2.0 place name is the hyphenated UUID.
    #[test]
    fn place_ids_are_hyphenated_uuids() {
        assert_eq!(
            super::place_id("8b1ba534f3284cc1b939dafd92863522"),
            "8b1ba534-f328-4cc1-b939-dafd92863522"
        );
        assert_eq!(
            super::place_id("8b1ba534-f328-4cc1-b939-dafd92863522"),
            "8b1ba534-f328-4cc1-b939-dafd92863522"
        );
        assert_eq!(super::place_id("not-a-uuid"), "not-a-uuid");
        assert_eq!(
            super::canonical_instance_id("inst_a164e846e1ad4d7fb66e4fed4e28b2aa"),
            "a164e846-e1ad-4d7f-b66e-4fed4e28b2aa"
        );
    }
}