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
//! Plan a workflow, platform, and package set from a natural-language prompt.
//!
//! Matching is deterministic from registry keyword metadata.

use serde::Serialize;

use crate::intent::{classify_entrance, mentions_existing_app, IntentMatch};
use crate::model::Architecture;
use crate::resolve::Resolution;
use crate::search::tokenize;
use crate::store::Registry;
use crate::RegistryError;

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Plan {
    pub prompt: String,
    pub workflow: String,
    pub workflow_title: String,
    pub platform: String,
    pub template: Option<String>,
    pub capabilities: Vec<String>,
    pub resolution: Resolution,
    pub architecture: Architecture,
    pub skills: Vec<String>,
    /// Classified P2P dimensions when workflow is `custom-p2p-app`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub p2p_profile: Option<P2pProfile>,
    /// Other workflows that also scored, with their scores, so callers can
    /// present alternatives.
    pub alternatives: Vec<ScoredWorkflow>,
    /// Set when the prompt described one of the workflow entrances (handoff,
    /// retained event delivery, nearby service): the matched terms.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub intent: Option<IntentMatch>,
    /// The prompt is about adding to an application that already exists.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub existing_app: bool,
}

/// Workflows for the three outcome-based entrances.
pub const ENTRANCE_WORKFLOWS: &[&str] = &["local-handoff", "backend-delivery", "nearby-service"];

/// Used when a prompt matches nothing: the generic custom P2P shell, with the
/// entrances offered as alternatives.
const DEFAULT_WORKFLOW: &str = "custom-p2p-app";

/// Discovery, topology, sync, and transport choices for custom P2P apps.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct P2pProfile {
    pub discovery: String,
    pub topology: String,
    pub sync_model: String,
    pub transport_profile: String,
    /// What the scaffold should emphasize in domain/UI (`generic`, `tic-tac-toe`, `ludo`, …).
    pub app_kind: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct ScoredWorkflow {
    pub workflow: String,
    pub score: f32,
}

