difflore-cli 0.2.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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
//! Distribution and marketplace manifest verification.
//!
//! A guardrail against release drift: checks that the repo's plugin manifests
//! agree with the CLI package version and that the plugin bundle still contains
//! the runtime files the marketplaces expect.

use std::collections::BTreeSet;
use std::fs;
use std::path::{Path, PathBuf};

use serde::Serialize;
use serde_json::Value;

use crate::support::util::exit_code;

const REQUIRED_SKILL_DIRS: &[&str] = &[
    "difflore-onboard",
    "knowledge-agent",
    "memory-candidate-triage",
    "pre-submit-review",
    "remember-rule-guide",
    "rule-diff",
    "rule-gap",
    "rule-journey",
    "rule-search",
    "rule-why-fired",
    "session-recap",
    "smart-explore",
];
const PLUGIN_MCP_WRAPPER: &str = "${PLUGIN_ROOT}/scripts/difflore-mcp.js";
const PLUGIN_HOOK_WRAPPER_COMMAND: &str = "node \"${PLUGIN_ROOT}/scripts/difflore-hook.js\"";
const PLUGIN_HOOK_WRAPPER_COMMAND_JSON: &str =
    "node \\\"${PLUGIN_ROOT}/scripts/difflore-hook.js\\\"";

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum DistSeverity {
    Error,
    Warning,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DistIssue {
    pub severity: DistSeverity,
    pub path: String,
    pub message: String,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DistCheckReport {
    pub repo_root: String,
    pub expected_version: Option<String>,
    pub issues: Vec<DistIssue>,
}

impl DistCheckReport {
    pub(crate) fn ok(&self) -> bool {
        self.issues
            .iter()
            .all(|issue| issue.severity != DistSeverity::Error)
    }

    pub(crate) fn error_count(&self) -> usize {
        self.issues
            .iter()
            .filter(|issue| issue.severity == DistSeverity::Error)
            .count()
    }

    pub(crate) fn warning_count(&self) -> usize {
        self.issues
            .iter()
            .filter(|issue| issue.severity == DistSeverity::Warning)
            .count()
    }
}

pub fn find_repo_root_from(start: &Path) -> Option<PathBuf> {
    let mut cur = start.to_path_buf();
    loop {
        if cur.join("Cargo.toml").exists()
            && cur.join("crates").is_dir()
            && cur.join("plugin").is_dir()
        {
            return Some(cur);
        }
        if !cur.pop() {
            return None;
        }
    }
}

pub fn verify_from_cwd() -> Result<DistCheckReport, String> {
    let cwd = std::env::current_dir().map_err(|e| format!("could not resolve cwd: {e}"))?;
    // `dist verify` only has work inside a difflore source checkout.
    let root = find_repo_root_from(&cwd).ok_or_else(|| {
        format!(
            "`difflore dist verify` is a maintainer command — run it from a checkout \
             of the difflore source tree (the one with `crates/difflore-cli/`). \
             Current directory: {}",
            cwd.display()
        )
    })?;
    Ok(verify_repo(&root))
}

/// Maintainer-only entry point for `difflore dist verify`.
/// Exits non-zero when release-drift errors are found.
pub(crate) fn handle_verify(json: bool) {
    let report = match verify_from_cwd() {
        Ok(report) => report,
        Err(message) => {
            eprintln!("{message}");
            exit_code(2);
        }
    };

    if json {
        match serde_json::to_string_pretty(&report) {
            Ok(rendered) => println!("{rendered}"),
            Err(e) => {
                eprintln!("could not serialize dist report: {e}");
                exit_code(2);
            }
        }
    } else {
        println!("dist verify — repo root: {}", report.repo_root);
        if let Some(version) = &report.expected_version {
            println!("manifest version: {version}");
        }
        for issue in &report.issues {
            println!("  {:?}: {} — {}", issue.severity, issue.path, issue.message);
        }
        println!(
            "{}: {} error(s), {} warning(s)",
            if report.ok() { "ok" } else { "FAILED" },
            report.error_count(),
            report.warning_count(),
        );
    }

    if !report.ok() {
        exit_code(1);
    }
}

pub fn verify_repo(root: &Path) -> DistCheckReport {
    let expected_version = read_crate_version(&root.join("crates/difflore-cli/Cargo.toml"));
    let mut report = DistCheckReport {
        repo_root: root.display().to_string(),
        expected_version,
        issues: Vec::new(),
    };

    check_required_files(root, &mut report);
    check_json_manifest(root, ".claude-plugin/plugin.json", &mut report);
    check_json_manifest(root, ".codex-plugin/plugin.json", &mut report);
    check_marketplace(root, &mut report);
    check_mcp_bundle(root, &mut report);
    check_hook_bundle(root, &mut report);
    check_codex_hook_reachability(root, &mut report);

    report
}

fn check_required_files(root: &Path, report: &mut DistCheckReport) {
    for rel in [
        ".claude-plugin/marketplace.json",
        ".claude-plugin/plugin.json",
        ".codex-plugin/plugin.json",
        "plugin/.mcp.json",
        "plugin/hooks/hooks.json",
        "plugin/scripts/difflore-runtime.js",
        "plugin/scripts/difflore-mcp.js",
        "plugin/scripts/difflore-hook.js",
    ] {
        if !root.join(rel).exists() {
            push(
                report,
                DistSeverity::Error,
                rel,
                "required distribution file is missing",
            );
        }
    }
    check_skill_bundle(root, report);
}

fn check_skill_bundle(root: &Path, report: &mut DistCheckReport) {
    let skills_rel = "plugin/skills";
    let expected: BTreeSet<&str> = REQUIRED_SKILL_DIRS.iter().copied().collect();
    let entries = match fs::read_dir(root.join(skills_rel)) {
        Ok(entries) => entries,
        Err(e) => {
            push(
                report,
                DistSeverity::Error,
                skills_rel,
                &format!("could not read skills directory: {e}"),
            );
            return;
        }
    };
    let mut actual = BTreeSet::new();

    for entry in entries {
        let entry = match entry {
            Ok(entry) => entry,
            Err(e) => {
                push(
                    report,
                    DistSeverity::Error,
                    skills_rel,
                    &format!("could not read skills directory entry: {e}"),
                );
                continue;
            }
        };
        let file_type = match entry.file_type() {
            Ok(file_type) => file_type,
            Err(e) => {
                let path = entry.path().display().to_string();
                push(
                    report,
                    DistSeverity::Error,
                    &path,
                    &format!("could not inspect skills directory entry: {e}"),
                );
                continue;
            }
        };
        if !file_type.is_dir() {
            continue;
        }

        let skill_name = entry.file_name().to_string_lossy().to_string();
        let skill_rel = format!("{skills_rel}/{skill_name}");
        actual.insert(skill_name);
        if !entry.path().join("SKILL.md").exists() {
            push(
                report,
                DistSeverity::Error,
                &skill_rel,
                "skill directory is missing SKILL.md",
            );
        }
    }

    let actual_names: BTreeSet<&str> = actual.iter().map(String::as_str).collect();
    for skill in expected.difference(&actual_names) {
        let rel = format!("{skills_rel}/{skill}/SKILL.md");
        push(
            report,
            DistSeverity::Error,
            &rel,
            "required distribution skill is missing",
        );
    }
    for skill in &actual {
        if !expected.contains(skill.as_str()) {
            let rel = format!("{skills_rel}/{skill}");
            push(
                report,
                DistSeverity::Error,
                &rel,
                "skill directory is not registered in dist verify",
            );
        }
    }
}

fn check_json_manifest(root: &Path, rel: &str, report: &mut DistCheckReport) {
    let Some(value) = read_json(root, rel, report) else {
        return;
    };
    expect_string(&value, "name", "difflore", rel, report);
    expect_string(&value, "license", "Apache-2.0", rel, report);
    if let Some(version) = report.expected_version.clone() {
        expect_string(&value, "version", &version, rel, report);
    }
    let repo = value
        .get("repository")
        .and_then(Value::as_str)
        .unwrap_or("");
    let canonical = difflore_core::cloud::endpoints::GITHUB_REPO;
    if !repo.contains(canonical) {
        push(
            report,
            DistSeverity::Warning,
            rel,
            &format!("repository does not point at {canonical}"),
        );
    }
}

fn check_marketplace(root: &Path, report: &mut DistCheckReport) {
    let rel = ".claude-plugin/marketplace.json";
    let Some(value) = read_json(root, rel, report) else {
        return;
    };
    expect_string(&value, "name", "difflore", rel, report);
    let plugins = value.get("plugins").and_then(Value::as_array);
    let difflore_plugins = plugins.map_or_else(Vec::new, |plugins| {
        plugins
            .iter()
            .filter(|p| p.get("name") == Some(&Value::String("difflore".into())))
            .collect::<Vec<_>>()
    });
    let Some(plugin) = difflore_plugins.first().copied() else {
        push(
            report,
            DistSeverity::Error,
            rel,
            "plugins[] does not contain a difflore entry",
        );
        return;
    };
    if difflore_plugins.len() > 1 {
        push(
            report,
            DistSeverity::Error,
            rel,
            "plugins[] contains duplicate difflore entries",
        );
    }
    if let Some(version) = report.expected_version.clone() {
        expect_string(plugin, "version", &version, rel, report);
    }
    expect_string(plugin, "source", ".", rel, report);
}

fn check_mcp_bundle(root: &Path, report: &mut DistCheckReport) {
    let rel = "plugin/.mcp.json";
    let Some(value) = read_json(root, rel, report) else {
        return;
    };
    let server = value
        .pointer("/mcpServers/difflore")
        .or_else(|| value.pointer("/servers/difflore"));
    let Some(server) = server else {
        push(
            report,
            DistSeverity::Error,
            rel,
            "missing mcpServers.difflore entry",
        );
        return;
    };
    expect_string(server, "command", "node", rel, report);
    let has_mcp_wrapper_arg = server
        .get("args")
        .and_then(Value::as_array)
        .is_some_and(|args| {
            args.iter()
                .any(|arg| arg.as_str() == Some(PLUGIN_MCP_WRAPPER))
        });
    if !has_mcp_wrapper_arg {
        push(
            report,
            DistSeverity::Error,
            rel,
            "difflore MCP entry must invoke the plugin runtime wrapper",
        );
    }
}

fn check_hook_bundle(root: &Path, report: &mut DistCheckReport) {
    let rel = "plugin/hooks/hooks.json";
    let raw = match fs::read_to_string(root.join(rel)) {
        Ok(raw) => raw,
        Err(e) => {
            push(
                report,
                DistSeverity::Error,
                rel,
                &format!("could not read hooks bundle: {e}"),
            );
            return;
        }
    };
    // No PreToolUse: the Read pre-hook was retired to a dispatcher noop and
    // its registration removed (it cost a hook spawn per Read for nothing).
    if !raw_contains_hook_wrapper(&raw) {
        push(
            report,
            DistSeverity::Error,
            rel,
            &format!("hooks bundle missing `{PLUGIN_HOOK_WRAPPER_COMMAND}`"),
        );
    }
    for needle in [
        "PostToolUse",
        "SessionStart",
        "UserPromptSubmit",
        "Stop",
        "SessionEnd",
    ] {
        if !raw.contains(needle) {
            push(
                report,
                DistSeverity::Error,
                rel,
                &format!("hooks bundle missing `{needle}`"),
            );
        }
    }
}

fn check_codex_hook_reachability(root: &Path, report: &mut DistCheckReport) {
    let adapter_rel = "crates/difflore-cli/src/hook/adapters/codex.rs";
    if !root.join(adapter_rel).exists() {
        return;
    }

    let mut codex_hook_route = false;
    for rel in [".codex-plugin/plugin.json", "plugin/hooks/hooks.json"] {
        if fs::read_to_string(root.join(rel)).is_ok_and(|raw| raw_contains_hook_wrapper(&raw)) {
            codex_hook_route = true;
            break;
        }
    }
    if root.join(".codex-plugin/hooks.json").exists()
        || root.join(".codex-plugin/hooks/hooks.json").exists()
    {
        codex_hook_route = true;
    }

    if !codex_hook_route {
        push(
            report,
            DistSeverity::Warning,
            ".codex-plugin/plugin.json",
            "Codex hook adapter exists but no Codex lifecycle hook distribution route was found; Codex installs currently wire MCP only",
        );
    }
}

fn raw_contains_hook_wrapper(raw: &str) -> bool {
    raw.contains(PLUGIN_HOOK_WRAPPER_COMMAND) || raw.contains(PLUGIN_HOOK_WRAPPER_COMMAND_JSON)
}

fn read_json(root: &Path, rel: &str, report: &mut DistCheckReport) -> Option<Value> {
    let path = root.join(rel);
    let raw = match fs::read_to_string(&path) {
        Ok(raw) => raw,
        Err(e) => {
            push(
                report,
                DistSeverity::Error,
                rel,
                &format!("could not read JSON: {e}"),
            );
            return None;
        }
    };
    match serde_json::from_str(&raw) {
        Ok(v) => Some(v),
        Err(e) => {
            push(
                report,
                DistSeverity::Error,
                rel,
                &format!("invalid JSON: {e}"),
            );
            None
        }
    }
}

fn expect_string(
    value: &Value,
    key: &str,
    expected: &str,
    rel: &str,
    report: &mut DistCheckReport,
) {
    match value.get(key).and_then(Value::as_str) {
        Some(actual) if actual == expected => {}
        Some(actual) => push(
            report,
            DistSeverity::Error,
            rel,
            &format!("`{key}` is `{actual}`, expected `{expected}`"),
        ),
        None => push(
            report,
            DistSeverity::Error,
            rel,
            &format!("missing string field `{key}`"),
        ),
    }
}

fn read_crate_version(path: &Path) -> Option<String> {
    let raw = fs::read_to_string(path).ok()?;
    let manifest: toml::Value = toml::from_str(&raw).ok()?;
    manifest
        .get("package")?
        .get("version")?
        .as_str()
        .map(ToOwned::to_owned)
}

fn push(report: &mut DistCheckReport, severity: DistSeverity, path: &str, message: &str) {
    report.issues.push(DistIssue {
        severity,
        path: path.to_owned(),
        message: message.to_owned(),
    });
}

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

    #[test]
    fn crate_version_parser_reads_package_version() {
        let tmp = tempfile::TempDir::new().expect("tempdir");
        let path = tmp.path().join("Cargo.toml");
        fs::write(
            &path,
            "[package]\nname = \"difflore-cli\"\nversion = \"0.1.0\"\n",
        )
        .expect("write");
        assert_eq!(read_crate_version(&path).as_deref(), Some("0.1.0"));
    }

    #[test]
    fn crate_version_parser_ignores_versions_outside_package() {
        let tmp = tempfile::TempDir::new().expect("tempdir");
        let path = tmp.path().join("Cargo.toml");
        fs::write(
            &path,
            "[workspace.dependencies]\nserde = { version = \"9.9.9\" }\n\n[package]\nname = \"difflore-cli\"\nversion = \"0.2.0\"\n\n[package.metadata.release]\nversion = \"1.2.3\"\n",
        )
        .expect("write");
        assert_eq!(read_crate_version(&path).as_deref(), Some("0.2.0"));
    }

    #[test]
    fn skill_bundle_flags_missing_and_unregistered_skill_dirs() {
        let tmp = tempfile::TempDir::new().expect("tempdir");
        let root = tmp.path();
        for skill in REQUIRED_SKILL_DIRS {
            if *skill == "session-recap" {
                continue;
            }
            let dir = root.join("plugin/skills").join(skill);
            fs::create_dir_all(&dir).expect("mkdir");
            fs::write(dir.join("SKILL.md"), "# skill\n").expect("write");
        }
        let extra = root.join("plugin/skills/unlisted-skill");
        fs::create_dir_all(&extra).expect("mkdir");
        fs::write(extra.join("SKILL.md"), "# extra\n").expect("write");

        let mut report = DistCheckReport {
            repo_root: root.display().to_string(),
            expected_version: None,
            issues: Vec::new(),
        };
        check_skill_bundle(root, &mut report);
        assert!(
            report
                .issues
                .iter()
                .any(|issue| issue.path.contains("session-recap")),
            "missing expected skill should be reported: {:?}",
            report.issues
        );
        assert!(
            report
                .issues
                .iter()
                .any(|issue| issue.path.contains("unlisted-skill")),
            "extra skill should be reported: {:?}",
            report.issues
        );
    }

    #[test]
    fn report_ok_requires_no_error_issues() {
        let mut report = DistCheckReport {
            repo_root: ".".into(),
            expected_version: Some("0.1.0".into()),
            issues: Vec::new(),
        };
        push(&mut report, DistSeverity::Warning, "x", "warn");
        assert!(report.ok());
        push(&mut report, DistSeverity::Error, "x", "error");
        assert!(!report.ok());
        assert_eq!(report.error_count(), 1);
        assert_eq!(report.warning_count(), 1);
    }

    #[test]
    fn marketplace_reports_duplicate_difflore_plugin_entries() {
        let tmp = tempfile::TempDir::new().expect("tempdir");
        let root = tmp.path();
        fs::create_dir_all(root.join(".claude-plugin")).expect("mkdir");
        fs::write(
            root.join(".claude-plugin/marketplace.json"),
            r#"{
              "name": "difflore",
              "plugins": [
                {"name": "difflore", "version": "0.1.0", "source": "."},
                {"name": "difflore", "version": "0.0.0", "source": "./stale"}
              ]
            }"#,
        )
        .expect("write");

        let mut report = DistCheckReport {
            repo_root: root.display().to_string(),
            expected_version: Some("0.1.0".to_owned()),
            issues: Vec::new(),
        };
        check_marketplace(root, &mut report);

        assert!(
            report
                .issues
                .iter()
                .any(|issue| issue.message.contains("duplicate difflore")),
            "duplicate marketplace entry should be reported: {:?}",
            report.issues
        );
    }

    #[test]
    fn hook_bundle_requires_stop_and_session_end_events() {
        let tmp = tempfile::TempDir::new().expect("tempdir");
        let root = tmp.path();
        fs::create_dir_all(root.join("plugin/hooks")).expect("mkdir");
        fs::write(
            root.join("plugin/hooks/hooks.json"),
            r#"{
              "hooks": {
                "PostToolUse": [{"hooks": [{"command": "node \"${PLUGIN_ROOT}/scripts/difflore-hook.js\""}]}],
                "SessionStart": [{"hooks": [{"command": "node \"${PLUGIN_ROOT}/scripts/difflore-hook.js\""}]}],
                "UserPromptSubmit": [{"hooks": [{"command": "node \"${PLUGIN_ROOT}/scripts/difflore-hook.js\""}]}]
              }
            }"#,
        )
        .expect("write");

        let mut report = DistCheckReport {
            repo_root: root.display().to_string(),
            expected_version: None,
            issues: Vec::new(),
        };
        check_hook_bundle(root, &mut report);
        assert!(
            report
                .issues
                .iter()
                .any(|issue| issue.message.contains("Stop")),
            "missing Stop should be reported: {:?}",
            report.issues
        );
        assert!(
            report
                .issues
                .iter()
                .any(|issue| issue.message.contains("SessionEnd")),
            "missing SessionEnd should be reported: {:?}",
            report.issues
        );
    }

    #[test]
    fn codex_adapter_without_hook_route_warns_in_dist_verify() {
        let tmp = tempfile::TempDir::new().expect("tempdir");
        let root = tmp.path();
        fs::create_dir_all(root.join("crates/difflore-cli/src/hook/adapters")).expect("mkdir");
        fs::create_dir_all(root.join(".codex-plugin")).expect("mkdir");
        fs::create_dir_all(root.join("plugin/hooks")).expect("mkdir");
        fs::write(
            root.join("crates/difflore-cli/src/hook/adapters/codex.rs"),
            "",
        )
        .expect("write");
        fs::write(root.join(".codex-plugin/plugin.json"), "{}").expect("write");
        fs::write(
            root.join("plugin/hooks/hooks.json"),
            r#"{"hooks":{"Stop":[{"hooks":[{"command":"difflore-hook --client claude-code"}]}]}}"#,
        )
        .expect("write");

        let mut report = DistCheckReport {
            repo_root: root.display().to_string(),
            expected_version: None,
            issues: Vec::new(),
        };
        check_codex_hook_reachability(root, &mut report);
        assert_eq!(report.warning_count(), 1);
        assert!(report.issues[0].message.contains("Codex hook adapter"));

        fs::write(
            root.join(".codex-plugin/plugin.json"),
            r#"{"hooks":[{"command":"node \"${PLUGIN_ROOT}/scripts/difflore-hook.js\""}]}"#,
        )
        .expect("write");
        let mut routed_report = DistCheckReport {
            repo_root: root.display().to_string(),
            expected_version: None,
            issues: Vec::new(),
        };
        check_codex_hook_reachability(root, &mut routed_report);
        assert!(routed_report.issues.is_empty());
    }
}