mobiler 0.63.0

Build mobile apps in Rust — one core, native UI on Android, iOS, and the web (CLI)
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
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
//! `mobiler plugin add <source>` — install a plugin into a scaffolded app by copying its
//! native handler files and patching the per-shell registration points. A plugin is a
//! self-describing package directory (`mobiler-plugin.toml` + native sources) — either a local
//! path or one of the FREE samples bundled in the CLI. Paid plugins ship as local licensed
//! packages, never bundled here. Android + iOS only; web degrades gracefully on its own.

use crate::templating::{Subs, substitute};
use anyhow::{Context, Result, bail};
use include_dir::{Dir, include_dir};
use serde::Deserialize;
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};

/// FREE first-party sample plugins, embedded like the project templates.
static BUNDLED: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/plugins");

#[derive(clap::Subcommand)]
pub enum PluginCmd {
    /// Install a plugin (SOURCE = a package directory or a bundled sample name).
    Add { source: String },
    /// List the bundled sample plugins.
    List,
}

pub fn run(cmd: PluginCmd) -> Result<()> {
    match cmd {
        PluginCmd::Add { source } => add(&source),
        PluginCmd::List => list(),
    }
}

// ---------------- manifest ----------------

#[derive(Deserialize)]
struct Manifest {
    name: String,
    #[serde(default)]
    summary: String,
    /// Free-form post-install notes printed after a successful add — for the one or two steps a
    /// plugin can't automate (e.g. push: drop `google-services.json` into `Android/app/`).
    #[serde(default)]
    notes: Vec<String>,
    #[serde(default)]
    android: Option<PlatformSpec>,
    #[serde(default)]
    ios: Option<IosSpec>,
}

#[derive(Deserialize)]
struct PlatformSpec {
    #[serde(default)]
    sources: Vec<String>,
    register: String,
    #[serde(default)]
    permissions: Vec<String>,
    /// Gradle dependency coordinates (e.g. "com.google.android.gms:play-services-code-scanner:16.1.0").
    /// Each becomes an `implementation("…")` line in the app's build.gradle.kts.
    #[serde(default)]
    gradle_deps: Vec<String>,
    /// Gradle plugin coordinates "plugin.id:version" (e.g. "com.google.gms.google-services:4.4.2").
    /// Each adds `id("plugin.id") version "version" apply false` to the **project** build.gradle.kts
    /// (`// mobiler:gradle-plugins-classpath`) and `id("plugin.id")` to the **app** build.gradle.kts
    /// (`// mobiler:gradle-plugins`) — for plugins that must be APPLIED (e.g. google-services), which a
    /// plain `gradle_deps` `implementation(…)` line can't express.
    #[serde(default)]
    gradle_plugins: Vec<String>,
    /// XML snippets inserted inside `<application>` in AndroidManifest.xml — e.g. a
    /// `<receiver android:name=".NotificationReceiver" android:exported="false"/>` a plugin needs
    /// to fire while the app is closed. Each should carry a unique `android:name` (used for the
    /// idempotency check).
    #[serde(default)]
    manifest_application: Vec<String>,
}

#[derive(Deserialize)]
struct IosSpec {
    #[serde(default)]
    sources: Vec<String>,
    register: String,
    /// Optional streaming-dispatch registration (a `Plugins.subscribe` case), inserted at the
    /// `// mobiler:plugins-stream` marker. Set by streaming-capable plugins (e.g. websocket) in
    /// addition to `register` (their request/response case).
    #[serde(default)]
    register_stream: Option<String>,
    /// Lines inserted at the `// mobiler:app-launch` anchor in App.swift's
    /// `didFinishLaunchingWithOptions` — for plugins that MUST run code at app launch (e.g.
    /// `BGTaskScheduler.register(...)`, CLLocationManager region-monitor re-instantiation), which a
    /// lazy request/response plugin can't do. The iOS twin of Android's statically-declared manifest
    /// receiver/worker (which already run at launch with no hook).
    #[serde(default)]
    app_launch: Vec<String>,
    /// Info.plist keys → values. Values are TOML scalars OR arrays, rendered as inline YAML via
    /// `yaml_scalar` — so a plugin can set array keys (`UIBackgroundModes = ["location"]`,
    /// `BGTaskSchedulerPermittedIdentifiers = [...]`), not just strings.
    #[serde(default)]
    info_plist: BTreeMap<String, toml::Value>,
    #[serde(default)]
    entitlements: BTreeMap<String, toml::Value>,
    /// Remote SwiftPM packages, each "name|url|version|product" (pipe-delimited — URLs contain `:`/`/`).
    /// Adds a remote package entry to the iOS project.yml `packages:` block (`# mobiler:spm-packages`)
    /// AND a target `- package: <name> / product: <product>` dependency (`# mobiler:spm-dependencies`)
    /// — the iOS twin of `android.gradle_plugins`, for plugins that pull an SPM dependency (e.g. Firebase).
    #[serde(default)]
    spm_packages: Vec<String>,
}

// ---------------- source resolution ----------------

enum Source {
    Local(PathBuf),
    Bundled(&'static Dir<'static>),
}

impl Source {
    fn read_text(&self, rel: &str) -> Result<String> {
        match self {
            Source::Local(dir) => fs::read_to_string(dir.join(rel))
                .with_context(|| format!("reading {}", dir.join(rel).display())),
            Source::Bundled(d) => {
                // `Dir::get_file` resolves relative to the embed ROOT, so a file inside a
                // sub-dir needs its full path (e.g. `battery/mobiler-plugin.toml`).
                let full = d.path().join(rel);
                d.get_file(&full)
                    .and_then(|f| f.contents_utf8())
                    .map(str::to_string)
                    .ok_or_else(|| anyhow::anyhow!("bundled plugin file `{rel}` missing or not UTF-8"))
            }
        }
    }
}

fn resolve_source(source: &str) -> Result<Source> {
    let p = Path::new(source);
    if p.is_dir() {
        return Ok(Source::Local(p.to_path_buf()));
    }
    if let Some(dir) = BUNDLED.get_dir(source) {
        return Ok(Source::Bundled(dir));
    }
    bail!(
        "`{source}` is neither a plugin directory nor a bundled sample. Bundled: {}",
        bundled_names().join(", ")
    )
}

fn bundled_names() -> Vec<String> {
    BUNDLED
        .dirs()
        .filter_map(|d| d.path().file_name().map(|n| n.to_string_lossy().to_string()))
        .collect()
}

// ---------------- list ----------------

fn list() -> Result<()> {
    let names = bundled_names();
    if names.is_empty() {
        println!("No bundled sample plugins.");
    } else {
        println!("Bundled sample plugins (free):");
        for name in names {
            let summary = resolve_source(&name)
                .and_then(|s| s.read_text("mobiler-plugin.toml"))
                .ok()
                .and_then(|t| toml::from_str::<Manifest>(&t).ok())
                .map(|m| m.summary)
                .unwrap_or_default();
            println!("  {name:<12} {summary}");
        }
    }
    println!("\nInstall:  mobiler plugin add <name>   |   mobiler plugin add ./path/to/package");
    Ok(())
}

// ---------------- add ----------------

fn add(source: &str) -> Result<()> {
    let root = std::env::current_dir().context("reading current directory")?;
    add_at(&root, source)
}

fn add_at(root: &Path, source: &str) -> Result<()> {
    if !root.join("Android").is_dir() || !root.join("iOS").is_dir() {
        bail!("run `mobiler plugin add` from a Mobiler app root (the dir with Android/ and iOS/)");
    }
    let subs = Subs::from_app_root(root)?;
    let src = resolve_source(source)?;
    let manifest: Manifest = toml::from_str(&src.read_text("mobiler-plugin.toml")?)
        .context("parsing mobiler-plugin.toml")?;

    check_push_bridge(root, &src, &manifest)?;

    println!("Installing plugin `{}`{}", manifest.name, fmt_summary(&manifest.summary));
    let mut notes: Vec<String> = Vec::new();

    if let Some(a) = &manifest.android {
        let dst_dir = root.join("Android/app/src/main/java").join(&subs.package_path);
        for rel in &a.sources {
            copy_source(&src, rel, &dst_dir, &subs, root)?;
        }
        let core_kt = dst_dir.join("Core.kt");
        report(insert_before(&core_kt, "// mobiler:plugins", &format!("{},", a.register), &a.register)?, "Android registration");
        let manifest_xml = root.join("Android/app/src/main/AndroidManifest.xml");
        for perm in &a.permissions {
            let (name, line) = permission_line(perm);
            // The quoted attribute, so BLUETOOTH isn't taken as present because BLUETOOTH_SCAN is.
            let needle = format!("android:name=\"{name}\"");
            report(insert_before(&manifest_xml, "mobiler:permissions", &line, &needle)?, "Android permission");
        }
        let gradle = root.join("Android/app/build.gradle.kts");
        for dep in &a.gradle_deps {
            let line = format!("implementation(\"{dep}\")");
            report(insert_before(&gradle, "mobiler:gradle-deps", &line, dep)?, "Android Gradle dependency");
        }
        let gradle_proj = root.join("Android/build.gradle.kts");
        for gp in &a.gradle_plugins {
            // "plugin.id:version" → applied in the app block + declared (apply false) at project level.
            let (id, ver) = gp.split_once(':').unwrap_or((gp.as_str(), ""));
            let needle = format!("id(\"{id}\")");
            report(insert_before(&gradle, "mobiler:gradle-plugins", &needle, &needle)?, "Android Gradle plugin (app)");
            let proj_line = if ver.is_empty() {
                format!("id(\"{id}\") apply false")
            } else {
                format!("id(\"{id}\") version \"{ver}\" apply false")
            };
            report(insert_before(&gradle_proj, "mobiler:gradle-plugins-classpath", &proj_line, &needle)?, "Android Gradle plugin (project)");
        }
        for xml in &a.manifest_application {
            // Idempotency key: the snippet's android:name (unique per receiver/service/provider),
            // falling back to the trimmed snippet if it has none.
            let needle = manifest_name(xml).unwrap_or_else(|| xml.trim().to_string());
            report(insert_before(&manifest_xml, "mobiler:manifest-application", xml.trim(), &needle)?, "Android manifest entry");
        }
    }

    if let Some(i) = &manifest.ios {
        let dst_dir = root.join("iOS/Sources");
        for rel in &i.sources {
            copy_source(&src, rel, &dst_dir, &subs, root)?;
        }
        let core_swift = root.join("iOS/Sources/Core.swift");
        report(insert_before(&core_swift, "// mobiler:plugins", &i.register, &i.register)?, "iOS registration");
        if let Some(rs) = &i.register_stream {
            report(insert_before(&core_swift, "// mobiler:plugins-stream", rs, rs)?, "iOS streaming registration");
        }
        // Launch-time hooks (BGTaskScheduler.register, CLLocationManager re-arm) injected into
        // App.swift's didFinishLaunchingWithOptions — the only place that runs before the OS
        // delivers a queued background event.
        let app_swift = root.join("iOS/Sources/App.swift");
        for line in &i.app_launch {
            report(insert_before(&app_swift, "// mobiler:app-launch", line, line)?, "iOS app-launch hook");
        }

        let project_yml = root.join("iOS/project.yml");
        for (key, val) in &i.info_plist {
            match val {
                // Array keys (UIBackgroundModes, BGTaskSchedulerPermittedIdentifiers) MERGE — two
                // plugins setting the same key (e.g. geofence's [location] + background-fetch's
                // [fetch]) must union, not skip (insert_before's key-name idempotency would drop one).
                toml::Value::Array(arr) => {
                    let items: Vec<String> = arr.iter().map(yaml_scalar).collect();
                    report(merge_plist_array(&project_yml, key, &items)?, "iOS Info.plist key");
                }
                _ => {
                    let line = format!("{key}: {}", yaml_scalar(val));
                    report(insert_before(&project_yml, "# mobiler:info-plist", &line, key)?, "iOS Info.plist key");
                }
            }
        }
        if !i.entitlements.is_empty() {
            install_entitlements(&project_yml, &i.entitlements, &mut notes)?;
            notes.push(
                "iOS: enable the matching capability on your App ID in the Apple Developer \
                 portal (the one step that can't be automated)."
                    .to_string(),
            );
        }
        for entry in &i.spm_packages {
            install_spm_package(&project_yml, entry)?;
        }
    }

    notes.extend(manifest.notes.iter().cloned());
    println!("\n✓ Plugin `{}` installed.", manifest.name);
    for n in notes {
        println!("  • {n}");
    }
    Ok(())
}

