difflore-cli 0.5.0

Your AI coding agent learned public code, not your team's private decisions. difflore turns past PR reviews into source-backed local rules.
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
use difflore_core::review_store::{ReviewCommentRecord, ReviewItemWithComments};

use crate::support::file_ext::{is_review_file_extension, is_source_code_extension};

pub(super) fn is_import_review_noise_line(line: &str) -> bool {
    let trimmed = line
        .trim()
        .trim_start_matches(['>', '-', '*'])
        .trim()
        .trim_matches('`')
        .trim();
    let lower = trimmed.to_ascii_lowercase();
    lower == "[!caution]"
        || lower.contains("some comments are outside the diff")
        || lower.starts_with("outside diff range comment")
        || lower.starts_with("outside diff range comments")
        || lower.starts_with("review table")
        || lower.starts_with("review details")
        || is_plus_more_scope_marker(trimmed)
        || is_review_table_wrapper_line(trimmed)
}

fn is_plus_more_scope_marker(value: &str) -> bool {
    let trimmed = value
        .trim()
        .trim_matches('|')
        .trim()
        .trim_end_matches(['.', ',', ';', ':'])
        .trim();
    let Some(rest) = trimmed.strip_prefix('+') else {
        return false;
    };
    let rest = rest.trim_start();
    let digit_count = rest.chars().take_while(char::is_ascii_digit).count();
    if digit_count == 0 {
        return false;
    }
    rest[digit_count..].trim_start().starts_with("more")
}

pub(super) fn is_review_table_wrapper_line(line: &str) -> bool {
    let trimmed = line.trim();
    if !trimmed.starts_with('|') {
        return false;
    }
    let lower = trimmed.to_ascii_lowercase();
    [
        "reviewable files",
        "files reviewed",
        "files changed",
        "additional comments",
        "outside diff",
        "comments outside the diff",
        "committable suggestions",
        "sequence diagrams",
        "review profile",
    ]
    .iter()
    .any(|needle| lower.contains(needle))
}

pub(super) fn is_high_leverage_scope_path(path: &str) -> bool {
    let lower = path.replace('\\', "/").to_ascii_lowercase();
    let file = lower.rsplit('/').next().unwrap_or(lower.as_str());
    lower.starts_with(".github/workflows/") || is_manifest_filename(file)
}

fn is_manifest_filename(file_name: &str) -> bool {
    let lower = file_name.to_ascii_lowercase();
    matches!(
        lower.as_str(),
        "go.mod"
            | "go.sum"
            | "cargo.toml"
            | "cargo.lock"
            | "package.json"
            | "package-lock.json"
            | "pnpm-lock.yaml"
            | "yarn.lock"
            | "bun.lockb"
            | "uv.lock"
            | "poetry.lock"
            | "requirements.txt"
            | "dockerfile"
    )
}

fn source_scope_extension(path: &str) -> Option<String> {
    let normalized = path.trim().trim_start_matches("./").replace('\\', "/");
    let (_, ext_raw) = normalized.rsplit_once('.')?;
    if ext_raw.is_empty() || ext_raw.contains('/') || ext_raw.contains('\\') {
        return None;
    }
    let ext = ext_raw.to_ascii_lowercase();
    is_review_file_extension(&ext).then_some(ext)
}

fn has_source_scope_anchor(paths: &[String]) -> bool {
    paths
        .iter()
        .any(|path| !is_high_leverage_scope_path(path) && source_scope_extension(path).is_some())
}

fn drop_manifest_scope_when_source_anchor_exists(mut paths: Vec<String>) -> Vec<String> {
    if has_source_scope_anchor(&paths) {
        paths.retain(|path| !is_high_leverage_scope_path(path));
    }
    paths
}

pub(super) fn file_pattern_from_path(path: &str) -> Option<String> {
    file_patterns_from_path(path).into_iter().next()
}

pub(super) fn repo_wide_file_pattern_from_path(path: &str) -> Option<String> {
    let trimmed = path.trim().trim_start_matches("./");
    if trimmed.is_empty() || trimmed.contains(' ') {
        return None;
    }
    let normalized = trimmed.replace('\\', "/");
    if !normalized.contains('.') {
        return None;
    }
    let (_, ext_raw) = normalized.rsplit_once('.')?;
    if ext_raw.is_empty() || ext_raw.contains('/') || ext_raw.contains('\\') {
        return None;
    }
    let ext = ext_raw.to_ascii_lowercase();
    if !is_source_code_extension(&ext) {
        return None;
    }
    Some(format!("**/*.{ext}"))
}