impl Registry {
    /// Build a project plan from a freeform prompt.
    ///
    /// `platform` may be `None`, in which case it is inferred from the prompt
    /// (mentions of "react native"/"mobile"/"ios"/"android" vs "web"/"next"),
    /// falling back to the first platform the chosen workflow supports.
    pub fn plan(&self, prompt: &str, platform: Option<&str>) -> Result<Plan, RegistryError> {
        // A prompt that names a framework the registry has no packages for must
        // not silently turn into a React Native or web plan. An explicit
        // `platform` is the caller's decision, so it proceeds with a notice.
        let unsupported = unsupported_framework(prompt);
        if let (Some(framework), None) = (unsupported, platform) {
            return Err(RegistryError::Incompatible(unsupported_framework_message(
                framework,
            )));
        }

        let mut scored: Vec<ScoredWorkflow> = self
            .search_workflows(prompt)
            .into_iter()
            .map(|h| ScoredWorkflow {
                workflow: h.name,
                score: h.score,
            })
            .collect();
        // Outcome routing first: a handoff, retained events for a backend or
        // a nearby service call selects its entrance even when chat or custom
        // P2P share more vocabulary with the prompt.
        let intent = classify_entrance(prompt).filter(|m| self.workflow(&m.workflow).is_some());
        if let Some(m) = &intent {
            scored.retain(|s| s.workflow != m.workflow);
            scored.insert(
                0,
                ScoredWorkflow {
                    workflow: m.workflow.clone(),
                    score: m.score,
                },
            );
        } else if scored.is_empty() {
            // No keyword hits: the generic shell, with the entrances as
            // alternatives rather than whatever sorts first.
            scored = std::iter::once(DEFAULT_WORKFLOW)
                .chain(ENTRANCE_WORKFLOWS.iter().copied())
                .chain(self.workflows().map(|w| w.name.as_str()))
                .filter(|name| self.workflow(name).is_some())
                .fold(Vec::<ScoredWorkflow>::new(), |mut acc, name| {
                    if !acc.iter().any(|s| s.workflow == name) {
                        acc.push(ScoredWorkflow {
                            workflow: name.to_string(),
                            score: 0.0,
                        });
                    }
                    acc
                });
        }
        let best = scored.first().expect("registry has workflows").clone();
        let wf = self
            .workflow(&best.workflow)
            .expect("scored workflows exist")
            .clone();

        let platform_input = platform.unwrap_or_default();
        let platform = match platform {
            Some(p) => normalize_platform(p)
                .ok_or_else(|| RegistryError::Incompatible(format!("unknown platform `{p}`")))?,
            None => infer_platform(prompt)
                .filter(|p| wf.packages.contains_key(p))
                .or_else(|| wf.packages.keys().next().cloned())
                .ok_or_else(|| {
                    RegistryError::Validation(format!(
                        "workflow `{}` has no platform package sets",
                        wf.name
                    ))
                })?,
        };

        // Platforms with packages but no workflow plans (Python, Rust, the
        // native previews, firmware): say what to install instead of
        // reporting that one workflow is missing the platform.
        if !self.workflows().any(|w| w.packages.contains_key(&platform)) {
            return Err(RegistryError::Incompatible(
                self.package_platform_message(&platform),
            ));
        }

        let mut resolution = self
            .resolve_workflow(&wf.name, &platform)
            .map_err(|e| restate_platform(e, platform_input, &platform))?;
        if let Some(framework) = unsupported {
            resolution.warnings.insert(
                0,
                format!(
                    "The prompt names {framework}, which the planner has no workflow plan or \
starter template for. This plan targets `{platform}` because that platform was passed \
explicitly; it is not a {framework} integration."
                ),
            );
        }
        let template = wf.templates.get(&platform).cloned();

        let mut skills: Vec<String> = wf.skills.clone();
        let mut seen: std::collections::HashSet<String> = skills.iter().cloned().collect();
        // Workflows that declare their skills get exactly those; the others
        // list their packages' skills.
        for rp in resolution.packages.iter().filter(|_| wf.skills.is_empty()) {
            if let Some(pkg) = self.package(&rp.name) {
                for s in &pkg.skills {
                    if seen.insert(s.clone()) {
                        skills.push(s.clone());
                    }
                }
            }
        }

        let p2p_profile = if wf.name == "custom-p2p-app" {
            prepend_custom_p2p_skills(&mut skills, &mut seen);
            Some(classify_p2p_profile(prompt))
        } else {
            None
        };

        Ok(Plan {
            prompt: prompt.to_string(),
            workflow: wf.name.clone(),
            workflow_title: wf.title.clone(),
            platform,
            template,
            capabilities: wf.capabilities.clone(),
            resolution,
            architecture: wf.architecture.clone(),
            skills,
            p2p_profile,
            alternatives: scored.into_iter().skip(1).take(3).collect(),
            intent,
            existing_app: mentions_existing_app(prompt),
        })
    }
}

const CUSTOM_P2P_SKILLS: &[&str] = &[
    "p2p-app-architecture",
    "p2p-discovery-patterns",
    "p2p-sync-patterns",
];

fn prepend_custom_p2p_skills(
    skills: &mut Vec<String>,
    seen: &mut std::collections::HashSet<String>,
) {
    for skill in CUSTOM_P2P_SKILLS.iter().rev() {
        if seen.insert((*skill).to_string()) {
            skills.insert(0, (*skill).to_string());
        }
    }
}

/// Which game or app shape the scaffold should target (domain/UI), not mesh `appId`.
pub fn classify_p2p_app_kind(prompt: &str) -> String {
    let lower = prompt.to_lowercase();
    let tokens = tokenize(prompt);
    let has = |t: &str| tokens.iter().any(|x| x == t);
    let has_any = |ts: &[&str]| ts.iter().any(|t| has(t));

    if has_any(&[
        "file",
        "transfer",
        "photo",
        "photos",
        "share",
        "upload",
        "download",
        "chunk",
        "poll",
        "vote",
        "survey",
        "tally",
        "counter",
        "broadcast",
        "chat",
        "messaging",
        "message",
        "document",
        "collaborate",
        "tool",
        "rpc",
    ]) && !has_any(&["game", "board", "ludo", "chess", "tic", "tac"])
    {
        return "generic".to_string();
    }

    if has("ludo") || lower.contains("snakes and ladders") {
        return "ludo".to_string();
    }
    if has_any(&["chess", "checkers", "draughts"]) {
        return "chess".to_string();
    }
    if has("battleship") {
        return "battleship".to_string();
    }
    if lower.contains("connect four") || lower.contains("connect 4") {
        return "connect-four".to_string();
    }
    if lower.contains("tic tac") || lower.contains("tictac") || (has("tic") && has("tac")) {
        return "tic-tac-toe".to_string();
    }

    if has_any(&[
        "game",
        "board",
        "turn",
        "multiplayer",
        "1v1",
        "versus",
        "vs",
        "play",
        "player",
    ]) {
        return "tic-tac-toe".to_string();
    }

    "generic".to_string()
}

