offline-registry 0.4.0

Registry of Offline Protocol packages, skills, workflows, and templates
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
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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
//! # offline-registry
//!
//! The knowledge core of the Offline Protocol CLI and MCP server: package
//! manifests, skill documents, workflow definitions, and starter-template
//! metadata, embedded into the binary and queryable offline.

pub mod example_apps;
pub mod intent;
pub mod llms;
pub mod model;
pub mod plan;
pub mod resolve;
pub mod search;
pub mod search_index;
pub mod store;

pub use example_apps::{is_example_app_template, EXAMPLE_APP_TEMPLATE_IDS};
pub use intent::{classify_entrance, entrance_scores, mentions_existing_app, IntentMatch};
pub use model::{
    Architecture, Capability, CapabilityTerms, Example, PackageManifest, Skill, TemplateMeta,
    TemplateVariable, Workflow,
};
pub use plan::{
    architecture_markdown, classify_p2p, classify_p2p_app_kind, classify_p2p_profile,
    implementation_plan_markdown, normalize_platform, platform_label, restate_platform,
    unsupported_framework, P2pProfile, Plan, BROWSER_NOTE, PACKAGE_ONLY_PLATFORMS,
};
pub use resolve::{Resolution, ResolvedPackage};
pub use search::SearchHit;
pub use store::{Registry, RegistrySource, REGISTRY_DIR_ENV};

/// npm package that ships the `offline` binary and its MCP server.
pub const CLI_NPM_PACKAGE: &str = "@offline-protocol/cli";

/// Version of this build. The npm package is published at the same version.
pub const CLI_VERSION: &str = env!("CARGO_PKG_VERSION");

/// Command and arguments that start this release's stdio MCP server through
/// npx, so generated project configs work without a global `offline` install.
pub fn mcp_serve_command() -> (&'static str, Vec<String>) {
    (
        "npx",
        vec![
            "-y".to_string(),
            format!("{CLI_NPM_PACKAGE}@{CLI_VERSION}"),
            "mcp".to_string(),
            "serve".to_string(),
        ],
    )
}

/// [`mcp_serve_command`] as one shell line, for docs and agent guidance.
pub fn mcp_serve_command_line() -> String {
    let (cmd, args) = mcp_serve_command();
    format!("{cmd} {}", args.join(" "))
}

#[derive(Debug, thiserror::Error)]
pub enum RegistryError {
    #[error("registry source not found: {0}")]
    SourceNotFound(String),
    #[error("failed to read {0}: {1}")]
    Io(String, #[source] std::io::Error),
    #[error("failed to parse {0}: {1}")]
    Parse(String, String),
    #[error("registry validation failed: {0}")]
    Validation(String),
    #[error("not found: {0}")]
    NotFound(String),
    #[error("incompatible: {0}")]
    Incompatible(String),
}

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

    fn reg() -> Registry {
        Registry::load_embedded().expect("embedded registry loads")
    }

    #[test]
    fn plan_offline_id_mesh_chat_selects_workflow() {
        let r = reg();
        let plan = r
            .plan("Create a React Native mesh chat app using Offline ID", None)
            .expect("plan succeeds");
        assert_eq!(plan.workflow, "offline-id-mesh-chat");
        assert_eq!(plan.platform, "react-native");
    }

    #[test]
    fn resolve_offline_id_mesh_chat_includes_both_sdks() {
        let r = reg();
        let res = r
            .resolve_workflow("offline-id-mesh-chat", "react-native")
            .expect("offline-id-mesh-chat resolves on react-native");
        let names: Vec<&str> = res.packages.iter().map(|p| p.name.as_str()).collect();
        assert!(names.contains(&"@offline-protocol/id-react-native"));
        assert!(names.contains(&"@offline-protocol/mesh-sdk"));
    }

    #[test]
    fn plan_offline_id_mesh_group_chat_selects_workflow() {
        let r = reg();
        let plan = r
            .plan("Build a BLE group chat app with Offline ID and mesh", None)
            .expect("plan succeeds");
        assert_eq!(plan.workflow, "offline-id-mesh-chat");
        assert!(plan.capabilities.contains(&"group-messaging".to_string()));
    }

