asurada 0.3.0

Asurada — a memory + cognition daemon that grows with the user. Local-first, BYOK, shared by Devist/Webchemist Core/etc.
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
// Severity / Priority / Scope 분류 로직.
//
// 설계 원칙:
//   1. 초창기엔 사용자의 잦은 override 가 자연스러움 — 보수적 디폴트로 시작.
//   2. Override 는 학습 신호로 기록 (장기적으로 디폴트 개선의 근거).
//   3. Claude 가 1차 태깅 → 이 모듈이 sanity check / fallback 제공.
//   4. 사용자가 직접 설정한 분류는 source='user' 로 마킹되어 자동 변경 안 됨 (policies 와 연결).

#![allow(dead_code)]

use serde::{Deserialize, Serialize};
use std::str::FromStr;

// ───── Severity (advice 발급 시) ─────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    /// 단순 알림. 행동 요구 X.
    Info,
    /// 개선 제안. 안 따라도 무방.
    Suggest,
    /// 잠재 문제. 봐야 함.
    Warn,
    /// 작동 안 함. 즉시 조치 필요.
    Block,
}

impl Severity {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Info => "info",
            Self::Suggest => "suggest",
            Self::Warn => "warn",
            Self::Block => "block",
        }
    }
}

impl Default for Severity {
    /// 보수적 기본값 — 의심 시 가장 약한 신호.
    fn default() -> Self {
        Self::Info
    }
}

impl FromStr for Severity {
    type Err = ();
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "info" => Ok(Self::Info),
            "suggest" => Ok(Self::Suggest),
            "warn" | "warning" => Ok(Self::Warn),
            "block" | "blocker" => Ok(Self::Block),
            _ => Err(()),
        }
    }
}

// ───── Priority (memory 저장 시) ─────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Priority {
    /// 단순 사실 / 컨텍스트.
    Info,
    /// 약한 선호.
    Preference,
    /// 강한 선호. 거의 항상 적용.
    Strong,
    /// 절대 규칙. 어기면 안 됨.
    Constraint,
}

impl Priority {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Info => "info",
            Self::Preference => "preference",
            Self::Strong => "strong",
            Self::Constraint => "constraint",
        }
    }
}

impl Default for Priority {
    /// 보수적 기본값. 시작은 항상 낮은 우선순위.
    fn default() -> Self {
        Self::Info
    }
}

impl FromStr for Priority {
    type Err = ();
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "info" => Ok(Self::Info),
            "preference" => Ok(Self::Preference),
            "strong" => Ok(Self::Strong),
            "constraint" => Ok(Self::Constraint),
            _ => Err(()),
        }
    }
}

// ───── Scope (memory 적용 범위) ──────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Scope {
    /// 사용자 본인에 관한 사실 — 모든 프로젝트 공통.
    User,
    /// 특정 프로젝트에 한정.
    Project,
    /// 기술 / 도메인 지식 — 사용자 무관, 기술 매칭 시 적용.
    Tech,
}

impl Scope {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::User => "user",
            Self::Project => "project",
            Self::Tech => "tech",
        }
    }
}

impl FromStr for Scope {
    type Err = ();
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "user" => Ok(Self::User),
            "project" => Ok(Self::Project),
            "tech" => Ok(Self::Tech),
            _ => Err(()),
        }
    }
}

// ───── Sanity check / fallback 로직 ─────────────────────

/// Claude 가 태깅한 severity 의 sanity check.
/// 근거가 약하면 한 단계 다운그레이드. (block→warn, warn→suggest)
///
/// 휴리스틱은 단순함:
///   - "block": 텍스트에 빌드/타입/import/syntax 같은 hard-error 신호 있어야 함
///   - "warn":  문제/위험/누락/오류 같은 명시적 신호 있어야 함
///   - 그 외는 그대로
pub fn sanitize_severity(claimed: Severity, advice_text: &str) -> Severity {
    let text = advice_text.to_lowercase();
    match claimed {
        Severity::Block => {
            if has_block_evidence(&text) {
                Severity::Block
            } else {
                Severity::Warn
            }
        }
        Severity::Warn => {
            if has_warn_evidence(&text) {
                Severity::Warn
            } else {
                Severity::Suggest
            }
        }
        other => other,
    }
}

