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
// SPDX-License-Identifier: Apache-2.0
//! V1 done-when: the old "Session learnings" drafts (truncated raw text) are
//! replaced, and nothing that fails the capture gate is shared.

use lean_ctx_time::UtcDateTime;

use super::*;
use crate::capture::ReasonCode;
use lean_ctx::core::knowledge::ProjectKnowledge;

struct Place {
    _dirs: tempfile::TempDir,
    store: CloudStore,
    root: std::path::PathBuf,
}

pub(crate) fn git(root: &Path, args: &[&str]) {
    let out = std::process::Command::new("git")
        .arg("-C")
        .arg(root)
        .args(["-c", "user.name=t", "-c", "user.email=t@example.com"])
        .args(args)
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_NOSYSTEM", "1")
        .output()
        .unwrap();
    assert!(out.status.success(), "git {args:?}: {out:?}");
}

fn place() -> Place {
    let dirs = tempfile::tempdir().unwrap();
    let store = CloudStore::at(dirs.path().join("config"), dirs.path().join("data"));
    crate::bus::control::enroll_for_tests(&store, 1);
    let root = dirs.path().join("thinkery");
    std::fs::create_dir_all(root.join("src")).unwrap();
    std::fs::write(root.join("src/relay.rs"), "pub fn relay() {}\n").unwrap();
    git(&root, &["init", "-q"]);
    git(
        &root,
        &[
            "remote",
            "add",
            "origin",
            "https://github.com/acme/thinkery.git",
        ],
    );
    git(&root, &["add", "."]);
    git(&root, &["commit", "-q", "-m", "init"]);
    let root = root.canonicalize().unwrap();
    Place {
        _dirs: dirs,
        store,
        root,
    }
}

fn queued_drafts(place: &Place) -> Vec<DraftProposalV1> {
    Outbox::at(place.store.data_dir())
        .list(CHANNEL_KNOWLEDGE)
        .into_iter()
        .filter_map(|item| queued(&item.payload))
        .map(|q| q.draft)
        .collect()
}

/// What sessions wrote into project knowledge: one clean, referenced claim
/// and the kinds of text the old drafts shipped truncated.
fn remember_session(root: &str) {
    let policy = lean_ctx::core::memory_policy::MemoryPolicy::default();
    ProjectKnowledge::mutate_locked(root, |k| {
        k.remember(
            "architecture",
            "relay-frames",
            "The relay drops frames when the link is slower than 1 Mbit/s.",
            "s1",
            0.9,
            &policy,
        );
        let f = k.facts.last_mut().unwrap();
        f.capture.refs = vec!["file:src/relay.rs".into()];
        k.remember(
            "build-log",
            "run-17",
            "error[E0308]: mismatched types\n --> src/relay.rs:1:1\n[exit:101]",
            "s1",
            0.5,
            &policy,
        );
        k.remember(
            "architecture",
            "long",
            &format!(
                "{}.",
                "The scheduler renews leases and retries pushes ".repeat(10)
            ),
            "s1",
            0.8,
            &policy,
        );
        k.remember(
            "architecture",
            "unreferenced",
            "The relay keeps one socket per peer for its lifetime.",
            "s1",
            0.8,
            &policy,
        );
    })
    .unwrap();
}