    #[test]
    fn plan_nearby_group_chat_selects_nearby_or_group_workflow() {
        let r = reg();
        let plan = r
            .plan("Nearby BLE group chat without accounts", None)
            .expect("plan succeeds");
        assert!(
            plan.workflow == "nearby-chat" || plan.workflow == "group-messaging",
            "expected nearby-chat or group-messaging, got {}",
            plan.workflow
        );
        assert!(plan.capabilities.contains(&"group-messaging".to_string()));
    }

    #[test]
    fn embedded_registry_loads_and_validates() {
        let r = reg();
        assert!(r.packages().count() >= 6, "expected at least 6 packages");
        assert!(r.workflows().count() >= 6, "expected at least 6 workflows");
        assert!(r.skills().count() >= 13, "expected at least 13 skills");
        assert!(r.templates().count() >= 6, "expected at least 6 templates");
    }

    #[test]
    fn search_finds_mesh_sdk_for_peer_discovery() {
        let r = reg();
        let hits = r.search_packages("peer discovery offline chat");
        assert!(!hits.is_empty());
        assert_eq!(hits[0].name, "@offline-protocol/mesh-sdk");
    }

    fn top_capabilities(r: &Registry, query: &str, n: usize) -> Vec<String> {
        r.search_capabilities(query)
            .into_iter()
            .take(n)
            .map(|h| h.name)
            .collect()
    }

    #[test]
    fn capability_search_matches_the_words_developers_type() {
        let r = reg();
        let cases: &[(&str, &[&str])] = &[
            ("bluetooth", &["mesh-networking", "peer-discovery"]),
            ("ble", &["mesh-networking", "peer-discovery"]),
            ("nearby", &["peer-discovery", "service-discovery"]),
            ("offline messaging", &["offline-messaging"]),
            ("sign in", &["identity"]),
            ("login", &["identity"]),
            ("wifi", &["mesh-networking", "transport-fallback"]),
            ("internet", &["mesh-networking", "transport-fallback"]),
            ("p2p", &["mesh-networking"]),
            ("avatar", &["identicons"]),
            ("who is here", &["peer-discovery", "presence"]),
            // SDK 0.28.0 platforms and features.
            ("python", &["server-runtime"]),
            ("swift", &["native-mobile"]),
            ("kotlin", &["native-mobile"]),
            ("android native", &["native-mobile"]),
            ("esp32", &["embedded-leaf"]),
            ("local api", &["local-api"]),
            ("custody", &["custody"]),
            ("wi-fi direct", &["mesh-networking"]),
            // SDK 0.29.0: the HTTP front and the verifier.
            ("http", &["http-front"]),
            ("curl", &["http-front"]),
            ("docker", &["http-front"]),
            ("offline-protocol-verify", &["local-api"]),
            // SDK 0.30.0: the Flutter plugin, Java and the C API.
            ("flutter", &["native-mobile"]),
            ("dart", &["native-mobile"]),
            ("java", &["server-runtime"]),
            ("jvm", &["server-runtime"]),
            ("cgo", &["server-runtime"]),
            // SDK 0.31.0: the Ruby binding and the browser engine.
            ("ruby", &["server-runtime"]),
            ("rubygems", &["server-runtime"]),
            ("webrtc", &["browser-node"]),
            ("web worker", &["browser-node"]),
            ("opfs", &["browser-node"]),
            ("rssi", &["peer-discovery"]),
            // SDK 0.32.0: service subscriptions and the C# binding.
            ("subscribe to a service", &["service-subscriptions"]),
            ("pubsub", &["service-subscriptions"]),
            ("csharp", &["server-runtime"]),
            ("dotnet", &["server-runtime"]),
        ];
        for (query, expected) in cases {
            let top = top_capabilities(&r, query, 3);
            for name in *expected {
                assert!(top.iter().any(|t| t == name), "{query}: {top:?}");
            }
        }
        assert_eq!(
            top_capabilities(&r, "offline messaging", 1),
            ["offline-messaging"]
        );
    }

    #[test]
    fn capability_search_ranks_mesh_first_for_a_plain_sentence() {
        let r = reg();
        let hits = r.search_capabilities(
            "phones near each other share data over Bluetooth without wifi or server",
        );
        let first = &hits.first().expect("capability hits").name;
        assert!(
            ["mesh-networking", "peer-discovery"].contains(&first.as_str()),
            "{hits:?}"
        );
        let mesh = r.package("@offline-protocol/mesh-sdk").unwrap();
        for hit in hits.iter().take(3) {
            assert!(mesh.capabilities.contains(&hit.name), "{hits:?}");
        }
    }