fn has_block_evidence(text_lower: &str) -> bool {
    const SIGNALS: &[&str] = &[
        // 영어
        "build fail",
        "compile error",
        "compilation error",
        "syntax error",
        "type error",
        "import error",
        "module not found",
        "undefined",
        "cannot find",
        "panic",
        "crash",
        // 한국어
        "빌드 실패",
        "컴파일 오류",
        "컴파일 에러",
        "타입 오류",
        "타입 에러",
        "구문 오류",
        "구문 에러",
        "동작 안",
        "작동 안",
        "실행 안",
    ];
    SIGNALS.iter().any(|s| text_lower.contains(s))
}

fn has_warn_evidence(text_lower: &str) -> bool {
    const SIGNALS: &[&str] = &[
        // 영어
        "missing",
        "leak",
        "undefined behavior",
        "race",
        "deadlock",
        "incorrect",
        "wrong",
        "bug",
        "vulnerability",
        "security",
        "deprecated",
        "warning",
        // 한국어
        "누락",
        "유출",
        "버그",
        "잘못",
        "오류",
        "에러",
        "위험",
        "취약",
        "보안",
        "문제",
        "주의",
    ];
    SIGNALS.iter().any(|s| text_lower.contains(s))
}

/// 메모리 추출 시 source 별 보수적 기본 priority.
/// Claude 가 명시 태깅한 게 있으면 그것을 우선 — 이 함수는 fallback.
pub fn default_priority_for_source(source: &str) -> Priority {
    match source {
        "user" => Priority::Preference, // 사용자가 쓴 것은 의미 있음 → preference 부터
        _ => Priority::Info,            // Asurada 추출은 보수적으로 info
    }
}

/// 텍스트 + 프로젝트 컨텍스트로 scope 추론 (fallback).
/// Claude 태깅이 없을 때만 사용.
pub fn infer_scope(text: &str, current_project: Option<&str>) -> Scope {
    let lower = text.to_lowercase();

    // 1. 프로젝트 명이 직접 언급되면 project
    if let Some(p) = current_project {
        if lower.contains(&p.to_lowercase()) {
            return Scope::Project;
        }
    }

    // 2. 기술 / 프레임워크 키워드만 있고 사용자/프로젝트 언급 없으면 tech
    let has_tech_keyword = TECH_KEYWORDS.iter().any(|k| lower.contains(k));
    let has_personal_or_project_signal = PERSONAL_SIGNALS.iter().any(|k| lower.contains(k))
        || current_project
            .map(|p| lower.contains(&p.to_lowercase()))
            .unwrap_or(false);

    if has_tech_keyword && !has_personal_or_project_signal {
        return Scope::Tech;
    }

    // 3. 그 외는 user (사용자 본인 또는 작업 흐름에 관한 사실)
    Scope::User
}

const TECH_KEYWORDS: &[&str] = &[
    "react",
    "rust",
    "typescript",
    "python",
    "supabase",
    "postgres",
    "node",
    "vite",
    "tailwind",
    "useeffect",
    "usestate",
    "trait",
    "async",
    "tokio",
    "axum",
    "javascript",
    "go ",
    "java ",
];

const PERSONAL_SIGNALS: &[&str] = &[
    "alice",
    "bob",
    "user",
    "사용자",
    "본인",
    "i ",
    " me ",
    " my ",
    "내가",
    "나는",
    "저는",
    "제가",
];

// ───── 사용자 override 추적 ──────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ClassifiedField {
    Severity,
    Priority,
    Scope,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OverrideRecord {
    pub memory_or_event_id: String,
    pub field: ClassifiedField,
    pub original: String,
    pub corrected_to: String,
    pub at: chrono::DateTime<chrono::Utc>,
    pub by_user_id: String,
}