#[test]
fn recapture_replaces_broken_session_drafts_with_gated_claims() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
    let place = place();
    let root = place.root.to_string_lossy().into_owned();
    remember_session(&root);

    // A draft of the old shape is waiting in the outbox.
    let stable = stable_identity(&project_identity(&place.root).unwrap());
    let old = QueuedDraft {
        stable_identity: stable,
        root: root.clone(),
        draft: DraftProposalV1 {
            schema: DRAFT_PROPOSAL_SCHEMA.into(),
            state: ProposalState::Draft,
            summary: Some("Session learnings: 3 facts".into()),
            body: Some("Learned in a lean-ctx session:\n- error[E0308]: mismatched".into()),
            sources: Vec::new(),
            context_patch: ContextPatchV1 {
                base_revision: 0,
                ops: Vec::new(),
            },
            session_ref: session_ref("old"),
            engine_screening: Screen::for_installation().counts(),
            origin: None,
        },
        ref_keyed: false,
    };
    Outbox::at(place.store.data_dir())
        .enqueue(
            CHANNEL_KNOWLEDGE,
            serde_json::to_value(old).unwrap(),
            UtcDateTime::now(),
        )
        .unwrap();

    let mut screen = Screen::for_installation();
    let done = recapture(
        &place.store,
        &CloudConfig::default(),
        &place.root,
        &mut screen,
        UtcDateTime::now(),
    )
    .unwrap();
    assert_eq!(done.removed, 1, "the broken draft is gone");
    assert_eq!(done.queued.len(), 1);
    assert_eq!(done.counts.considered, 4);
    assert_eq!(done.counts.captured, 1);
    assert_eq!(done.counts.rejected.get(&ReasonCode::NoType), Some(&1));
    assert_eq!(done.counts.rejected.get(&ReasonCode::TooLong), Some(&1));
    assert_eq!(done.counts.rejected.get(&ReasonCode::NoReference), Some(&1));

    let drafts = queued_drafts(&place);
    assert_eq!(drafts.len(), 1);
    let draft = &drafts[0];
    assert_eq!(draft.summary.as_deref(), Some("Captured 1 fact"));
    let body = draft.body.as_deref().unwrap();
    assert!(!body.contains("Session learnings"), "{body}");
    assert!(
        body.contains("- The relay drops frames when the link is slower than 1 Mbit/s.\n"),
        "the claim is listed whole: {body}"
    );
    // No shared item fails the gate.
    for op in &draft.context_patch.ops {
        let PatchOpV1::AddFact { fact } = op else {
            panic!("only facts")
        };
        assert_eq!(
            crate::capture::rules::check_statement(&fact.statement),
            Ok(())
        );
        assert!(
            fact.sources.iter().any(|s| s == "file:src/relay.rs"),
            "{fact:?}"
        );
    }

    // Nothing new on the next run; the counts are kept for the place.
    let again = enqueue_session_draft(
        &place.store,
        &CloudConfig::default(),
        &place.root,
        "s2",
        Trigger::SessionEnd,
        &mut screen,
        UtcDateTime::now(),
    )
    .unwrap();
    assert!(again.is_none());
    let counts = crate::capture::load_counts(place.store.data_dir());
    assert_eq!(counts.values().map(|c| c.captured).sum::<u32>(), 1);
}

/// Sets the capture fields of the stored fact as a `ctx_knowledge remember`
/// with `--ref` stores them (`capture_remembered`, tested with the tool):
/// `changed_at` moves only when a field changed.
fn remember_with_refs(root: &str, statement: &str, changed_at: lean_ctx_time::UtcDateTime) {
    ProjectKnowledge::mutate_locked(root, |k| {
        let fact = k
            .facts
            .iter_mut()
            .find(|f| f.is_current() && f.value == statement)
            .expect("remembered fact");
        fact.capture = lean_ctx::core::knowledge::FactCapture {
            refs: vec!["file:src/relay.rs".into()],
            changed_at: Some(changed_at),
            ..Default::default()
        };
    })
    .unwrap();
}