/// Derive narrow and, for common monorepo layouts, sibling-broadening
/// file patterns from a comment-anchor path.
pub(super) fn file_patterns_from_path(path: &str) -> Vec<String> {
    let trimmed = path.trim().trim_start_matches("./");
    if trimmed.is_empty() || trimmed.contains(' ') {
        return Vec::new();
    }
    let normalized = trimmed.replace('\\', "/");
    let file_name = normalized.rsplit('/').next().unwrap_or(normalized.as_str());
    let exact_manifest = is_manifest_filename(file_name);
    if exact_manifest {
        let pat = if let Some((dir, _)) = normalized.rsplit_once('/') {
            format!("{dir}/**/{file_name}")
        } else {
            format!("**/{file_name}")
        };
        return vec![pat];
    }
    if !normalized.contains('.') {
        return Vec::new();
    }
    let Some((_, ext_raw)) = normalized.rsplit_once('.') else {
        return Vec::new();
    };
    if ext_raw.is_empty() || ext_raw.contains('/') || ext_raw.contains('\\') {
        return Vec::new();
    }
    let ext = ext_raw.to_ascii_lowercase();
    if !is_review_file_extension(&ext) {
        return Vec::new();
    }
    let dir = normalized.rsplit_once('/').map_or("**", |(dir, _)| dir);
    if ext == "md" && dir == "**" {
        return vec![format!("**/{file_name}")];
    }
    let narrow = if dir == "**" {
        format!("**/*.{ext}")
    } else {
        format!("{dir}/**/*.{ext}")
    };
    let mut out = vec![narrow];
    // Monorepo broadening for sibling packages with the same shape.
    for prefix in ["packages/", "apps/", "crates/", "pkg/", "examples/"] {
        if let Some(rest) = normalized.strip_prefix(prefix)
            && rest.contains('/')
        {
            // `packages/router-core/src/foo.ts` -> `packages/**/*.ts`
            let broad = format!("{prefix}**/*.{ext}");
            if !out.contains(&broad) {
                out.push(broad);
            }
            break;
        }
    }
    out
}

fn normalize_review_file_path(value: &str) -> Option<String> {
    let trimmed = value
        .trim()
        .trim_matches('`')
        .trim_matches('"')
        .trim_matches('\'')
        .trim()
        .trim_start_matches("./")
        .trim_end_matches([',', '.', ';', ':'])
        .replace('\\', "/");
    if trimmed.is_empty()
        || trimmed.contains(char::is_whitespace)
        || is_plus_more_scope_marker(&trimmed)
        || is_import_review_noise_line(&trimmed)
        || trimmed.starts_with("http://")
        || trimmed.starts_with("https://")
        || trimmed.contains('<')
        || trimmed.contains('>')
        || trimmed == "File"
        || trimmed.chars().all(|ch| ch == '-')
    {
        return None;
    }
    file_pattern_from_path(&trimmed).map(|_| trimmed)
}

fn backticked_segments(line: &str) -> Vec<String> {
    let mut segments = Vec::new();
    let mut rest = line;
    while let Some(start) = rest.find('`') {
        rest = &rest[start + 1..];
        let Some(end) = rest.find('`') else {
            break;
        };
        segments.push(rest[..end].to_owned());
        rest = &rest[end + 1..];
    }
    segments
}

fn review_file_paths_from_content(content: &str) -> Vec<String> {
    let mut paths = Vec::new();
    let mut seen = std::collections::HashSet::new();
    let mut push_path = |value: &str| {
        if let Some(path) = normalize_review_file_path(value)
            && (path.contains('/') || is_high_leverage_scope_path(&path))
            && seen.insert(path.clone())
        {
            paths.push(path);
        }
    };
    for line in content.lines() {
        if is_import_review_noise_line(line) {
            continue;
        }
        for segment in backticked_segments(line) {
            push_path(&segment);
        }
        let trimmed = line.trim();
        if trimmed.starts_with('|') {
            for cell in trimmed.split('|') {
                push_path(cell);
            }
        }
    }
    paths
}