fn fmt_summary(s: &str) -> String {
    if s.is_empty() { String::new() } else { format!(" — {s}") }
}

// ---------------- drift detection (for `mobiler upgrade`) ----------------

/// Where `add_at` copies a plugin source: Android sources land in the app's package dir,
/// iOS sources in `iOS/Sources`, both under the source file's basename.
fn installed_paths(root: &Path, subs: &Subs, m: &Manifest) -> Vec<(String, PathBuf)> {
    let mut out = Vec::new();
    let mut push = |rel: &str, dir: PathBuf| {
        if let Some(name) = Path::new(rel).file_name() {
            out.push((rel.to_string(), dir.join(name)));
        }
    };
    if let Some(a) = &m.android {
        let dir = root.join("Android/app/src/main/java").join(&subs.package_path);
        for rel in &a.sources {
            push(rel, dir.clone());
        }
    }
    if let Some(i) = &m.ios {
        let dir = root.join("iOS/Sources");
        for rel in &i.sources {
            push(rel, dir.clone());
        }
    }
    out
}

/// Whether `plugin add` registered this plugin: its `register` line is present in Core.kt / Core.swift
/// for every platform the manifest declares.
fn registered(root: &Path, subs: &Subs, m: &Manifest) -> bool {
    let has = |path: PathBuf, line: &str| fs::read_to_string(path).is_ok_and(|t| t.contains(line));
    let android = m.android.as_ref().is_none_or(|a| {
        has(root.join("Android/app/src/main/java").join(&subs.package_path).join("Core.kt"), &a.register)
    });
    let ios = m.ios.as_ref().is_none_or(|i| has(root.join("iOS/Sources/Core.swift"), &i.register));
    (m.android.is_some() || m.ios.is_some()) && android && ios
}

/// Bundled plugins that are installed in this app but whose on-disk shell sources differ from
/// the versions this CLI ships.
///
/// `upgrade` syncs template files and bumps the `mobiler-core` pin, but it deliberately never
/// touches plugin bodies — they were copied in by `plugin add` and may carry user edits. That
/// leaves a gap: a release can ship a new core API whose shell half lives only in a plugin
/// body, so the app compiles against the new core while the stale plugin silently ignores the
/// new request fields. Reporting the drift turns that silent mismatch into an instruction.
///
/// Best-effort: an unreadable manifest or source is skipped rather than failing the upgrade.
pub(crate) fn drifted(root: &Path, subs: &Subs) -> Vec<String> {
    // "Installed" = registered on every platform it declares. Source files alone can't tell:
    // alternative plugins share file names (`push` and `push-firebase-only` both ship
    // PushPlugin.kt), so file presence would report the one that isn't installed — and
    // re-adding it would collide with the one that is.
    let mut candidates = Vec::new();
    for name in bundled_names() {
        let Ok(src) = resolve_source(&name) else { continue };
        let Ok(manifest) = src
            .read_text("mobiler-plugin.toml")
            .and_then(|t| toml::from_str::<Manifest>(&t).context("parsing mobiler-plugin.toml"))
        else {
            continue;
        };
        let paths = installed_paths(root, subs, &manifest);
        if paths.is_empty() || !registered(root, subs, &manifest) {
            continue;
        }
        // Each (shipped, on-disk) pair; `None` on disk = missing from the app.
        let files: Vec<(PathBuf, Option<String>, Option<String>)> = paths
            .iter()
            .map(|(rel, dst)| {
                let shipped = src.read_text(rel).ok().map(|t| substitute(&t, subs));
                (dst.clone(), shipped, fs::read_to_string(dst).ok())
            })
            .collect();
        let missing_permission = missing_permissions(root, &manifest);
        candidates.push((name, files, missing_permission));
    }

    // Some alternatives register identical lines too (`geolocation` / `geolocation-fused`), so both
    // look registered. Where registered plugins claim the same file, the app's copy decides: only
    // the variant whose shipped body shares the most lines with it counts as installed, fresh or
    // stale. A tie (a copy rewritten beyond both) beats neither, so both are judged as before.
    // Both variants are compared against the same on-disk files, so a count of matching lines ranks them.
    let closeness = |files: &[(PathBuf, Option<String>, Option<String>)], shared: &[&PathBuf]| -> usize {
        files
            .iter()
            .filter(|(dst, _, _)| shared.contains(&dst))
            .map(|(_, shipped, on_disk)| match (shipped, on_disk) {
                (Some(shipped), Some(on_disk)) => lines_in_common(shipped, on_disk),
                _ => 0,
            })
            .sum()
    };
    let mut drifted = Vec::new();
    for (name, files, missing_permission) in &candidates {
        let beaten = candidates.iter().any(|(other, other_files, _)| {
            let shared: Vec<&PathBuf> =
                files.iter().map(|(d, _, _)| d).filter(|d| other_files.iter().any(|(o, _, _)| o == *d)).collect();
            other != name && !shared.is_empty() && closeness(other_files, &shared) > closeness(files, &shared)
        });
        if beaten {
            continue;
        }
        let stale = files.iter().any(|(_, shipped, on_disk)| match (shipped, on_disk) {
            (Some(shipped), Some(on_disk)) => shipped != on_disk,
            // A source this CLI ships that is missing from the app is itself drift (a release
            // that adds a second file to an existing plugin).
            (Some(_), None) => true,
            _ => false,
        });
        // A permission the plugin now declares but the app's manifest lacks (bluetooth's legacy pair
        // for Android 8–11) is drift too: re-adding the plugin inserts it.
        if stale || *missing_permission {
            drifted.push(name.clone());
        }
    }
    drifted
}

/// Whether the app's manifest lacks (as a live line) a permission this plugin declares.
fn missing_permissions(root: &Path, manifest: &Manifest) -> bool {
    let Some(a) = &manifest.android else { return false };
    let path = root.join("Android/app/src/main/AndroidManifest.xml");
    let Ok(content) = fs::read_to_string(&path) else { return false };
    let live = without_comments(&path, &content);
    a.permissions.iter().any(|p| !live.contains(&format!("android:name=\"{}\"", permission_line(p).0)))
}

/// How many of the app's lines (`on_disk`) also appear in one shipped variant's body.
fn lines_in_common(shipped: &str, on_disk: &str) -> usize {
    let shipped: std::collections::HashSet<&str> = shipped.lines().collect();
    on_disk.lines().filter(|l| shipped.contains(l)).count()
}

fn report(res: Insert, what: &str) {
    match res {
        Insert::Inserted => println!("  + {what}"),
        Insert::AlreadyPresent => println!("  · {what} already present (skipped)"),
        Insert::MarkerMissing(m) => println!("  ! {what}: anchor `{m}` not found — add it manually"),
    }
}

/// Extract the value of `android:name="…"` from a manifest XML snippet (the idempotency key
/// for a `<receiver>` / `<service>` / `<provider>` entry).
fn manifest_name(xml: &str) -> Option<String> {
    let key = "android:name=\"";
    let start = xml.find(key)? + key.len();
    let end = xml[start..].find('"')? + start;
    Some(xml[start..end].to_string())
}

/// Copy one plugin source file into `dst_dir`, substituting `{{PACKAGE}}` etc.
fn copy_source(src: &Source, rel: &str, dst_dir: &Path, subs: &Subs, root: &Path) -> Result<()> {
    let raw = src.read_text(rel)?;
    let name = Path::new(rel)
        .file_name()
        .ok_or_else(|| anyhow::anyhow!("plugin source `{rel}` has no file name"))?;
    fs::create_dir_all(dst_dir).with_context(|| format!("creating {}", dst_dir.display()))?;
    let dst = dst_dir.join(name);
    fs::write(&dst, substitute(&raw, subs)).with_context(|| format!("writing {}", dst.display()))?;
    println!("  + {}", dst.strip_prefix(root).unwrap_or(&dst).display());
    Ok(())
}