/// Live 26.10.: a fact remembered without `refs` is rejected
/// (`no_reference`) and the watermark moves past it; the agent then
/// remembers the same statement again with `--ref`. That second remember
/// must bring the fact back to the gate, which now captures it; a third,
/// identical remember changes nothing and captures nothing twice.
#[test]
fn refs_added_by_a_later_remember_bring_a_rejected_fact_back() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
    let place = place();
    let root = place.root.to_string_lossy().into_owned();
    let statement = "The relay keeps one socket per peer for its lifetime.";
    let policy = lean_ctx::core::memory_policy::MemoryPolicy::default();
    ProjectKnowledge::mutate_locked(&root, |k| {
        k.remember("architecture", "socket", statement, "s1", 0.8, &policy);
    })
    .unwrap();
    let mut screen = Screen::for_installation();
    let run = |screen: &mut Screen| {
        capture_session(
            &place.store,
            &CloudConfig::default(),
            &place.root,
            "s1",
            Trigger::SessionEnd,
            screen,
            UtcDateTime::now(),
        )
        .unwrap()
    };
    let (first, counts) = run(&mut screen);
    assert!(first.is_none());
    assert_eq!(counts.rejected.get(&ReasonCode::NoReference), Some(&1));

    let changed = UtcDateTime::now();
    remember_with_refs(&root, statement, changed);
    let (second, counts) = run(&mut screen);
    assert!(second.is_some(), "the referenced fact is captured");
    assert_eq!((counts.considered, counts.captured), (1, 1));

    remember_with_refs(&root, statement, changed);
    let (third, counts) = run(&mut screen);
    assert!(third.is_none(), "unchanged refs: not considered again");
    assert_eq!(counts.considered, 0);
}

/// Live 26.10. (lead decision): a vault that syncs through its C0 2.0
/// replica gets knowledge only as signed events. Session end, save and
/// shutdown queue no 1.x draft for it (that duplicated the claims and fed
/// the frozen review flow as "Sent draft #1"), nor for a project that is
/// neither linked nor bound; against a 1.x Cloud the same project still
/// drafts.
#[test]
fn a_vault_on_the_v2_replica_gets_no_v1_draft() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
    let place = place();
    let root = place.root.to_string_lossy().into_owned();
    remember_session(&root);
    let stable = stable_identity(&project_identity(&place.root).unwrap());
    let mut map = VaultMap::default();
    map.vaults.insert(
        stable.clone(),
        crate::vault::VaultRecord {
            vault_id: "1bae9408a81f40368b48645fad237bd6".into(),
            ns: "thinkery".into(),
            name: "thinkery".into(),
            sealed: false,
            roots: vec![root.clone()],
        },
    );
    map.save(place.store.data_dir()).unwrap();
    let draft = |trigger| {
        enqueue_session_draft(
            &place.store,
            &CloudConfig::default(),
            &place.root,
            "s1",
            trigger,
            &mut Screen::for_installation(),
            UtcDateTime::now(),
        )
        .unwrap()
    };

    crate::bus::relay_v2::record_protocol(&place.store, true).unwrap();
    assert!(syncs_through_replica(&place.store, &stable, &place.root));
    for trigger in [Trigger::SessionEnd, Trigger::Save, Trigger::Shutdown] {
        assert_eq!(draft(trigger), None, "{trigger:?}: no draft on the replica");
    }
    assert!(queued_drafts(&place).is_empty());
    VaultMap::default().save(place.store.data_dir()).unwrap();
    assert!(!syncs_through_replica(&place.store, &stable, &place.root));
    assert_eq!(draft(Trigger::SessionEnd), None, "unbound: no draft either");
    assert!(queued_drafts(&place).is_empty());
    map.save(place.store.data_dir()).unwrap();

    crate::bus::relay_v2::record_protocol(&place.store, false).unwrap();
    assert!(!syncs_through_replica(&place.store, &stable, &place.root));
    assert!(
        draft(Trigger::SessionEnd).is_some(),
        "a 1.x Cloud server still drafts"
    );
    assert_eq!(queued_drafts(&place).len(), 1);
}