fn collect_source_path_value(value: &serde_json::Value, push_path: &mut impl FnMut(&str)) {
    match value {
        serde_json::Value::String(path) => push_path(path),
        serde_json::Value::Array(items) => {
            for item in items {
                collect_source_path_value(item, push_path);
            }
        }
        serde_json::Value::Object(object) => {
            for key in [
                "path", "filePath", "filename", "newPath", "new_path", "oldPath", "old_path",
            ] {
                if let Some(path) = object.get(key).and_then(serde_json::Value::as_str) {
                    push_path(path);
                }
            }
            if let Some(nodes) = object.get("nodes") {
                collect_source_path_value(nodes, push_path);
            }
        }
        _ => {}
    }
}

fn source_paths_from_item_metadata(metadata: Option<&str>) -> Vec<String> {
    let Some(metadata) = metadata else {
        return Vec::new();
    };
    let Ok(value) = serde_json::from_str::<serde_json::Value>(metadata) else {
        return Vec::new();
    };
    let mut paths = Vec::new();
    let mut seen = std::collections::HashSet::new();
    let mut push_path = |value: &str| {
        if let Some(path) = normalize_review_file_path(value)
            && seen.insert(path.clone())
        {
            paths.push(path);
        }
    };
    for key in [
        "sourcePaths",
        "source_paths",
        "changedFilePaths",
        "changed_file_paths",
        "changedFiles",
        "changed_files",
        "filePaths",
        "file_paths",
        "files",
    ] {
        if let Some(value) = value.get(key) {
            collect_source_path_value(value, &mut push_path);
        }
    }
    paths
}

fn strip_diff_path_prefix(value: &str) -> Option<&str> {
    let value = value.trim().trim_matches('"');
    if value == "/dev/null" {
        return None;
    }
    Some(
        value
            .strip_prefix("a/")
            .or_else(|| value.strip_prefix("b/"))
            .unwrap_or(value),
    )
}

fn diff_git_b_path(line: &str) -> Option<&str> {
    line.strip_prefix("diff --git ")?
        .split_whitespace()
        .find_map(|token| token.strip_prefix("b/"))
}

fn source_paths_from_diff_content(diff_content: &str) -> Vec<String> {
    let mut paths = Vec::new();
    let mut seen = std::collections::HashSet::new();
    let mut push_path = |value: &str| {
        if let Some(value) = strip_diff_path_prefix(value)
            && let Some(path) = normalize_review_file_path(value)
            && seen.insert(path.clone())
        {
            paths.push(path);
        }
    };
    for line in diff_content.lines() {
        let trimmed = line.trim();
        if let Some(path) = diff_git_b_path(trimmed) {
            push_path(path);
        } else if let Some(path) = trimmed.strip_prefix("+++ ") {
            push_path(path);
        } else if let Some(path) = trimmed.strip_prefix("--- ") {
            push_path(path);
        } else if let Some(path) = trimmed.strip_prefix("rename to ") {
            push_path(path);
        } else if let Some(path) = trimmed.strip_prefix("rename from ") {
            push_path(path);
        }
    }
    paths
}

fn item_source_paths(item: &ReviewItemWithComments) -> Vec<String> {
    let mut paths = Vec::new();
    let mut seen = std::collections::HashSet::new();
    let mut push_path = |path: String| {
        if seen.insert(path.clone()) {
            paths.push(path);
        }
    };
    for path in source_paths_from_item_metadata(item.item.metadata.as_deref()) {
        push_path(path);
    }
    for path in source_paths_from_diff_content(&item.item.diff_content) {
        push_path(path);
    }
    paths
}

pub(super) fn candidate_scope_paths(
    item: &ReviewItemWithComments,
    comment: &ReviewCommentRecord,
) -> Vec<String> {
    let mut paths = Vec::new();
    let mut seen = std::collections::HashSet::new();
    let mut push_path = |value: &str| {
        if let Some(path) = normalize_review_file_path(value)
            && seen.insert(path.clone())
        {
            paths.push(path);
        }
    };
    if let Some(path) = comment_file_path(comment) {
        push_path(&path);
    }
    push_path(&item.item.file_path);
    for path in review_file_paths_from_content(&comment.content) {
        push_path(&path);
    }
    for path in item_source_paths(item) {
        push_path(&path);
    }
    drop_manifest_scope_when_source_anchor_exists(paths)
}