pub fn classify_p2p_profile(prompt: &str) -> P2pProfile {
    let mut profile = classify_p2p(prompt);
    profile.app_kind = classify_p2p_app_kind(prompt);
    profile
}

/// Classify a prompt into P2P discovery, topology, sync, and transport dimensions.
pub fn classify_p2p(prompt: &str) -> P2pProfile {
    let tokens = tokenize(prompt);
    let has = |t: &str| tokens.iter().any(|x| x == t);
    let has_any = |ts: &[&str]| ts.iter().any(|t| has(t));

    let discovery = if has_any(&["group", "room", "groups", "team"])
        && !has_any(&["game", "host", "join", "lobby"])
    {
        "mls-group"
    } else if has_any(&[
        "host", "join", "lobby", "browse", "nearby", "discover", "service", "game",
    ]) {
        "mesh-services"
    } else if has_any(&["direct", "pair", "friend", "connect"]) {
        "direct-link"
    } else {
        "mesh-services"
    };

    let topology = if has_any(&["group", "room", "several", "many", "multi"])
        && !has_any(&["two", "pair", "1v1", "versus", "vs"])
    {
        "host-and-clients"
    } else {
        "one-to-one"
    };

    let sync_model = if has_any(&[
        "turn",
        "game",
        "board",
        "move",
        "tic",
        "tac",
        "chess",
        "ludo",
        "dice",
        "authority",
    ]) {
        "host-authority"
    } else if has_any(&[
        "file", "transfer", "send", "upload", "download", "chunk", "share",
    ]) {
        "request-response"
    } else if has_any(&["vote", "poll", "live", "counter", "broadcast", "tally"]) {
        "broadcast"
    } else if has_any(&["sync", "log", "history", "collaborate", "document", "state"]) {
        "event-log"
    } else {
        "host-authority"
    };

    let transport_profile = if has_any(&["internet", "relay", "remote", "dors"])
        && !has_any(&["ble", "bluetooth", "nearby", "local", "airplane"])
    {
        "full-dors"
    } else {
        "nearby-only"
    };

    P2pProfile {
        discovery: discovery.to_string(),
        topology: topology.to_string(),
        sync_model: sync_model.to_string(),
        transport_profile: transport_profile.to_string(),
        app_kind: String::new(),
    }
}

/// Frameworks and languages the planner has no workflow plans or starter
/// templates for, as `(prompt token, display name)`. Some have packages (the
/// native Swift and Kotlin previews, the Flutter plugin, the Java, Ruby and
/// C# bindings), which the limitation names. Matching is on whole tokens.
const UNSUPPORTED_FRAMEWORKS: &[(&str, &str)] = &[
    ("flutter", "Flutter"),
    ("dart", "Dart"),
    ("kotlin", "Kotlin"),
    ("swift", "Swift"),
    ("swiftui", "SwiftUI"),
    ("objc", "Objective-C"),
    ("jetpack", "Jetpack Compose"),
    ("java", "Java"),
    ("ruby", "Ruby"),
    ("csharp", "C#"),
    ("dotnet", ".NET"),
    ("xamarin", "Xamarin"),
    ("maui", ".NET MAUI"),
    ("unity", "Unity"),
];