/// A session draft names its session by the keyed ref, never the unsalted
/// digest; without a readable local key no draft is queued at all and the
/// watermark stays, so the next run with a key still drafts.
#[test]
fn a_session_draft_carries_the_keyed_ref_or_is_not_queued() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
    let place = place();
    remember_session(&place.root.to_string_lossy());
    let data = place.store.data_dir().to_path_buf();
    let draft = || {
        enqueue_session_draft(
            &place.store,
            &CloudConfig::default(),
            &place.root,
            "s1",
            Trigger::SessionEnd,
            &mut Screen::for_installation(),
            UtcDateTime::now(),
        )
    };

    let key = data.join("receipts.hmac-key");
    crate::session_ref::make_keyless(&data);
    let error = draft().unwrap_err();
    assert!(error.to_string().contains("receipts.hmac-key"), "{error}");
    assert!(queued_drafts(&place).is_empty());

    std::fs::remove_dir(&key).unwrap();
    assert!(draft().unwrap().is_some(), "the watermark stayed");
    let drafts = queued_drafts(&place);
    assert_eq!(drafts.len(), 1);
    assert_eq!(
        drafts[0].session_ref,
        crate::session_ref::uploaded_ses_ref(&data, "s1").unwrap()
    );
    assert_ne!(drafts[0].session_ref, session_ref("s1"));
    let item = &Outbox::at(&data).list(CHANNEL_KNOWLEDGE)[0];
    assert!(queued(&item.payload).unwrap().ref_keyed);
}

/// A draft queued before refs were keyed holds only the unsalted digest;
/// it is keyed (once) before it is sent, and stays queued without a key.
#[test]
fn a_draft_queued_before_keying_is_rekeyed_once() {
    let dir = tempfile::tempdir().unwrap();
    let legacy = serde_json::json!({
        "stable_identity": "a".repeat(64),
        "root": "/tmp/p",
        "draft": {
            "schema": DRAFT_PROPOSAL_SCHEMA,
            "state": "draft",
            "summary": "Captured 1 fact",
            "context_patch": {"base_revision": 0, "ops": []},
            "session_ref": session_ref("20261116-091500u123456p4242s0"),
            "engine_screening": Screen::for_installation().counts(),
        }
    });
    let mut old = queued(&legacy).expect("the old payload still reads");
    assert!(!old.ref_keyed);
    let stored = old.draft.session_ref.clone();

    let keyless = tempfile::tempdir().unwrap();
    crate::session_ref::make_keyless(keyless.path());
    assert!(old.clone().rekey_legacy_ref(keyless.path()).is_err());

    assert!(old.rekey_legacy_ref(dir.path()).unwrap());
    assert_eq!(
        old.draft.session_ref,
        crate::session_ref::rekeyed_legacy_ref(dir.path(), &stored).unwrap()
    );
    assert_ne!(old.draft.session_ref, stored);
    assert!(old.ref_keyed);
    assert_eq!(
        old.draft.session_ref.len(),
        stored.len(),
        "the contract shape"
    );
    assert!(old.draft.session_ref.starts_with("ses_"));
    let keyed = old.draft.session_ref.clone();
    assert!(!old.rekey_legacy_ref(dir.path()).unwrap(), "only once");
    assert_eq!(old.draft.session_ref, keyed);
    // The marker survives the outbox round trip.
    let back = queued(&serde_json::to_value(&old).unwrap()).unwrap();
    assert!(back.ref_keyed);
}

#[test]
fn a_session_end_after_unlink_queues_no_draft() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
    let place = place();
    remember_session(&place.root.to_string_lossy());
    let draft = || {
        enqueue_session_draft(
            &place.store,
            &CloudConfig::default(),
            &place.root,
            "s1",
            Trigger::SessionEnd,
            &mut Screen::for_installation(),
            UtcDateTime::now(),
        )
    };

    // M2 (rc4-6): the folder was unlinked; a session that ends queues
    // nothing, so no draft shares it again on the next sync.
    crate::unlinked::add(place.store.data_dir(), &place.root).unwrap();
    assert_eq!(draft().unwrap(), None);
    assert!(queued_drafts(&place).is_empty());

    // Linked again: the session's learnings are queued as before.
    crate::unlinked::remove(place.store.data_dir(), &place.root).unwrap();
    assert!(draft().unwrap().is_some());
    assert_eq!(queued_drafts(&place).len(), 1);
}