    #[test]
    fn search_ignores_stopwords() {
        let r = reg();
        // "of" and "in" used to prefix-match "offline" and "invocation".
        let location = top_capabilities(&r, "proof of location", 10);
        assert_eq!(location, ["proof-of-location", "location-proofs"]);
        assert!(!top_capabilities(&r, "sign in", 10).contains(&"service-invocation".to_string()));
        assert!(r.search_capabilities("the of in on or").is_empty());
        assert!(r.search_packages("each other without the").is_empty());
    }

    #[test]
    fn every_capability_has_curated_search_keywords() {
        let r = reg();
        for cap in r.capabilities() {
            let terms = r.capability_terms.get(&cap.name);
            assert!(
                terms.is_some_and(|t| !t.keywords.is_empty()),
                "add `{}` to registry/capabilities.json",
                cap.name
            );
        }
    }

    #[test]
    fn capability_keywords_for_unknown_capabilities_are_rejected() {
        let dir =
            std::env::temp_dir().join(format!("offline-registry-capterms-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("packages")).unwrap();
        std::fs::write(
            dir.join("packages/demo.json"),
            r#"{"name":"demo","version":"1.0.0","description":"d","platforms":["web"],"license":"MIT","capabilities":["demo-cap"]}"#,
        )
        .unwrap();
        std::fs::write(
            dir.join("capabilities.json"),
            r#"{"demo-cap":{"keywords":["demo"]}}"#,
        )
        .unwrap();
        let ok = Registry::load_from_dir(&dir).expect("known capability loads");
        assert_eq!(top_capabilities(&ok, "demo", 1), ["demo-cap"]);
        std::fs::write(
            dir.join("capabilities.json"),
            r#"{"missing-cap":{"keywords":["demo"]}}"#,
        )
        .unwrap();
        let err = Registry::load_from_dir(&dir)
            .err()
            .expect("unknown capability fails");
        let _ = std::fs::remove_dir_all(&dir);
        assert!(matches!(err, RegistryError::Validation(_)), "{err}");
    }

    #[test]
    fn sdk_packages_share_the_release_pin() {
        let r = reg();
        let pin = &r.package("@offline-protocol/mesh-sdk").unwrap().version;
        assert_eq!(pin, "0.34.0");
        // offline-protocol-swift is tagged by the Swift repository's own
        // scheduled publish, after the SDK release; it stays on the newest tag
        // that exists until that run, then rejoins the shared pin.
        assert_eq!(
            r.package("offline-protocol-swift").unwrap().version,
            "0.33.0"
        );
        for name in [
            "offline-protocol-sdk",
            "offline-protocol-android",
            "offline-protocol",
            "offline-protocol-leaf",
            "offline-protocol-java",
            "offline-protocol-c",
            "offline-protocol-flutter",
            "offline-protocol-ruby",
            "offline-protocol-web",
            "offline-protocol-csharp",
        ] {
            let p = r.package(name).unwrap_or_else(|| panic!("{name} missing"));
            assert_eq!(&p.version, pin, "{name}");
        }
        // The previews say so wherever they are resolved.
        for name in [
            "offline-protocol-swift",
            "offline-protocol-android",
            "offline-protocol-leaf",
            "offline-protocol-flutter",
            "offline-protocol-csharp",
        ] {
            assert_eq!(r.package(name).unwrap().status, "preview", "{name}");
        }
        assert_eq!(
            r.package("offline-protocol-web").unwrap().status,
            "experimental"
        );
    }

    #[test]
    fn package_only_platforms_install_from_their_own_channels() {
        let r = reg();
        let cmds = |name: &str, platform: &str| {
            r.resolve_packages(&[name.to_string()], platform)
                .unwrap()
                .install_commands
                .join("\n")
        };
        assert_eq!(
            cmds("offline-protocol-sdk", "python"),
            "pip install offline-protocol-sdk==0.34.0"
        );
        assert_eq!(
            cmds("offline-protocol", "rust"),
            "cargo add offline-protocol@0.34.0"
        );
        assert!(cmds("offline-protocol-swift", "ios-native").contains(
            "https://github.com/Offline-Protocol/offline-protocol-swift.git\", from: \"0.33.0\""
        ));
        assert_eq!(
            cmds("offline-protocol-android", "android-native"),
            "implementation(\"com.offlineprotocol:offline-protocol-sdk:0.34.0\")"
        );
        assert!(cmds("offline-protocol-leaf", "embedded")
            .starts_with("cargo add offline-protocol-leaf@0.34.0 --no-default-features"));
        // SDK 0.30.0: Java on Maven Central, the C API from the release
        // archives, and the Flutter plugin from a checkout.
        assert_eq!(
            cmds("offline-protocol-java", "java"),
            "implementation(\"com.offlineprotocol:offline-protocol-java:0.34.0\")"
        );
        let c = cmds("offline-protocol-c", "c");
        assert!(
            c.contains("releases/tag/v0.34.0") && c.contains("-loffline_protocol_uniffi"),
            "{c}"
        );
        let flutter = cmds("offline-protocol-flutter", "flutter");
        assert!(
            flutter.contains("v0.34.0") && flutter.contains("bindings/flutter/offline_protocol"),
            "{flutter}"
        );
        assert!(!flutter.contains("flutter pub add"), "{flutter}");
        // SDK 0.31.0: the Ruby gem on RubyGems, and the browser engine (the
        // crate on crates.io, the JavaScript client from a checkout).
        let ruby = cmds("offline-protocol-ruby", "ruby");
        assert!(
            ruby.starts_with("gem \"offline_protocol\", \"~> 0.34.0\"")
                && ruby.contains("releases/tag/v0.34.0"),
            "{ruby}"
        );
        let web = cmds("offline-protocol-web", "nextjs");
        assert!(
            web.contains("v0.34.0")
                && web.contains("bindings/web/scripts/build.sh")
                && web.contains("cargo add offline-protocol-web@0.34.0"),
            "{web}"
        );
        assert!(!web.contains("npm install"), "{web}");
        // SDK 0.32.0: the C# binding, a project reference from a checkout.
        let csharp = cmds("offline-protocol-csharp", "csharp");
        assert!(
            csharp.contains("v0.34.0")
                && csharp
                    .contains("bindings/csharp/src/OfflineProtocol.Sdk/OfflineProtocol.Sdk.csproj")
                && csharp.contains("offline-protocol-0.34.0-<platform>"),
            "{csharp}"
        );
        assert!(!csharp.contains("dotnet add package"), "{csharp}");
        let err = r
            .resolve_packages(&["offline-protocol-sdk".to_string()], "react-native")
            .unwrap_err();
        assert!(err.to_string().contains("[python]"), "{err}");
    }

    #[test]
    fn plans_name_the_packages_of_a_platform_without_workflows() {
        let r = reg();
        // Python plans nearby chat now (template python-mesh-chat).
        let python = r.plan("nearby chat", Some("python")).unwrap();
        assert_eq!(python.workflow, "nearby-chat");
        assert_eq!(python.template.as_deref(), Some("python-mesh-chat"));
        // So does Java (template kotlin-mesh-chat).
        let java = r.plan("nearby chat", Some("jvm")).unwrap();
        assert_eq!(java.workflow, "nearby-chat");
        assert_eq!(java.template.as_deref(), Some("kotlin-mesh-chat"));
        for (platform, package) in [
            ("swift", "offline-protocol-swift 0.33.0 (preview)"),
            ("kotlin", "offline-protocol-android 0.34.0 (preview)"),
            ("esp32", "offline-protocol-leaf 0.34.0 (preview)"),
            ("rust", "offline-protocol 0.34.0 (stable)"),
            ("flutter", "offline-protocol-flutter 0.34.0 (preview)"),
            ("c", "offline-protocol-c 0.34.0 (stable)"),
            ("ruby", "offline-protocol-ruby 0.34.0 (stable)"),
            ("csharp", "offline-protocol-csharp 0.34.0 (preview)"),
        ] {
            let err = r
                .plan("nearby chat", Some(platform))
                .unwrap_err()
                .to_string();
            assert!(err.contains("no plan generated"), "{err}");
            assert!(err.contains(package), "{platform}: {err}");
        }
        for (prompt, needle) in [
            (
                "native iOS app for nearby chat",
                "offline-protocol-swift 0.33.0",
            ),
            ("A SwiftUI app with offline messaging", "early preview"),
            (
                "Native Android Kotlin app that sends files over Wi-Fi Direct",
                "com.offlineprotocol:offline-protocol-sdk",
            ),
        ] {
            let err = r.plan(prompt, None).unwrap_err().to_string();
            assert!(err.contains(needle), "{prompt}: {err}");
        }
        // SDK 0.30.0: a Flutter or Java prompt names its package, still
        // without a plan.
        for (prompt, needle) in [
            (
                "A Flutter app for nearby chat",
                "offline-protocol-flutter 0.34.0",
            ),
            ("A Flutter app for nearby chat", "not on pub.dev"),
            (
                "A Java desktop app for nearby chat",
                "com.offlineprotocol:offline-protocol-java",
            ),
            // SDK 0.31.0.
            (
                "A Ruby service that relays messages",
                "offline_protocol gem",
            ),
            ("A Flutter app for nearby chat", "MeshSdk"),
            // SDK 0.32.0.
            (
                "A C# desktop app for nearby chat",
                "offline-protocol-csharp",
            ),
            ("A .NET service that relays messages", "not on NuGet"),
        ] {
            let err = r.plan(prompt, None).unwrap_err().to_string();
            assert!(err.contains("no plan generated"), "{prompt}: {err}");
            assert!(err.contains(needle), "{prompt}: {err}");
        }
        // Frameworks with no package at all keep the plain answer.
        let err = r
            .plan("A Xamarin app for nearby chat", None)
            .unwrap_err()
            .to_string();
        assert!(err.contains("There is no Xamarin package"), "{err}");
    }

    #[test]
    fn package_registry_and_install_are_validated() {
        let dir =
            std::env::temp_dir().join(format!("offline-registry-install-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("packages")).unwrap();
        let write = |body: &str| std::fs::write(dir.join("packages/demo.json"), body).unwrap();
        let load = || Registry::load_from_dir(&dir);

        write(
            r#"{"name":"demo","version":"1.0.0","description":"d","platforms":["python"],"registry":"pypi","license":"MIT"}"#,
        );
        assert!(load().is_ok());
        write(
            r#"{"name":"demo","version":"1.0.0","description":"d","platforms":["ios-native"],"registry":"swiftpm","license":"MIT"}"#,
        );
        assert!(load()
            .err()
            .unwrap()
            .to_string()
            .contains("needs an `install`"));
        write(
            r#"{"name":"demo","version":"1.0.0","description":"d","platforms":["ios-native"],"registry":"swiftpm","install":"from: 0.9.0","license":"MIT"}"#,
        );
        assert!(load()
            .err()
            .unwrap()
            .to_string()
            .contains("does not name version 1.0.0"));
        write(
            r#"{"name":"demo","version":"1.0.0","description":"d","platforms":["android-native"],"registry":"maven","license":"MIT"}"#,
        );
        assert!(load()
            .err()
            .unwrap()
            .to_string()
            .contains("needs an `install`"));
        write(
            r#"{"name":"demo","version":"1.0.0","description":"d","platforms":["python"],"registry":"conda","license":"MIT"}"#,
        );
        assert!(load()
            .err()
            .unwrap()
            .to_string()
            .contains("unknown registry"));
        write(
            r#"{"name":"demo","version":"1.0.0","description":"d","platforms":["flutter"],"registry":"source","license":"MIT"}"#,
        );
        assert!(load()
            .err()
            .unwrap()
            .to_string()
            .contains("needs an `install`"));
        write(
            r#"{"name":"demo","version":"1.0.0","description":"d","platforms":["xamarin"],"license":"MIT"}"#,
        );
        assert!(load()
            .err()
            .unwrap()
            .to_string()
            .contains("unknown platform"));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn resolve_workflow_includes_transitive_requirements() {
        let r = reg();
        let res = r
            .resolve_workflow("offline-social-network", "react-native")
            .expect("offline-social-network resolves on react-native");
        let names: Vec<&str> = res.packages.iter().map(|p| p.name.as_str()).collect();
        assert!(names.contains(&"@offline-protocol/id-react-native"));
        // id-react-native requires core
        assert!(names.contains(&"@offline-protocol/core"));
        assert!(!res.install_commands.is_empty());
    }

    #[test]
    fn resolve_rejects_wrong_platform() {
        let r = reg();
        let err = r
            .resolve_packages(&["@offline-protocol/id-react".to_string()], "react-native")
            .unwrap_err();
        assert!(matches!(err, RegistryError::Incompatible(_)));
    }

    #[test]
    fn plan_local_social_app_selects_offline_social_network() {
        let r = reg();
        let plan = r
            .plan("Build an offline social network with feed", None)
            .expect("plan succeeds");
        assert_eq!(plan.workflow, "offline-social-network");
        assert!(!plan.resolution.packages.is_empty());
        let md = architecture_markdown(&plan);
        assert!(md.contains("offline-social-network"));
        let ip = implementation_plan_markdown(&plan);
        assert!(ip.contains("offline doctor"));
    }

    #[test]
    fn plan_custom_p2p_game_selects_custom_workflow() {
        let r = reg();
        let plan = r
            .plan(
                "Build a tic tac toe game two phones can play over BLE",
                None,
            )
            .expect("plan succeeds");
        assert_eq!(plan.workflow, "custom-p2p-app");
        assert_eq!(plan.platform, "react-native");
        assert_eq!(
            plan.template.as_deref(),
            Some("react-native-mesh-custom-app")
        );
        let p2p = plan.p2p_profile.as_ref().expect("p2p profile present");
        assert_eq!(p2p.sync_model, "host-authority");
        assert_eq!(p2p.discovery, "mesh-services");
        assert_eq!(p2p.app_kind, "tic-tac-toe");
        assert!(plan.skills.contains(&"p2p-app-architecture".to_string()));
        let md = architecture_markdown(&plan);
        assert!(md.contains("## P2P profile"));
        assert!(md.contains("host-authority"));
    }

    #[test]
    fn plan_custom_p2p_file_share_classifies_request_response() {
        let r = reg();
        let plan = r
            .plan("Nearby file transfer app to share photos offline", None)
            .expect("plan succeeds");
        assert_eq!(plan.workflow, "custom-p2p-app");
        let p2p = plan.p2p_profile.as_ref().expect("p2p profile present");
        assert_eq!(p2p.sync_model, "request-response");
        assert_eq!(p2p.app_kind, "generic");
    }

    /// The founder-review prompts and paraphrases, with the entrance each must select.
    const ENTRANCE_PROMPTS: &[(&str, &str)] = &[
        ("local-handoff", "Durable equipment handoff between field engineers, with persistence and backend reconciliation"),
        ("local-handoff", "Hand over a work order from one technician's phone to another without signal and sync it to our backend later"),
        ("local-handoff", "Shift change app: the outgoing crew passes custody of tools to the incoming crew, offline"),
        ("local-handoff", "Chain of custody for evidence bags between officers, acknowledged on both devices"),
        ("local-handoff", "Inspection results handed off between site operators with durable storage and later reconciliation"),
        ("local-handoff", "Transfer responsibility for a pump from one field engineer's tablet to another with an acknowledgement"),
        ("backend-delivery", "Retain sensor telemetry during outages and deliver it to a backend with explicit acceptance"),
        ("backend-delivery", "Buffer IoT readings on the phone when the network drops and upload them to our API with idempotent retries"),
        ("backend-delivery", "Store-and-forward pipeline for field inspection results into Kafka"),
        ("backend-delivery", "Queue measurements offline and ingest them into our system of record once connectivity returns"),
        ("backend-delivery", "Collect readings from nearby devices through a gateway phone and deliver them to the cloud"),
        ("backend-delivery", "Keep device events during outages and push them to the server exactly once"),
        ("nearby-service", "Discover and invoke an authorised nearby service from an existing application"),
        ("nearby-service", "Let our existing app call a nearby printer's print capability over Bluetooth"),
        ("nearby-service", "Query equipment diagnostics from a nearby device via RPC with authorization"),
        ("nearby-service", "Expose a status service on one phone and let approved phones discover and call it"),
        ("nearby-service", "Find a nearby provider and send it a request, then correlate the response"),
        ("nearby-service", "Advertise a capability from a kiosk and invoke it from staff devices"),
    ];

    #[test]
    fn plan_routes_entrance_prompts_to_their_workflows() {
        let r = reg();
        for (workflow, prompt) in ENTRANCE_PROMPTS {
            let plan = r.plan(prompt, None).expect("plan succeeds");
            assert_eq!(plan.workflow, *workflow, "{prompt}");
            assert_eq!(plan.platform, "react-native", "{prompt}");
            assert!(plan.p2p_profile.is_none(), "{prompt}");
            assert_eq!(
                plan.intent.as_ref().map(|i| i.workflow.as_str()),
                Some(*workflow)
            );
            assert_eq!(
                plan.skills,
                r.workflow(workflow).unwrap().skills,
                "{prompt}"
            );
            // Workflow search agrees with the planner.
            assert_eq!(r.search_workflows(prompt)[0].name, *workflow, "{prompt}");
        }
    }

    #[test]
    fn entrance_plans_carry_their_template_and_guidance_not_games_or_chat() {
        let r = reg();
        let cases = [
            ("Durable equipment handoff between field engineers, with persistence and backend reconciliation", "react-native-mesh-handoff", "local-handoff"),
            ("Retain sensor telemetry during outages and deliver it to a backend with explicit acceptance", "react-native-mesh-event-delivery", "backend-delivery"),
            ("Discover and invoke an authorised nearby service from an existing application", "react-native-mesh-service", "nearby-service"),
        ];
        for (prompt, template, skill) in cases {
            let plan = r.plan(prompt, None).unwrap();
            assert_eq!(plan.template.as_deref(), Some(template));
            assert_eq!(plan.skills[0], skill);
            let md = architecture_markdown(&plan);
            let ip = implementation_plan_markdown(&plan);
            assert!(md.contains("**Why this workflow:**"), "{md}");
            for text in [&md, &ip] {
                let lower = text.to_lowercase();
                for banned in [
                    "game",
                    "tic-tac-toe",
                    "chat thread",
                    "groups list",
                    "host/join",
                    "create or join a session",
                ] {
                    assert!(!lower.contains(banned), "{template}: `{banned}` in\n{text}");
                }
            }
            assert!(
                ip.contains("Force quit") || ip.contains("outcome unknown"),
                "{ip}"
            );
        }
        let service = r.plan(cases[2].0, None).unwrap();
        assert!(service.existing_app);
        let md = architecture_markdown(&service);
        assert!(md.contains("## Existing application"));
        assert!(md.contains("attachServices"));
        assert!(!r.plan(cases[0].0, None).unwrap().existing_app);
    }

    #[test]
    fn explicit_game_chat_and_social_prompts_keep_their_workflows() {
        let r = reg();
        for (prompt, workflow) in [
            (
                "Build a tic tac toe game two phones can play over BLE",
                "custom-p2p-app",
            ),
            ("offline Ludo for two phones", "custom-p2p-app"),
            ("Nearby BLE group chat without accounts", "nearby-chat"),
            (
                "Build an offline social network with feed",
                "offline-social-network",
            ),
            (
                "Create a React Native mesh chat app using Offline ID",
                "offline-id-mesh-chat",
            ),
            (
                "Nearby file transfer app to share photos offline",
                "custom-p2p-app",
            ),
            ("live poll at an event over BLE", "custom-p2p-app"),
        ] {
            let plan = r.plan(prompt, None).expect("plan succeeds");
            assert_eq!(plan.workflow, workflow, "{prompt}");
            assert!(plan.intent.is_none(), "{prompt}");
        }
    }

    #[test]
    fn unmatched_prompts_get_a_generic_shell_with_the_entrances_as_alternatives() {
        let r = reg();
        let plan = r.plan("qwerty zxcv", None).expect("plan succeeds");
        assert_eq!(plan.workflow, "custom-p2p-app");
        assert_eq!(plan.p2p_profile.as_ref().unwrap().app_kind, "generic");
        let alternatives: Vec<&str> = plan
            .alternatives
            .iter()
            .map(|a| a.workflow.as_str())
            .collect();
        assert_eq!(
            alternatives,
            ["local-handoff", "backend-delivery", "nearby-service"]
        );
        let md = architecture_markdown(&plan).to_lowercase();
        assert!(!md.contains("game"), "{md}");
    }

    #[test]
    fn workflow_skills_must_exist() {
        let r = reg();
        for wf in r.workflows() {
            for skill in &wf.skills {
                assert!(
                    r.skill(skill).is_some(),
                    "{} lists unknown skill {skill}",
                    wf.name
                );
            }
        }
    }

    #[test]
    fn classify_p2p_app_kind_prefers_named_games() {
        assert_eq!(classify_p2p_app_kind("offline Ludo for two phones"), "ludo");
        assert_eq!(
            classify_p2p_app_kind("Build a tic tac toe game over BLE"),
            "tic-tac-toe"
        );
        assert_eq!(
            classify_p2p_app_kind("two player board game nearby"),
            "tic-tac-toe"
        );
        assert_eq!(
            classify_p2p_app_kind("nearby file transfer for photos"),
            "generic"
        );
        assert_eq!(classify_p2p_app_kind("custom P2P voting app"), "generic");
    }

    #[test]
    fn classify_p2p_is_deterministic() {
        let a = classify_p2p("live poll at an event over BLE");
        let b = classify_p2p("live poll at an event over BLE");
        assert_eq!(a.sync_model, "broadcast");
        assert_eq!(a, b);
    }

    #[test]
    fn plan_refuses_unsupported_frameworks_without_explicit_platform() {
        let r = reg();
        for prompt in [
            "Build a Flutter app for kitchen order handoff over Bluetooth",
            "Native Android Kotlin app that sends files over Wi-Fi Direct",
            "native iOS app for nearby chat",
            "Objective-C app with offline messaging",
        ] {
            let err = r.plan(prompt, None).unwrap_err();
            assert!(matches!(err, RegistryError::Incompatible(_)), "{prompt}");
            assert!(err.to_string().contains("no plan generated"), "{prompt}");
        }
        assert_eq!(
            unsupported_framework("A community unity event app"),
            Some("Unity")
        );
        assert_eq!(
            unsupported_framework("React Native chat with a Swift native module"),
            None
        );
        let plan = r
            .plan("Flutter-style nearby chat", Some("react-native"))
            .expect("explicit platform plans");
        assert!(plan.resolution.warnings[0].contains("Flutter"));
    }

    #[test]
    fn plan_restates_web_platform_in_errors() {
        let r = reg();
        let err = r
            .plan("nearby BLE chat without accounts", Some("web"))
            .unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("not `web` (resolved as `nextjs`)"), "{msg}");
    }

    #[test]
    fn plan_infers_web_platform() {
        let r = reg();
        let plan = r
            .plan("community platform for the web with profiles", None)
            .expect("plan succeeds");
        assert_eq!(plan.platform, "nextjs");
    }

    #[test]
    fn template_files_load_for_all_templates() {
        let r = reg();
        for t in r.templates() {
            let files = r.template_files(&t.name).expect("template files load");
            assert!(!files.is_empty(), "template `{}` has no files", t.name);
        }
    }

    #[test]
    fn example_app_templates_embed_shared_packages() {
        let r = reg();
        for id in EXAMPLE_APP_TEMPLATE_IDS {
            let t = r.template(id).expect(id);
            assert!(t.example_app);
            assert!(t.requires_mesh);
            let files = r.template_files(id).expect("files");
            assert!(
                files
                    .iter()
                    .any(|(p, _)| p.to_string_lossy().contains("packages/mesh/src")),
                "{id}: mesh sources"
            );
        }
    }

    #[test]
    fn llms_txt_mentions_every_skill() {
        let r = reg();
        let txt = llms::llms_txt(&r);
        for s in r.skills() {
            assert!(txt.contains(&s.name), "llms.txt missing skill {}", s.name);
        }
    }

    #[test]
    fn capabilities_aggregate_packages_and_workflows() {
        let r = reg();
        let caps = r.capabilities();
        let mesh = caps
            .iter()
            .find(|c| c.name == "mesh-networking")
            .expect("mesh-networking capability exists");
        assert!(mesh
            .packages
            .contains(&"@offline-protocol/mesh-sdk".to_string()));
        assert!(!mesh.workflows.is_empty());
    }
}