/// Returns the display name of an unsupported framework the prompt asks for,
/// unless the prompt also names a platform the registry covers (for example
/// a React Native app with a Kotlin native module).
pub fn unsupported_framework(prompt: &str) -> Option<&'static str> {
    let lower = prompt.to_lowercase();
    let tokens = tokenize(prompt);
    let has = |t: &str| tokens.iter().any(|x| x == t);
    // Only React-family names count: "Flutter web" is still Flutter, and
    // "next" is too common a word to mean Next.js.
    let names_supported = has("react")
        || has("rn")
        || has("expo")
        || has("nextjs")
        || lower.contains("next.js")
        || has("vite");
    if names_supported {
        return None;
    }
    if let Some((_, name)) = UNSUPPORTED_FRAMEWORKS.iter().find(|(t, _)| has(t)) {
        return Some(name);
    }
    if lower.contains("objective-c") {
        return Some("Objective-C");
    }
    // "C#" and ".NET" tokenize to nothing useful ("c" is dropped, ".net"
    // becomes "net"), so match them on the text.
    if lower.contains("c#") || lower.contains(".net ") || lower.ends_with(".net") {
        return Some("C#");
    }
    if has("native") && (has("android") || has("ios")) {
        return Some(if has("android") {
            "native Android"
        } else {
            "native iOS"
        });
    }
    None
}

fn unsupported_framework_message(framework: &str) -> String {
    let native = match framework {
        "Swift" | "SwiftUI" | "native iOS" => Some(NATIVE_SWIFT_NOTE),
        "Kotlin" | "Jetpack Compose" | "native Android" => Some(NATIVE_ANDROID_NOTE),
        "Flutter" | "Dart" => Some(FLUTTER_NOTE),
        "Java" => Some(JAVA_NOTE),
        "Ruby" => Some(RUBY_NOTE),
        "C#" | ".NET" => Some(CSHARP_NOTE),
        _ => None,
    };
    match native {
        Some(note) => format!(
            "no plan generated: the prompt asks for {framework}, and the planner's workflow plans \
and starter templates target React Native and React web apps only, so a React Native plan would \
not be a {framework} integration. {note} Tell the user about this gap. If they choose React \
Native instead, call again with platform \"react-native\". Platform and transport support: \
https://www.offlineprotocol.com/docs/getting-started/platforms"
        ),
        None => format!(
            "no plan generated: the prompt asks for {framework}, and the Offline Protocol packages in \
this registry target React Native (@offline-protocol/mesh-sdk, id-react-native, pol), React web \
apps (@offline-protocol/id-react, pol), Python, Rust, Java, Ruby, C, the browser (experimental) and, \
as previews, native Swift, Kotlin, Flutter and C#. There is no {framework} package, and a React Native plan would not be a {framework} \
integration. Tell the user about this gap. If they choose React Native instead, call again with \
platform \"react-native\". Platform and transport support: \
https://www.offlineprotocol.com/docs/getting-started/platforms"
        ),
    }
}

/// What exists for a native Swift app (SDK 0.28.0).
const NATIVE_SWIFT_NOTE: &str = "A native Swift package exists as an early preview: \
offline-protocol-swift 0.33.0 (Swift Package Manager, product OfflineProtocolSDK, iOS 13 or later). \
Its storage providers are not public yet, wiring transports to the engine is the app's job, and its \
API names may change. Read package offline-protocol-swift and skill native-platforms before \
recommending it.";

/// What exists for a native Kotlin app (SDK 0.28.0).
const NATIVE_ANDROID_NOTE: &str = "A native Android build exists as an early preview: \
offline-protocol-android 0.34.0 on Maven Central (com.offlineprotocol:offline-protocol-sdk, minSdk 24): \
the generated Kotlin bindings, the native libraries and the Android transport and storage classes. \
The app wires the transports to the engine itself, OfflineProtocolReferenceStorage opens the SDK's own storage, and the API may change. Read package offline-protocol-android and skill native-platforms before \
recommending it.";

/// What exists for a Flutter app (SDK 0.30.0, React Native parity in 0.31.0).
const FLUTTER_NOTE: &str = "A Flutter plugin exists as a preview: offline-protocol-flutter 0.34.0, \
the Dart package offline_protocol in the offline-protocol-sdk repository (Flutter 3.10 or later, iOS 13, \
Android API 24). It compiles the React Native module's shared native bridge, so it has the same \
transports, and MeshSdk gives Dart the React Native module's native surface. It is not on pub.dev: \
the app depends on its path in a checkout of the SDK at v0.34.0 after building the native libraries. \
Read package offline-protocol-flutter and skill native-platforms before recommending it.";