impl OverrideRecord {
    pub fn new(
        id: impl Into<String>,
        field: ClassifiedField,
        original: impl Into<String>,
        corrected_to: impl Into<String>,
        by_user_id: impl Into<String>,
    ) -> Self {
        Self {
            memory_or_event_id: id.into(),
            field,
            original: original.into(),
            corrected_to: corrected_to.into(),
            at: chrono::Utc::now(),
            by_user_id: by_user_id.into(),
        }
    }
}

// ───── 단위 테스트 ─────────────────────────────────────

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

    // --- Severity sanitization ---

    #[test]
    fn block_with_evidence_stays() {
        assert_eq!(
            sanitize_severity(Severity::Block, "build fails because of missing import"),
            Severity::Block
        );
    }

    #[test]
    fn block_without_evidence_downgrades() {
        assert_eq!(
            sanitize_severity(Severity::Block, "이 함수 더 짧게 쓸 수 있어"),
            Severity::Warn
        );
    }

    #[test]
    fn block_korean_evidence_stays() {
        assert_eq!(
            sanitize_severity(Severity::Block, "빌드 실패 — 타입 오류 있음"),
            Severity::Block
        );
    }

    #[test]
    fn warn_with_evidence_stays() {
        assert_eq!(
            sanitize_severity(Severity::Warn, "여기 cleanup 누락 가능"),
            Severity::Warn
        );
    }

    #[test]
    fn warn_without_evidence_downgrades() {
        assert_eq!(
            sanitize_severity(Severity::Warn, "이 함수 이름 좀 바꿔도 괜찮을 듯"),
            Severity::Suggest
        );
    }

    #[test]
    fn suggest_unchanged() {
        assert_eq!(
            sanitize_severity(Severity::Suggest, "anything here"),
            Severity::Suggest
        );
    }

    // --- Priority defaults ---

    #[test]
    fn user_source_starts_at_preference() {
        assert_eq!(default_priority_for_source("user"), Priority::Preference);
    }

    #[test]
    fn asurada_source_starts_at_info() {
        assert_eq!(default_priority_for_source("asurada"), Priority::Info);
    }

    // --- Scope inference ---

    #[test]
    fn project_name_in_text_means_project_scope() {
        assert_eq!(
            infer_scope("Devist 는 Rust 만 쓴다", Some("Devist")),
            Scope::Project
        );
    }

    #[test]
    fn tech_keyword_only_means_tech_scope() {
        assert_eq!(
            infer_scope("useEffect cleanup 함수가 필요하다", None),
            Scope::Tech
        );
    }

    #[test]
    fn personal_signal_means_user_scope() {
        assert_eq!(
            infer_scope("alice는 짧은 함수를 선호한다", None),
            Scope::User
        );
    }

    #[test]
    fn ambiguous_defaults_to_user() {
        assert_eq!(infer_scope("뭔가 일반적인 메모", None), Scope::User);
    }

    // --- Round trip ---

    #[test]
    fn enum_string_roundtrip() {
        for s in &[
            Severity::Info,
            Severity::Suggest,
            Severity::Warn,
            Severity::Block,
        ] {
            assert_eq!(s.as_str().parse::<Severity>().unwrap(), *s);
        }
        for p in &[
            Priority::Info,
            Priority::Preference,
            Priority::Strong,
            Priority::Constraint,
        ] {
            assert_eq!(p.as_str().parse::<Priority>().unwrap(), *p);
        }
        for sc in &[Scope::User, Scope::Project, Scope::Tech] {
            assert_eq!(sc.as_str().parse::<Scope>().unwrap(), *sc);
        }
    }

    // --- Override record ---

    #[test]
    fn override_record_constructs() {
        let rec = OverrideRecord::new(
            "mem-123",
            ClassifiedField::Priority,
            "info",
            "strong",
            "alice",
        );
        assert_eq!(rec.field, ClassifiedField::Priority);
        assert_eq!(rec.corrected_to, "strong");
    }
}