fn comment_file_path(comment: &ReviewCommentRecord) -> Option<String> {
    let metadata = comment.metadata.as_deref()?;
    let value: serde_json::Value = serde_json::from_str(metadata).ok()?;
    value
        .get("filePath")
        .and_then(serde_json::Value::as_str)
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(ToOwned::to_owned)
}

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

    fn review_item(file_path: &str) -> ReviewItemWithComments {
        ReviewItemWithComments {
            item: ReviewItemRecord {
                id: "item-1".to_owned(),
                session_id: None,
                project_id: None,
                file_path: file_path.to_owned(),
                diff_content: String::new(),
                status: "open".to_owned(),
                source: "github".to_owned(),
                source_kind: "pull_request".to_owned(),
                external_review_id: Some("1".to_owned()),
                repo_full_name: Some("owner/repo".to_owned()),
                pr_number: Some(1),
                author: Some("reviewer".to_owned()),
                synced_at: None,
                metadata: None,
                created_at: "2026-06-15 00:00:00".to_owned(),
                reviewed_at: None,
            },
            comments: Vec::new(),
        }
    }

    fn review_comment(content: &str) -> ReviewCommentRecord {
        ReviewCommentRecord {
            id: "comment-1".to_owned(),
            review_item_id: "item-1".to_owned(),
            external_comment_id: Some("c1".to_owned()),
            line_number: None,
            content: content.to_owned(),
            author: Some("reviewer".to_owned()),
            comment_url: Some("https://example.test/review".to_owned()),
            thread_id: None,
            metadata: None,
            created_at: "2026-06-15 00:00:00".to_owned(),
        }
    }

    #[test]
    fn candidate_scope_paths_drop_manifest_when_source_anchor_exists() {
        let item = review_item("package.json");
        let comment = review_comment(
            "Use the base media component in `src/components/developers/Hero.tsx`; \
             package.json changed only because the PR touched dependencies.",
        );

        let paths = candidate_scope_paths(&item, &comment);

        assert_eq!(paths, vec!["src/components/developers/Hero.tsx"]);
    }

    #[test]
    fn candidate_scope_paths_keep_manifest_without_source_anchor() {
        let item = review_item("package.json");
        let comment = review_comment("Keep dependency versions aligned in `package.json`.");

        let paths = candidate_scope_paths(&item, &comment);

        assert_eq!(paths, vec!["package.json"]);
    }

    #[test]
    fn candidate_scope_paths_backfill_item_changed_file_metadata() {
        let mut item = review_item("Release checklist");
        item.item.metadata = Some(
            serde_json::json!({
                "changedFilePaths": [
                    "src/http/request.rs",
                    { "path": "web/components/Button.tsx" },
                    { "newPath": "packages/ui/src/dialog.ts" }
                ]
            })
            .to_string(),
        );
        let comment = review_comment(
            "We should validate the request before decoding because malformed payloads can panic.",
        );

        let paths = candidate_scope_paths(&item, &comment);

        assert_eq!(
            paths,
            vec![
                "src/http/request.rs",
                "web/components/Button.tsx",
                "packages/ui/src/dialog.ts",
            ]
        );
    }

    #[test]
    fn candidate_scope_paths_backfill_item_diff_content_paths() {
        let mut item = review_item("PR summary");
        item.item.diff_content = "\
diff --git a/src/http/request.rs b/src/http/request.rs
index 111..222 100644
--- a/src/http/request.rs
+++ b/src/http/request.rs
diff --git a/web/old.tsx b/web/new.tsx
similarity index 91%
rename from web/old.tsx
rename to web/new.tsx
"
        .to_owned();
        let comment = review_comment(
            "Please keep validation consistent before decoding because malformed payloads can panic.",
        );

        let paths = candidate_scope_paths(&item, &comment);

        assert_eq!(
            paths,
            vec!["src/http/request.rs", "web/new.tsx", "web/old.tsx"]
        );
    }
}