/// What exists for a Java app (SDK 0.30.0).
const JAVA_NOTE: &str = "A Java binding exists for the JVM on desktops and servers: \
offline-protocol-java 0.34.0 on Maven Central (com.offlineprotocol:offline-protocol-java, JDK 22 or later), \
with the native library from the GitHub release's desktop archives. The app owns the transports and \
storage. On Android, use offline-protocol-android instead. Read package offline-protocol-java and skill \
native-platforms before recommending it.";

/// What exists for a Ruby program (SDK 0.31.0).
const RUBY_NOTE: &str = "A Ruby binding exists for scripts, tooling and servers: \
offline-protocol-ruby 0.34.0, the offline_protocol gem on RubyGems (Ruby 3.3 or later, over the ffi gem), \
with the native library from the GitHub release's desktop archives. The app owns the transports and \
storage. Read package offline-protocol-ruby and skill native-platforms before recommending it.";

/// What exists for a C# program (SDK 0.32.0).
const CSHARP_NOTE: &str = "A C# binding exists as a preview for .NET 8 programs on desktops and servers \
(Windows first, also Linux and macOS): offline-protocol-csharp 0.34.0, the OfflineProtocol.Sdk project \
in the SDK repository at v0.34.0, over the C API with the native library from the GitHub release's \
desktop archives. It is not on NuGet: reference the project from a checkout. The app owns the \
transports and storage. Read package offline-protocol-csharp and skill native-platforms before \
recommending it.";

/// What exists for an app that runs in a browser (SDK 0.31.0).
pub const BROWSER_NOTE: &str = "The engine also runs in a browser, experimental: \
offline-protocol-web 0.34.0, a full node in a Web Worker with durable storage (OPFS), WebRTC between \
devices, a nearby room for browsers on one network, the Nostr transport over the application's relays \
and, in Chromium, Web Bluetooth to a phone or a board. The crate is on crates.io and the JavaScript \
client is built from the SDK repository at v0.34.0. Read package offline-protocol-web and skill \
native-platforms before recommending it.";

/// Platforms that have packages but no workflow plans or starter templates.
/// Python and Java left this list when the `python-mesh-chat` and
/// `kotlin-mesh-chat` starters arrived.
pub const PACKAGE_ONLY_PLATFORMS: &[&str] = &[
    "ios-native",
    "android-native",
    "embedded",
    "flutter",
    "c",
    "ruby",
    "csharp",
];

/// A platform value as people say it.
pub fn platform_label(platform: &str) -> &str {
    match platform {
        "react-native" => "React Native",
        "nextjs" => "Next.js",
        "react-vite" => "React with Vite",
        "rust" => "Rust",
        "python" => "Python",
        "ios-native" => "native iOS (Swift)",
        "android-native" => "native Android (Kotlin)",
        "embedded" => "embedded firmware",
        "flutter" => "Flutter",
        "java" => "Java (JVM)",
        "c" => "C",
        "ruby" => "Ruby",
        "csharp" => "C# (.NET)",
        other => other,
    }
}

impl Registry {
    /// Why there is no plan for a platform whose packages have no workflow
    /// plans or starter templates, and what to install instead.
    pub fn package_platform_message(&self, platform: &str) -> String {
        let label = platform_label(platform);
        let packages: Vec<String> = self
            .packages()
            .filter(|p| p.platforms.iter().any(|x| x == platform))
            .map(|p| format!("{} {} ({})", p.name, p.version, p.status))
            .collect();
        let offer = if packages.is_empty() {
            format!("There is no {label} package.")
        } else {
            format!(
                "{label} packages: {}. Read each package's entry and its guide for the install \
line, requirements and maturity.",
                packages.join(", ")
            )
        };
        format!(
            "no plan generated: the planner's workflow plans and starter templates target React \
Native and React web apps, and there is none for {label}. {offer} If the user wants a React \
Native app instead, call again with platform \"react-native\"."
        )
    }
}