// ---------------- marker-based insertion ----------------

enum Insert {
    Inserted,
    AlreadyPresent,
    MarkerMissing(String),
}

/// Whether `line` contains `marker` at a token boundary — i.e. `marker` is NOT immediately
/// followed by `-`, `_`, or an alphanumeric. This stops a marker from matching a longer marker
/// that has it as a prefix (e.g. `mobiler:plugins` must not match `mobiler:plugins-stream`).
fn line_has_marker(line: &str, marker: &str) -> bool {
    let mut from = 0;
    while let Some(pos) = line[from..].find(marker) {
        let end = from + pos + marker.len();
        let next = line[end..].chars().next();
        if !matches!(next, Some(c) if c == '-' || c == '_' || c.is_alphanumeric()) {
            return true;
        }
        from = end;
    }
    false
}

/// Insert `payload` (one logical line) immediately before the line containing `marker` (matched at
/// a token boundary), with the marker's indentation. Idempotent: skip if `needle` is already present.
fn insert_before(path: &Path, marker: &str, payload: &str, needle: &str) -> Result<Insert> {
    let content = fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
    // Only live lines count: a template's commented-out opt-in line (ADR-0035) must not stop the
    // plugin that needs it from inserting the real one.
    if without_comments(path, &content).contains(needle) {
        return Ok(Insert::AlreadyPresent);
    }
    let Some(marker_line) = content.lines().find(|l| line_has_marker(l, marker)) else {
        return Ok(Insert::MarkerMissing(marker.to_string()));
    };
    let indent: String = marker_line.chars().take_while(|c| c.is_whitespace()).collect();
    let anchor = format!("{marker_line}\n");
    let updated = content.replacen(&anchor, &format!("{indent}{payload}\n{anchor}"), 1);
    fs::write(path, updated).with_context(|| format!("writing {}", path.display()))?;
    Ok(Insert::Inserted)
}

/// The push plugins call `PushBridge.detach(id)`, which lives in the app's App.swift, not in the
/// plugin. Checked before writing anything: an App.swift that predates it wouldn't compile.
fn check_push_bridge(root: &Path, src: &Source, manifest: &Manifest) -> Result<()> {
    if let Some(i) = &manifest.ios {
        let needs_new_bridge =
            i.sources.iter().any(|rel| src.read_text(rel).is_ok_and(|t| t.contains("PushBridge.shared.detach(id)")));
        let app_swift = fs::read_to_string(root.join("iOS/Sources/App.swift")).unwrap_or_default();
        if needs_new_bridge && app_swift.contains("final class PushBridge") && !app_swift.contains("func detach(_ id: Int)") {
            bail!(
                "`{}` needs a newer iOS/Sources/App.swift (PushBridge.detach(_:)). Run `mobiler upgrade --apply` first, then re-run `mobiler plugin add {}`.",
                manifest.name,
                manifest.name
            );
        }
    }
    Ok(())
}

/// A manifest `permissions` entry as its name and `<uses-permission>` line. An entry may carry a
/// ceiling for permissions newer Android replaced: `"android.permission.BLUETOOTH;maxSdkVersion=30"`.
fn permission_line(entry: &str) -> (&str, String) {
    if let Some((name, max)) = entry.split_once(";maxSdkVersion=") {
        (name, format!("<uses-permission android:name=\"{name}\" android:maxSdkVersion=\"{max}\" />"))
    } else {
        (entry, format!("<uses-permission android:name=\"{entry}\" />"))
    }
}

/// `content` with its comments removed, by file type: `<!-- … -->` blocks in XML (they can span
/// lines), whole-line `#` comments in YAML and whole-line `//` comments elsewhere. Only whole lines
/// are dropped outside XML, so a `//` inside a URL or string is never cut.
fn without_comments(path: &Path, content: &str) -> String {
    match path.extension().and_then(|e| e.to_str()) {
        Some("xml") => {
            let mut out = String::with_capacity(content.len());
            let mut rest = content;
            while let Some(start) = rest.find("<!--") {
                out.push_str(&rest[..start]);
                rest = rest[start..].find("-->").map_or("", |end| &rest[start + end + 3..]);
            }
            out.push_str(rest);
            out
        }
        ext => {
            let prefix = if matches!(ext, Some("yml" | "yaml")) { "#" } else { "//" };
            content.lines().filter(|l| !l.trim_start().starts_with(prefix)).collect::<Vec<_>>().join("\n")
        }
    }
}

/// Insert or MERGE an array-valued Info.plist key. If the key already exists — whether inline
/// (`key: [..]`) or YAML block form (`key:` then `- item` lines, e.g. a hand-authored UIBackgroundModes
/// PiP opt-in) — union the new items into it; otherwise insert a fresh inline line at the
/// `# mobiler:info-plist` anchor. `items` are already YAML-rendered (quoted). Idempotent — re-adding the
/// same items reports AlreadyPresent. Two plugins (geofence `[location]` + background-fetch `[fetch]`)
/// or a plugin layered on a hand-authored block must union, not silently drop one (which would leave a
/// background capability undeclared).
fn merge_plist_array(project_yml: &Path, key: &str, items: &[String]) -> Result<Insert> {
    let content =
        fs::read_to_string(project_yml).with_context(|| format!("reading {}", project_yml.display()))?;

    // Inline form: `<indent>key: [a, b]`.
    let inline_prefix = format!("{key}: [");
    if let Some(existing) = content.lines().find(|l| l.trim_start().starts_with(&inline_prefix)) {
        let indent: String = existing.chars().take_while(|c| c.is_whitespace()).collect();
        let inner = existing.trim().trim_start_matches(&inline_prefix).trim_end().trim_end_matches(']');
        let mut merged: Vec<String> =
            inner.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect();
        let mut added = false;
        for it in items {
            if !merged.iter().any(|m| m == it) {
                merged.push(it.clone());
                added = true;
            }
        }
        if !added {
            return Ok(Insert::AlreadyPresent);
        }
        let new_line = format!("{indent}{key}: [{}]", merged.join(", "));
        let updated = content.replacen(existing, &new_line, 1);
        fs::write(project_yml, updated).with_context(|| format!("writing {}", project_yml.display()))?;
        return Ok(Insert::Inserted);
    }

    // Block form: `<indent>key:` followed by `<indent>  - item` lines.
    let lines: Vec<&str> = content.lines().collect();
    if let Some(key_idx) = lines.iter().position(|l| l.trim() == format!("{key}:")) {
        let key_indent: String = lines[key_idx].chars().take_while(|c| c.is_whitespace()).collect();
        let item_indent = format!("{key_indent}  ");
        let mut existing_bare: Vec<String> = Vec::new();
        let mut last_item: Option<&str> = None;
        for &l in lines.iter().skip(key_idx + 1) {
            if l.starts_with(&item_indent) && l.trim_start().starts_with("- ") {
                existing_bare.push(l.trim_start().trim_start_matches("- ").trim().trim_matches('"').to_string());
                last_item = Some(l);
            } else {
                break; // end of this key's block
            }
        }
        if let Some(anchor_line) = last_item {
            let additions: Vec<String> = items
                .iter()
                .filter(|it| !existing_bare.iter().any(|e| e == it.trim_matches('"')))
                .map(|it| format!("{item_indent}- {it}"))
                .collect();
            if additions.is_empty() {
                return Ok(Insert::AlreadyPresent);
            }
            let anchor = format!("{anchor_line}\n");
            let replacement = format!("{anchor}{}\n", additions.join("\n"));
            let updated = content.replacen(&anchor, &replacement, 1);
            fs::write(project_yml, updated).with_context(|| format!("writing {}", project_yml.display()))?;
            return Ok(Insert::Inserted);
        }
    }

    let line = format!("{key}: [{}]", items.join(", "));
    insert_before(project_yml, "# mobiler:info-plist", &line, key)
}

/// Add an xcodegen target-level `entitlements:` block at the `# mobiler:target-extra` anchor.
/// v1 handles the create case; if a block already exists, leaves a note to merge by hand.
fn install_entitlements(
    project_yml: &Path,
    entitlements: &BTreeMap<String, toml::Value>,
    notes: &mut Vec<String>,
) -> Result<()> {
    let content = fs::read_to_string(project_yml)?;
    if content.lines().any(|l| l.trim_start().starts_with("entitlements:")) {
        notes.push(format!(
            "iOS: an `entitlements:` block already exists in project.yml — add these keys by hand: {}",
            entitlements.keys().cloned().collect::<Vec<_>>().join(", ")
        ));
        return Ok(());
    }
    let Some(marker_line) = content.lines().find(|l| l.contains("# mobiler:target-extra")) else {
        notes.push("iOS: anchor `# mobiler:target-extra` not found — add the entitlements block manually.".into());
        return Ok(());
    };
    let indent: String = marker_line.chars().take_while(|c| c.is_whitespace()).collect();
    let mut block =
        format!("{indent}entitlements:\n{indent}  path: Sources/App.entitlements\n{indent}  properties:\n");
    for (key, val) in entitlements {
        block.push_str(&format!("{indent}    {key}: {}\n", yaml_scalar(val)));
    }
    let anchor = format!("{marker_line}\n");
    let updated = content.replacen(&anchor, &format!("{block}{anchor}"), 1);
    fs::write(project_yml, updated)?;
    println!("  + iOS entitlements block");
    Ok(())
}

