Skip to main content

lean_ctx_cloud/capture/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Capture quality gate (Cloud v4 V1, SPEC-ENGINE §3.1).
3//!
4//! Every item that leaves the machine for a vault is one typed claim:
5//! a single complete sentence of 24–300 characters, a node type, at least
6//! one valid reference, an evidence level, deduplicated against what the
7//! place holds, admitted and screened. The gate is rule-based: it rejects
8//! with a stable [`ReasonCode`], it never rewrites or splits (E1). A fact
9//! that fails stays in the local knowledge store unchanged.
10
11pub mod conflicts;
12pub mod dedupe;
13pub mod derived;
14pub mod emit;
15pub mod episode;
16pub mod lifecycle;
17pub mod refs;
18pub mod rules;
19pub mod sharing;
20
21use std::collections::BTreeMap;
22use std::path::Path;
23
24use serde::{Deserialize, Serialize};
25
26use lean_ctx::core::knowledge::{
27    EvidenceLevel, FactOrigin, KnowledgeArchetype, KnowledgeFact, NodeType, ProcedureCommand,
28};
29use lean_ctx::core::sensitivity::SensitivityLevel;
30
31use self::refs::{Checkout, RefState};
32
33/// Version of the gate rules, carried with every count and event.
34pub const GATE_VERSION: u32 = 1;
35/// References a claim may carry (G10).
36pub const MAX_REFERENCES: usize = 10;
37/// A candidate whose only reference is an unpublished commit waits this
38/// long before it is rejected finally (G10).
39pub const PENDING_DAYS: i64 = 14;
40
41/// Why the gate refused a candidate. Stable snake_case strings: counted,
42/// shown in `cloud status`, reported to the place as counts only.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
44#[serde(rename_all = "snake_case")]
45pub enum ReasonCode {
46    NoType,
47    TooShort,
48    TooLong,
49    MultiLine,
50    MultiClaim,
51    NotSentence,
52    LogText,
53    Truncated,
54    NoReference,
55    TooManyReferences,
56    Sensitivity,
57    ProcedureShape,
58    EpisodeShape,
59    ScreenSecret,
60    ScreenPii,
61    ScreenRedaction,
62    ScreenForbidden,
63    ScreenLocalPath,
64    Duplicate,
65    NearDuplicateMerged,
66    BudgetBatchFull,
67    Admission,
68    PurgedContent,
69    UnpublishedRef,
70}
71
72impl ReasonCode {
73    pub fn as_str(self) -> &'static str {
74        match self {
75            Self::NoType => "no_type",
76            Self::TooShort => "too_short",
77            Self::TooLong => "too_long",
78            Self::MultiLine => "multi_line",
79            Self::MultiClaim => "multi_claim",
80            Self::NotSentence => "not_sentence",
81            Self::LogText => "log_text",
82            Self::Truncated => "truncated",
83            Self::NoReference => "no_reference",
84            Self::TooManyReferences => "too_many_references",
85            Self::Sensitivity => "sensitivity",
86            Self::ProcedureShape => "procedure_shape",
87            Self::EpisodeShape => "episode_shape",
88            Self::ScreenSecret => "screen_secret",
89            Self::ScreenPii => "screen_pii",
90            Self::ScreenRedaction => "screen_redaction",
91            Self::ScreenForbidden => "screen_forbidden",
92            Self::ScreenLocalPath => "screen_local_path",
93            Self::Duplicate => "duplicate",
94            Self::NearDuplicateMerged => "near_duplicate_merged",
95            Self::BudgetBatchFull => "budget_batch_full",
96            Self::Admission => "admission",
97            Self::PurgedContent => "purged_content",
98            Self::UnpublishedRef => "unpublished_ref",
99        }
100    }
101
102    /// Why a fact cannot be shared as is, in plain words, with how to fix
103    /// it where a person can (`knowledge remember`, the web's "can't be
104    /// shared as is").
105    pub fn plain(self) -> &'static str {
106        match self {
107            Self::NoType => "lean-ctx cannot tell what kind of knowledge it is",
108            Self::TooShort => "it is shorter than 24 characters; write one full sentence",
109            Self::TooLong => "it is longer than 300 characters; keep it to one sentence",
110            Self::MultiLine => "it spans several lines; write it as one sentence",
111            Self::MultiClaim => "it says several things at once; remember one fact per sentence",
112            Self::NotSentence => {
113                "it is not a full sentence; start with a capital letter and end with a period"
114            }
115            Self::LogText => "it looks like log or tool output, not a statement",
116            Self::Truncated => "it looks cut off; finish the sentence",
117            Self::NoReference => {
118                "it names no source others can check; add --ref file:<path> (or sym:, test:, commit:, https://)"
119            }
120            Self::TooManyReferences => "it names more than 10 sources",
121            Self::Sensitivity => "it is marked as more sensitive than this vault allows",
122            Self::ProcedureShape => "the steps or commands of this procedure are not complete",
123            Self::EpisodeShape => "the episode summary is not complete",
124            Self::ScreenSecret => "it contains what looks like a secret",
125            Self::ScreenPii => "it contains personal data",
126            Self::ScreenRedaction => "it contains text your filters redact",
127            Self::ScreenForbidden => "your workspace's policy does not allow sharing it",
128            Self::ScreenLocalPath => "it contains a path that only exists on this machine",
129            Self::Duplicate => "the vault already has it",
130            Self::NearDuplicateMerged => "the vault already has almost the same fact",
131            Self::BudgetBatchFull => "this sync's batch is full; it goes with the next one",
132            Self::Admission => "this vault does not take knowledge from this machine",
133            Self::PurgedContent => "it was removed from the vault before",
134            Self::UnpublishedRef => {
135                "its only source is a commit that is not pushed yet; it shares once it is"
136            }
137        }
138    }
139
140    /// The screening reason (1:1 to [`Blocked`](crate::knowledge::screening::Blocked)).
141    pub fn of_screen(blocked: &crate::knowledge::screening::Blocked) -> Self {
142        use crate::knowledge::screening::Blocked;
143        match blocked {
144            Blocked::Secret(_) => Self::ScreenSecret,
145            Blocked::Pii(_) => Self::ScreenPii,
146            Blocked::Redaction => Self::ScreenRedaction,
147            // A broken local rule refuses like a forbidden pattern (fails closed).
148            Blocked::Forbidden | Blocked::BrokenRules(_) => Self::ScreenForbidden,
149            Blocked::LocalPath => Self::ScreenLocalPath,
150        }
151    }
152}
153
154impl std::fmt::Display for ReasonCode {
155    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
156        f.write_str(self.as_str())
157    }
158}
159
160/// A local fact shaped for the gate.
161#[derive(Debug, Clone, PartialEq, Eq)]
162pub struct CaptureCandidate {
163    pub node_type: NodeType,
164    /// The claim; the title of a procedure.
165    pub statement: String,
166    pub steps: Vec<String>,
167    pub commands: Vec<ProcedureCommand>,
168    /// Raw references: the fact's `refs`, its anchors as `file:`/`sym:`, and
169    /// its import source.
170    pub refs: Vec<String>,
171    pub evidence: EvidenceLevel,
172    pub sensitivity: SensitivityLevel,
173}
174
175/// A fact the gate let through, with its valid references and where it
176/// came from in the local store (for `own_sources`, never shared).
177#[derive(Debug, Clone, PartialEq, Eq)]
178pub struct CapturedFact {
179    pub candidate: CaptureCandidate,
180    pub refs: Vec<String>,
181    pub category: String,
182    pub key: String,
183    pub value: String,
184    /// Live vault nodes the fact names itself (`node:<id>` references,
185    /// [`derived::link`]); each becomes a `derived_from` edge next to the
186    /// fact's `node.add` when the claim body carries the reference.
187    pub derived_from: Vec<String>,
188    /// V9: the local engine session the fact was learned in. It stays on
189    /// this machine: its events carry only the keyed ref
190    /// ([`crate::session_ref::SessionRefs::event_ref`]), and only when Cloud
191    /// accepts it; `None` for imports and facts without a session.
192    pub session: Option<String>,
193}
194
195/// Category tokens that never make a shareable node (G1).
196const DENY_TOKENS: [&str; 5] = ["log", "trace", "debug", "output", "temp"];
197
198/// Node type of a fact (SPEC-ENGINE §3.1.3), `Err(NoType)` for a category
199/// in the deny map.
200pub fn node_type_of(f: &KnowledgeFact) -> Result<NodeType, ReasonCode> {
201    if let Some(t) = f.capture.node_type {
202        return Ok(t);
203    }
204    match f.archetype {
205        KnowledgeArchetype::Decision => return Ok(NodeType::Decision),
206        KnowledgeArchetype::Gotcha => return Ok(NodeType::Gotcha),
207        KnowledgeArchetype::Workflow => {
208            return Ok(if f.capture.steps.is_empty() {
209                NodeType::Fact
210            } else {
211                NodeType::Procedure
212            });
213        }
214        _ => {}
215    }
216    let category = f.category.to_lowercase();
217    let tokens: Vec<&str> = category
218        .split(['-', '_', ':', '/', ' '])
219        .filter(|t| !t.is_empty())
220        .collect();
221    let has = |words: &[&str]| tokens.iter().any(|t| words.contains(t));
222    if has(&DENY_TOKENS) {
223        Err(ReasonCode::NoType)
224    } else if has(&["decision", "adr"]) {
225        Ok(NodeType::Decision)
226    } else if has(&["gotcha", "pitfall", "warning"]) {
227        Ok(NodeType::Gotcha)
228    } else if has(&["procedure", "howto", "runbook"]) && !f.capture.steps.is_empty() {
229        Ok(NodeType::Procedure)
230    } else {
231        Ok(NodeType::Fact)
232    }
233}
234
235/// Evidence level of a fact: explicit; `imported` for imports and provider
236/// or derived origins; `observed` for a local fact with an anchor; else
237/// `stated`.
238pub fn evidence_of(f: &KnowledgeFact, imported: bool) -> EvidenceLevel {
239    if let Some(e) = f.capture.evidence {
240        return e;
241    }
242    match &f.origin {
243        _ if imported => EvidenceLevel::Imported,
244        FactOrigin::Provider(_) | FactOrigin::Derived(_) => EvidenceLevel::Imported,
245        FactOrigin::Local if !f.anchors.is_empty() => EvidenceLevel::Observed,
246        FactOrigin::Local | FactOrigin::Unverified => EvidenceLevel::Stated,
247    }
248}
249
250/// Shape a fact into a candidate (G1). `import_ref` is the reference its
251/// import source names (`file:<path>` or `commit:<sha>`).
252pub fn shape(
253    f: &KnowledgeFact,
254    import_ref: Option<String>,
255) -> Result<CaptureCandidate, ReasonCode> {
256    let node_type = if import_ref.is_some() {
257        NodeType::Fact
258    } else {
259        node_type_of(f)?
260    };
261    let mut refs = f.capture.refs.clone();
262    for anchor in &f.anchors {
263        refs.push(match &anchor.symbol {
264            Some(symbol) => format!("sym:{}::{symbol}", anchor.path),
265            None => format!("file:{}", anchor.path),
266        });
267    }
268    refs.extend(import_ref);
269    let mut seen = std::collections::HashSet::new();
270    refs.retain(|r| seen.insert(r.clone()));
271    Ok(CaptureCandidate {
272        node_type,
273        statement: f.value.trim().to_string(),
274        steps: f.capture.steps.clone(),
275        commands: f.capture.commands.clone(),
276        refs,
277        evidence: evidence_of(f, f.imported_from.is_some()),
278        sensitivity: f.sensitivity,
279    })
280}
281
282/// Procedure shape (SPEC-ENGINE §3.1.4): title, 1–20 steps, 0–10 commands.
283fn check_procedure(c: &CaptureCandidate) -> Result<(), ReasonCode> {
284    let title = &c.statement;
285    rules::check_length(title, 8, 120).map_err(|_| ReasonCode::NotSentence)?;
286    rules::check_single_line(title).map_err(|_| ReasonCode::NotSentence)?;
287    rules::check_sentence(title, false)?;
288    let shape = |ok: bool| {
289        if ok {
290            Ok(())
291        } else {
292            Err(ReasonCode::ProcedureShape)
293        }
294    };
295    shape((1..=20).contains(&c.steps.len()))?;
296    for step in &c.steps {
297        shape(
298            rules::check_length(step, 8, 300).is_ok()
299                && rules::check_single_line(step).is_ok()
300                && rules::check_log(step).is_ok()
301                && rules::check_truncated(step).is_ok(),
302        )?;
303    }
304    shape(c.commands.len() <= 10)?;
305    for cmd in &c.commands {
306        shape(
307            matches!(cmd.shell.as_str(), "sh" | "pwsh" | "cmd")
308                && !cmd.cmd.trim().is_empty()
309                && cmd.cmd.chars().count() <= 500
310                && cmd
311                    .cwd_hint
312                    .as_ref()
313                    .is_none_or(|h| h.chars().count() <= 120),
314        )?;
315    }
316    Ok(())
317}
318
319/// The rules G2–G11 on a shaped candidate. Returns the valid references.
320pub fn gate(c: &CaptureCandidate, checkout: &mut Checkout) -> Result<Vec<String>, ReasonCode> {
321    if c.node_type == NodeType::Procedure {
322        check_procedure(c)?;
323    } else {
324        rules::check_statement(&c.statement)?;
325    }
326    let mut valid = Vec::new();
327    let mut unpublished = false;
328    for raw in &c.refs {
329        let Some(parsed) = refs::parse(raw) else {
330            continue;
331        };
332        match checkout.check(&parsed) {
333            RefState::Valid => {
334                let r = parsed.to_contract();
335                if !valid.contains(&r) {
336                    valid.push(r);
337                }
338            }
339            RefState::Unpublished => unpublished = true,
340            RefState::Invalid => {}
341        }
342    }
343    if valid.is_empty() {
344        return Err(if unpublished {
345            ReasonCode::UnpublishedRef
346        } else {
347            ReasonCode::NoReference
348        });
349    }
350    if valid.len() > MAX_REFERENCES {
351        return Err(ReasonCode::TooManyReferences);
352    }
353    if c.sensitivity != SensitivityLevel::Public {
354        return Err(ReasonCode::Sensitivity);
355    }
356    Ok(valid)
357}
358
359/// Counts of capture runs (SPEC-ENGINE §3.1.2 step 7): never any text.
360#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
361pub struct CaptureCounts {
362    pub gate_version: u32,
363    pub window_from: Option<i64>,
364    pub window_to: Option<i64>,
365    pub considered: u32,
366    pub captured: u32,
367    pub rejected: BTreeMap<ReasonCode, u32>,
368}
369
370impl CaptureCounts {
371    pub fn reject(&mut self, reason: ReasonCode) {
372        *self.rejected.entry(reason).or_default() += 1;
373    }
374
375    /// Add a run's counts to these (the window grows to cover both).
376    pub fn absorb(&mut self, run: &CaptureCounts) {
377        self.gate_version = GATE_VERSION;
378        self.window_from = match (self.window_from, run.window_from) {
379            (Some(a), Some(b)) => Some(a.min(b)),
380            (a, b) => a.or(b),
381        };
382        self.window_to = self.window_to.max(run.window_to);
383        self.considered += run.considered;
384        self.captured += run.captured;
385        for (reason, n) in &run.rejected {
386            *self.rejected.entry(*reason).or_default() += n;
387        }
388    }
389
390    /// `considered / captured / rejected by reason`, one line.
391    pub fn summary(&self) -> String {
392        let mut line = format!("{} considered, {} captured", self.considered, self.captured);
393        if !self.rejected.is_empty() {
394            let reasons: Vec<String> = self
395                .rejected
396                .iter()
397                .map(|(r, n)| format!("{r} {n}"))
398                .collect();
399            line.push_str(&format!(", rejected: {}", reasons.join(", ")));
400        }
401        line
402    }
403}
404
405/// Unsent counts per vault, `<data>/cloud/capture/counts.json`.
406pub type CountsFile = BTreeMap<String, CaptureCounts>;
407
408fn capture_dir(data_dir: &Path) -> std::path::PathBuf {
409    data_dir.join("capture")
410}
411
412pub fn load_counts(data_dir: &Path) -> CountsFile {
413    std::fs::read(capture_dir(data_dir).join("counts.json"))
414        .ok()
415        .and_then(|b| serde_json::from_slice(&b).ok())
416        .unwrap_or_default()
417}
418
419/// Add one run's counts to the vault's unsent counts.
420pub fn record_counts(
421    data_dir: &Path,
422    vault: &str,
423    run: &CaptureCounts,
424) -> Result<(), crate::CloudError> {
425    let mut all = load_counts(data_dir);
426    all.entry(vault.to_string()).or_default().absorb(run);
427    let bytes = serde_json::to_vec(&all).map_err(|e| crate::CloudError::Local(e.to_string()))?;
428    crate::state::write_private(&capture_dir(data_dir), "counts.json", &bytes)
429}
430
431/// A candidate waiting for its commit to reach a remote-tracking branch.
432#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
433pub struct Pending {
434    pub fact_key_hash: String,
435    pub first_seen_ms: i64,
436}
437
438fn pending_file(vault: &str) -> String {
439    format!("{vault}.pending.json")
440}
441
442pub fn load_pending(data_dir: &Path, vault: &str) -> Vec<Pending> {
443    std::fs::read(capture_dir(data_dir).join(pending_file(vault)))
444        .ok()
445        .and_then(|b| serde_json::from_slice(&b).ok())
446        .unwrap_or_default()
447}
448
449pub fn save_pending(
450    data_dir: &Path,
451    vault: &str,
452    pending: &[Pending],
453) -> Result<(), crate::CloudError> {
454    let bytes = serde_json::to_vec(pending).map_err(|e| crate::CloudError::Local(e.to_string()))?;
455    crate::state::write_private(&capture_dir(data_dir), &pending_file(vault), &bytes)
456}
457
458/// `hex(blake3_keyed(pk_id, category || 0x00 || key))`: names a local fact
459/// in the pending file without its slug.
460pub fn fact_key_hash(pk_id: &[u8; 32], f: &KnowledgeFact) -> String {
461    let mut h = blake3::Hasher::new_keyed(pk_id);
462    h.update(f.category.as_bytes());
463    h.update(&[0]);
464    h.update(f.key.as_bytes());
465    h.finalize().to_hex().to_string()
466}
467
468/// One capture run for one place: the gate's inputs and what it counted.
469pub struct CaptureRun<'a> {
470    pub screen: &'a mut crate::knowledge::screening::Screen,
471    pub checkout: Checkout,
472    pub pk_id: [u8; 32],
473    pub counts: CaptureCounts,
474    pub pending: Vec<Pending>,
475    pub now_ms: i64,
476}
477
478impl<'a> CaptureRun<'a> {
479    pub fn new(
480        screen: &'a mut crate::knowledge::screening::Screen,
481        root: &Path,
482        pk_id: [u8; 32],
483        pending: Vec<Pending>,
484        now_ms: i64,
485    ) -> Self {
486        Self {
487            screen,
488            checkout: Checkout::new(root),
489            pk_id,
490            counts: CaptureCounts {
491                gate_version: GATE_VERSION,
492                window_from: Some(now_ms),
493                window_to: Some(now_ms),
494                ..CaptureCounts::default()
495            },
496            pending,
497            now_ms,
498        }
499    }
500
501    /// Whether `f` waits for its commit (it is re-checked on every run).
502    pub fn is_pending(&self, f: &KnowledgeFact) -> bool {
503        let hash = fact_key_hash(&self.pk_id, f);
504        self.pending.iter().any(|p| p.fact_key_hash == hash)
505    }
506
507    /// Record an `unpublished_ref` verdict: pending for [`PENDING_DAYS`],
508    /// then rejected finally (the caller counts it once per run either way).
509    pub fn unpublished(&mut self, f: &KnowledgeFact) {
510        let hash = fact_key_hash(&self.pk_id, f);
511        let limit = PENDING_DAYS * 86_400_000;
512        match self.pending.iter().position(|p| p.fact_key_hash == hash) {
513            Some(i) if self.now_ms - self.pending[i].first_seen_ms >= limit => {
514                self.pending.remove(i);
515            }
516            Some(_) => {}
517            None => self.pending.push(Pending {
518                fact_key_hash: hash,
519                first_seen_ms: self.now_ms,
520            }),
521        }
522    }
523
524    /// `f` passed (or failed for another reason): it no longer waits.
525    pub fn settled(&mut self, f: &KnowledgeFact) {
526        let hash = fact_key_hash(&self.pk_id, f);
527        self.pending.retain(|p| p.fact_key_hash != hash);
528    }
529}
530
531/// Open a capture run for the project `stable` at `root`: the vault it is
532/// bound to (or the project itself before it is), its pending candidates.
533/// Returns the run and the place name its counts are kept under.
534pub fn open_run<'a>(
535    data_dir: &Path,
536    stable: &str,
537    root: &Path,
538    screen: &'a mut crate::knowledge::screening::Screen,
539    now_ms: i64,
540) -> (CaptureRun<'a>, String) {
541    let record = crate::vault::VaultMap::load(data_dir)
542        .vaults
543        .get(stable)
544        .cloned();
545    let place = record
546        .as_ref()
547        .map_or_else(|| stable.to_string(), |r| r.vault_id.clone());
548    let pending = load_pending(data_dir, &place);
549    let run = CaptureRun::new(screen, root, local_pk_id(&place), pending, now_ms);
550    (run, place)
551}
552
553/// Keep what a run found: its counts and the candidates still pending.
554pub fn finish_run(
555    data_dir: &Path,
556    place: &str,
557    run: &CaptureRun<'_>,
558) -> Result<(), crate::CloudError> {
559    if run.counts.considered == 0 && run.counts.rejected.is_empty() {
560        return Ok(());
561    }
562    record_counts(data_dir, place, &run.counts)?;
563    save_pending(data_dir, place, &run.pending)
564}
565
566/// The place id key of a vault until the replica delivers the server's
567/// `id_salt` (SPEC-ENGINE §3.1.5).
568// lean-ctx: derived from the vault id, so local-only; replace with the
569// snapshot's `id_salt` when the replica lands (V4).
570pub fn local_pk_id(vault: &str) -> [u8; 32] {
571    blake3::derive_key("leanctx.cloud.capture.pk-local.v1", vault.as_bytes())
572}
573
574#[cfg(test)]
575pub(crate) mod tests;