/// Restate a platform error in the caller's words: `web` is resolved as
/// `nextjs`, and an error naming `nextjs` confuses a caller who passed `web`.
pub fn restate_platform(err: RegistryError, requested: &str, resolved: &str) -> RegistryError {
    if requested.is_empty() || requested == resolved {
        return err;
    }
    let restate = |msg: String| {
        msg.replace(
            &format!("not `{resolved}`"),
            &format!("not `{requested}` (resolved as `{resolved}`)"),
        )
    };
    match err {
        RegistryError::Incompatible(msg) => RegistryError::Incompatible(restate(msg)),
        other => other,
    }
}

pub fn normalize_platform(input: &str) -> Option<String> {
    match input.to_lowercase().as_str() {
        "react-native" | "reactnative" | "rn" | "mobile" | "ios" | "android" => {
            Some("react-native".to_string())
        }
        "react-vite" | "vite" | "react/vite" => Some("react-vite".to_string()),
        "nextjs" | "next" | "next.js" | "web" => Some("nextjs".to_string()),
        "react" => Some("react-vite".to_string()),
        "rust" => Some("rust".to_string()),
        // Package-only platforms (packages, no workflow plans or templates).
        "python" | "py" | "python3" | "pypi" => Some("python".to_string()),
        "ios-native" | "native-ios" | "swift" | "swiftui" | "swiftpm" => {
            Some("ios-native".to_string())
        }
        "android-native" | "native-android" | "kotlin" => Some("android-native".to_string()),
        "embedded" | "esp32" | "firmware" | "microcontroller" | "mcu" => {
            Some("embedded".to_string())
        }
        "flutter" | "dart" => Some("flutter".to_string()),
        "java" | "jvm" | "jdk" => Some("java".to_string()),
        "c" | "c-api" | "capi" | "c-binding" => Some("c".to_string()),
        "ruby" | "rb" | "rubygems" => Some("ruby".to_string()),
        "csharp" | "c#" | "c-sharp" | "dotnet" | ".net" | "net" | "cs" => {
            Some("csharp".to_string())
        }
        _ => None,
    }
}

fn infer_platform(prompt: &str) -> Option<String> {
    let tokens = tokenize(prompt);
    let has = |t: &str| tokens.iter().any(|x| x == t);
    if has("react") && has("native") || has("mobile") || has("ios") || has("android") || has("app")
    {
        // "app" alone is ambiguous; only treat it as mobile when web terms are absent.
        if !(has("web") || has("next") || has("nextjs") || has("browser") || has("site")) {
            return Some("react-native".to_string());
        }
    }
    if has("web")
        || has("next")
        || has("nextjs")
        || has("browser")
        || has("site")
        || has("dashboard")
    {
        return Some("nextjs".to_string());
    }
    None
}