/// Add a remote SwiftPM package (`name|url|version|product`) to the iOS project.yml: a package entry
/// in the top-level `packages:` block (at `# mobiler:spm-packages`) + a target product dependency in
/// `dependencies:` (at `# mobiler:spm-dependencies`). Idempotent — skips the package if its `url` is
/// already present, and the dependency if `product: <product>` is. The iOS twin of `gradle_plugins`.
fn install_spm_package(project_yml: &Path, entry: &str) -> Result<()> {
    let parts: Vec<&str> = entry.split('|').collect();
    let [name, url, version, product] = parts[..] else {
        bail!("spm_packages entry must be 'name|url|version|product', got `{entry}`");
    };
    let mut content =
        fs::read_to_string(project_yml).with_context(|| format!("reading {}", project_yml.display()))?;

    // 1) Remote package entry in the `packages:` block.
    if !content.contains(url) {
        match content.lines().find(|l| line_has_marker(l, "# mobiler:spm-packages")).map(str::to_string) {
            Some(marker) => {
                let indent: String = marker.chars().take_while(|c| c.is_whitespace()).collect();
                let block = format!("{indent}{name}:\n{indent}  url: {url}\n{indent}  from: {version}\n");
                let anchor = format!("{marker}\n");
                content = content.replacen(&anchor, &format!("{block}{anchor}"), 1);
                println!("  + iOS SwiftPM package {name}");
            }
            None => println!("  ! iOS SwiftPM package: anchor `# mobiler:spm-packages` not found — add it manually"),
        }
    }

    // 2) Target product dependency in the `dependencies:` block.
    let dep_needle = format!("product: {product}");
    if !content.contains(&dep_needle) {
        match content.lines().find(|l| line_has_marker(l, "# mobiler:spm-dependencies")).map(str::to_string) {
            Some(marker) => {
                let indent: String = marker.chars().take_while(|c| c.is_whitespace()).collect();
                let block = format!("{indent}- package: {name}\n{indent}  product: {product}\n");
                let anchor = format!("{marker}\n");
                content = content.replacen(&anchor, &format!("{block}{anchor}"), 1);
                println!("  + iOS SwiftPM dependency {product}");
            }
            None => println!("  ! iOS SwiftPM dependency: anchor `# mobiler:spm-dependencies` not found — add it manually"),
        }
    }

    fs::write(project_yml, content).with_context(|| format!("writing {}", project_yml.display()))?;
    Ok(())
}

