1pub 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
30pub const GATE_VERSION: u32 = 1;
32pub const MAX_REFERENCES: usize = 10;
34pub const PENDING_DAYS: i64 = 14;
37
38#[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 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 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#[derive(Debug, Clone, PartialEq, Eq)]
158pub struct CaptureCandidate {
159 pub node_type: NodeType,
160 pub statement: String,
162 pub steps: Vec<String>,
163 pub commands: Vec<ProcedureCommand>,
164 pub refs: Vec<String>,
167 pub evidence: EvidenceLevel,
168 pub sensitivity: SensitivityLevel,
169}
170
171#[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 pub derived_from: Vec<String>,
184}
185
186const DENY_TOKENS: [&str; 5] = ["log", "trace", "debug", "output", "temp"];
188
189pub 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
226pub 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
241pub 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
273fn 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
310pub 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#[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 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 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
405pub 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
419pub 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#[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
460pub 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
470pub 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 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 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 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
536pub 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
559pub 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
572pub 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;