/// Render `architecture.md` for a plan.
pub fn architecture_markdown(plan: &Plan) -> String {
    let mut md = String::new();
    md.push_str(&format!("# Architecture — {}\n\n", plan.workflow_title));
    md.push_str(&format!(
        "> Generated by `offline` for prompt: _{}_\n\n",
        plan.prompt
    ));
    md.push_str(&format!(
        "- **Workflow:** `{}`\n- **Platform:** `{}`\n",
        plan.workflow, plan.platform
    ));
    if let Some(t) = &plan.template {
        md.push_str(&format!("- **Starter template:** `{t}`\n"));
    }
    md.push_str(&format!(
        "- **Capabilities:** {}\n",
        plan.capabilities.join(", ")
    ));
    if let Some(intent) = &plan.intent {
        md.push_str(&format!(
            "- **Why this workflow:** the prompt describes {}\n",
            intent.signals.join(", ")
        ));
    }
    md.push('\n');

    md.push_str("## Packages\n\n| Package | Version | Why |\n|---|---|---|\n");
    for p in &plan.resolution.packages {
        md.push_str(&format!(
            "| `{}` | {} | {} |\n",
            p.name, p.version, p.reason
        ));
    }
    if !plan.resolution.warnings.is_empty() {
        md.push_str("\n### Notices\n\n");
        for w in &plan.resolution.warnings {
            md.push_str(&format!("- {w}\n"));
        }
    }

    if let Some(p2p) = &plan.p2p_profile {
        md.push_str("\n## P2P profile\n\n");
        md.push_str(&format!(
            "- **Discovery:** `{}` — see skill `p2p-discovery-patterns`\n",
            p2p.discovery
        ));
        md.push_str(&format!("- **Topology:** `{}`\n", p2p.topology));
        md.push_str(&format!(
            "- **Sync model:** `{}` — implement `session.ts` using this archetype in skill `p2p-sync-patterns`\n",
            p2p.sync_model
        ));
        md.push_str(&format!("- **Transport:** `{}`\n", p2p.transport_profile));
        md.push_str(&format!("- **App scaffold focus:** `{}`\n", p2p.app_kind));
        match p2p.app_kind.as_str() {
            "tic-tac-toe" => {
                md.push_str(
                    "\nThe starter includes a **playable tic-tac-toe** sample (domain, session, UI). \
Replace it when you asked for a different game in a follow-up prompt.\n",
                );
            }
            "generic" => {
                md.push_str(
                    "\nThe starter is a **generic P2P session shell**: implement your app in \
`src/domain/`, `src/wire.ts`, and `App.tsx`. The mesh layer does not depend on your app logic.\n",
                );
            }
            other => {
                md.push_str(&format!(
                    "\nYou asked for **`{other}`**. The mesh layer is ready; implement `{other}` rules in \
`src/domain/` and build UI in `App.tsx` (see `GAME-SCAFFOLD.md`).\n",
                ));
            }
        }
        md.push_str(
            "\nKeep `@offline-protocol/mesh-sdk` imports only in `src/mesh.ts`. Run `npm test` before editing mesh.\n",
        );
    }

    if plan.existing_app {
        md.push_str(&existing_app_markdown(plan));
    }

    let a = &plan.architecture;
    if !a.screens.is_empty() {
        md.push_str("\n## Screens\n\n");
        for s in &a.screens {
            md.push_str(&format!("- {s}\n"));
        }
    }
    if !a.services.is_empty() {
        md.push_str("\n## Services / providers\n\n");
        for s in &a.services {
            md.push_str(&format!("- {s}\n"));
        }
    }
    if !a.data_models.is_empty() {
        md.push_str("\n## Data models\n\n");
        for s in &a.data_models {
            md.push_str(&format!("- {s}\n"));
        }
    }
    if !a.events.is_empty() {
        md.push_str("\n## Protocol events to handle\n\n");
        for s in &a.events {
            md.push_str(&format!("- `{s}`\n"));
        }
    }
    if !a.notes.is_empty() {
        md.push_str("\n## Notes\n\n");
        for s in &a.notes {
            md.push_str(&format!("- {s}\n"));
        }
    }
    if !plan.skills.is_empty() {
        md.push_str("\n## Relevant skills\n\nRead these with `offline skills show <name>` (or the MCP `get_skill` tool):\n\n");
        for s in &plan.skills {
            md.push_str(&format!("- `{s}`\n"));
        }
    }
    md
}

