Skip to main content

lean_ctx/core/hive/capture/
mod.rs

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