lcsa-core 0.1.0

Local context substrate for AI-native software - typed signals for clipboard, selection, and focus
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
use std::fmt;
use std::time::SystemTime;

use serde::{Deserialize, Serialize};

use crate::filesystem::SemanticSignal;
use crate::topology::SignalSource;

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SignalType {
    Clipboard,
    Selection,
    Focus,
}

impl SignalType {
    pub fn as_str(self) -> &'static str {
        match self {
            SignalType::Clipboard => "clipboard",
            SignalType::Selection => "selection",
            SignalType::Focus => "focus",
        }
    }
}

impl fmt::Display for SignalType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ContentType {
    Text,
    Image,
    Html,
    Code,
    Unknown,
}

impl ContentType {
    pub fn as_str(&self) -> &'static str {
        match self {
            ContentType::Text => "text",
            ContentType::Image => "image",
            ContentType::Html => "html",
            ContentType::Code => "code",
            ContentType::Unknown => "unknown",
        }
    }
}

impl fmt::Display for ContentType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ClipboardSignal {
    pub content_type: ContentType,
    pub size_bytes: usize,
    pub source_app: String,
    pub likely_sensitive: bool,
    pub likely_command: bool,
    pub timestamp: SystemTime,
}

impl ClipboardSignal {
    pub fn text(content: &str, source_app: String) -> Self {
        Self {
            content_type: detect_content_type(content),
            size_bytes: content.len(),
            source_app,
            likely_sensitive: is_likely_sensitive_text(content),
            likely_command: is_likely_command_text(content),
            timestamp: SystemTime::now(),
        }
    }

