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>,
#[serde(skip_serializing_if = "Option::is_none")]
pub p2p_profile: Option<P2pProfile>,
pub alternatives: Vec<ScoredWorkflow>,
#[serde(skip_serializing_if = "Option::is_none")]
pub intent: Option<IntentMatch>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub existing_app: bool,
}
pub const ENTRANCE_WORKFLOWS: &[&str] = &["local-handoff", "backend-delivery", "nearby-service"];
const DEFAULT_WORKFLOW: &str = "custom-p2p-app";
#[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,
pub app_kind: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct ScoredWorkflow {
pub workflow: String,
pub score: f32,
}
impl Registry {
pub fn plan(&self, prompt: &str, platform: Option<&str>) -> Result<Plan, RegistryError> {
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();
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() {
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
))
})?,
};
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();
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());
}
}
}
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
}
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(),
}
}
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"),
];
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);
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");
}
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"
),
}
}
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.";
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.";
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.";
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.";
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.";
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.";
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.";
pub const PACKAGE_ONLY_PLATFORMS: &[&str] = &[
"ios-native",
"android-native",
"embedded",
"flutter",
"c",
"ruby",
"csharp",
];
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 {
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\"."
)
}
}
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()),
"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")
{
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
}
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
}
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
}
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
}
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,
}
}