/// Render a TOML scalar/array as an inline YAML value (strings, bools, ints, arrays of strings).
fn yaml_scalar(v: &toml::Value) -> String {
    match v {
        toml::Value::String(s) => format!("\"{s}\""),
        toml::Value::Boolean(b) => b.to_string(),
        toml::Value::Integer(i) => i.to_string(),
        toml::Value::Array(a) => {
            let items: Vec<String> = a.iter().map(yaml_scalar).collect();
            format!("[{}]", items.join(", "))
        }
        other => format!("\"{other}\""),
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    static COUNTER: AtomicUsize = AtomicUsize::new(0);

    /// A throwaway temp dir with a minimal Mobiler app skeleton carrying the anchor markers.
    fn skeleton() -> PathBuf {
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let root = std::env::temp_dir().join(format!("mob_plugin_test_{}_{n}", std::process::id()));
        let _ = fs::remove_dir_all(&root);
        let pkg = root.join("Android/app/src/main/java/dev/mobiler/demo");
        fs::create_dir_all(&pkg).unwrap();
        fs::create_dir_all(root.join("iOS/Sources")).unwrap();
        fs::write(pkg.join("MainActivity.kt"), "package dev.mobiler.demo\nclass MainActivity\n").unwrap();
        fs::write(
            pkg.join("Core.kt"),
            "package dev.mobiler.demo\nval plugins = mapOf(\n    \"http\" to HttpPlugin(),\n    // mobiler:plugins\n)\n",
        )
        .unwrap();
        fs::write(
            root.join("Android/app/src/main/AndroidManifest.xml"),
            "<manifest>\n    <!-- mobiler:permissions -->\n    <application>\n        <!-- mobiler:manifest-application -->\n    </application>\n</manifest>\n",
        )
        .unwrap();
        fs::write(root.join("Android/settings.gradle.kts"), "rootProject.name = \"Demo\"\n").unwrap();
        fs::write(
            root.join("Android/build.gradle.kts"),
            "plugins {\n    alias(libs.plugins.android.application) apply false\n    // mobiler:gradle-plugins-classpath\n}\n",
        )
        .unwrap();
        fs::write(
            root.join("Android/app/build.gradle.kts"),
            "plugins {\n    alias(libs.plugins.android.application)\n    // mobiler:gradle-plugins\n}\ndependencies {\n    implementation(project(\":shared\"))\n    // mobiler:gradle-deps\n}\n",
        )
        .unwrap();
        fs::write(
            root.join("iOS/Sources/Core.swift"),
            "func subscribe() {\n        switch plugin {\n        // mobiler:plugins-stream\n        default: break\n        }\n    }\n    func handle() {\n        switch plugin {\n        case \"http\": return x\n        // mobiler:plugins\n        default: return y\n        }\n    }\n",
        )
        .unwrap();
        fs::write(
            root.join("iOS/Sources/App.swift"),
            "func application() -> Bool {\n        UNUserNotificationCenter.current().delegate = self\n        // mobiler:app-launch\n        return true\n    }\n",
        )
        .unwrap();
        fs::write(
            root.join("iOS/project.yml"),
            "packages:\n  SharedTypes:\n    path: generated/SharedTypes\n  # mobiler:spm-packages\ntargets:\n  Demo:\n    dependencies:\n      - package: SharedTypes\n      # mobiler:spm-dependencies\n    info:\n      properties:\n        PRODUCT_BUNDLE_IDENTIFIER: dev.mobiler.demo\n        # mobiler:info-plist\n    settings:\n      base:\n        FOO: bar\n    # mobiler:target-extra\n",
        )
        .unwrap();
        root
    }

    fn read(root: &Path, rel: &str) -> String {
        fs::read_to_string(root.join(rel)).unwrap()
    }

    #[test]
    fn add_bundled_battery_copies_and_registers() {
        let root = skeleton();
        add_at(&root, "battery").unwrap();

        // Native source copied with {{PACKAGE}} substituted to the app's package.
        let kt = read(&root, "Android/app/src/main/java/dev/mobiler/demo/BatteryPlugin.kt");
        assert!(kt.contains("package dev.mobiler.demo"), "package substituted");
        // Registered in both shells, before the marker.
        let core_kt = read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt");
        assert!(core_kt.contains("\"battery\" to BatteryPlugin(application),"));
        let core_swift = read(&root, "iOS/Sources/Core.swift");
        assert!(core_swift.contains("case \"battery\": return await BatteryPlugin.handle"));
        let _ = fs::remove_dir_all(&root);
    }

    /// `drifted` is what stops an upgrade from silently leaving a plugin's shell half behind:
    /// not-installed → quiet, freshly installed → clean, edited/stale → reported.
    #[test]
    fn drifted_reports_only_installed_and_stale_plugins() {
        let root = skeleton();
        let subs = Subs::from_app_root(&root).unwrap();

        // Nothing installed yet: no plugin may be reported.
        assert!(drifted(&root, &subs).is_empty(), "no plugins installed → nothing drifted");

        add_at(&root, "battery").unwrap();
        assert!(
            !drifted(&root, &subs).contains(&"battery".to_string()),
            "a just-installed plugin matches what the CLI ships"
        );

        // Simulate the real case: the app carries an older copy of the plugin's shell source
        // (what a 0.49 project looks like after upgrading to a CLI whose plugin body moved on).
        let kt = root.join("Android/app/src/main/java/dev/mobiler/demo/BatteryPlugin.kt");
        let stale = fs::read_to_string(&kt).unwrap().replace("package dev.mobiler.demo", "package dev.mobiler.demo\n// older version");
        fs::write(&kt, stale).unwrap();
        assert!(
            drifted(&root, &subs).contains(&"battery".to_string()),
            "a stale plugin body is reported so the mismatch is not silent"
        );

        // Re-adding is the documented fix — it must clear the report.
        add_at(&root, "battery").unwrap();
        assert!(
            !drifted(&root, &subs).contains(&"battery".to_string()),
            "`plugin add` refreshes the body and clears the drift"
        );
        let _ = fs::remove_dir_all(&root);
    }

    /// `push` and `push-firebase-only` are mutually exclusive but share Android file names. A stale
    /// `push` must not also report `push-firebase-only`: re-adding it would collide at build.
    #[test]
    fn drifted_does_not_report_an_alternative_plugin_sharing_file_names() {
        let root = skeleton();
        let subs = Subs::from_app_root(&root).unwrap();
        add_at(&root, "push").unwrap();

        let kt = root.join("Android/app/src/main/java/dev/mobiler/demo/PushPlugin.kt");
        let stale = fs::read_to_string(&kt).unwrap().replace("package dev.mobiler.demo", "package dev.mobiler.demo\n// older version");
        fs::write(&kt, stale).unwrap();

        let report = drifted(&root, &subs);
        assert!(report.contains(&"push".to_string()), "the installed plugin is reported: {report:?}");
        assert!(!report.contains(&"push-firebase-only".to_string()), "the alternative is not: {report:?}");
        let _ = fs::remove_dir_all(&root);
    }

    /// `geolocation` and `geolocation-fused` register the SAME lines and share both file names, so
    /// registration can't tell them apart. The installed file's content must: only the variant whose
    /// shipped body the app's copy is closest to counts as installed, fresh or stale.
    #[test]
    fn drifted_tells_variants_with_identical_registrations_apart() {
        for (installed, other) in [("geolocation", "geolocation-fused"), ("geolocation-fused", "geolocation")] {
            let root = skeleton();
            let subs = Subs::from_app_root(&root).unwrap();
            add_at(&root, installed).unwrap();
            assert!(drifted(&root, &subs).is_empty(), "fresh {installed} → nothing drifted: {:?}", drifted(&root, &subs));

            let kt = root.join("Android/app/src/main/java/dev/mobiler/demo/GeolocationPlugin.kt");
            let stale = fs::read_to_string(&kt).unwrap().replace("package dev.mobiler.demo", "package dev.mobiler.demo\n// older version");
            fs::write(&kt, stale).unwrap();
            let report = drifted(&root, &subs);
            assert!(report.contains(&installed.to_string()), "stale {installed} is reported: {report:?}");
            assert!(!report.contains(&other.to_string()), "{other} is not installed, so not reported: {report:?}");
            let _ = fs::remove_dir_all(&root);
        }
    }

    /// The push plugins call `PushBridge.detach(id)`, which lives in the app's App.swift. An app
    /// whose App.swift predates it must be told to upgrade before anything is written, or its Swift
    /// fails to compile with no hint why.
    #[test]
    fn add_push_to_an_app_with_an_old_push_bridge_asks_for_upgrade_first() {
        let root = skeleton();
        fs::write(
            root.join("iOS/Sources/App.swift"),
            "final class PushBridge {\n    func attach(_ sink: @escaping @Sendable (String) -> Void) {}\n    func detach() { sink = nil }\n}\n// mobiler:app-launch\n",
        )
        .unwrap();
        for name in ["push", "push-firebase-only"] {
            let err = add_at(&root, name).expect_err("an old PushBridge must stop the install").to_string();
            assert!(err.contains("mobiler upgrade"), "{name}: {err}");
            assert!(!root.join("iOS/Sources/PushPlugin.swift").exists() && !root.join("iOS/Sources/FirebasePushPlugin.swift").exists());
        }
        let _ = fs::remove_dir_all(&root);
    }

    /// A key the template leaves commented out (opt-in, ADR-0035) is not "already present": the
    /// plugin that needs it must still insert the live line.
    #[test]
    fn insert_before_ignores_commented_out_keys() {
        let dir = std::env::temp_dir().join(format!("mobiler-commented-{}", std::process::id()));
        fs::create_dir_all(&dir).unwrap();
        let yml = dir.join("project.yml");
        fs::write(&yml, "    info:\n        # NSCameraUsageDescription: \"Take photos.\"\n        # mobiler:info-plist\n").unwrap();
        let line = "NSCameraUsageDescription: \"Scan codes.\"";
        assert!(matches!(insert_before(&yml, "# mobiler:info-plist", line, "NSCameraUsageDescription").unwrap(), Insert::Inserted));
        assert!(read(&dir, "project.yml").contains(&format!("        {line}\n        # mobiler:info-plist")));
        // A live key is still detected, so re-adding stays a no-op.
        assert!(matches!(insert_before(&yml, "# mobiler:info-plist", line, "NSCameraUsageDescription").unwrap(), Insert::AlreadyPresent));

        let xml = dir.join("AndroidManifest.xml");
        fs::write(
            &xml,
            "<manifest>\n    <!-- Uncomment to enable haptics:\n    <uses-permission android:name=\"android.permission.VIBRATE\" /> -->\n    <!-- mobiler:permissions -->\n</manifest>\n",
        )
        .unwrap();
        let perm = "<uses-permission android:name=\"android.permission.VIBRATE\" />";
        assert!(matches!(insert_before(&xml, "mobiler:permissions", perm, "android.permission.VIBRATE").unwrap(), Insert::Inserted));
        assert!(matches!(insert_before(&xml, "mobiler:permissions", perm, "android.permission.VIBRATE").unwrap(), Insert::AlreadyPresent));
        let _ = fs::remove_dir_all(&dir);
    }

    /// Bluetooth on Android 8–11 needs the legacy `BLUETOOTH` / `BLUETOOTH_ADMIN` permissions, which
    /// Android 12 replaced; the manifest entry carries the ceiling.
    #[test]
    fn add_bundled_bluetooth_declares_legacy_permissions_up_to_android_11() {
        let root = skeleton();
        add_at(&root, "bluetooth").unwrap();
        let manifest = read(&root, "Android/app/src/main/AndroidManifest.xml");
        for legacy in ["BLUETOOTH", "BLUETOOTH_ADMIN"] {
            assert!(
                manifest.contains(&format!(
                    "<uses-permission android:name=\"android.permission.{legacy}\" android:maxSdkVersion=\"30\" />"
                )),
                "{legacy} with maxSdkVersion 30: {manifest}"
            );
        }
        assert!(manifest.contains("<uses-permission android:name=\"android.permission.BLUETOOTH_SCAN\" />"));
        let _ = fs::remove_dir_all(&root);
    }

    /// A plugin whose manifest gained a permission (bluetooth's legacy pair for Android 8–11) is
    /// drifted even when its sources didn't change: re-adding it is how the app gets the line.
    #[test]
    fn drifted_reports_a_plugin_missing_a_declared_permission() {
        let root = skeleton();
        let subs = Subs::from_app_root(&root).unwrap();
        add_at(&root, "bluetooth").unwrap();
        assert!(!drifted(&root, &subs).contains(&"bluetooth".to_string()), "fresh install is clean");
        let manifest = root.join("Android/app/src/main/AndroidManifest.xml");
        let without = fs::read_to_string(&manifest)
            .unwrap()
            .lines()
            .filter(|l| !l.contains("android.permission.BLUETOOTH_ADMIN"))
            .collect::<Vec<_>>()
            .join("\n");
        fs::write(&manifest, without).unwrap();
        assert!(drifted(&root, &subs).contains(&"bluetooth".to_string()), "a missing permission is drift");
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn line_has_marker_respects_token_boundaries() {
        // A marker must not match a longer marker that has it as a prefix.
        assert!(line_has_marker("    // mobiler:plugins — inserts here", "// mobiler:plugins"));
        assert!(!line_has_marker("    // mobiler:plugins-stream — inserts here", "// mobiler:plugins"));
        assert!(line_has_marker("    // mobiler:plugins-stream — inserts here", "// mobiler:plugins-stream"));
    }

    #[test]
    fn add_bundled_websocket_registers_handle_and_stream_cases() {
        let root = skeleton();
        add_at(&root, "websocket").unwrap();

        let core_swift = read(&root, "iOS/Sources/Core.swift");
        // The request/response case lands at // mobiler:plugins …
        let handle_at = core_swift.find("case \"websocket\": return await WebSocketPlugin.handle").expect("handle case");
        // … and the streaming case lands at the // mobiler:plugins-stream marker.
        let stream_at = core_swift.find("case \"websocket\": await WebSocketPlugin.subscribe").expect("stream case");
        // Crucially, each lands in its OWN switch — the stream case (in `subscribe`, earlier in the
        // file) before the handle case (in `handle`). Guards the marker prefix-collision bug:
        // `// mobiler:plugins` must NOT match the `// mobiler:plugins-stream` line.
        assert!(stream_at < handle_at, "stream case must be in subscribe(), handle case in handle()");
        assert!(handle_at > core_swift.find("func handle()").unwrap(), "handle case must be inside handle()");
        // Android registers once (its streaming is the polymorphic subscribe() override).
        let core_kt = read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt");
        assert!(core_kt.contains("\"websocket\" to WebSocketPlugin(application),"));
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn add_bundled_connectivity_copies_registers_and_adds_permission() {
        let root = skeleton();
        add_at(&root, "connectivity").unwrap();

        let kt = read(&root, "Android/app/src/main/java/dev/mobiler/demo/ConnectivityPlugin.kt");
        assert!(kt.contains("package dev.mobiler.demo"), "package substituted");
        let core_kt = read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt");
        assert!(core_kt.contains("\"connectivity\" to ConnectivityPlugin(application),"));
        let core_swift = read(&root, "iOS/Sources/Core.swift");
        assert!(core_swift.contains("case \"connectivity\": return await ConnectivityPlugin.handle"));
        let manifest = read(&root, "Android/app/src/main/AndroidManifest.xml");
        assert!(manifest.contains("android.permission.ACCESS_NETWORK_STATE"), "permission injected");
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn add_bundled_filepicker_copies_both_sources_and_registers_activity() {
        let root = skeleton();
        add_at(&root, "filepicker").unwrap();

        // Both Android sources copied with the package substituted.
        let plugin = read(&root, "Android/app/src/main/java/dev/mobiler/demo/FilePickerPlugin.kt");
        assert!(plugin.contains("package dev.mobiler.demo"));
        let activity = read(&root, "Android/app/src/main/java/dev/mobiler/demo/FilePickerActivity.kt");
        assert!(activity.contains("class FilePickerActivity"));
        // Registered in both shells + the helper Activity declared in the manifest.
        let core_kt = read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt");
        assert!(core_kt.contains("\"filepicker\" to FilePickerPlugin(application),"));
        let core_swift = read(&root, "iOS/Sources/Core.swift");
        assert!(core_swift.contains("case \"filepicker\": return await FilePickerPlugin.handle"));
        let manifest = read(&root, "Android/app/src/main/AndroidManifest.xml");
        assert!(manifest.contains("android:name=\".FilePickerActivity\""), "helper activity declared");
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn add_bundled_files_copies_sources_registers_and_declares_export_activity() {
        let root = skeleton();
        add_at(&root, "files").unwrap();

        // Both Android sources copied with the package substituted.
        let plugin = read(&root, "Android/app/src/main/java/dev/mobiler/demo/FilesPlugin.kt");
        assert!(plugin.contains("package dev.mobiler.demo"));
        assert!(plugin.contains("class FilesPlugin"));
        let activity = read(&root, "Android/app/src/main/java/dev/mobiler/demo/FileExportActivity.kt");
        assert!(activity.contains("class FileExportActivity"));
        // Registered in both shells + the export helper Activity declared in the manifest.
        let core_kt = read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt");
        assert!(core_kt.contains("\"files\" to FilesPlugin(application),"));
        let core_swift = read(&root, "iOS/Sources/Core.swift");
        assert!(core_swift.contains("case \"files\": return await FilesPlugin.handle"));
        let manifest = read(&root, "Android/app/src/main/AndroidManifest.xml");
        assert!(manifest.contains("android:name=\".FileExportActivity\""), "export helper activity declared");
        let swift = read(&root, "iOS/Sources/FilesPlugin.swift");
        assert!(swift.contains("enum FilesPlugin"));
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn add_bundled_geolocation_adds_permissions_and_plist_key() {
        let root = skeleton();
        add_at(&root, "geolocation").unwrap();

        let kt = read(&root, "Android/app/src/main/java/dev/mobiler/demo/GeolocationPlugin.kt");
        assert!(kt.contains("package dev.mobiler.demo"));
        let core_kt = read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt");
        assert!(core_kt.contains("\"geolocation\" to GeolocationPlugin(application),"));
        let core_swift = read(&root, "iOS/Sources/Core.swift");
        assert!(core_swift.contains("case \"geolocation\": return await GeolocationPlugin.handle"));
        let manifest = read(&root, "Android/app/src/main/AndroidManifest.xml");
        assert!(manifest.contains("android.permission.ACCESS_FINE_LOCATION"), "fine perm injected");
        assert!(manifest.contains("android.permission.ACCESS_COARSE_LOCATION"), "coarse perm injected");
        let yml = read(&root, "iOS/project.yml");
        assert!(yml.contains("NSLocationWhenInUseUsageDescription"), "iOS usage-description injected");
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn add_bundled_geofence_registers_stream_app_launch_perms_dep_and_array_plist() {
        let root = skeleton();
        add_at(&root, "geofence").unwrap();

        // Both Android sources copied with the package substituted.
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/GeofencePlugin.kt").contains("package dev.mobiler.demo"));
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/GeofenceBroadcastReceiver.kt").contains("class GeofenceBroadcastReceiver"));
        // Registered in both shells — handle case + the streaming case.
        let core_kt = read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt");
        assert!(core_kt.contains("\"geofence\" to GeofencePlugin(application),"));
        let core_swift = read(&root, "iOS/Sources/Core.swift");
        let handle_at = core_swift.find("case \"geofence\": return await GeofencePlugin.handle").expect("handle case");
        let stream_at = core_swift.find("case \"geofence\": await GeofencePlugin.subscribe").expect("stream case");
        assert!(stream_at < handle_at, "stream case in subscribe(), handle case in handle()");
        // The NEW app-launch hook — bootstrap() injected into App.swift's didFinishLaunching.
        let app_swift = read(&root, "iOS/Sources/App.swift");
        assert!(app_swift.contains("GeofencePlugin.bootstrap()"), "app-launch hook injected into App.swift");
        // Permissions (incl. background location) + Play Services dep + the static receiver.
        let manifest = read(&root, "Android/app/src/main/AndroidManifest.xml");
        assert!(manifest.contains("android.permission.ACCESS_BACKGROUND_LOCATION"), "background-location perm injected");
        assert!(manifest.contains("android:name=\".GeofenceBroadcastReceiver\""), "geofence receiver declared");
        let gradle = read(&root, "Android/app/build.gradle.kts");
        assert!(gradle.contains("com.google.android.gms:play-services-location"), "play-services-location dep injected");
        // The NEW array-valued Info.plist key — UIBackgroundModes renders as an inline YAML array.
        let yml = read(&root, "iOS/project.yml");
        assert!(yml.contains("UIBackgroundModes: [\"location\"]"), "UIBackgroundModes array injected, got:\n{yml}");
        assert!(yml.contains("NSLocationAlwaysAndWhenInUseUsageDescription"), "Always usage-description injected");
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn add_bundled_background_fetch_registers_stream_app_launch_workdep_and_array_plists() {
        let root = skeleton();
        add_at(&root, "background-fetch").unwrap();

        // Both Android sources copied with the package substituted.
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/BackgroundFetchPlugin.kt").contains("package dev.mobiler.demo"));
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/BackgroundFetchWorker.kt").contains("class BackgroundFetchWorker"));
        // Registered in both shells — handle case + the streaming case.
        let core_kt = read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt");
        assert!(core_kt.contains("\"background-fetch\" to BackgroundFetchPlugin(application),"));
        let core_swift = read(&root, "iOS/Sources/Core.swift");
        let handle_at = core_swift.find("case \"background-fetch\": return await BackgroundFetchPlugin.handle").expect("handle case");
        let stream_at = core_swift.find("case \"background-fetch\": await BackgroundFetchPlugin.subscribe").expect("stream case");
        assert!(stream_at < handle_at, "stream case in subscribe(), handle case in handle()");
        // app-launch hook + WorkManager dep + POST_NOTIFICATIONS, but NO location perms.
        let app_swift = read(&root, "iOS/Sources/App.swift");
        assert!(app_swift.contains("BackgroundFetchPlugin.bootstrap()"), "app-launch hook injected");
        let gradle = read(&root, "Android/app/build.gradle.kts");
        assert!(gradle.contains("androidx.work:work-runtime-ktx"), "WorkManager dep injected");
        let manifest = read(&root, "Android/app/src/main/AndroidManifest.xml");
        assert!(manifest.contains("android.permission.POST_NOTIFICATIONS"), "POST_NOTIFICATIONS injected");
        assert!(!manifest.contains("ACCESS_FINE_LOCATION"), "no location perms for background-fetch");
        // Two array-valued Info.plist keys.
        let yml = read(&root, "iOS/project.yml");
        assert!(yml.contains("UIBackgroundModes: [\"fetch\", \"processing\"]"), "UIBackgroundModes array, got:\n{yml}");
        assert!(yml.contains("BGTaskSchedulerPermittedIdentifiers: [\"mobiler.refresh\"]"), "BGTask identifiers array injected");
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn add_bundled_sensors_copies_and_registers() {
        let root = skeleton();
        add_at(&root, "sensors").unwrap();
        let kt = read(&root, "Android/app/src/main/java/dev/mobiler/demo/SensorsPlugin.kt");
        assert!(kt.contains("package dev.mobiler.demo"));
        let core_kt = read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt");
        assert!(core_kt.contains("\"sensors\" to SensorsPlugin(application),"));
        let core_swift = read(&root, "iOS/Sources/Core.swift");
        assert!(core_swift.contains("case \"sensors\": return await SensorsPlugin.handle"));
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn add_bundled_contacts_copies_both_sources_and_registers_activity() {
        let root = skeleton();
        add_at(&root, "contacts").unwrap();
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/ContactsPlugin.kt").contains("package dev.mobiler.demo"));
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/ContactsPickerActivity.kt").contains("class ContactsPickerActivity"));
        let core_kt = read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt");
        assert!(core_kt.contains("\"contacts\" to ContactsPlugin(application),"));
        let core_swift = read(&root, "iOS/Sources/Core.swift");
        assert!(core_swift.contains("case \"contacts\": return await ContactsPlugin.handle"));
        let manifest = read(&root, "Android/app/src/main/AndroidManifest.xml");
        assert!(manifest.contains("android:name=\".ContactsPickerActivity\""));
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn add_bundled_calendar_registers_and_adds_plist_keys() {
        let root = skeleton();
        add_at(&root, "calendar").unwrap();
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/CalendarPlugin.kt").contains("package dev.mobiler.demo"));
        let core_kt = read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt");
        assert!(core_kt.contains("\"calendar\" to CalendarPlugin(application),"));
        let core_swift = read(&root, "iOS/Sources/Core.swift");
        assert!(core_swift.contains("case \"calendar\": return await CalendarPlugin.handle"));
        let yml = read(&root, "iOS/project.yml");
        assert!(yml.contains("NSCalendarsUsageDescription"), "iOS calendar usage key injected");
        assert!(yml.contains("NSCalendarsWriteOnlyAccessUsageDescription"), "iOS 17+ write-only key injected");
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn add_bundled_audio_adds_record_permission_and_mic_plist_key() {
        let root = skeleton();
        add_at(&root, "audio").unwrap();
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/AudioPlugin.kt").contains("package dev.mobiler.demo"));
        let core_kt = read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt");
        assert!(core_kt.contains("\"audio\" to AudioPlugin(application),"));
        let core_swift = read(&root, "iOS/Sources/Core.swift");
        assert!(core_swift.contains("case \"audio\": return await AudioPlugin.handle"));
        let manifest = read(&root, "Android/app/src/main/AndroidManifest.xml");
        assert!(manifest.contains("android.permission.RECORD_AUDIO"), "RECORD_AUDIO injected");
        let yml = read(&root, "iOS/project.yml");
        assert!(yml.contains("NSMicrophoneUsageDescription"), "mic usage key injected");
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn add_bundled_composer_copies_and_registers() {
        let root = skeleton();
        add_at(&root, "composer").unwrap();
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/ComposerPlugin.kt").contains("package dev.mobiler.demo"));
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt").contains("\"composer\" to ComposerPlugin(application),"));
        assert!(read(&root, "iOS/Sources/Core.swift").contains("case \"composer\": return await ComposerPlugin.handle"));
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn add_bundled_tts_copies_and_registers() {
        let root = skeleton();
        add_at(&root, "tts").unwrap();
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/TtsPlugin.kt").contains("package dev.mobiler.demo"));
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt").contains("\"tts\" to TtsPlugin(application),"));
        assert!(read(&root, "iOS/Sources/Core.swift").contains("case \"tts\": return await TtsPlugin.handle"));
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn add_bundled_review_registers_and_adds_gradle_dep() {
        let root = skeleton();
        add_at(&root, "review").unwrap();
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt").contains("\"review\" to ReviewPlugin(application),"));
        assert!(read(&root, "iOS/Sources/Core.swift").contains("case \"review\": return await ReviewPlugin.handle"));
        assert!(read(&root, "Android/app/build.gradle.kts").contains("com.google.android.play:review"), "gradle dep injected");
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn add_bundled_sharefile_copies_and_registers() {
        let root = skeleton();
        add_at(&root, "sharefile").unwrap();
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/SharefilePlugin.kt").contains("package dev.mobiler.demo"));
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt").contains("\"sharefile\" to SharefilePlugin(application),"));
        assert!(read(&root, "iOS/Sources/Core.swift").contains("case \"sharefile\": return await SharefilePlugin.handle"));
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn add_bundled_video_registers_activity_and_plist_keys() {
        let root = skeleton();
        add_at(&root, "video").unwrap();
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/VideoCaptureActivity.kt").contains("class VideoCaptureActivity"));
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt").contains("\"video\" to VideoPlugin(application),"));
        assert!(read(&root, "iOS/Sources/Core.swift").contains("case \"video\": return await VideoPlugin.handle"));
        assert!(read(&root, "Android/app/src/main/AndroidManifest.xml").contains("android:name=\".VideoCaptureActivity\""));
        assert!(read(&root, "iOS/project.yml").contains("NSCameraUsageDescription"));
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn add_bundled_speech_registers_both_platforms_and_plist() {
        let root = skeleton();
        add_at(&root, "speech").unwrap();
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/SpeechActivity.kt").contains("class SpeechActivity"));
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt").contains("\"speech\" to SpeechPlugin(application),"));
        assert!(read(&root, "Android/app/src/main/AndroidManifest.xml").contains("android:name=\".SpeechActivity\""));
        // iOS now shipped: registration + usage-description plist keys.
        assert!(read(&root, "iOS/Sources/SpeechPlugin.swift").contains("SFSpeechRecognizer"));
        assert!(read(&root, "iOS/Sources/Core.swift").contains("case \"speech\": return await SpeechPlugin.handle"));
        let yml = read(&root, "iOS/project.yml");
        assert!(yml.contains("NSSpeechRecognitionUsageDescription"));
        assert!(yml.contains("NSMicrophoneUsageDescription"));
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn add_bundled_sqlite_registers_both_platforms() {
        let root = skeleton();
        add_at(&root, "sqlite").unwrap();
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/SqlitePlugin.kt").contains("package dev.mobiler.demo"));
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt").contains("\"sqlite\" to SqlitePlugin(application),"));
        // iOS now shipped.
        assert!(read(&root, "iOS/Sources/SqlitePlugin.swift").contains("import SQLite3"));
        assert!(read(&root, "iOS/Sources/Core.swift").contains("case \"sqlite\": return await SqlitePlugin.handle"));
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn add_bundled_bluetooth_adds_perms_registration_and_plist() {
        let root = skeleton();
        add_at(&root, "bluetooth").unwrap();
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/BluetoothPlugin.kt").contains("BluetoothGattCallback"));
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt").contains("\"bluetooth\" to BluetoothPlugin(application),"));
        let manifest = read(&root, "Android/app/src/main/AndroidManifest.xml");
        assert!(manifest.contains("android.permission.BLUETOOTH_SCAN"));
        assert!(manifest.contains("android.permission.BLUETOOTH_CONNECT"));
        assert!(read(&root, "iOS/Sources/BluetoothPlugin.swift").contains("CBCentralManager"));
        let core_swift = read(&root, "iOS/Sources/Core.swift");
        assert!(core_swift.contains("case \"bluetooth\": return await BluetoothPlugin.handle"));
        // write op + the notify stream (register_stream) are present.
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/BluetoothPlugin.kt").contains("\"write\" -> write(input)"));
        assert!(core_swift.contains("case \"bluetooth\": await BluetoothPlugin.subscribe"), "bluetooth notify stream case");
        assert!(read(&root, "iOS/project.yml").contains("NSBluetoothAlwaysUsageDescription"));
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn add_bundled_geolocation_fused_registers_under_geolocation_with_play_services() {
        let root = skeleton();
        add_at(&root, "geolocation-fused").unwrap();
        // Registers under the SAME cx name "geolocation" (mutually-exclusive alt to the default plugin).
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/GeolocationPlugin.kt").contains("FusedLocationProviderClient"));
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt").contains("\"geolocation\" to GeolocationPlugin(application),"));
        assert!(read(&root, "iOS/Sources/Core.swift").contains("case \"geolocation\": return await GeolocationPlugin.handle"));
        let gradle = read(&root, "Android/app/build.gradle.kts");
        assert!(gradle.contains("com.google.android.gms:play-services-location"), "play-services dep injected");
        let manifest = read(&root, "Android/app/src/main/AndroidManifest.xml");
        assert!(manifest.contains("android.permission.ACCESS_FINE_LOCATION"));
        assert!(read(&root, "iOS/project.yml").contains("NSLocationWhenInUseUsageDescription"));
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn add_bundled_oauth_copies_sources_registers_and_declares_redirect_activity() {
        let root = skeleton();
        add_at(&root, "oauth").unwrap();
        // Both Android sources copied with the package substituted.
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/OAuthPlugin.kt").contains("package dev.mobiler.demo"));
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/OAuthActivity.kt").contains("class OAuthActivity"));
        // Registered in both shells.
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt").contains("\"oauth\" to OAuthPlugin(application),"));
        assert!(read(&root, "iOS/Sources/Core.swift").contains("case \"oauth\": return await OAuthPlugin.handle"));
        // Redirect-catcher Activity declared in the manifest, keyed on ${applicationId}.
        let manifest = read(&root, "Android/app/src/main/AndroidManifest.xml");
        assert!(manifest.contains("android:name=\".OAuthActivity\""), "redirect activity declared");
        assert!(manifest.contains("android:scheme=\"${applicationId}\""), "redirect scheme = applicationId");
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn add_bundled_push_registers_service_perm_dep_gradle_plugin_and_entitlement() {
        let root = skeleton();
        add_at(&root, "push").unwrap();

        // Both Android sources copied with the package substituted.
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/PushPlugin.kt").contains("package dev.mobiler.demo"));
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/PushMessagingService.kt").contains("class PushMessagingService"));
        // Registered in both shells — handle case + the streaming case (cx.subscribe).
        let core_kt = read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt");
        assert!(core_kt.contains("\"push\" to PushPlugin(application),"));
        let core_swift = read(&root, "iOS/Sources/Core.swift");
        let handle_at = core_swift.find("case \"push\": return await PushPlugin.handle").expect("handle case");
        let stream_at = core_swift.find("case \"push\": await PushPlugin.subscribe").expect("stream case");
        assert!(stream_at < handle_at, "stream case in subscribe(), handle case in handle()");
        // Permission + FCM service + firebase dep.
        let manifest = read(&root, "Android/app/src/main/AndroidManifest.xml");
        assert!(manifest.contains("android.permission.POST_NOTIFICATIONS"), "POST_NOTIFICATIONS injected");
        assert!(manifest.contains("android:name=\".PushMessagingService\""), "FCM service declared");
        let gradle = read(&root, "Android/app/build.gradle.kts");
        assert!(gradle.contains("com.google.firebase:firebase-messaging"), "firebase dep injected");
        // The new gradle_plugins field: applied in the app block + declared (apply false) at project level.
        assert!(gradle.contains("id(\"com.google.gms.google-services\")"), "google-services applied in app gradle");
        let gradle_proj = read(&root, "Android/build.gradle.kts");
        assert!(
            gradle_proj.contains("id(\"com.google.gms.google-services\") version \"4.4.2\" apply false"),
            "google-services declared (apply false) in project gradle"
        );
        // iOS aps-environment entitlement (first plugin to exercise the entitlements path).
        let yml = read(&root, "iOS/project.yml");
        assert!(yml.contains("entitlements:") && yml.contains("aps-environment"), "aps-environment entitlement added");
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn add_bundled_iap_registers_both_switches_and_adds_billing_dep() {
        let root = skeleton();
        add_at(&root, "iap").unwrap();

        // Source copied with the package substituted.
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/IapPlugin.kt").contains("package dev.mobiler.demo"));
        // Registered in both shells; the streaming case lands in subscribe(), the handle case in handle().
        let core_kt = read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt");
        assert!(core_kt.contains("\"iap\" to IapPlugin(application),"));
        let core_swift = read(&root, "iOS/Sources/Core.swift");
        let handle_at = core_swift.find("case \"iap\": return await IapPlugin.handle").expect("handle case");
        let stream_at = core_swift.find("case \"iap\": await IapPlugin.subscribe").expect("stream case");
        assert!(stream_at < handle_at, "stream case in subscribe(), handle case in handle()");
        // Play Billing Gradle dependency injected; NO gradle plugin / entitlements / permissions.
        let gradle = read(&root, "Android/app/build.gradle.kts");
        assert!(gradle.contains("com.android.billingclient:billing"), "billing dep injected");
        assert!(!gradle.contains("google-services"), "no gradle plugin for iap");
        let yml = read(&root, "iOS/project.yml");
        assert!(!yml.contains("entitlements:"), "iap adds no iOS entitlements");
        let manifest = read(&root, "Android/app/src/main/AndroidManifest.xml");
        assert!(!manifest.contains("uses-permission"), "iap declares no permissions (billing AAR merges its own)");
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn add_bundled_analytics_registers_app_launch_firebase_deps_plugins_and_spm() {
        let root = skeleton();
        add_at(&root, "analytics").unwrap();

        // Source copied with the package substituted; registered in handle() (no stream).
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/AnalyticsPlugin.kt").contains("package dev.mobiler.demo"));
        let core_kt = read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt");
        assert!(core_kt.contains("\"analytics\" to AnalyticsPlugin(application),"));
        let core_swift = read(&root, "iOS/Sources/Core.swift");
        assert!(core_swift.contains("case \"analytics\": return await AnalyticsPlugin.handle"));
        // app-launch hook → FirebaseApp.configure at launch.
        assert!(read(&root, "iOS/Sources/App.swift").contains("AnalyticsPlugin.bootstrap()"), "app-launch hook injected");
        // Android: both Firebase deps + the google-services AND crashlytics Gradle plugins.
        let gradle = read(&root, "Android/app/build.gradle.kts");
        assert!(gradle.contains("com.google.firebase:firebase-analytics"), "analytics dep");
        assert!(gradle.contains("com.google.firebase:firebase-crashlytics"), "crashlytics dep");
        assert!(gradle.contains("id(\"com.google.gms.google-services\")"), "google-services plugin applied");
        assert!(gradle.contains("id(\"com.google.firebase.crashlytics\")"), "crashlytics plugin applied");
        let gradle_proj = read(&root, "Android/build.gradle.kts");
        assert!(gradle_proj.contains("com.google.firebase.crashlytics") && gradle_proj.contains("apply false"), "crashlytics plugin declared at project level");
        // iOS: the Firebase SPM package + BOTH product dependencies.
        let yml = read(&root, "iOS/project.yml");
        assert!(yml.contains("url: https://github.com/firebase/firebase-ios-sdk"), "Firebase SPM package");
        assert!(yml.contains("product: FirebaseAnalytics"), "FirebaseAnalytics product");
        assert!(yml.contains("product: FirebaseCrashlytics"), "FirebaseCrashlytics product");
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn add_bundled_push_firebase_only_injects_spm_package_and_registers_under_push() {
        let root = skeleton();
        add_at(&root, "push-firebase-only").unwrap();

        // iOS Firebase plugin + Android copies present.
        assert!(read(&root, "iOS/Sources/FirebasePushPlugin.swift").contains("FirebasePushPlugin"));
        assert!(read(&root, "Android/app/src/main/java/dev/mobiler/demo/PushPlugin.kt").contains("package dev.mobiler.demo"));
        // Registered under the cx name "push" in both shells (handle + stream cases).
        let core_kt = read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt");
        assert!(core_kt.contains("\"push\" to PushPlugin(application),"));
        let core_swift = read(&root, "iOS/Sources/Core.swift");
        let handle_at = core_swift.find("case \"push\": return await FirebasePushPlugin.handle").expect("handle case");
        let stream_at = core_swift.find("case \"push\": await FirebasePushPlugin.subscribe").expect("stream case");
        assert!(stream_at < handle_at, "stream case in subscribe(), handle case in handle()");
        // The NEW spm_packages capability: Firebase remote package + the FirebaseMessaging product dep.
        let yml = read(&root, "iOS/project.yml");
        assert!(yml.contains("url: https://github.com/firebase/firebase-ios-sdk"), "Firebase SPM package injected");
        assert!(yml.contains("from: 11."), "Firebase version pinned");
        assert!(yml.contains("product: FirebaseMessaging"), "FirebaseMessaging product dependency injected");
        // Android FCM bits (same as push) + the iOS aps-environment entitlement.
        let gradle = read(&root, "Android/app/build.gradle.kts");
        assert!(gradle.contains("com.google.firebase:firebase-messaging"), "firebase dep");
        assert!(gradle.contains("id(\"com.google.gms.google-services\")"), "google-services gradle plugin");
        let manifest = read(&root, "Android/app/src/main/AndroidManifest.xml");
        assert!(manifest.contains("android:name=\".PushMessagingService\""), "FCM service");
        assert!(yml.contains("aps-environment"), "aps-environment entitlement");
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn array_plist_keys_merge_across_plugins() {
        let root = skeleton();
        add_at(&root, "geofence").unwrap();          // UIBackgroundModes = ["location"]
        add_at(&root, "background-fetch").unwrap();   // UIBackgroundModes = ["fetch","processing"] → must UNION
        let yml = read(&root, "iOS/project.yml");
        let line = yml.lines().find(|l| l.trim_start().starts_with("UIBackgroundModes:")).expect("UIBackgroundModes line");
        assert!(line.contains("\"location\""), "geofence's location mode kept: {line}");
        assert!(line.contains("\"fetch\""), "background-fetch's fetch mode merged in: {line}");
        assert!(line.contains("\"processing\""), "background-fetch's processing mode merged in: {line}");
        assert_eq!(yml.matches("UIBackgroundModes:").count(), 1, "still a single UIBackgroundModes line");
        // background-fetch's own identifier key is also present.
        assert!(yml.contains("BGTaskSchedulerPermittedIdentifiers: [\"mobiler.refresh\"]"));
        // Re-adding is idempotent — no duplicate modes.
        add_at(&root, "geofence").unwrap();
        let yml2 = read(&root, "iOS/project.yml");
        assert_eq!(yml2.matches("\"location\"").count(), 1, "no duplicate location mode on re-add");
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn merge_plist_array_handles_inline_and_block_forms() {
        let dir = std::env::temp_dir().join(format!("mob_plist_{}_{}", std::process::id(), COUNTER.fetch_add(1, Ordering::SeqCst)));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let yml = dir.join("project.yml");
        // Hand-authored YAML block form (the PiP UIBackgroundModes opt-in pattern).
        fs::write(&yml, "      properties:\n        UIBackgroundModes:\n          - audio\n        # mobiler:info-plist\n").unwrap();
        // A plugin must UNION its mode into the existing block, not skip it.
        assert!(matches!(merge_plist_array(&yml, "UIBackgroundModes", &["\"location\"".into()]).unwrap(), Insert::Inserted));
        let c = fs::read_to_string(&yml).unwrap();
        assert!(c.contains("- audio") && c.contains("- \"location\""), "block union kept both:\n{c}");
        assert_eq!(c.matches("UIBackgroundModes:").count(), 1, "still one key");
        // Idempotent.
        assert!(matches!(merge_plist_array(&yml, "UIBackgroundModes", &["\"location\"".into()]).unwrap(), Insert::AlreadyPresent));
        // A brand-new array key inserts inline at the anchor.
        assert!(matches!(merge_plist_array(&yml, "BGTaskSchedulerPermittedIdentifiers", &["\"mobiler.refresh\"".into()]).unwrap(), Insert::Inserted));
        assert!(fs::read_to_string(&yml).unwrap().contains("BGTaskSchedulerPermittedIdentifiers: [\"mobiler.refresh\"]"));
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn add_is_idempotent() {
        let root = skeleton();
        add_at(&root, "battery").unwrap();
        add_at(&root, "battery").unwrap(); // second run must not duplicate
        let core_kt = read(&root, "Android/app/src/main/java/dev/mobiler/demo/Core.kt");
        assert_eq!(core_kt.matches("\"battery\" to").count(), 1, "no duplicate registration");
        let _ = fs::remove_dir_all(&root);
    }

    /// Guards against template/installer drift: the REAL scaffold templates must carry every
    /// anchor `insert_before` targets, or `plugin add` silently no-ops on a real app (which a
    /// skeleton-based test can't catch — this is exactly the bug that slipped through once).
    #[test]
    fn templates_carry_every_anchor() {
        let t = |rel: &str| {
            std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/templates").to_string() + "/" + rel)
                .unwrap_or_else(|_| panic!("missing template {rel}"))
        };
        assert!(
            t("Android/app/src/main/java/__PACKAGE_PATH__/Core.kt").contains("// mobiler:plugins"),
            "Core.kt needs the // mobiler:plugins anchor"
        );
        assert!(
            t("iOS/Sources/Core.swift").contains("// mobiler:plugins"),
            "Core.swift needs the // mobiler:plugins anchor"
        );
        assert!(
            t("iOS/Sources/App.swift").contains("// mobiler:app-launch"),
            "App.swift needs the // mobiler:app-launch anchor (launch-time plugin hooks)"
        );
        let manifest = t("Android/app/src/main/AndroidManifest.xml");
        assert!(manifest.contains("mobiler:permissions"), "AndroidManifest.xml needs the mobiler:permissions anchor");
        assert!(manifest.contains("mobiler:manifest-application"), "AndroidManifest.xml needs the mobiler:manifest-application anchor");
        let yml = t("iOS/project.yml");
        assert!(yml.contains("# mobiler:info-plist"), "project.yml needs the info-plist anchor");
        assert!(yml.contains("# mobiler:target-extra"), "project.yml needs the target-extra anchor");
        assert!(yml.contains("# mobiler:spm-packages"), "project.yml needs the spm-packages anchor (packages: block)");
        assert!(yml.contains("# mobiler:spm-dependencies"), "project.yml needs the spm-dependencies anchor (target deps)");
        assert!(
            t("Android/app/build.gradle.kts").contains("mobiler:gradle-deps"),
            "build.gradle.kts needs the mobiler:gradle-deps anchor"
        );
        assert!(
            t("Android/app/build.gradle.kts").contains("// mobiler:gradle-plugins"),
            "app build.gradle.kts needs the // mobiler:gradle-plugins anchor (apply a Gradle plugin)"
        );
        assert!(
            t("Android/build.gradle.kts").contains("// mobiler:gradle-plugins-classpath"),
            "project build.gradle.kts needs the // mobiler:gradle-plugins-classpath anchor"
        );
    }

    #[test]
    fn add_local_package_patches_permission_and_entitlements() {
        let root = skeleton();
        // A tiny local plugin package with a permission, an Info.plist key, and an entitlement.
        let pkg = std::env::temp_dir().join(format!("mob_pkg_{}", std::process::id()));
        let _ = fs::remove_dir_all(&pkg);
        fs::create_dir_all(pkg.join("android")).unwrap();
        fs::create_dir_all(pkg.join("ios")).unwrap();
        fs::write(pkg.join("android/FooPlugin.kt"), "package {{PACKAGE}}\nclass FooPlugin\n").unwrap();
        fs::write(pkg.join("ios/FooPlugin.swift"), "enum FooPlugin {}\n").unwrap();
        fs::write(
            pkg.join("mobiler-plugin.toml"),
            r#"name = "foo"
[android]
sources = ["android/FooPlugin.kt"]
register = '"foo" to FooPlugin(application)'
permissions = ["android.permission.NFC"]
gradle_deps = ["com.example:foo:1.2.3"]
manifest_application = ['<receiver android:name=".FooReceiver" android:exported="false"/>']
[ios]
sources = ["ios/FooPlugin.swift"]
register = 'case "foo": return await FooPlugin.handle(op: op, input: input)'
[ios.info_plist]
NFCReaderUsageDescription = "use nfc"
[ios.entitlements]
"com.apple.developer.nfc.readersession.formats" = ["NDEF"]
"#,
        )
        .unwrap();

        add_at(&root, pkg.to_str().unwrap()).unwrap();

        let manifest = read(&root, "Android/app/src/main/AndroidManifest.xml");
        assert!(manifest.contains("android.permission.NFC"), "permission added");
    let gradle = read(&root, "Android/app/build.gradle.kts");
    assert!(gradle.contains("implementation(\"com.example:foo:1.2.3\")"), "gradle dep added");
        let project = read(&root, "iOS/project.yml");
        assert!(project.contains("NFCReaderUsageDescription: \"use nfc\""), "info.plist key added");
        assert!(
            project.contains("entitlements:")
                && project.contains("com.apple.developer.nfc.readersession.formats")
                && project.contains("NDEF"),
            "entitlements added"
        );
        let kt = read(&root, "Android/app/src/main/java/dev/mobiler/demo/FooPlugin.kt");
        assert!(kt.contains("package dev.mobiler.demo"), "package substituted in local source");

        let _ = fs::remove_dir_all(&root);
        let _ = fs::remove_dir_all(&pkg);
    }
}