    pub fn image(size_bytes: usize, source_app: String) -> Self {
        Self {
            content_type: ContentType::Image,
            size_bytes,
            source_app,
            likely_sensitive: false,
            likely_command: false,
            timestamp: SystemTime::now(),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SelectionSignal {
    pub content_type: ContentType,
    pub size_bytes: usize,
    pub source_app: String,
    pub likely_sensitive: bool,
    pub is_editable: bool,
    pub timestamp: SystemTime,
}

impl SelectionSignal {
    pub fn text(content: &str, source_app: String, is_editable: bool) -> Self {
        Self {
            content_type: detect_content_type(content),
            size_bytes: content.len(),
            source_app,
            likely_sensitive: is_likely_sensitive_text(content),
            is_editable,
            timestamp: SystemTime::now(),
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FocusTarget {
    Application,
    Window,
    TextInput,
    Browser,
    Terminal,
    Unknown,
}

impl FocusTarget {
    pub fn as_str(&self) -> &'static str {
        match self {
            FocusTarget::Application => "application",
            FocusTarget::Window => "window",
            FocusTarget::TextInput => "text_input",
            FocusTarget::Browser => "browser",
            FocusTarget::Terminal => "terminal",
            FocusTarget::Unknown => "unknown",
        }
    }
}

impl fmt::Display for FocusTarget {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FocusSignal {
    pub source_app: String,
    pub target: FocusTarget,
    pub is_editable: bool,
    pub timestamp: SystemTime,
}

impl FocusSignal {
    pub fn new(source_app: String, target: FocusTarget, is_editable: bool) -> Self {
        Self {
            source_app,
            target,
            is_editable,
            timestamp: SystemTime::now(),
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ClipboardContent {
    pub payload: ClipboardPayload,
    pub source_app: String,
    pub captured_at: SystemTime,
}

impl ClipboardContent {
    pub fn redacted_preview(&self) -> String {
        match &self.payload {
            ClipboardPayload::Text(text) if is_likely_sensitive_text(text) => {
                format!("{} chars redacted", text.chars().count())
            }
            ClipboardPayload::Text(text) => text.chars().take(80).collect(),
            ClipboardPayload::Image {
                width,
                height,
                size_bytes,
            } => format!("image {}x{} ({} bytes)", width, height, size_bytes),
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ClipboardPayload {
    Text(String),
    Image {
        width: usize,
        height: usize,
        size_bytes: usize,
    },
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "signal", rename_all = "snake_case")]
pub enum StructuralSignal {
    Clipboard(ClipboardSignal),
    Selection(SelectionSignal),
    Focus(FocusSignal),
    Filesystem(SemanticSignal),
}

impl StructuralSignal {
    pub fn signal_type(&self) -> Option<SignalType> {
        match self {
            StructuralSignal::Clipboard(_) => Some(SignalType::Clipboard),
            StructuralSignal::Selection(_) => Some(SignalType::Selection),
            StructuralSignal::Focus(_) => Some(SignalType::Focus),
            StructuralSignal::Filesystem(_) => None,
        }
    }

    pub fn source(&self) -> SignalSource {
        match self {
            StructuralSignal::Clipboard(_) => SignalSource::Clipboard,
            StructuralSignal::Selection(_) => SignalSource::Selection,
            StructuralSignal::Focus(_) => SignalSource::Focus,
            StructuralSignal::Filesystem(_) => SignalSource::Filesystem,
        }
    }

    pub fn matches(&self, signal_type: SignalType) -> bool {
        self.signal_type() == Some(signal_type)
    }
}

pub fn detect_content_type(content: &str) -> ContentType {
    let trimmed = content.trim();
    let lowercase = trimmed.to_ascii_lowercase();

    if lowercase.starts_with("<!doctype html")
        || lowercase.starts_with("<html")
        || (lowercase.contains("<body") && lowercase.contains("</"))
    {
        return ContentType::Html;
    }

    let code_markers = [
        "fn ",
        "def ",
        "class ",
        "import ",
        "from ",
        "const ",
        "let ",
        "var ",
        "function ",
        "#include",
        "SELECT ",
        "{\n",
    ];

    if code_markers.iter().any(|marker| trimmed.contains(marker))
        || (trimmed.lines().count() > 2
            && trimmed.contains('{')
            && trimmed.contains('}')
            && trimmed.contains(';'))
    {
        return ContentType::Code;
    }

    if trimmed.is_empty() {
        ContentType::Unknown
    } else {
        ContentType::Text
    }
}

pub fn is_likely_sensitive_text(content: &str) -> bool {
    let trimmed = content.trim();

    if trimmed.is_empty() || trimmed.contains('\n') {
        return false;
    }

    let jwt_like = trimmed.matches('.').count() == 2 && trimmed.len() > 20;
    let token_prefix = ["sk-", "ghp_", "xoxb-", "AKIA", "-----BEGIN", "eyJ"];

    // Require higher entropy to avoid false positives like "myFile123" or "config_v2"
    // Real secrets/tokens have high entropy (5.0+ bits), normal text has ~4.0-4.5 bits
    let looks_like_secret = trimmed.len() >= 16
        && !trimmed.contains(' ')
        && trimmed.chars().any(|c| c.is_ascii_alphabetic())
        && trimmed.chars().any(|c| c.is_ascii_digit())
        && shannon_entropy(trimmed) > 4.0;

    jwt_like
        || token_prefix
            .iter()
            .any(|prefix| trimmed.starts_with(prefix))
        || looks_like_secret
}

fn shannon_entropy(input: &str) -> f64 {
    if input.is_empty() {
        return 0.0;
    }

    let mut frequency = [0u32; 256];
    for byte in input.bytes() {
        frequency[byte as usize] += 1;
    }

    let len = input.len() as f64;
    frequency
        .iter()
        .filter(|&&count| count > 0)
        .map(|&count| {
            let p = count as f64 / len;
            -p * p.log2()
        })
        .sum()
}

pub fn is_likely_command_text(content: &str) -> bool {
    let trimmed = content.trim();

    if trimmed.is_empty() || trimmed.contains('\n') {
        return false;
    }

    let normalized = trimmed.strip_prefix("$ ").unwrap_or(trimmed);
    let command_prefixes = [
        "cargo ", "git ", "npm ", "pnpm ", "yarn ", "python ", "pip ", "uv ", "docker ",
        "kubectl ", "ls", "cd ", "mkdir ", "rm ", "cp ", "mv ",
    ];

    command_prefixes
        .iter()
        .any(|prefix| normalized.starts_with(prefix))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn detects_html() {
        assert_eq!(
            detect_content_type("<!DOCTYPE html><html></html>"),
            ContentType::Html
        );
    }

    #[test]
    fn detects_code() {
        assert_eq!(
            detect_content_type("fn main() {\n println!(\"hi\");\n}"),
            ContentType::Code
        );
    }

    #[test]
    fn detects_plain_text() {
        assert_eq!(detect_content_type("hello world"), ContentType::Text);
    }

    #[test]
    fn marks_sensitive_tokens() {
        assert!(is_likely_sensitive_text("sk-live-1234567890abcdef"));
    }

    #[test]
    fn rejects_false_positive_filenames() {
        // These were triggering false positives before entropy check
        assert!(!is_likely_sensitive_text("myFile123"));
        assert!(!is_likely_sensitive_text("config_v2"));
        assert!(!is_likely_sensitive_text("user2024"));
        assert!(!is_likely_sensitive_text("version1.0"));
        assert!(!is_likely_sensitive_text("data_backup_01"));
    }

    #[test]
    fn detects_high_entropy_secrets() {
        // Real secrets have high entropy
        assert!(is_likely_sensitive_text(
            "ghp_aBcDeFgHiJkLmNoPqRsTuVwXyZ123456"
        ));
        assert!(is_likely_sensitive_text(
            "sk-proj-abcdefghijklmnop1234567890"
        ));
        // JWT-like tokens
        assert!(is_likely_sensitive_text(
            "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U"
        ));
    }

    #[test]
    fn shannon_entropy_values() {
        // Low entropy - repeated characters
        assert!(shannon_entropy("aaaaaaaaaa") < 1.0);
        // Medium entropy - normal text
        let medium = shannon_entropy("hello_world");
        assert!(medium > 2.0 && medium < 4.0);
        // High entropy - random-looking
        let high = shannon_entropy("aB3xK9mP2qR7sT4uV8wY1zC5dE6fG0hI");
        assert!(high > 4.5);
    }

    #[test]
    fn marks_commands() {
        assert!(is_likely_command_text("cargo test"));
    }

    #[test]
    fn selection_signal_tracks_text_metadata() {
        let signal = SelectionSignal::text("let value = 1;", "editor".to_string(), true);
        assert_eq!(signal.content_type, ContentType::Code);
        assert!(signal.is_editable);
        assert_eq!(signal.size_bytes, 14);
    }

    #[test]
    fn structural_signal_maps_to_source() {
        assert_eq!(
            StructuralSignal::Focus(FocusSignal::new(
                "terminal".to_string(),
                FocusTarget::Terminal,
                true,
            ))
            .source(),
            SignalSource::Focus
        );
    }
}