difflore-core 0.5.0

Core library for the difflore CLI — rule store, retrieval, MCP server, hooks, cloud sync. Not intended for direct use; depend on `difflore-cli` instead.
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
481
use openapi_contract::api;
use serde::{Deserialize, Serialize};

use super::client::CloudClient;
use crate::contract::Success;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CandidateStatus {
    Pending,
    Approved,
    Rejected,
}

impl CandidateStatus {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Pending => "pending",
            Self::Approved => "approved",
            Self::Rejected => "rejected",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CandidateSeverity {
    Info,
    Warning,
    Error,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RuleCandidate {
    pub id: String,
    pub team_id: String,
    pub diff_signature: String,
    pub acceptance_count: f64,
    pub distinct_users: f64,
    pub generated_name: String,
    pub generated_description: String,
    pub generated_severity: String,
    pub example_before: String,
    pub example_after: String,
    pub language: Option<String>,
    pub status: String,
    pub reviewed_by: Option<String>,
    pub reviewed_at: Option<String>,
    pub rejection_reason: Option<String>,
    pub published_rule_id: Option<String>,
    pub origin: String,
    pub created_at: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RuleCandidateEvent {
    pub id: String,
    pub candidate_id: String,
    pub team_id: String,
    pub event_type: String,
    pub actor_id: Option<String>,
    pub status_from: Option<String>,
    pub status_to: Option<String>,
    pub reason: Option<String>,
    pub confidence_before: Option<f64>,
    pub confidence_after: Option<f64>,
    pub created_at: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RuleCandidateDetail {
    #[serde(flatten)]
    pub candidate: RuleCandidate,
    pub events: Vec<RuleCandidateEvent>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ListCandidatesRequest {
    pub team_id: String,
    pub limit: Option<i64>,
    pub offset: Option<i64>,
    pub status: Option<CandidateStatus>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CountCandidatesRequest {
    pub team_id: String,
    pub status: Option<CandidateStatus>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CandidateCount {
    pub total: f64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct CandidateApprovalEdits {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub severity: Option<CandidateSeverity>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ApproveCandidateRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub edits: Option<CandidateApprovalEdits>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApproveCandidateResponse {
    pub candidate_id: String,
    pub rule_id: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct RejectCandidateRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DismissSignatureRequest {
    pub team_id: String,
    pub signature: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateCandidateSettingsRequest {
    pub team_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_count: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_distinct_users: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lookback_days: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CandidateSettings {
    pub team_id: String,
    pub min_count: f64,
    pub min_distinct_users: f64,
    pub lookback_days: f64,
    pub enabled: bool,
}

pub async fn list_candidates(
    client: &CloudClient,
    request: ListCandidatesRequest,
) -> crate::Result<Vec<RuleCandidate>> {
    let limit = request.limit.unwrap_or(20);
    let offset = request.offset.unwrap_or(0);
    if let Some(status) = request.status {
        client
            .fetch_api_json(
                api!(GET "/rules/candidates", query = {
                    teamId: &request.team_id,
                    limit: limit,
                    offset: offset,
                    status: status.as_str(),
                }),
                "list_candidates",
            )
            .await
    } else {
        client
            .fetch_api_json(
                api!(GET "/rules/candidates", query = {
                    teamId: &request.team_id,
                    limit: limit,
                    offset: offset,
                }),
                "list_candidates",
            )
            .await
    }
}

pub async fn count_candidates(
    client: &CloudClient,
    request: CountCandidatesRequest,
) -> crate::Result<CandidateCount> {
    if let Some(status) = request.status {
        client
            .fetch_api_json(
                api!(GET "/rules/candidates/count", query = {
                    teamId: &request.team_id,
                    status: status.as_str(),
                }),
                "count_candidates",
            )
            .await
    } else {
        client
            .fetch_api_json(
                api!(GET "/rules/candidates/count", query = {
                    teamId: &request.team_id,
                }),
                "count_candidates",
            )
            .await
    }
}

pub async fn get_candidate(
    client: &CloudClient,
    candidate_id: &str,
) -> crate::Result<RuleCandidateDetail> {
    client
        .fetch_api_json(
            api!(GET "/rules/candidates/{candidateId}", candidateId = candidate_id),
            "get_candidate",
        )
        .await
}

pub async fn approve_candidate(
    client: &CloudClient,
    candidate_id: &str,
    edits: Option<CandidateApprovalEdits>,
) -> crate::Result<ApproveCandidateResponse> {
    if let Some(edits) = edits {
        let request = ApproveCandidateRequest { edits: Some(edits) };
        client
            .fetch_api_json(
                api!(
                    POST "/rules/candidates/{candidateId}/approve",
                    candidateId = candidate_id,
                    body = &request
                ),
                "approve_candidate",
            )
            .await
    } else {
        client
            .fetch_api_json(
                api!(
                    POST "/rules/candidates/{candidateId}/approve",
                    candidateId = candidate_id
                ),
                "approve_candidate",
            )
            .await
    }
}

pub async fn reject_candidate(
    client: &CloudClient,
    candidate_id: &str,
    reason: Option<String>,
) -> crate::Result<()> {
    let _: Success = if let Some(reason) = reason {
        let request = RejectCandidateRequest {
            reason: Some(reason),
        };
        client
            .fetch_api_json(
                api!(
                    POST "/rules/candidates/{candidateId}/reject",
                    candidateId = candidate_id,
                    body = &request
                ),
                "reject_candidate",
            )
            .await?
    } else {
        client
            .fetch_api_json(
                api!(
                    POST "/rules/candidates/{candidateId}/reject",
                    candidateId = candidate_id
                ),
                "reject_candidate",
            )
            .await?
    };
    Ok(())
}

pub async fn dismiss_signature(
    client: &CloudClient,
    request: &DismissSignatureRequest,
) -> crate::Result<()> {
    let _: Success = client
        .fetch_api_json(
            api!(POST "/rules/candidates/dismiss-signature", body = request),
            "dismiss_signature",
        )
        .await?;
    Ok(())
}

pub async fn update_settings(
    client: &CloudClient,
    request: &UpdateCandidateSettingsRequest,
) -> crate::Result<CandidateSettings> {
    client
        .fetch_api_json(
            api!(POST "/rules/candidates/settings", body = request),
            "update_candidate_settings",
        )
        .await
}

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

    fn assert_float_eq(actual: f64, expected: f64) {
        assert!(
            (actual - expected).abs() < f64::EPSILON,
            "expected {expected}, got {actual}"
        );
    }

    fn candidate_json() -> serde_json::Value {
        json!({
            "id": "cand-1",
            "teamId": "team-1",
            "diffSignature": "sig-1",
            "acceptanceCount": 4,
            "distinctUsers": 2,
            "generatedName": "Use typed errors",
            "generatedDescription": "Prefer typed errors over stringly status checks.",
            "generatedSeverity": "warning",
            "exampleBefore": "if err == \"missing\" {}",
            "exampleAfter": "if matches!(err, Error::Missing) {}",
            "language": "rust",
            "status": "pending",
            "reviewedBy": null,
            "reviewedAt": null,
            "rejectionReason": null,
            "publishedRuleId": null,
            "origin": "observation_cluster",
            "meta": {"source": "test"},
            "createdAt": "2026-06-30T00:00:00.000Z"
        })
    }

    #[test]
    fn parses_list_candidate_shape_from_contract() {
        let candidates: Vec<RuleCandidate> =
            serde_json::from_value(json!([candidate_json()])).unwrap();

        assert_eq!(candidates.len(), 1);
        assert_eq!(candidates[0].id, "cand-1");
        assert_eq!(candidates[0].team_id, "team-1");
        assert_float_eq(candidates[0].acceptance_count, 4.0);
        assert_float_eq(candidates[0].distinct_users, 2.0);
        assert_eq!(candidates[0].language.as_deref(), Some("rust"));
        assert_eq!(candidates[0].status, "pending");
    }

    #[test]
    fn parses_candidate_detail_events_shape_from_contract() {
        let mut value = candidate_json();
        value.as_object_mut().unwrap().insert(
            "events".to_owned(),
            json!([{
                "id": "event-1",
                "candidateId": "cand-1",
                "teamId": "team-1",
                "eventType": "status_changed",
                "actorId": "user-1",
                "statusFrom": null,
                "statusTo": "pending",
                "reason": null,
                "confidenceBefore": null,
                "confidenceAfter": 0.92,
                "metadata": {"ignored": true},
                "createdAt": "2026-06-30T00:01:00.000Z"
            }]),
        );

        let detail: RuleCandidateDetail = serde_json::from_value(value).unwrap();

        assert_eq!(detail.candidate.id, "cand-1");
        assert_eq!(detail.events.len(), 1);
        assert_eq!(detail.events[0].candidate_id, "cand-1");
        assert_eq!(detail.events[0].confidence_after, Some(0.92));
    }

    #[test]
    fn serializes_approve_edits_without_absent_fields() {
        let request = ApproveCandidateRequest {
            edits: Some(CandidateApprovalEdits {
                name: Some("Use typed errors".to_owned()),
                severity: Some(CandidateSeverity::Warning),
                ..CandidateApprovalEdits::default()
            }),
        };

        assert_eq!(
            serde_json::to_value(request).unwrap(),
            json!({
                "edits": {
                    "name": "Use typed errors",
                    "severity": "warning"
                }
            })
        );
    }

    #[test]
    fn serializes_reject_request_without_null_reason() {
        assert_eq!(
            serde_json::to_value(RejectCandidateRequest::default()).unwrap(),
            json!({})
        );
        assert_eq!(
            serde_json::to_value(RejectCandidateRequest {
                reason: Some("duplicate".to_owned()),
            })
            .unwrap(),
            json!({"reason": "duplicate"})
        );
    }

    #[test]
    fn serializes_settings_request_without_absent_fields() {
        let request = UpdateCandidateSettingsRequest {
            team_id: "team-1".to_owned(),
            min_count: Some(3),
            min_distinct_users: None,
            lookback_days: Some(30),
            enabled: Some(true),
        };

        assert_eq!(
            serde_json::to_value(request).unwrap(),
            json!({
                "teamId": "team-1",
                "minCount": 3,
                "lookbackDays": 30,
                "enabled": true
            })
        );
    }

    #[test]
    fn parses_count_and_settings_responses() {
        let count: CandidateCount = serde_json::from_value(json!({"total": 7})).unwrap();
        assert_float_eq(count.total, 7.0);

        let settings: CandidateSettings = serde_json::from_value(json!({
            "teamId": "team-1",
            "minCount": 3,
            "minDistinctUsers": 2,
            "lookbackDays": 30,
            "enabled": true
        }))
        .unwrap();

        assert_eq!(settings.team_id, "team-1");
        assert_float_eq(settings.min_count, 3.0);
        assert_float_eq(settings.min_distinct_users, 2.0);
        assert_float_eq(settings.lookback_days, 30.0);
        assert!(settings.enabled);
    }
}