/// Render `implementation-plan.md` for a plan.
pub fn implementation_plan_markdown(plan: &Plan) -> String {
    let mut md = String::new();
    md.push_str(&format!(
        "# Implementation Plan — {}\n\n",
        plan.workflow_title
    ));
    md.push_str("## 1. Setup\n\n");
    for cmd in &plan.resolution.install_commands {
        md.push_str(&format!("```bash\n{cmd}\n```\n\n"));
    }
    if !plan.resolution.peer_dependencies.is_empty() {
        md.push_str("Peer dependencies your app must provide:\n\n");
        for (name, range) in &plan.resolution.peer_dependencies {
            md.push_str(&format!("- `{name}` {range}\n"));
        }
        md.push('\n');
    }
    md.push_str("## 2. Wire the SDKs\n\n");
    md.push_str("Follow the skill documents for each integration step:\n\n");
    for s in &plan.skills {
        md.push_str(&format!("- `offline skills show {s}`\n"));
    }
    md.push_str("\n## 3. Build screens\n\n");
    for s in &plan.architecture.screens {
        md.push_str(&format!("- [ ] {s}\n"));
    }
    md.push_str("\n## 4. Handle protocol events\n\n");
    for e in &plan.architecture.events {
        md.push_str(&format!("- [ ] `{e}`\n"));
    }
    md.push_str("\n## 5. Verify\n\n");
    md.push_str("- [ ] `offline doctor` passes\n");
    if let Some(checks) = entrance_checks(&plan.workflow) {
        for check in checks {
            md.push_str(&format!("- [ ] {check}\n"));
        }
    } else if plan.workflow == "custom-p2p-app" {
        md.push_str("- [ ] Two physical devices with Bluetooth enabled\n");
        md.push_str("- [ ] Host/Join session flow completes over BLE (guest joins only via `service_discovered` list)\n");
        md.push_str("- [ ] Host taps Accept after guest requests join\n");
        md.push_str("- [ ] App wire messages round-trip (`message_received` → session)\n");
        if let Some(p2p) = &plan.p2p_profile {
            md.push_str(&format!(
                "- [ ] Session sync follows **`{}`** archetype (skill `p2p-sync-patterns`)\n",
                p2p.sync_model
            ));
        }
    } else {
        md.push_str("- [ ] Two-device messaging smoke test (BLE and internet transports)\n");
        md.push_str("- [ ] Encryption sessions establish (`secure_session_established` events)\n");
    }
    md
}

/// How to take an entrance into an application that already exists.
fn existing_app_markdown(plan: &Plan) -> String {
    let mut md = String::from("\n## Existing application\n\n");
    md.push_str(
        "Add the packages to the app you have instead of starting over: MCP \
`integrate_packages` then `init_project` (or `offline add <package>` and `offline init`). \
Keep one `OfflineProtocol` instance per app and install your handlers before `start()`.\n",
    );
    if let Some(template) = &plan.template {
        let modules = match plan.workflow.as_str() {
            "local-handoff" => Some("`src/core/`, `src/handoff/` and `src/backend/client.ts`"),
            "backend-delivery" => Some("`src/core/`, `src/delivery/` and `src/backend/client.ts`"),
            "nearby-service" => Some(
                "`src/core/`, `src/service/` and `src/platform/existingApp.ts` \
(`attachServices(protocol, handlers)` connects them to your existing instance)",
            ),
            _ => None,
        };
        if let Some(modules) = modules {
            md.push_str(&format!(
                "\nThe `{template}` starter is the reference: generate it next to your app (`preview_scaffold` \
or `offline create {template}`) and copy {modules}. They depend only on small ports, not on the \
starter's screens.\n"
            ));
        }
    }
    md
}

/// Verification steps for the entrance workflows.
fn entrance_checks(workflow: &str) -> Option<&'static [&'static str]> {
    match workflow {
        "local-handoff" => Some(&[
            "`npm test`, `npm run typecheck` and `npm run backend:test` pass",
            "Two physical devices with Bluetooth on, same `APP_ID`, enrolled with each other",
            "A handoff shows Delivered before the receiver decides, and Accepted only after the receiver accepts",
            "Force quit both apps mid-handoff and reopen: the same operation ID is applied once, with the same decision",
            "With the backend back, both devices reconcile and the backend holds one record with sender and receiver reports",
        ]),
        "backend-delivery" => Some(&[
            "`npm test`, `npm run typecheck` and `npm run backend:test` pass",
            "Backend stopped or airplane mode on: events stay pending and the oldest pending age grows",
            "Force quit and reopen: the same event IDs are still pending",
            "Backend restored: every event is accepted once (compare with `GET /v1/events?source=<address>`)",
            "Optional collector: a nearby enrolled device takes custody, delivers, and relays the backend receipts",
        ]),
        "nearby-service" => Some(&[
            "`npm test` and `npm run typecheck` pass",
            "Two physical devices with Bluetooth on, same `APP_ID`; provider allows the requester and requester approves the provider",
            "`status` returns a response correlated to its request ID and provider",
            "An unapproved requester gets no response and shows a timeout",
            "A `reserve` whose response is lost times out as outcome unknown; retrying returns the stored result without reserving twice",
        ]),
        _ => None,
    }
}